summaryrefslogtreecommitdiffstats
path: root/gerrit-server/src/main/java/com/google/gerrit/server/TopicUtil.java
blob: 067cfe452d258717db67465a67f51fbad0bb3a7d (plain)
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
// Copyright (C) 2011 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.gerrit.server;

import static com.google.gerrit.reviewdb.ApprovalCategory.SUBMIT;
import static com.google.gerrit.reviewdb.ApprovalCategory.STAGING;

import com.google.gerrit.common.ChangeHookRunner;
import com.google.gerrit.reviewdb.AbstractEntity;
import com.google.gerrit.reviewdb.Account;
import com.google.gerrit.reviewdb.ApprovalCategory;
import com.google.gerrit.reviewdb.Branch;
import com.google.gerrit.reviewdb.Change;
import com.google.gerrit.reviewdb.ChangeSet;
import com.google.gerrit.reviewdb.ChangeSetApproval;
import com.google.gerrit.reviewdb.ChangeSetElement;
import com.google.gerrit.reviewdb.ChangeSetInfo;
import com.google.gerrit.reviewdb.Project;
import com.google.gerrit.reviewdb.ReviewDb;
import com.google.gerrit.reviewdb.Topic;
import com.google.gerrit.reviewdb.TopicMessage;
import com.google.gerrit.server.IdentifiedUser;
import com.google.gerrit.server.git.GitRepositoryManager;
import com.google.gerrit.server.git.MergeOp;
import com.google.gerrit.server.git.MergeQueue;
import com.google.gerrit.server.git.ReplicationQueue;
import com.google.gerrit.server.patch.PatchSetInfoFactory;
import com.google.gerrit.server.patch.PatchSetInfoNotAvailableException;
import com.google.gerrit.server.project.InvalidChangeOperationException;
import com.google.gerrit.server.project.NoSuchChangeException;
import com.google.gerrit.server.project.NoSuchRefException;
import com.google.gerrit.server.project.NoSuchTopicException;
import com.google.gerrit.server.project.TopicControl;
import com.google.gerrit.server.mail.AbandonedSender;
import com.google.gerrit.server.mail.AddReviewerSender;
import com.google.gerrit.server.mail.EmailException;
import com.google.gerrit.server.mail.RestoredSender;
import com.google.gerrit.server.mail.RevertedSender;
import com.google.gwtorm.client.AtomicUpdate;
import com.google.gwtorm.client.OrmConcurrencyException;
import com.google.gwtorm.client.OrmException;

import org.eclipse.jgit.errors.IncorrectObjectTypeException;
import org.eclipse.jgit.errors.MissingObjectException;
import org.eclipse.jgit.lib.PersonIdent;
import org.eclipse.jgit.lib.Repository;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;


public class TopicUtil {

  public static void touch(final Topic topic, ReviewDb db)
      throws OrmException {
    try {
      updated(topic);
      db.topics().update(Collections.singleton(topic));
    } catch (OrmConcurrencyException e) {
      // Ignore a concurrent update, we just wanted to tag it as newer.
    }
  }

  public static void updated(final Topic t) {
    t.resetLastUpdatedOn();
    computeSortKey(t);
  }

  public static void submit(final ChangeSet.Id changeSetId,
      final IdentifiedUser user, final ReviewDb db,
      final MergeOp.Factory opFactory, final MergeQueue merger)
      throws OrmException {
    final Topic.Id topicId = changeSetId.getParentKey();
    final ChangeSetApproval approval = createSubmitApproval(changeSetId, user, db);

    db.changeSetApprovals().upsert(Collections.singleton(approval));

    final Topic updatedTopic = db.topics().atomicUpdate(topicId,
        new AtomicUpdate<Topic>() {
      @Override
      public Topic update(Topic topic) {
        if (topic.getStatus() == Topic.Status.NEW) {
          topic.setStatus(Topic.Status.SUBMITTED);
          TopicUtil.updated(topic);
        }
        return topic;
      }
    });

    if (updatedTopic.getStatus() == Topic.Status.SUBMITTED) {
      // Submit the changes belonging to the Topic
      //
      List<Change> toSubmit = db.changes().byTopicOpenAll(topicId).toList();
      for(Change c : toSubmit) {
        ChangeUtil.submit(c.currentPatchSetId(), user, db, opFactory, merger);
      }
    }
  }

