Skip to main content
summaryrefslogtreecommitdiffstats
blob: 45e9da036aeb9eac65d31c0641ff4814d7de5651 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
/*******************************************************************************
 * Copyright (c) 2004, 2007 Boeing.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     Boeing - initial API and implementation
 *******************************************************************************/
package org.eclipse.osee.framework.skynet.core.transaction;

import static org.eclipse.osee.framework.db.connection.core.schema.SkynetDatabase.TRANSACTION_DETAIL_TABLE;
import static org.eclipse.osee.framework.db.connection.core.schema.SkynetDatabase.TXD_COMMENT;
import static org.eclipse.osee.framework.skynet.core.change.ModificationType.CHANGE;
import static org.eclipse.osee.framework.skynet.core.change.ModificationType.DELETED;
import static org.eclipse.osee.framework.skynet.core.change.ModificationType.NEW;
import java.sql.SQLException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.osee.framework.db.connection.ConnectionHandler;
import org.eclipse.osee.framework.db.connection.info.SQL3DataType;
import org.eclipse.osee.framework.jdk.core.type.Pair;
import org.eclipse.osee.framework.jdk.core.util.Strings;
import org.eclipse.osee.framework.jdk.core.util.time.GlobalTime;
import org.eclipse.osee.framework.messaging.event.skynet.ISkynetEvent;
import org.eclipse.osee.framework.plugin.core.config.ConfigUtil;
import org.eclipse.osee.framework.skynet.core.SkynetAuthentication;
import org.eclipse.osee.framework.skynet.core.User;
import org.eclipse.osee.framework.skynet.core.artifact.Artifact;
import org.eclipse.osee.framework.skynet.core.artifact.Branch;
import org.eclipse.osee.framework.skynet.core.artifact.RemoteEventManager;
import org.eclipse.osee.framework.skynet.core.attribute.utils.AttributeURL;
import org.eclipse.osee.framework.skynet.core.change.ModificationType;
import org.eclipse.osee.framework.skynet.core.dbinit.SkynetDbInit;
import org.eclipse.osee.framework.skynet.core.event.LocalTransactionEvent;
import org.eclipse.osee.framework.skynet.core.event.SkynetEventManager;
import org.eclipse.osee.framework.skynet.core.linking.HttpProcessor;
import org.eclipse.osee.framework.skynet.core.transaction.data.ArtifactTransactionData;
import org.eclipse.osee.framework.skynet.core.transaction.data.AttributeTransactionData;
import org.eclipse.osee.framework.skynet.core.transaction.data.ITransactionData;
import org.eclipse.osee.framework.ui.plugin.event.Event;

/**
 * @author Robert A. Fisher
 */
public class SkynetTransaction {
   private static final Logger logger = ConfigUtil.getConfigFactory().getLogger(SkynetTransaction.class);
   private static final SkynetEventManager eventManager = SkynetEventManager.getInstance();
   private static final String INSERT_INTO_TRANSACTION_DETAIL_TABLE =
         "INSERT INTO " + TRANSACTION_DETAIL_TABLE.columnsForInsert("transaction_id", TXD_COMMENT, "time", "author",
               "branch_id", "tx_type");
   private static final String INSERT_INTO_TRANSACTION_TABLE =
         "INSERT INTO osee_define_txs (transaction_id, gamma_id, mod_type, tx_current) VALUES (?, ?, ?, ?)";

   private static final String DELETE_TRANSACTION_DETAIL =
         "DELETE FROM " + TRANSACTION_DETAIL_TABLE + " WHERE transaction_id =?";

   private static final TransactionIdManager transactionIdManager = TransactionIdManager.getInstance();
   private final Map<String, List<Object[]>> preparedBatch;
   private String transactionName;
   private String comment;
   private TransactionId transactionId;
   private final Branch branch;
   private List<ISkynetEvent> remoteEvents;
   private List<Event> localEvents;
   private Map<ITransactionData, ITransactionData> transactionItems;

   // IMPORTANT: The transactionNumber for this transaction is kept in addition to the TransactionId reference
   //            since the number in the TransactionId may be updated from events, and the number of this
   //            exact transaction must be known over the life of this transaction despite the head transaction
   //            potentially moving on from other transactions occurring in parallel.
   private Integer transactionNumber;

   public SkynetTransaction(Branch branch) throws SQLException {
      this(branch, SkynetAuthentication.getUser());
   }

