Search in sources :

Example 41 with OrmException

use of com.google.gwtorm.server.OrmException in project gerrit by GerritCodeReview.

the class ChangeUpdate method applyImpl.

@Override
protected CommitBuilder applyImpl(RevWalk rw, ObjectInserter ins, ObjectId curr) throws OrmException, IOException {
    checkState(deleteCommentRewriter == null, "cannot update and rewrite ref in one BatchUpdate");
    CommitBuilder cb = new CommitBuilder();
    int ps = psId != null ? psId.get() : getChange().currentPatchSetId().get();
    StringBuilder msg = new StringBuilder();
    if (commitSubject != null) {
        msg.append(commitSubject);
    } else {
        msg.append("Update patch set ").append(ps);
    }
    msg.append("\n\n");
    if (changeMessage != null) {
        msg.append(changeMessage);
        msg.append("\n\n");
    }
    addPatchSetFooter(msg, ps);
    if (currentPatchSet) {
        addFooter(msg, FOOTER_CURRENT, Boolean.TRUE);
    }
    if (psDescription != null) {
        addFooter(msg, FOOTER_PATCH_SET_DESCRIPTION, psDescription);
    }
    if (changeId != null) {
        addFooter(msg, FOOTER_CHANGE_ID, changeId);
    }
    if (subject != null) {
        addFooter(msg, FOOTER_SUBJECT, subject);
    }
    if (branch != null) {
        addFooter(msg, FOOTER_BRANCH, branch);
    }
    if (status != null) {
        addFooter(msg, FOOTER_STATUS, status.name().toLowerCase());
    }
    if (topic != null) {
        addFooter(msg, FOOTER_TOPIC, topic);
    }
    if (commit != null) {
        addFooter(msg, FOOTER_COMMIT, commit);
    }
    if (assignee != null) {
        if (assignee.isPresent()) {
            addFooter(msg, FOOTER_ASSIGNEE);
            addIdent(msg, assignee.get()).append('\n');
        } else {
            addFooter(msg, FOOTER_ASSIGNEE).append('\n');
        }
    }
    Joiner comma = Joiner.on(',');
    if (hashtags != null) {
        addFooter(msg, FOOTER_HASHTAGS, comma.join(hashtags));
    }
    if (tag != null) {
        addFooter(msg, FOOTER_TAG, tag);
    }
    if (groups != null) {
        addFooter(msg, FOOTER_GROUPS, comma.join(groups));
    }
    for (Map.Entry<Account.Id, ReviewerStateInternal> e : reviewers.entrySet()) {
        addFooter(msg, e.getValue().getFooterKey());
        addIdent(msg, e.getKey()).append('\n');
    }
    for (Map.Entry<Address, ReviewerStateInternal> e : reviewersByEmail.entrySet()) {
        addFooter(msg, e.getValue().getByEmailFooterKey(), e.getKey().toString());
    }
    for (Table.Cell<String, Account.Id, Optional<Short>> c : approvals.cellSet()) {
        addFooter(msg, FOOTER_LABEL);
        // Label names/values are safe to append without sanitizing.
        if (!c.getValue().isPresent()) {
            msg.append('-').append(c.getRowKey());
        } else {
            msg.append(LabelVote.create(c.getRowKey(), c.getValue().get()).formatWithEquals());
        }
        Account.Id id = c.getColumnKey();
        if (!id.equals(getAccountId())) {
            addIdent(msg.append(' '), id);
        }
        msg.append('\n');
    }
    if (submissionId != null) {
        addFooter(msg, FOOTER_SUBMISSION_ID, submissionId);
    }
    if (submitRecords != null) {
        for (SubmitRecord rec : submitRecords) {
            addFooter(msg, FOOTER_SUBMITTED_WITH).append(rec.status);
            if (rec.errorMessage != null) {
                msg.append(' ').append(sanitizeFooter(rec.errorMessage));
            }
            msg.append('\n');
            if (rec.labels != null) {
                for (SubmitRecord.Label label : rec.labels) {
                    // Label names/values are safe to append without sanitizing.
                    addFooter(msg, FOOTER_SUBMITTED_WITH).append(label.status).append(": ").append(label.label);
                    if (label.appliedBy != null) {
                        msg.append(": ");
                        addIdent(msg, label.appliedBy);
                    }
                    msg.append('\n');
                }
            }
        }
    }
    if (!Objects.equals(accountId, realAccountId)) {
        addFooter(msg, FOOTER_REAL_USER);
        addIdent(msg, realAccountId).append('\n');
    }
    if (readOnlyUntil != null) {
        addFooter(msg, FOOTER_READ_ONLY_UNTIL, ChangeNoteUtil.formatTime(serverIdent, readOnlyUntil));
    }
    if (isPrivate != null) {
        addFooter(msg, FOOTER_PRIVATE, isPrivate);
    }
    if (workInProgress != null) {
        addFooter(msg, FOOTER_WORK_IN_PROGRESS, workInProgress);
    }
    cb.setMessage(msg.toString());
    try {
        ObjectId treeId = storeRevisionNotes(rw, ins, curr);
        if (treeId != null) {
            cb.setTreeId(treeId);
        }
    } catch (ConfigInvalidException e) {
        throw new OrmException(e);
    }
    return cb;
}
Also used : Account(com.google.gerrit.reviewdb.client.Account) Joiner(com.google.common.base.Joiner) TreeBasedTable(com.google.common.collect.TreeBasedTable) Table(com.google.common.collect.Table) Address(com.google.gerrit.server.mail.Address) Optional(java.util.Optional) ConfigInvalidException(org.eclipse.jgit.errors.ConfigInvalidException) ObjectId(org.eclipse.jgit.lib.ObjectId) CommitBuilder(org.eclipse.jgit.lib.CommitBuilder) SubmitRecord(com.google.gerrit.common.data.SubmitRecord) OrmException(com.google.gwtorm.server.OrmException) RequestId(com.google.gerrit.server.util.RequestId) ObjectId(org.eclipse.jgit.lib.ObjectId) RevId(com.google.gerrit.reviewdb.client.RevId) Map(java.util.Map) NoteMap(org.eclipse.jgit.notes.NoteMap) LinkedHashMap(java.util.LinkedHashMap)