  public static void stage(final ChangeSet.Id changeSetId,
      final IdentifiedUser user, final ReviewDb db,
      final MergeOp.Factory opFactory, final MergeQueue merger,
      final Repository git, final ChangeHookRunner hooks)
      throws OrmException, IOException, NoSuchRefException {
    final Topic.Id topicId = changeSetId.getParentKey();
    final ChangeSetApproval approval = createStagingApproval(changeSetId, user, db);

    db.changeSetApprovals().upsert(Collections.singleton(approval));

    final Topic updatedTopic = db.topics().atomicUpdate(topicId,
        new AtomicUpdate<Topic>() {
      @Override
      public Topic update(Topic topic) {
        if (topic.getStatus() == Topic.Status.NEW) {
          topic.setStatus(Topic.Status.STAGED);
          TopicUtil.updated(topic);
        }
        return topic;
      }
    });

    if (updatedTopic.getStatus() == Topic.Status.STAGED) {
      // Submit the changes belonging to the Topic
      //

      List<Change> toStage = db.changes().byTopicOpenAll(topicId).toList();
      for(Change c : toStage) {
        ChangeUtil.moveToStaging(opFactory, c.currentPatchSetId(), user, db,
            merger, git, hooks);
      }
    }
  }

  public static void rejectStagedTopic(final ChangeSet.Id changeSetId,
      final IdentifiedUser user, final ReviewDb db,
      final MergeOp.Factory opFactory, final MergeQueue merger,
      final Repository git, final ChangeHookRunner hooks) throws OrmException {
    // Delete all STAGING approvals for the change set.
    final ChangeSetApproval.Key stagingKey =
      new ChangeSetApproval.Key(changeSetId, user.getAccountId(), STAGING);
    db.changeSetApprovals().deleteKeys(Collections.singleton(stagingKey));

    // Set topic state to NEW.
    final Topic.Id topicId = changeSetId.getParentKey();
    AtomicUpdate<Topic> atomicUpdate =
      new AtomicUpdate<Topic>() {
      @Override
      public Topic update(Topic topic) {
        if (topic.getStatus() == AbstractEntity.Status.INTEGRATING
            || topic.getStatus() == AbstractEntity.Status.STAGED) {
          topic.setStatus(AbstractEntity.Status.NEW);
          TopicUtil.updated(topic);
        }
        return topic;
      }
    };
    db.topics().atomicUpdate(topicId, atomicUpdate);
  }

  public static ChangeSetApproval createSubmitApproval(
      final ChangeSet.Id changeSetId, final IdentifiedUser user, final ReviewDb db
      ) throws OrmException {
    final List<ChangeSetApproval> allApprovals =
        new ArrayList<ChangeSetApproval>(db.changeSetApprovals().byChangeSet(
            changeSetId).toList());

    final ChangeSetApproval.Key akey =
        new ChangeSetApproval.Key(changeSetId, user.getAccountId(), SUBMIT);

    for (final ChangeSetApproval approval : allApprovals) {
      if (akey.equals(approval.getKey())) {
        approval.setValue((short) 1);
        approval.setGranted();
        return approval;
      }
    }
    return new ChangeSetApproval(akey, (short) 1);
  }

public static ChangeSetApproval createStagingApproval(
      final ChangeSet.Id changeSetId, final IdentifiedUser user, final ReviewDb db
      ) throws OrmException {
    final List<ChangeSetApproval> allApprovals =
        new ArrayList<ChangeSetApproval>(db.changeSetApprovals().byChangeSet(
            changeSetId).toList());

    final ChangeSetApproval.Key akey =
        new ChangeSetApproval.Key(changeSetId, user.getAccountId(), STAGING);

    for (final ChangeSetApproval approval : allApprovals) {
      if (akey.equals(approval.getKey())) {
        approval.setValue((short) 1);
        approval.setGranted();
        return approval;
      }
    }
    return new ChangeSetApproval(akey, (short) 1);
  }

