Skip to main content
summaryrefslogtreecommitdiffstats
blob: 06ea6628d213f4119c06ce227c3f77d46f78a6ac (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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
/*******************************************************************************
 * 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.artifact;

import static org.eclipse.osee.framework.core.enums.CoreBranches.COMMON;
import static org.eclipse.osee.framework.core.enums.CoreBranches.SYSTEM_ROOT;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.function.Predicate;
import java.util.logging.Level;
import javax.ws.rs.core.Response;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.osee.framework.core.client.OseeClientProperties;
import org.eclipse.osee.framework.core.data.BranchId;
import org.eclipse.osee.framework.core.data.IOseeBranch;
import org.eclipse.osee.framework.core.data.ITransaction;
import org.eclipse.osee.framework.core.data.TokenFactory;
import org.eclipse.osee.framework.core.enums.BranchArchivedState;
import org.eclipse.osee.framework.core.enums.BranchState;
import org.eclipse.osee.framework.core.enums.BranchType;
import org.eclipse.osee.framework.core.enums.CoreBranches;
import org.eclipse.osee.framework.core.enums.SystemUser;
import org.eclipse.osee.framework.core.exception.BranchDoesNotExist;
import org.eclipse.osee.framework.core.exception.MultipleBranchesExist;
import org.eclipse.osee.framework.core.model.Branch;
import org.eclipse.osee.framework.core.model.MergeBranch;
import org.eclipse.osee.framework.core.model.TransactionDelta;
import org.eclipse.osee.framework.core.model.TransactionRecord;
import org.eclipse.osee.framework.core.model.cache.BranchCache;
import org.eclipse.osee.framework.core.model.cache.BranchFilter;
import org.eclipse.osee.framework.core.operation.IOperation;
import org.eclipse.osee.framework.core.operation.OperationBuilder;
import org.eclipse.osee.framework.core.operation.Operations;
import org.eclipse.osee.framework.jdk.core.type.OseeCoreException;
import org.eclipse.osee.framework.jdk.core.util.Conditions;
import org.eclipse.osee.framework.jdk.core.util.Lib;
import org.eclipse.osee.framework.jdk.core.util.Strings;
import org.eclipse.osee.framework.logging.OseeLog;
import org.eclipse.osee.framework.plugin.core.util.ExtensionDefinedObjects;
import org.eclipse.osee.framework.skynet.core.UserManager;
import org.eclipse.osee.framework.skynet.core.artifact.operation.UpdateBranchOperation;
import org.eclipse.osee.framework.skynet.core.artifact.search.ArtifactQuery;
import org.eclipse.osee.framework.skynet.core.artifact.update.ConflictResolverOperation;
import org.eclipse.osee.framework.skynet.core.commit.actions.CommitAction;
import org.eclipse.osee.framework.skynet.core.conflict.ConflictManagerExternal;
import org.eclipse.osee.framework.skynet.core.event.OseeEventManager;
import org.eclipse.osee.framework.skynet.core.event.model.BranchEvent;
import org.eclipse.osee.framework.skynet.core.event.model.BranchEventType;
import org.eclipse.osee.framework.skynet.core.httpRequests.CommitBranchHttpRequestOperation;
import org.eclipse.osee.framework.skynet.core.httpRequests.CreateBranchHttpRequestOperation;
import org.eclipse.osee.framework.skynet.core.httpRequests.PurgeBranchHttpRequestOperation;
import org.eclipse.osee.framework.skynet.core.internal.Activator;
import org.eclipse.osee.framework.skynet.core.internal.ServiceUtil;
import org.eclipse.osee.framework.skynet.core.internal.accessors.DatabaseBranchAccessor;
import org.eclipse.osee.framework.skynet.core.transaction.TransactionManager;
import org.eclipse.osee.framework.skynet.core.utility.ArtifactJoinQuery;
import org.eclipse.osee.framework.skynet.core.utility.ConnectionHandler;
import org.eclipse.osee.framework.skynet.core.utility.JoinUtility;
import org.eclipse.osee.framework.skynet.core.utility.OseeInfo;
import org.eclipse.osee.orcs.rest.client.OseeClient;
import org.eclipse.osee.orcs.rest.model.BranchEndpoint;

/**
 * Provides access to all branches as well as support for creating branches of all types
 *
 * @author Ryan D. Brooks
 */
public final class BranchManager {
   private static final String LAST_DEFAULT_BRANCH = "LastDefaultBranchUuid";
   public static final String COMMIT_COMMENT = "Commit Branch ";
   private static final String SELECT_BRANCH_BY_NAME = "select * from osee_branch where branch_name = ?";
   private static IOseeBranch lastBranch;

   private BranchManager() {
      // this private empty constructor exists to prevent the default constructor from allowing public construction
   }

   private static BranchCache getCache() throws OseeCoreException {
      return ServiceUtil.getOseeCacheService().getBranchCache();
   }

   public static List<Branch> getBranches(Predicate<Branch> branchFilter) throws OseeCoreException {
      return getCache().getBranches(branchFilter);
   }

   public static Branch getBranch(Predicate<Branch> branchFilter) throws OseeCoreException {
      List<Branch> branches = BranchManager.getBranches(branchFilter);
      if (branches.isEmpty()) {
         return null;
      } else if (branches.size() == 1) {
         return branches.get(0);
      } else {
         throw new MultipleBranchesExist("More than 1 branch exists that matches the filter: " + branchFilter);
      }
   }

   public static void refreshBranches() throws OseeCoreException {
      String refreshWindow = OseeInfo.getValue("cache.reload.throttle.millis");
      boolean reload = true;
      if (Strings.isNumeric(refreshWindow)) {
         long timeInMillis = Long.parseLong(refreshWindow);
         long diff = System.currentTimeMillis() - getCache().getLastLoaded();
         if (diff < timeInMillis) {
            reload = false;
         }
      }
      if (reload) {
         getCache().reloadCache();
      }
   }

   public static IOseeBranch getBranch(String branchName) throws OseeCoreException {
      Collection<IOseeBranch> branches = getBranchesByName(branchName);
      if (branches.isEmpty()) {
         throw new BranchDoesNotExist("No branch exists with the name: [%s]", branchName);
      }
      if (branches.size() > 1) {
         throw new MultipleBranchesExist("More than 1 branch exists with the name: [%s]", branchName);
      }
      return branches.iterator().next();
   }

   public static Collection<IOseeBranch> getBranchesByName(String branchName) throws OseeCoreException {
      Collection<IOseeBranch> branches = new ArrayList<>(1);
      ConnectionHandler.getJdbcClient().runQuery(stmt -> branches.add(getBranch(stmt.getLong("branch_id"))),
         SELECT_BRANCH_BY_NAME, branchName);
      return branches;
   }

   public static IOseeBranch getBranchToken(BranchId branch) throws OseeCoreException {
      return getBranch(branch);
   }

   public static IOseeBranch getBranchToken(Long branchId) throws OseeCoreException {
      return getBranch(branchId);
   }

   public static Branch getBranch(BranchId branch) throws OseeCoreException {
      if (branch instanceof Branch) {
         return (Branch) branch;
      } else {
         return getBranch(branch.getId());
      }
   }

   public static Branch getBranch(Long branchId) throws OseeCoreException {
      if (branchId == null) {
         throw new BranchDoesNotExist("Branch Uuid is null");
      }

      Branch branch = getCache().getById(branchId);
      if (branch == null) {
         branch = loadBranchToCache(branchId);
      }
      return branch;
   }

   /**
    * Do not call this method unless absolutely neccessary due to performance impacts.
    */
   public static synchronized void checkAndReload(BranchId branch) throws OseeCoreException {
      if (!branchExists(branch)) {
         loadBranchToCache(branch.getId());
      }
   }

   private static Branch loadBranchToCache(Long branchId) {
      Branch branch = DatabaseBranchAccessor.loadBranch(getCache(), branchId);
      getCache().cache(branch);
      return branch;
   }

   public static boolean branchExists(BranchId branch) throws OseeCoreException {
      return getCache().get(branch) != null;
   }

   public static boolean branchExists(long uuid) throws OseeCoreException {
      return getCache().getById(uuid) != null;
   }

   /**
    * returns the merge branch for this source destination pair from the cache or null if not found
    */
   public static IOseeBranch getMergeBranch(BranchId sourceBranch, BranchId destinationBranch) throws OseeCoreException {
      return getCache().findMergeBranch(sourceBranch, destinationBranch);
   }

   /**
    * returns the first merge branch for this source destination pair from the cache or null if not found
    */
   public static MergeBranch getFirstMergeBranch(BranchId sourceBranch) throws OseeCoreException {
      return getCache().findFirstMergeBranch(sourceBranch);
   }

   /**
    * returns a list tof all the merge branches for this source branch from the cache or null if not found
    */
   public static List<MergeBranch> getMergeBranches(BranchId sourceBranch) throws OseeCoreException {
      List<MergeBranch> mergeBranches = getCache().findAllMergeBranches(sourceBranch);
      return mergeBranches;
   }

   /**
    * returns whether a source branch has existing merge branches
    */
   public static boolean hasMergeBranches(BranchId sourceBranch) throws OseeCoreException {
      return !getMergeBranches(sourceBranch).isEmpty();
   }

   /**
    * returns whether a merge branch exists for a source and dest branch pair
    */
   public static boolean doesMergeBranchExist(BranchId sourceBranch, BranchId destBranch) throws OseeCoreException {
      return getMergeBranch(sourceBranch, destBranch) != null;
   }

   public static void reloadBranch(BranchId branch) {
      loadBranchToCache(branch.getId());
   }

   public static IStatus isDeleteable(Collection<Artifact> artifacts) throws OseeCoreException {
      List<Integer> artIdsToCheck = new LinkedList<>();
      for (Artifact art : artifacts) {
         if (art.isOnBranch(CoreBranches.COMMON_ID)) {
            artIdsToCheck.add(art.getArtId());
         }
      }

      if (!artIdsToCheck.isEmpty()) {
         for (IOseeBranch branch : getCache().getAll()) {
            Integer associatedArtifactId = getAssociatedArtifactId(branch);
            if (getState(branch) != BranchState.DELETED && artIdsToCheck.contains(associatedArtifactId)) {
               return new Status(IStatus.ERROR, Activator.PLUGIN_ID,
                  String.format("Cannot delete artId [%d] because it is the associated artifact of branch [%s]",
                     associatedArtifactId, branch.getName()));
            }
         }
      }

      return ArtifactCheck.OK_STATUS;
   }

   /**
    * returns a list tof all the merge branches for this source branch from the cache or null if not found
    */
   public static boolean isUpdatable(BranchId branchToUpdate) throws OseeCoreException {
      if (!hasMergeBranches(branchToUpdate) || getState(branchToUpdate).isRebaselineInProgress()) {
         return true;
      }
      return false;
   }

   /**
    * Update branch
    */
   public static Job updateBranch(IOseeBranch branch, final ConflictResolverOperation resolver) {
      IOperation operation = new UpdateBranchOperation(branch, resolver);
      return Operations.executeAsJob(operation, true);
   }

   public static Job updateBranch(Branch branch, IOseeBranch fromBranch, ConflictResolverOperation resolver) {
      IOperation operation = new UpdateBranchOperation(branch, fromBranch, resolver);
      return Operations.executeAsJob(operation, true);
   }

   public static void purgeBranch(BranchId branch) throws OseeCoreException {
      Operations.executeWorkAndCheckStatus(new PurgeBranchHttpRequestOperation(branch, false));
   }

   public static void setType(BranchId branch, BranchType type) throws OseeCoreException {
      BranchEndpoint proxy = ServiceUtil.getOseeClient().getBranchEndpoint();
      Response response = proxy.setBranchType(branch.getId(), type);
      if (response.getStatus() == javax.ws.rs.core.Response.Status.OK.getStatusCode()) {
         BranchManager.getBranch(branch).setBranchType(type);
         OseeEventManager.kickBranchEvent(BranchManager.class, new BranchEvent(BranchEventType.TypeUpdated, branch));
      }
   }

   public static void setState(BranchId branch, BranchState state) {
      BranchEndpoint proxy = ServiceUtil.getOseeClient().getBranchEndpoint();
      Response response = proxy.setBranchState(branch.getId(), state);
      if (response.getStatus() == javax.ws.rs.core.Response.Status.OK.getStatusCode()) {
         BranchManager.getBranch(branch).setBranchState(state);
         OseeEventManager.kickBranchEvent(BranchManager.class, new BranchEvent(BranchEventType.StateUpdated, branch));
      }
   }

   public static void setArchiveState(BranchId branch, BranchArchivedState state) throws OseeCoreException {
      BranchEndpoint proxy = ServiceUtil.getOseeClient().getBranchEndpoint();
      Long branchId = branch.getUuid();
      if (state.isArchived()) {
         Response response = proxy.archiveBranch(branchId);
         if (response.getStatus() == javax.ws.rs.core.Response.Status.OK.getStatusCode()) {
            BranchManager.getBranch(branch).setArchived(true);
            OseeEventManager.kickBranchEvent(BranchManager.class,
               new BranchEvent(BranchEventType.ArchiveStateUpdated, branch));
         }
      } else {
         Response response = proxy.unarchiveBranch(branchId);
         if (response.getStatus() == javax.ws.rs.core.Response.Status.OK.getStatusCode()) {
            BranchManager.getBranch(branch).setArchived(false);
            OseeEventManager.kickBranchEvent(BranchManager.class,
               new BranchEvent(BranchEventType.ArchiveStateUpdated, branch));
         }
      }
   }

   public static void setName(BranchId branch, String newBranchName) {
      BranchEndpoint proxy = ServiceUtil.getOseeClient().getBranchEndpoint();
      Response response = proxy.setBranchName(branch.getId(), newBranchName);
      if (response.getStatus() == javax.ws.rs.core.Response.Status.OK.getStatusCode()) {
         BranchManager.getBranch(branch).setName(newBranchName);
         OseeEventManager.kickBranchEvent(BranchManager.class, new BranchEvent(BranchEventType.Renamed, branch));
      }
   }

   /**
    * Delete a branch from the system. (This operation will set the branch state to deleted. This operation is
    * undo-able)
    */
   public static Job deleteBranch(final BranchId branch) {
      return Operations.executeAsJob(new DeleteBranchOperation(branch), true);
   }

   public static IStatus deleteBranchAndPend(final BranchId branch) {
      return Operations.executeWork(new DeleteBranchOperation(branch));
   }

   /**
    * Delete branches from the system. (sets branch state to deleted. operation is undo-able)
    *
    * @throws OseeCoreException
    */
   public static Job deleteBranch(final List<? extends BranchId> branches) {
      List<IOperation> ops = new ArrayList<>();
      for (BranchId branch : branches) {
         ops.add(new DeleteBranchOperation(branch));
      }
      OperationBuilder builder = Operations.createBuilder("Deleting multiple branches...");
      builder.addAll(ops);
      return Operations.executeAsJob(builder.build(), false);
   }

   /**
    * Commit the net changes from the source branch into the destination branch. If there are conflicts between the two
    * branches, the source branch changes will override those on the destination branch.
    */
   public static void commitBranch(IProgressMonitor monitor, ConflictManagerExternal conflictManager, boolean archiveSourceBranch, boolean overwriteUnresolvedConflicts) throws OseeCoreException {
      if (monitor == null) {
         monitor = new NullProgressMonitor();
      }
      if (conflictManager.remainingConflictsExist() && !overwriteUnresolvedConflicts) {
         throw new OseeCoreException("Commit failed due to unresolved conflicts");
      }
      if (!isEditable(conflictManager.getDestinationBranch())) {
         throw new OseeCoreException("Commit failed - unable to commit into a non-editable branch");
      }

      boolean skipCommitChecksAndEvents = OseeClientProperties.isSkipCommitChecksAndEvents();
      if (!skipCommitChecksAndEvents) {
         runCommitExtPointActions(conflictManager);
      }

      IOperation operation =
         new CommitBranchHttpRequestOperation(UserManager.getUser(), conflictManager.getSourceBranch(),
            conflictManager.getDestinationBranch(), archiveSourceBranch, skipCommitChecksAndEvents);
      Operations.executeWorkAndCheckStatus(operation, monitor);
   }

   private static void runCommitExtPointActions(ConflictManagerExternal conflictManager) throws OseeCoreException {
      ExtensionDefinedObjects<CommitAction> extensions = new ExtensionDefinedObjects<CommitAction>(
         "org.eclipse.osee.framework.skynet.core.CommitActions", "CommitActions", "className");
      for (CommitAction commitAction : extensions.getObjects()) {
         commitAction.runCommitAction(conflictManager.getSourceBranch(), conflictManager.getDestinationBranch());
      }
   }

   /**
    * Calls the getMergeBranch method and if it returns null it will create a new merge branch based on the artIds from
    * the source branch.
    */
   public static IOseeBranch getOrCreateMergeBranch(IOseeBranch sourceBranch, IOseeBranch destBranch, ArrayList<Integer> expectedArtIds) throws OseeCoreException {
      IOseeBranch mergeBranch = getMergeBranch(sourceBranch, destBranch);
      if (mergeBranch == null) {
         mergeBranch = createMergeBranch(sourceBranch, destBranch, expectedArtIds);
      } else {
         UpdateMergeBranch op = new UpdateMergeBranch(ConnectionHandler.getJdbcClient(), mergeBranch, expectedArtIds,
            destBranch, sourceBranch);
         Operations.executeWorkAndCheckStatus(op);
      }
      return mergeBranch;
   }

   private static IOseeBranch createMergeBranch(final IOseeBranch sourceBranch, final IOseeBranch destBranch, final ArrayList<Integer> expectedArtIds) throws OseeCoreException {
      ArtifactJoinQuery joinQuery = JoinUtility.createArtifactJoinQuery();
      for (int artId : expectedArtIds) {
         joinQuery.add(artId, sourceBranch.getUuid());
      }
      BranchId branch;
      try {
         joinQuery.store();

         TransactionRecord parentTx = getBaseTransaction(sourceBranch);
         String creationComment = String.format("New Merge Branch from %s(%s) and %s", sourceBranch.getName(),
            parentTx.getId(), destBranch.getName());
         String branchName = "Merge " + sourceBranch.getShortName() + " <=> " + destBranch.getShortName();
         branch = createBranch(BranchType.MERGE, parentTx, branchName, Lib.generateUuid(), UserManager.getUser(),
            creationComment, joinQuery.getQueryId(), destBranch);
      } finally {
         joinQuery.delete();
      }

      MergeBranch mergeBranch = (MergeBranch) BranchManager.getBranch(branch);
      mergeBranch.setSourceBranch(sourceBranch);
      mergeBranch.setDestinationBranch(destBranch);
      return mergeBranch;
   }

   public static IOseeBranch createWorkingBranch(TransactionRecord parentTransactionId, String childBranchName, Artifact associatedArtifact) throws OseeCoreException {
      return createWorkingBranch(parentTransactionId, childBranchName, Lib.generateUuid(), associatedArtifact);
   }

   public static IOseeBranch createWorkingBranch(TransactionRecord parentTransactionId, String childBranchName, Long childBranchUuid, Artifact associatedArtifact) throws OseeCoreException {
      Conditions.notNull(childBranchUuid, "childBranchUuid");
      String creationComment =
         String.format("New Branch from %s (%s)", getBranchName(parentTransactionId), parentTransactionId.getId());

      final String truncatedName = Strings.truncate(childBranchName, 195, true);
      return createBranch(BranchType.WORKING, parentTransactionId, truncatedName, childBranchUuid, associatedArtifact,
         creationComment);
   }

   /**
    * Creates a new Branch based on the most recent transaction on the parent branch.
    */
   public static IOseeBranch createWorkingBranchFromTx(TransactionRecord parentTransactionId, String childBranchName, Artifact associatedArtifact) throws OseeCoreException {
      String creationComment = String.format("New branch, copy of %s from transaction %s",
         getBranchName(parentTransactionId), parentTransactionId.getId());

      final String truncatedName = Strings.truncate(childBranchName, 195, true);

      CreateBranchHttpRequestOperation operation = new CreateBranchHttpRequestOperation(BranchType.WORKING,
         parentTransactionId, truncatedName, Lib.generateUuid(), associatedArtifact, creationComment);
      operation.setTxCopyBranchType(true);
      Operations.executeWorkAndCheckStatus(operation);
      return operation.getNewBranch();
   }

   public static IOseeBranch createPortBranchFromTx(TransactionRecord parentTransactionId, String childBranchName, Artifact associatedArtifact) throws OseeCoreException {
      String creationComment = String.format("New port branch, copy of %s from transaction %s",
         getBranchName(parentTransactionId), parentTransactionId.getId());

      final String truncatedName = Strings.truncate(childBranchName, 195, true);

      CreateBranchHttpRequestOperation operation = new CreateBranchHttpRequestOperation(BranchType.PORT,
         parentTransactionId, truncatedName, Lib.generateUuid(), associatedArtifact, creationComment);
      operation.setTxCopyBranchType(true);
      Operations.executeWorkAndCheckStatus(operation);
      return operation.getNewBranch();
   }

   public static IOseeBranch createWorkingBranch(BranchId parentBranch, String childBranchName) throws OseeCoreException {
      return createWorkingBranch(parentBranch, childBranchName, UserManager.getUser(SystemUser.OseeSystem));
   }

   public static IOseeBranch createWorkingBranch(BranchId parentBranch, String childBranchName, Artifact associatedArtifact) throws OseeCoreException {
      Conditions.checkNotNull(parentBranch, "Parent Branch");
      Conditions.checkNotNull(childBranchName, "Child Branch Name");
      Conditions.checkNotNull(associatedArtifact, "Associated Artifact");
      TransactionRecord parentTransactionId = TransactionManager.getHeadTransaction(parentBranch);
      return createWorkingBranch(parentTransactionId, childBranchName, Lib.generateUuid(), associatedArtifact);
   }

   public static IOseeBranch createWorkingBranch(BranchId parentBranch, IOseeBranch childBranch) throws OseeCoreException {
      return createWorkingBranch(parentBranch, childBranch, UserManager.getUser(SystemUser.OseeSystem));
   }

   public static IOseeBranch createWorkingBranch(BranchId parentBranch, IOseeBranch childBranch, Artifact associatedArtifact) throws OseeCoreException {
      TransactionRecord parentTransactionId = TransactionManager.getHeadTransaction(parentBranch);
      return createWorkingBranch(parentTransactionId, childBranch.getName(), childBranch.getUuid(), associatedArtifact);
   }

   /**
    * Creates a new Branch based on the most recent transaction on the parent branch.
    */
   public static BranchId createBaselineBranch(BranchId parentBranch, IOseeBranch childBranch) throws OseeCoreException {
      return createBaselineBranch(parentBranch, childBranch, UserManager.getUser(SystemUser.OseeSystem));
   }

   public static BranchId createBaselineBranch(BranchId parentBranch, IOseeBranch childBranch, Artifact associatedArtifact) throws OseeCoreException {
      TransactionRecord parentTransactionId = TransactionManager.getHeadTransaction(parentBranch);
      String creationComment = String.format("Branch Creation for %s", childBranch.getName());
      return createBranch(BranchType.BASELINE, parentTransactionId, childBranch.getName(), childBranch.getUuid(),
         associatedArtifact, creationComment);
   }

   private static IOseeBranch createBranch(BranchType branchType, TransactionRecord parentTransaction, String branchName, long branchUuid, Artifact associatedArtifact, String creationComment) {
      return createBranch(branchType, parentTransaction, branchName, branchUuid, associatedArtifact, creationComment,
         -1, BranchId.SENTINEL);
   }

   private static IOseeBranch createBranch(BranchType branchType, TransactionRecord parentTransaction, String branchName, long branchUuid, Artifact associatedArtifact, String creationComment, int mergeAddressingQueryId, BranchId destinationBranch) throws OseeCoreException {
      CreateBranchHttpRequestOperation operation = new CreateBranchHttpRequestOperation(branchType, parentTransaction,
         branchName, branchUuid, associatedArtifact, creationComment, mergeAddressingQueryId, destinationBranch);
      Operations.executeWorkAndCheckStatus(operation);
      return operation.getNewBranch();
   }

   /**
    * Creates a new root branch, imports skynet types and initializes.
    *
    * @param initializeArtifacts adds common artifacts needed by most normal root branches
    */
   public static BranchId createTopLevelBranch(IOseeBranch branch) throws OseeCoreException {
      return createBaselineBranch(SYSTEM_ROOT, branch, null);
   }

   public static BranchId createTopLevelBranch(final String branchName) throws OseeCoreException {
      return createTopLevelBranch(TokenFactory.createBranch(branchName));
   }

   public static List<? extends IOseeBranch> getBaselineBranches() throws OseeCoreException {
      return getBranches(BranchArchivedState.UNARCHIVED, BranchType.BASELINE);
   }

   public static List<Branch> getBranches(BranchArchivedState archivedState, BranchType... branchTypes) {
      return getCache().getBranches(new BranchFilter(archivedState, branchTypes));
   }

   private static BranchId getDefaultInitialBranch() throws OseeCoreException {
      ExtensionDefinedObjects<IDefaultInitialBranchesProvider> extensions =
         new ExtensionDefinedObjects<IDefaultInitialBranchesProvider>(
            "org.eclipse.osee.framework.skynet.core.DefaultInitialBranchProvider", "DefaultInitialBranchProvider",
            "class", true);
      for (IDefaultInitialBranchesProvider provider : extensions.getObjects()) {
         try {
            // Guard against problematic extensions
            for (BranchId branch : provider.getDefaultInitialBranches()) {
               if (branch != null) {
                  return branch;
               }
            }
         } catch (Exception ex) {
            OseeLog.log(Activator.class, Level.WARNING,
               "Exception occurred while trying to determine initial default branch", ex);
         }
      }
      return COMMON;
   }

   public static IOseeBranch getLastBranch() {
      if (lastBranch == null) {
         try {
            Long branchUuid = Long.valueOf(UserManager.getSetting(LAST_DEFAULT_BRANCH));
            lastBranch = getBranch(branchUuid);
         } catch (Exception ex) {
            try {
               lastBranch = getBranchToken(getDefaultInitialBranch());
               UserManager.setSetting(LAST_DEFAULT_BRANCH, lastBranch.getUuid());
            } catch (OseeCoreException ex1) {
               OseeLog.log(Activator.class, Level.SEVERE, ex1);
            }
         }
      }
      return lastBranch;
   }

   public static void setLastBranch(IOseeBranch branch) {
      lastBranch = branch;
   }

   public static void decache(Branch branch) throws OseeCoreException {
      getCache().decache(branch);
   }

   public static boolean hasChanges(BranchId branch) throws OseeCoreException {
      return !getBaseTransaction(branch).equals(TransactionManager.getHeadTransaction(branch));
   }

   public static boolean isChangeManaged(BranchId branch) throws OseeCoreException {
      Integer associatedArtifactId = getAssociatedArtifactId(branch);
      return associatedArtifactId > 0 && !associatedArtifactId.equals(SystemUser.OseeSystem);
   }

   public static void setAssociatedArtifactId(BranchId branch, Integer artifactId) {
      OseeClient client = ServiceUtil.getOseeClient();
      BranchEndpoint proxy = client.getBranchEndpoint();

      Response response = proxy.associateBranchToArtifact(branch.getId(), artifactId);
      if (javax.ws.rs.core.Response.Status.OK.getStatusCode() == response.getStatus()) {
         getBranch(branch).setAssociatedArtifactId(artifactId);
      }
   }

   public static Integer getAssociatedArtifactId(BranchId branch) {
      return getBranch(branch).getAssociatedArtifactId();
   }

   public static Artifact getAssociatedArtifact(BranchId branch) throws OseeCoreException {
      Integer associatedArtifactId = getAssociatedArtifactId(branch);
      if (associatedArtifactId == null || associatedArtifactId.equals(-1)) {
         return UserManager.getUser(SystemUser.OseeSystem);
      }
      return ArtifactQuery.getArtifactFromId(associatedArtifactId, COMMON);
   }

   public static Artifact getAssociatedArtifact(TransactionDelta txDelta) throws OseeCoreException {
      Artifact associatedArtifact = null;
      if (txDelta.areOnTheSameBranch()) {
         TransactionRecord txRecord = txDelta.getEndTx();
         int commitArtId = txRecord.getCommit();
         if (commitArtId != 0) {
            associatedArtifact = ArtifactQuery.getArtifactFromId(commitArtId, COMMON);
         }
      } else {
         BranchId sourceBranch = txDelta.getStartTx().getBranch();
         associatedArtifact = BranchManager.getAssociatedArtifact(sourceBranch);
      }
      return associatedArtifact;
   }

   public static void invalidateBranches() throws OseeCoreException {
      getCache().invalidate();
   }

   public static BranchId getParentBranch(BranchId branch) {
      return getBranch(branch).getParentBranch();
   }

   public static boolean isParentSystemRoot(BranchId branch) {
      return isParent(branch, SYSTEM_ROOT);
   }

   public static boolean isParent(BranchId branch, BranchId parentBranch) {
      return parentBranch.equals(getParentBranch(branch));
   }

   public static TransactionRecord getBaseTransaction(BranchId branch) {
      return getBranch(branch).getBaseTransaction();
   }

   public static TransactionRecord getSourceTransaction(BranchId branch) {
      return getBranch(branch).getSourceTransaction();
   }

   public static BranchState getState(BranchId branch) {
      return getBranch(branch).getBranchState();
   }

   public static BranchType getType(BranchId branch) {
      return getBranch(branch).getBranchType();
   }

   public static BranchType getType(TransactionRecord tx) {
      return getBranch(tx.getBranch()).getBranchType();
   }

   public static boolean isEditable(BranchId branch) {
      Branch fullBranch = getBranch(branch);
      BranchState state = fullBranch.getBranchState();
      return (state.isCreated() || state.isModified() || state.isRebaselineInProgress()) && !fullBranch.isArchived();
   }

   public static Collection<BranchId> getAncestors(BranchId branch) {
      return getBranch(branch).getAncestors();
   }

   public static boolean hasAncestor(BranchId branch, BranchId ancestor) {
      return getBranch(branch).hasAncestor(ancestor);
   }

   public static boolean isArchived(BranchId branch) {
      return getBranch(branch).isArchived();
   }

   public static String getArchivedStr(BranchId branch) {
      return BranchArchivedState.fromBoolean(getBranch(branch).isArchived()).name();
   }

   public static boolean hasChildren(BranchId branch) {
      return !getBranch(branch).getChildren().isEmpty();
   }

   /**
    * @param recurse if true all descendants are processed, otherwise, only direct descendants are.
    * @return all unarchived child branches that are not of type merge
    */
   public static Collection<Branch> getChildBranches(BranchId branch, boolean recurse) {
      Set<Branch> children = new HashSet<>();
      BranchFilter filter = new BranchFilter(BranchArchivedState.UNARCHIVED);
      filter.setNegatedBranchTypes(BranchType.MERGE);
      getBranch(branch).getChildBranches(children, recurse, filter);
      return children;
   }

   public static void resetWasLoaded() {
      getCache().invalidate();
   }

   public static boolean isLoaded() {
      return getCache().isLoaded();
   }

   public static String getBranchName(BranchId branch) {
      return getBranch(branch).getName();
   }

   public static String getBranchName(Long branchId) {
      return getBranch(branchId).getName();
   }

   public static String getBranchShortName(BranchId branch) {
      return getBranch(branch).getShortName();
   }

   public static String getBranchName(ITransaction tx) {
      return getBranch(tx.getBranch()).getName();
   }

   public static String getBranchShortName(ITransaction tx) {
      return getBranch(tx.getBranch()).getShortName();
   }
}

Back to the top