Example 42 with OrmException

use of com.google.gwtorm.server.OrmException in project gerrit by GerritCodeReview.

the class ChangeNotesTest method readOnlyUntilCleared.

@Test
public void readOnlyUntilCleared() throws Exception {
    Change c = newChange();
    ChangeUpdate update = newUpdate(c, changeOwner);
    Timestamp until = new Timestamp(TimeUtil.nowMs() + TimeUnit.DAYS.toMillis(30));
    update.setReadOnlyUntil(until);
    update.commit();
    update = newUpdate(c, changeOwner);
    update.setTopic("failing-topic");
    try {
        update.commit();
        assert_().fail("expected OrmException");
    } catch (OrmException e) {
        assertThat(e.getMessage()).contains("read-only until");
    }
    // Sentinel timestamp of 0 can be written to clear lease.
    update = newUpdate(c, changeOwner);
    update.setReadOnlyUntil(new Timestamp(0));
    update.commit();
    update = newUpdate(c, changeOwner);
    update.setTopic("succeeding-topic");
    update.commit();
    ChangeNotes notes = newNotes(c);
    assertThat(notes.getChange().getTopic()).isEqualTo("succeeding-topic");
    assertThat(notes.getReadOnlyUntil()).isEqualTo(new Timestamp(0));
}
Also used : OrmException(com.google.gwtorm.server.OrmException) Change(com.google.gerrit.reviewdb.client.Change) Timestamp(java.sql.Timestamp) Test(org.junit.Test)

Example 43 with OrmException

use of com.google.gwtorm.server.OrmException in project gerrit by GerritCodeReview.

the class ChangeNotesTest method commitChangeNotesUnique.