   public SkynetTransaction(Branch branch, String comment) throws SQLException {
      this(branch, SkynetAuthentication.getUser(), comment);
   }

   /**
    * 
    */
   @SuppressWarnings("unchecked")
   public SkynetTransaction(Branch branch, User userToBlame) throws SQLException {
      this(branch, userToBlame, "");
   }

   /**
    * 
    */
   @SuppressWarnings("unchecked")
   public SkynetTransaction(Branch branch, User userToBlame, String comment) throws SQLException {
      super();

      this.branch = branch;
      this.comment = "";
      this.remoteEvents = new LinkedList<ISkynetEvent>();
      this.localEvents = new LinkedList<Event>();
      this.comment = comment;

      Pair<Integer, TransactionId> nextTranData = transactionIdManager.createNextTransactionId(branch);
      this.transactionNumber = nextTranData.getKey();
      this.transactionId = nextTranData.getValue();
      List datas = new LinkedList();

      int blameArtId = -1;
      if (userToBlame == null || !userToBlame.isInDb()) {
         if (!SkynetDbInit.isDbInit()) {
            blameArtId = SkynetAuthentication.getNoOneArtifactId();
         }
      } else {
         blameArtId = userToBlame.getArtId();
      }

      datas.add(new Object[] {SQL3DataType.INTEGER, transactionNumber, SQL3DataType.VARCHAR, getComment(),
            SQL3DataType.TIMESTAMP, GlobalTime.GreenwichMeanTimestamp(), SQL3DataType.INTEGER, blameArtId,
            SQL3DataType.INTEGER, branch.getBranchId(), SQL3DataType.INTEGER,
            TransactionDetailsType.NonBaselined.getId()});
      ConnectionHandler.runPreparedUpdateBatch(INSERT_INTO_TRANSACTION_DETAIL_TABLE, datas);

      preparedBatch = new HashMap<String, List<Object[]>>();
      transactionItems = new HashMap<ITransactionData, ITransactionData>();
   }

   public void addToBatch(String sql, Object... data) {
      if (sql == null) throw new IllegalArgumentException("SQL can not be null.");

      List<Object[]> statementData;

      if (preparedBatch.containsKey(sql)) {
         statementData = preparedBatch.get(sql);
      } else {
         statementData = new LinkedList<Object[]>();
         preparedBatch.put(sql, statementData);
      }

      statementData.add(data);
   }

   public void execute() throws SQLException {
      execute(new NullProgressMonitor());
   }

   public synchronized void execute(IProgressMonitor monitor) throws SQLException {
      boolean deleteTransactionDetail = false;

      try {
         boolean insertBatchToTransactions = executeBatchToTransactions(monitor);
         boolean insertTransactionDataItems = executeTransactionDataItems();

         if (!insertBatchToTransactions && !insertTransactionDataItems) {
            deleteTransactionDetail = true;
         }

         setArtifactsNotDirty();
      } catch (SQLException ex) {
         deleteTransactionDetail = true;
         transactionCleanUp();
         ConnectionHandler.requestRollback();
         logger.log(Level.SEVERE, "Rollback occured for transaction: " + getTransactionId().getTransactionNumber(), ex);
         throw ex;
      } finally {
         if (deleteTransactionDetail) {
            localEvents = null;
            remoteEvents = null;
            ConnectionHandler.runPreparedUpdate(DELETE_TRANSACTION_DETAIL, SQL3DataType.INTEGER, transactionNumber);
         } else {
            transactionId.setLastSavedTransactionNumber(transactionNumber);
         }
      }
   }

   private void transactionCleanUp() {
      for (ITransactionData transactionData : transactionItems.keySet()) {
         if (transactionData instanceof AttributeTransactionData) {
            String uri = ((AttributeTransactionData) transactionData).getUri();
            if (Strings.isValid(uri)) {
               try {
                  HttpProcessor.delete(AttributeURL.getDeleteURL(uri));
               } catch (Exception ex) {
                  logger.log(Level.SEVERE, ex.toString(), ex);
               }
            }
         }
      }

   }