  public static void abandon(final ChangeSet.Id changeSetId,
      final IdentifiedUser user, final String message, final ReviewDb db,
      final AbandonedSender.Factory abandonedSenderFactory,
      final ChangeHookRunner hooks) throws NoSuchTopicException,
      NoSuchChangeException, InvalidChangeOperationException,
      EmailException, OrmException  {
    final Topic.Id topicId = changeSetId.getParentKey();
    final ChangeSet changeSet = db.changeSets().get(changeSetId);
    if (changeSet == null) {
      throw new NoSuchTopicException(topicId);
    }

    final TopicMessage tmsg =
        new TopicMessage(new TopicMessage.Key(topicId, ChangeUtil
            .messageUUID(db)), user.getAccountId());
    final StringBuilder msgBuf =
        new StringBuilder("Change Set " + changeSetId.get() + ": Abandoned");
    if (message != null && message.length() > 0) {
      msgBuf.append("\n\n");
      msgBuf.append(message);
    }
    tmsg.setMessage(msgBuf.toString());

    final Topic updatedTopic = db.topics().atomicUpdate(topicId,
        new AtomicUpdate<Topic>() {
      @Override
      public Topic update(Topic topic) {
        if (topic.getStatus().isOpen()
            && topic.currentChangeSetId().equals(changeSetId)) {
          topic.setStatus(Change.Status.ABANDONED);
          TopicUtil.updated(topic);
          return topic;
        } else {
          return null;
        }
      }
    });

    Change lastChange = null;
    if (updatedTopic == null) {
      throw new InvalidChangeOperationException(
          "Topic is no longer open or changeset is not latest");
    } else {
      // Abandon the changes belonging to the Topic
      //
      List<Change> toAbandon = db.changes().byTopicOpenAll(topicId).toList();
      for(Change c : toAbandon) {
        ChangeUtil.abandon(c.currentPatchSetId(), user, message, db,
            abandonedSenderFactory, hooks, false);
      }
      lastChange = toAbandon.get(toAbandon.size() - 1);
    }

    db.topicMessages().insert(Collections.singleton(tmsg));

    final List<ChangeSetApproval> approvals =
        db.changeSetApprovals().byTopic(topicId).toList();
    for (ChangeSetApproval a : approvals) {
      a.cache(updatedTopic);
    }
    db.changeSetApprovals().update(approvals);

    // Email the reviewers
    // TODO Topic support
    // Meanwhile, sending mails in "behalf" of the last change of the topic
    if (lastChange != null) {
      final AbandonedSender cm = abandonedSenderFactory.create(lastChange);
      cm.setFrom(user.getAccountId());
      cm.setTopicMessage(tmsg);
      cm.send();
    }
  }