@Test
public void commitChangeNotesUnique() throws Exception {
    // PatchSetId -> RevId must be a one to one mapping
    Change c = newChange();
    ChangeNotes notes = newNotes(c);
    PatchSet ps = notes.getCurrentPatchSet();
    assertThat(ps).isNotNull();
    // new revId for the same patch set, ps1
    ChangeUpdate update = newUpdate(c, changeOwner);
    RevCommit commit = tr.commit().message("PS1 again").create();
    update.setCommit(rw, commit);
    update.commit();
    try {
        notes = newNotes(c);
        fail("Expected IOException");
    } catch (OrmException e) {
        assertCause(e, ConfigInvalidException.class, "Multiple revisions parsed for patch set 1:" + " RevId{" + commit.name() + "} and " + ps.getRevision().get());
    }
}
Also used : ConfigInvalidException(org.eclipse.jgit.errors.ConfigInvalidException) OrmException(com.google.gwtorm.server.OrmException) PatchSet(com.google.gerrit.reviewdb.client.PatchSet) Change(com.google.gerrit.reviewdb.client.Change) RevCommit(org.eclipse.jgit.revwalk.RevCommit) Test(org.junit.Test)

Example 44 with OrmException

use of com.google.gwtorm.server.OrmException in project gerrit by GerritCodeReview.

the class ChangeNotesTest method readOnlyUntilExpires.

@Test
public void readOnlyUntilExpires() throws Exception {
    Change c = newChange();
    ChangeUpdate update = newUpdate(c, changeOwner);
    Timestamp until = new Timestamp(TimeUtil.nowMs() + 10000);
    update.setReadOnlyUntil(until);
    update.commit();
    update = newUpdate(c, changeOwner);
    update.setTopic("failing-topic");
    try {
        update.commit();
        assert_().fail("expected OrmException");
    } catch (OrmException e) {
        assertThat(e.getMessage()).contains("read-only until");
    }
    ChangeNotes notes = newNotes(c);
    assertThat(notes.getChange().getTopic()).isNotEqualTo("failing-topic");
    assertThat(notes.getReadOnlyUntil()).isEqualTo(until);
    TestTimeUtil.incrementClock(30, TimeUnit.SECONDS);
    update = newUpdate(c, changeOwner);
    update.setTopic("succeeding-topic");
    update.commit();
    // Write succeeded; lease still exists, even though it's expired.
    notes = newNotes(c);
    assertThat(notes.getChange().getTopic()).isEqualTo("succeeding-topic");
    assertThat(notes.getReadOnlyUntil()).isEqualTo(until);
    // New lease takes precedence.
    update = newUpdate(c, changeOwner);
    until = new Timestamp(TimeUtil.nowMs() + 10000);
    update.setReadOnlyUntil(until);
    update.commit();
    assertThat(newNotes(c).getReadOnlyUntil()).isEqualTo(until);
}
Also used : OrmException(com.google.gwtorm.server.OrmException) Change(com.google.gerrit.reviewdb.client.Change) Timestamp(java.sql.Timestamp) Test(org.junit.Test)

Example 45 with OrmException

use of com.google.gwtorm.server.OrmException in project gerrit by GerritCodeReview.

the class ExternalIdIT method failAfterRetryerGivesUp.