   public boolean executeTransactionDataItems() throws SQLException {
      boolean insertTransactionDataItems = transactionItems.size() > 0;

      for (ITransactionData transactionData : transactionItems.keySet()) {
         //This must be called before adding the new transaction information, because it
         //will update the current transaction to 0.
         ConnectionHandler.runPreparedUpdate(transactionData.setPreviousTxNotCurrentSql(),
               transactionData.getPreviousTxNotCurrentData().toArray());

         //Add current transaction information
         ModificationType modType = transactionData.getModificationType();

         ConnectionHandler.runPreparedUpdate(INSERT_INTO_TRANSACTION_TABLE, SQL3DataType.INTEGER,
               transactionData.getTransactionId(), SQL3DataType.INTEGER, transactionData.getGammaId(),
               SQL3DataType.INTEGER, modType.getValue(), SQL3DataType.INTEGER, modType.getCurrentValue());

         //Add specific object values to the their tables
         ConnectionHandler.runPreparedUpdate(transactionData.getTransactionChangeSql(),
               transactionData.getTransactionChangeData().toArray());
      }
      return insertTransactionDataItems;
   }

   private void setArtifactsNotDirty() throws SQLException {
      for (ITransactionData transactionData : transactionItems.keySet()) {
         if (transactionData instanceof ArtifactTransactionData) {
            Artifact artifact = ((ArtifactTransactionData) transactionData).getArtifact();
            artifact.setNotDirty();
         }
      }
   }

   // Supports adding new artifacts to the artifact table and
   // updating attributes that are not versioned.
   public boolean executeBatchToTransactions(IProgressMonitor monitor) throws SQLException {
      Collection<String> sqls = preparedBatch.keySet();
      int size = sqls.size();
      int count = 0;
      Iterator<String> iter = sqls.iterator();
      while (iter.hasNext()) {
         monitor.subTask("Processing Prepared SQL set " + (++count) + "/" + size);
         String sql = iter.next();
         ConnectionHandler.runPreparedUpdateBatch(sql, preparedBatch.get(sql));
         monitor.worked(1);
      }
      return preparedBatch.size() > 0;
   }

   public void addRemoteEvent(ISkynetEvent event) {
      if (event == null) throw new IllegalArgumentException("Remote event can not be null");

      if (!remoteEvents.contains(event)) {
         remoteEvents.add(event);
      }
   }

   public void addLocalEvent(Event event) {
      if (event == null) throw new IllegalArgumentException("local event can not be null");

      if (!localEvents.contains(event)) localEvents.add(event);
   }

   /**
    * Kicks local and remote events
    */
   public void kickEvents() {
      if (localEvents != null) {
         eventManager.kick(new LocalTransactionEvent(localEvents, this));
         localEvents.clear();
      }

      if (remoteEvents != null) {
         RemoteEventManager.kick(remoteEvents.toArray(ISkynetEvent.EMPTY_ARRAY));
         remoteEvents.clear();
      }
   }

   /**
    * @return Returns the transactionName.
    */
   public String getTransactionName() {
      return transactionName;
   }

   /**
    * @param transactionName The transactionName to set.
    */
   public void setTransactionName(String transactionName) {
      this.transactionName = transactionName;
   }

   /**
    * @return Returns the transactionId.
    */
   public Integer getTransactionNumber() {
      return transactionNumber;
   }

   /**
    * @return Returns the comment.
    */
   public String getComment() {
      return comment;
   }

   /**
    * @param comment The comment to set.
    */
   public void setComment(String comment) {
      this.comment = comment;
   }

   /**
    * Returns the amount of work that this Transaction has to do. This value is suitable for using to compute total work
    * for status to an IProgressMonitor.
    */
   protected int getWork() {
      return preparedBatch.keySet().size() + transactionItems.size();
   }

   /**
    * @return Returns the branch.
    */
   public Branch getBranch() {
      return branch;
   }

   /**
    * @return Returns the transactionId.
    */
   public TransactionId getTransactionId() {
      return transactionId;
   }

   public void addTransactionDataItem(ITransactionData dataItem) {
      ITransactionData oldDataItem = transactionItems.remove(dataItem);

      if (oldDataItem != null) {
         if (oldDataItem.getModificationType() == NEW && dataItem.getModificationType() == CHANGE) {
            dataItem.setModificationType(NEW);
            transactionItems.put(dataItem, dataItem);
         } else if (!(oldDataItem.getModificationType() == NEW && dataItem.getModificationType() == DELETED)) {
            transactionItems.put(dataItem, dataItem);
         }
      } else {
         transactionItems.put(dataItem, dataItem);
      }
   }
}

Back to the top