  public static void revert(final ChangeSet.Id changeSetId,
      final IdentifiedUser user, final String message, final ReviewDb db,
      final RevertedSender.Factory revertedSenderFactory,
      final ChangeHookRunner hooks, GitRepositoryManager gitManager,
      final PatchSetInfoFactory patchSetInfoFactory,
      final ReplicationQueue replication, PersonIdent myIdent)
      throws NoSuchChangeException, NoSuchTopicException, EmailException,
      OrmException, MissingObjectException, IncorrectObjectTypeException,
      IOException, PatchSetInfoNotAvailableException {

    final Topic.Id topicId = changeSetId.getParentKey();
    final Topic topic = db.topics().get(topicId);
    final ChangeSet changeSet = db.changeSets().get(changeSetId);
    if (changeSet == null) {
      throw new NoSuchTopicException(topicId);
    }

    final Topic newTopic = createTopic(user.getAccountId(), db, topic.getTopic(),
        topic.getDest(), message);
    final ChangeSet.Id newChangeSetId = newTopic.currentChangeSetId();
    // Revert the changes belonging to the Topic
    //
    Change lastChange = null;
    final List<ChangeSetElement> changeSetElements = db.changeSetElements().byChangeSet(changeSetId).toList();
    List<Change> toRevert = new ArrayList<Change>();
    for (ChangeSetElement cse : changeSetElements) {
      toRevert.add(db.changes().get(cse.getChangeId()));
    }
    for(Change c : toRevert) {
      ChangeUtil.revert(c.currentPatchSetId(), user, "Revert " + c.getSubject(), db,
          revertedSenderFactory, hooks, gitManager, patchSetInfoFactory,
          replication, myIdent, false, newChangeSetId,
          newTopic.getTopic(), newTopic.getId(), toRevert.indexOf(c));
    }
    lastChange = toRevert.get(toRevert.size() - 1);

    final TopicMessage tmsg =
      new TopicMessage(new TopicMessage.Key(topicId,
          ChangeUtil.messageUUID(db)), user.getAccountId());
    final StringBuilder msgBuf =
      new StringBuilder("Change Set " + changeSetId.get() + ": Reverted");
    msgBuf.append("\n\n");
    msgBuf.append("This changeset was reverted in topic: " + newTopic.getTopicId());

    tmsg.setMessage(msgBuf.toString());
    db.topicMessages().insert(Collections.singleton(tmsg));

    // TODO Topic support for RevertedSender
    // Meanwhile, sending mails in "behalf" of the last change of the topic
    final RevertedSender cm = revertedSenderFactory.create(lastChange);
    cm.setFrom(user.getAccountId());
    cm.setTopicMessage(tmsg);
    cm.send();
  }

  public static ChangeSetInfo createChangeSet(final Account.Id me,
      final Topic parentTopic, final ReviewDb db,
      final String message) throws OrmException {
    final Topic.Id topicId = parentTopic.getId();
    final ChangeSet cs = new ChangeSet(parentTopic.currChangeSetId());

    cs.setCreatedOn(parentTopic.getCreatedOn());
    cs.setUploader(me);
    cs.setTopicId(topicId);
    cs.setMessage(message);
    db.changeSets().insert(Collections.singleton(cs));

    final ChangeSetInfo csi = new ChangeSetInfo(cs.getId());
    csi.setMessage(message);
    csi.setSubject(parentTopic.getTopic());

    return csi;
  }

  public static Topic createTopic(final Account.Id me, final ReviewDb db,
      final String destTopicName, final Branch.NameKey destBranch,
      final String message) throws OrmException {
    final Topic.Id topicId = new Topic.Id(db.nextTopicId());
    final Topic.Key topicKey = new Topic.Key("T" + topicId.toString() + destTopicName);

    Topic parentTopic = new Topic(topicKey, topicId, me, destBranch);
    parentTopic.setTopic(destTopicName);
    parentTopic.setSortKey("lastUpdatedOn");
    parentTopic.nextChangeSetId();

    // Now we need to create the changeSet
    // and associate it to the Topic
    //
    final ChangeSetInfo csi = createChangeSet(me, parentTopic, db, message);
    parentTopic.setCurrentChangeSet(csi);

    db.topics().insert(Collections.singleton(parentTopic));
    return parentTopic;
  }