@Test
public void failAfterRetryerGivesUp() throws Exception {
    ExternalId.Key[] extIdsKeys = { ExternalId.Key.create("foo", "foo"), ExternalId.Key.create("bar", "bar"), ExternalId.Key.create("baz", "baz") };
    final AtomicInteger bgCounter = new AtomicInteger(0);
    ExternalIdsUpdate update = new ExternalIdsUpdate(repoManager, allUsers, metricMaker, externalIds, new DisabledExternalIdCache(), serverIdent.get(), serverIdent.get(), () -> {
        try {
            extIdsUpdate.create().insert(ExternalId.create(extIdsKeys[bgCounter.getAndAdd(1)], admin.id));
        } catch (IOException | ConfigInvalidException | OrmException e) {
        // Ignore, the successful insertion of the external ID is asserted later
        }
    }, RetryerBuilder.<RefsMetaExternalIdsUpdate>newBuilder().retryIfException(e -> e instanceof LockFailureException).withStopStrategy(StopStrategies.stopAfterAttempt(extIdsKeys.length)).build());
    assertThat(bgCounter.get()).isEqualTo(0);
    try {
        update.insert(ExternalId.create(ExternalId.Key.create("abc", "abc"), admin.id));
        fail("expected LockFailureException");
    } catch (LockFailureException e) {
    // Ignore, expected
    }
    assertThat(bgCounter.get()).isEqualTo(extIdsKeys.length);
    for (ExternalId.Key extIdKey : extIdsKeys) {
        assertThat(externalIds.get(extIdKey)).isNotNull();
    }
}
Also used : AllUsersName(com.google.gerrit.server.config.AllUsersName) TypeToken(com.google.gson.reflect.TypeToken) OrmException(com.google.gwtorm.server.OrmException) ObjectInserter(org.eclipse.jgit.lib.ObjectInserter) OBJ_BLOB(org.eclipse.jgit.lib.Constants.OBJ_BLOB) GlobalCapability(com.google.gerrit.common.data.GlobalCapability) Retryer(com.github.rholder.retry.Retryer) RetryerBuilder(com.github.rholder.retry.RetryerBuilder) Inject(com.google.inject.Inject) RestResponse(com.google.gerrit.acceptance.RestResponse) REGISTERED_USERS(com.google.gerrit.server.group.SystemGroupBackend.REGISTERED_USERS) BlockStrategy(com.github.rholder.retry.BlockStrategy) RevWalk(org.eclipse.jgit.revwalk.RevWalk) Config(org.eclipse.jgit.lib.Config) SCHEME_USERNAME(com.google.gerrit.server.account.externalids.ExternalId.SCHEME_USERNAME) ConsistencyProblemInfo(com.google.gerrit.extensions.api.config.ConsistencyCheckInfo.ConsistencyProblemInfo) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Locale(java.util.Locale) AuthException(com.google.gerrit.extensions.restapi.AuthException) Assert.fail(org.junit.Assert.fail) SCHEME_UUID(com.google.gerrit.server.account.externalids.ExternalId.SCHEME_UUID) NoteMap(org.eclipse.jgit.notes.NoteMap) CheckAccountExternalIdsInput(com.google.gerrit.extensions.api.config.ConsistencyCheckInput.CheckAccountExternalIdsInput) ImmutableSet(com.google.common.collect.ImmutableSet) Collection(java.util.Collection) Permission(com.google.gerrit.common.data.Permission) ConsistencyCheckInfo(com.google.gerrit.extensions.api.config.ConsistencyCheckInfo) Set(java.util.Set) ExternalIds(com.google.gerrit.server.account.externalids.ExternalIds) List(java.util.List) StopStrategies(com.github.rholder.retry.StopStrategies) RefNames(com.google.gerrit.reviewdb.client.RefNames) PushResult(org.eclipse.jgit.transport.PushResult) AbstractDaemonTest(com.google.gerrit.acceptance.AbstractDaemonTest) MetricMaker(com.google.gerrit.metrics.MetricMaker) ExternalIdsUpdate(com.google.gerrit.server.account.externalids.ExternalIdsUpdate) GitUtil.fetch(com.google.gerrit.acceptance.GitUtil.fetch) Iterables(com.google.common.collect.Iterables) Status(org.eclipse.jgit.transport.RemoteRefUpdate.Status) ConfigInvalidException(org.eclipse.jgit.errors.ConfigInvalidException) InMemoryRepository(org.eclipse.jgit.internal.storage.dfs.InMemoryRepository) OrmDuplicateKeyException(com.google.gwtorm.server.OrmDuplicateKeyException) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) RefsMetaExternalIdsUpdate(com.google.gerrit.server.account.externalids.ExternalIdsUpdate.RefsMetaExternalIdsUpdate) LockFailureException(com.google.gerrit.server.git.LockFailureException) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) DisabledExternalIdCache(com.google.gerrit.server.account.externalids.DisabledExternalIdCache) ImmutableList(com.google.common.collect.ImmutableList) AccountExternalIdInfo(com.google.gerrit.extensions.common.AccountExternalIdInfo) Account(com.google.gerrit.reviewdb.client.Account) ConsistencyCheckInput(com.google.gerrit.extensions.api.config.ConsistencyCheckInput) GitUtil.pushHead(com.google.gerrit.acceptance.GitUtil.pushHead) TestRepository(org.eclipse.jgit.junit.TestRepository) Sandboxed(com.google.gerrit.acceptance.Sandboxed) UTF_8(java.nio.charset.StandardCharsets.UTF_8) ExternalIdReader(com.google.gerrit.server.account.externalids.ExternalIdReader) IOException(java.io.IOException) Test(org.junit.Test) Truth.assertThat(com.google.common.truth.Truth.assertThat) SCHEME_MAILTO(com.google.gerrit.server.account.externalids.ExternalId.SCHEME_MAILTO) MutableInteger(org.eclipse.jgit.util.MutableInteger) ObjectId(org.eclipse.jgit.lib.ObjectId) TransportException(org.eclipse.jgit.api.errors.TransportException) Collectors.toList(java.util.stream.Collectors.toList) RemoteRefUpdate(org.eclipse.jgit.transport.RemoteRefUpdate) ExternalId(com.google.gerrit.server.account.externalids.ExternalId) Collections(java.util.Collections) Repository(org.eclipse.jgit.lib.Repository) ConfigInvalidException(org.eclipse.jgit.errors.ConfigInvalidException) RefsMetaExternalIdsUpdate(com.google.gerrit.server.account.externalids.ExternalIdsUpdate.RefsMetaExternalIdsUpdate) ExternalIdsUpdate(com.google.gerrit.server.account.externalids.ExternalIdsUpdate) RefsMetaExternalIdsUpdate(com.google.gerrit.server.account.externalids.ExternalIdsUpdate.RefsMetaExternalIdsUpdate) ExternalId(com.google.gerrit.server.account.externalids.ExternalId) IOException(java.io.IOException) LockFailureException(com.google.gerrit.server.git.LockFailureException) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) OrmException(com.google.gwtorm.server.OrmException) DisabledExternalIdCache(com.google.gerrit.server.account.externalids.DisabledExternalIdCache) AbstractDaemonTest(com.google.gerrit.acceptance.AbstractDaemonTest) Test(org.junit.Test)

Aggregations

OrmException (com.google.gwtorm.server.OrmException)172 IOException (java.io.IOException)78 Change (com.google.gerrit.reviewdb.client.Change)50 Repository (org.eclipse.jgit.lib.Repository)41 ConfigInvalidException (org.eclipse.jgit.errors.ConfigInvalidException)33 ReviewDb (com.google.gerrit.reviewdb.server.ReviewDb)31 ObjectId (org.eclipse.jgit.lib.ObjectId)29 Account (com.google.gerrit.reviewdb.client.Account)28 RevWalk (org.eclipse.jgit.revwalk.RevWalk)28 PatchSet (com.google.gerrit.reviewdb.client.PatchSet)24 ChangeData (com.google.gerrit.server.query.change.ChangeData)24 Map (java.util.Map)22 ArrayList (java.util.ArrayList)21 ChangeNotes (com.google.gerrit.server.notedb.ChangeNotes)20 Inject (com.google.inject.Inject)18 Provider (com.google.inject.Provider)17 RestApiException (com.google.gerrit.extensions.restapi.RestApiException)16 Set (java.util.Set)16 BatchUpdate (com.google.gerrit.server.update.BatchUpdate)15 CurrentUser (com.google.gerrit.server.CurrentUser)14