  public static void restore(final ChangeSet.Id changeSetId,
      final IdentifiedUser user, final String message, final ReviewDb db,
      final RestoredSender.Factory restoredSenderFactory,
      final ChangeHookRunner hooks) throws NoSuchChangeException,
      NoSuchTopicException, InvalidChangeOperationException,
      EmailException, OrmException {
    final Topic.Id topicId = changeSetId.getParentKey();
    final ChangeSet changeSet = db.changeSets().get(changeSetId);
    if (changeSet == null) {
      throw new NoSuchTopicException(topicId);
    }

    final TopicMessage tmsg =
        new TopicMessage(new TopicMessage.Key(topicId, ChangeUtil
            .messageUUID(db)), user.getAccountId());
    final StringBuilder msgBuf =
        new StringBuilder("Change Set " + changeSetId.get() + ": Restored");
    if (message != null && message.length() > 0) {
      msgBuf.append("\n\n");
      msgBuf.append(message);
    }
    tmsg.setMessage(msgBuf.toString());

    final Topic updatedTopic = db.topics().atomicUpdate(topicId,
        new AtomicUpdate<Topic>() {
      @Override
      public Topic update(Topic topic) {
        if (topic.getStatus() == Topic.Status.ABANDONED
            && topic.currentChangeSetId().equals(changeSetId)) {
          topic.setStatus(Topic.Status.NEW);
          TopicUtil.updated(topic);
          return topic;
        } else {
          return null;
        }
      }
    });

    Change lastChange = null;
    if (updatedTopic == null) {
      throw new InvalidChangeOperationException(
          "Topic is not abandoned or changeset is not latest");
    } else {
      // Restore the changes belonging to the Topic
      //
      final List<ChangeSetElement> cseList = db.changeSetElements().byChangeSet(changeSetId).toList();
      for(ChangeSetElement cse : cseList) {
        lastChange = db.changes().get(cse.getChangeId());
        ChangeUtil.restore(lastChange.currentPatchSetId(), user, message, db,
            restoredSenderFactory, hooks, false);
      }
    }

    db.topicMessages().insert(Collections.singleton(tmsg));

    final List<ChangeSetApproval> approvals =
        db.changeSetApprovals().byTopic(topicId).toList();
    for (ChangeSetApproval a : approvals) {
      a.cache(updatedTopic);
    }
    db.changeSetApprovals().update(approvals);

    // Meanwhile, sending mails in "behalf" of the last change of the topic
    if (lastChange != null) {
      final RestoredSender cm = restoredSenderFactory.create(lastChange);
      cm.setFrom(user.getAccountId());
      cm.setTopicMessage(tmsg);
      cm.send();
    }
  }

  public static void computeSortKey(final Topic t) {
    long lastUpdated = t.getLastUpdatedOn().getTime();
    int id = t.getId().get();
    t.setSortKey(ChangeUtil.sortKey(lastUpdated, id));
  }

  public static void addReviewers(final Set<Account.Id> reviewerIds, final ReviewDb db,
      final TopicControl control, final ApprovalCategory.Id addReviewerCategoryId,
      final IdentifiedUser currentUser, final AddReviewerSender.Factory addReviewerSenderFactory)
  throws OrmException, EmailException {

    // Add the reviewers to each of the changes belonging to the changeset
    //
    final ChangeSet.Id csid = control.getTopic().currentChangeSetId();
    List<ChangeSetElement> changeSetElements = db.changeSetElements().byChangeSet(csid).toList();
    List<Change> changes = new ArrayList<Change>();
    for (ChangeSetElement cse : changeSetElements) {
      changes.add(db.changes().get(cse.getChangeId()));
    }

    for (Change c : changes) {
      ChangeUtil.addReviewers(reviewerIds, db, c.currentPatchSetId(), addReviewerCategoryId, currentUser);
    }

    // Add the reviewers to the database
    //
    final Set<Account.Id> added = new HashSet<Account.Id>();
    final List<ChangeSetApproval> toInsert = new ArrayList<ChangeSetApproval>();

    for (final Account.Id reviewer : reviewerIds) {
      if (!exists(csid, reviewer, db)) {
        // This reviewer has not entered an approval for this topic yet.
        //
        final ChangeSetApproval myca = dummyApproval(csid, reviewer, addReviewerCategoryId);
        toInsert.add(myca);
        added.add(reviewer);
      }
    }
    db.changeSetApprovals().insert(toInsert);

    // Email the reviewers
    //
    // The user knows they added themselves, don't bother emailing them.
    added.remove(currentUser.getAccountId());
    if (!added.isEmpty()) {
      final AddReviewerSender cm;
      cm = addReviewerSenderFactory.create(changes.get(changes.size() - 1));
      cm.setFrom(currentUser.getAccountId());
      cm.addReviewers(added);
      cm.send();
    }
  }

  private static boolean exists(final ChangeSet.Id changeSetId,
      final Account.Id reviewerId, final ReviewDb db) throws OrmException {
    return db.changeSetApprovals().byChangeSetUser(changeSetId, reviewerId)
        .iterator().hasNext();
  }

  private static ChangeSetApproval dummyApproval(final ChangeSet.Id changeSetId,
      final Account.Id reviewerId, ApprovalCategory.Id addReviewerCategoryId) {
    return new ChangeSetApproval(new ChangeSetApproval.Key(changeSetId,
        reviewerId, addReviewerCategoryId), (short) 0);
  }

  /**
   * Create a new ChangeSet to be filled with some new changes
   *
   * @param result Topic to be modified
   * @param db
   * @param me
   * @return The updated topic
   * @throws OrmException
   */
  public static Topic setUpTopic(final Topic result, final ReviewDb db,
      final Account.Id me) throws OrmException {

    final ChangeSet.Id previousId = result.currentChangeSetId();
    result.nextChangeSetId();

    final ChangeSetInfo csi = createChangeSet(me, result, db,
        db.changeSets().get(previousId).getMessage());
    result.setCurrentChangeSet(csi);
    touch(result, db);
    return result;
  }

  /**
   * Finds an active topic matching the topic name in the given project & branch
   *
   * @param topicName
   * @param db
   * @param bKey
   * @param pKey
   * @return If it finds the Topic we are looking for, it returns it. Otherwise
   * it returns null
   * @throws OrmException
   */
  public static Topic findActiveTopic(final String topicName, final ReviewDb db,
      final Branch.NameKey bKey, final Project.NameKey pKey) throws OrmException {
    List<Topic> tList = db.topics().byBranchProject(bKey, pKey).toList();

    if (tList.size() >= 1) {
      for (Topic t : tList) {
        final AbstractEntity.Status tStatus = t.getStatus();
        if (t.getTopic().equals(topicName)) {
          if (tStatus.equals(AbstractEntity.Status.ABANDONED) ||
            tStatus.equals(AbstractEntity.Status.MERGED)) continue;
          // If we don't have a mess in our DB, we must have only
          // one topic with the same String in a different status than
          // MERGED or ABANDONED
          //
          else return t;
        }
      }
    }
    return null;
  }

  public static Topic setIntegrating(final Topic.Id topicId, ReviewDb db)
      throws OrmException {
    final Topic updatedTopic = db.topics().atomicUpdate(topicId,
        new AtomicUpdate<Topic>() {
      @Override
      public Topic update(Topic topic) {
        if (topic.getStatus() == Topic.Status.STAGED) {
          topic.setStatus(Topic.Status.INTEGRATING);
          TopicUtil.updated(topic);
        }
        return topic;
      }
    });

    return updatedTopic;
  }

  public static Topic setIntegratingToMerged(final Topic.Id topicId, ReviewDb db)
      throws OrmException {
    final Topic updatedTopic =
        db.topics().atomicUpdate(topicId, new AtomicUpdate<Topic>() {
          @Override
          public Topic update(Topic topic) {
            if (topic.getStatus() == Topic.Status.INTEGRATING) {
              topic.setStatus(Topic.Status.MERGED);
              TopicUtil.updated(topic);
            }
            return topic;
          }
        });
    return updatedTopic;
  }

  public static Topic setIntegratingToNew(final Topic.Id topicId, ReviewDb db)
      throws OrmException {
    final Topic updatedTopic =
        db.topics().atomicUpdate(topicId, new AtomicUpdate<Topic>() {
          @Override
          public Topic update(Topic topic) {
            if (topic.getStatus() == Topic.Status.INTEGRATING) {
              topic.setStatus(Topic.Status.NEW);
              TopicUtil.updated(topic);
            }
            return topic;
          }
        });
    return updatedTopic;
  }
}