Search in sources :

Example 51 with RestApiException

use of com.google.gerrit.extensions.restapi.RestApiException in project gerrit by GerritCodeReview.

the class ChangeEditUtil method publish.

/**
   * Promote change edit to patch set, by squashing the edit into its parent.
   *
   * @param updateFactory factory for creating updates.
   * @param ctl the {@code ChangeControl} of the change to which the change edit belongs
   * @param edit change edit to publish
   * @param notify Notify handling that defines to whom email notifications should be sent after the
   *     change edit is published.
   * @param accountsToNotify Accounts that should be notified after the change edit is published.
   * @throws IOException
   * @throws OrmException
   * @throws UpdateException
   * @throws RestApiException
   */
public void publish(BatchUpdate.Factory updateFactory, ChangeControl ctl, final ChangeEdit edit, NotifyHandling notify, ListMultimap<RecipientType, Account.Id> accountsToNotify) throws IOException, OrmException, RestApiException, UpdateException {
    Change change = edit.getChange();
    try (Repository repo = gitManager.openRepository(change.getProject());
        ObjectInserter oi = repo.newObjectInserter();
        ObjectReader reader = oi.newReader();
        RevWalk rw = new RevWalk(reader)) {
        PatchSet basePatchSet = edit.getBasePatchSet();
        if (!basePatchSet.getId().equals(change.currentPatchSetId())) {
            throw new ResourceConflictException("only edit for current patch set can be published");
        }
        RevCommit squashed = squashEdit(rw, oi, edit.getEditCommit(), basePatchSet);
        PatchSet.Id psId = ChangeUtil.nextPatchSetId(repo, change.currentPatchSetId());
        PatchSetInserter inserter = patchSetInserterFactory.create(ctl, psId, squashed).setNotify(notify).setAccountsToNotify(accountsToNotify);
        StringBuilder message = new StringBuilder("Patch Set ").append(inserter.getPatchSetId().get()).append(": ");
        // Previously checked that the base patch set is the current patch set.
        ObjectId prior = ObjectId.fromString(basePatchSet.getRevision().get());
        ChangeKind kind = changeKindCache.getChangeKind(change.getProject(), rw, repo.getConfig(), prior, squashed);
        if (kind == ChangeKind.NO_CODE_CHANGE) {
            message.append("Commit message was updated.");
            inserter.setDescription("Edit commit message");
        } else {
            message.append("Published edit on patch set ").append(basePatchSet.getPatchSetId()).append(".");
        }
        try (BatchUpdate bu = updateFactory.create(db.get(), change.getProject(), ctl.getUser(), TimeUtil.nowTs())) {
            bu.setRepository(repo, rw, oi);
            bu.addOp(change.getId(), inserter.setDraft(change.getStatus() == Status.DRAFT || basePatchSet.isDraft()).setMessage(message.toString()));
            bu.addOp(change.getId(), new BatchUpdateOp() {

                @Override
                public void updateRepo(RepoContext ctx) throws Exception {
                    ctx.addRefUpdate(edit.getEditCommit().copy(), ObjectId.zeroId(), edit.getRefName());
                }
            });
            bu.execute();
        }
        indexer.index(db.get(), inserter.getChange());
    }
}
Also used : RepoContext(com.google.gerrit.server.update.RepoContext) ObjectId(org.eclipse.jgit.lib.ObjectId) PatchSet(com.google.gerrit.reviewdb.client.PatchSet) Change(com.google.gerrit.reviewdb.client.Change) RevWalk(org.eclipse.jgit.revwalk.RevWalk) BatchUpdate(com.google.gerrit.server.update.BatchUpdate) OrmException(com.google.gwtorm.server.OrmException) UpdateException(com.google.gerrit.server.update.UpdateException) AuthException(com.google.gerrit.extensions.restapi.AuthException) NoSuchChangeException(com.google.gerrit.server.project.NoSuchChangeException) RestApiException(com.google.gerrit.extensions.restapi.RestApiException) IOException(java.io.IOException) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) Repository(org.eclipse.jgit.lib.Repository) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) ObjectInserter(org.eclipse.jgit.lib.ObjectInserter) PatchSetInserter(com.google.gerrit.server.change.PatchSetInserter) ObjectReader(org.eclipse.jgit.lib.ObjectReader) RevCommit(org.eclipse.jgit.revwalk.RevCommit) ChangeKind(com.google.gerrit.extensions.client.ChangeKind) BatchUpdateOp(com.google.gerrit.server.update.BatchUpdateOp)

Example 52 with RestApiException

use of com.google.gerrit.extensions.restapi.RestApiException in project gerrit by GerritCodeReview.

the class DeleteComment method applyImpl.

@Override
public CommentInfo applyImpl(BatchUpdate.Factory batchUpdateFactory, CommentResource rsrc, DeleteCommentInput input) throws RestApiException, IOException, ConfigInvalidException, OrmException, PermissionBackendException, UpdateException {
    CurrentUser user = userProvider.get();
    permissionBackend.user(user).check(GlobalPermission.ADMINISTRATE_SERVER);
    String newMessage = getCommentNewMessage(user.asIdentifiedUser().getName(), input.reason);
    DeleteCommentOp deleteCommentOp = new DeleteCommentOp(rsrc, newMessage);
    try (BatchUpdate batchUpdate = batchUpdateFactory.create(dbProvider.get(), rsrc.getRevisionResource().getProject(), user, TimeUtil.nowTs())) {
        batchUpdate.addOp(rsrc.getRevisionResource().getChange().getId(), deleteCommentOp).execute();
    }
    ChangeNotes updatedNotes = notesFactory.createChecked(rsrc.getRevisionResource().getChange().getId());
    List<Comment> changeComments = commentsUtil.publishedByChange(dbProvider.get(), updatedNotes);
    Optional<Comment> updatedComment = changeComments.stream().filter(c -> c.key.equals(rsrc.getComment().key)).findFirst();
    if (!updatedComment.isPresent()) {
        // This should not happen as this endpoint should not remove the whole comment.
        throw new ResourceNotFoundException("comment not found: " + rsrc.getComment().key);
    }
    return commentJson.get().newCommentFormatter().format(updatedComment.get());
}
Also used : ResourceNotFoundException(com.google.gerrit.extensions.restapi.ResourceNotFoundException) ReviewDb(com.google.gerrit.reviewdb.server.ReviewDb) PermissionBackendException(com.google.gerrit.server.permissions.PermissionBackendException) OrmException(com.google.gwtorm.server.OrmException) ConfigInvalidException(org.eclipse.jgit.errors.ConfigInvalidException) CommentInfo(com.google.gerrit.extensions.common.CommentInfo) Inject(com.google.inject.Inject) CommentsUtil(com.google.gerrit.server.CommentsUtil) PermissionBackend(com.google.gerrit.server.permissions.PermissionBackend) UpdateException(com.google.gerrit.server.update.UpdateException) Strings(com.google.common.base.Strings) Comment(com.google.gerrit.reviewdb.client.Comment) BatchUpdate(com.google.gerrit.server.update.BatchUpdate) RetryHelper(com.google.gerrit.server.update.RetryHelper) RestApiException(com.google.gerrit.extensions.restapi.RestApiException) RetryingRestModifyView(com.google.gerrit.server.update.RetryingRestModifyView) ChangeContext(com.google.gerrit.server.update.ChangeContext) GlobalPermission(com.google.gerrit.server.permissions.GlobalPermission) CurrentUser(com.google.gerrit.server.CurrentUser) DeleteCommentInput(com.google.gerrit.extensions.api.changes.DeleteCommentInput) TimeUtil(com.google.gerrit.common.TimeUtil) ChangeNotes(com.google.gerrit.server.notedb.ChangeNotes) IOException(java.io.IOException) Provider(com.google.inject.Provider) List(java.util.List) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) PatchSet(com.google.gerrit.reviewdb.client.PatchSet) Optional(java.util.Optional) BatchUpdateOp(com.google.gerrit.server.update.BatchUpdateOp) Singleton(com.google.inject.Singleton) Comment(com.google.gerrit.reviewdb.client.Comment) CurrentUser(com.google.gerrit.server.CurrentUser) ChangeNotes(com.google.gerrit.server.notedb.ChangeNotes) ResourceNotFoundException(com.google.gerrit.extensions.restapi.ResourceNotFoundException) BatchUpdate(com.google.gerrit.server.update.BatchUpdate)

Example 53 with RestApiException

use of com.google.gerrit.extensions.restapi.RestApiException in project gerrit by GerritCodeReview.

the class ReceiveCommits method insertChangesAndPatchSets.

private void insertChangesAndPatchSets() {
    ReceiveCommand magicBranchCmd = magicBranch != null ? magicBranch.cmd : null;
    if (magicBranchCmd != null && magicBranchCmd.getResult() != NOT_ATTEMPTED) {
        logWarn(String.format("Skipping change updates on %s because ref update failed: %s %s", project.getName(), magicBranchCmd.getResult(), Strings.nullToEmpty(magicBranchCmd.getMessage())));
        return;
    }
    try (BatchUpdate bu = batchUpdateFactory.create(db, project.getNameKey(), user.materializedCopy(), TimeUtil.nowTs());
        ObjectInserter ins = repo.newObjectInserter();
        ObjectReader reader = ins.newReader();
        RevWalk rw = new RevWalk(reader)) {
        bu.setRepository(repo, rw, ins).updateChangesInParallel();
        bu.setRequestId(receiveId);
        bu.setRefLogMessage("push");
        logDebug("Adding {} replace requests", newChanges.size());
        for (ReplaceRequest replace : replaceByChange.values()) {
            replace.addOps(bu, replaceProgress);
        }
        logDebug("Adding {} create requests", newChanges.size());
        for (CreateRequest create : newChanges) {
            create.addOps(bu);
        }
        logDebug("Adding {} group update requests", newChanges.size());
        updateGroups.forEach(r -> r.addOps(bu));
        logDebug("Adding {} additional ref updates", actualCommands.size());
        actualCommands.forEach(c -> bu.addRepoOnlyOp(new UpdateOneRefOp(c)));
        logDebug("Executing batch");
        try {
            bu.execute();
        } catch (UpdateException e) {
            throw INSERT_EXCEPTION.apply(e);
        }
        if (magicBranchCmd != null) {
            magicBranchCmd.setResult(OK);
        }
        for (ReplaceRequest replace : replaceByChange.values()) {
            String rejectMessage = replace.getRejectMessage();
            if (rejectMessage == null) {
                if (replace.inputCommand.getResult() == NOT_ATTEMPTED) {
                    // Not necessarily the magic branch, so need to set OK on the original value.
                    replace.inputCommand.setResult(OK);
                }
            } else {
                logDebug("Rejecting due to message from ReplaceOp");
                reject(replace.inputCommand, rejectMessage);
            }
        }
    } catch (ResourceConflictException e) {
        addMessage(e.getMessage());
        reject(magicBranchCmd, "conflict");
    } catch (RestApiException | IOException err) {
        logError("Can't insert change/patch set for " + project.getName(), err);
        reject(magicBranchCmd, "internal server error: " + err.getMessage());
    }
    if (magicBranch != null && magicBranch.submit) {
        try {
            submit(newChanges, replaceByChange.values());
        } catch (ResourceConflictException e) {
            addMessage(e.getMessage());
            reject(magicBranchCmd, "conflict");
        } catch (RestApiException | OrmException e) {
            logError("Error submitting changes to " + project.getName(), e);
            reject(magicBranchCmd, "error during submit");
        }
    }
}
Also used : ReceiveCommand(org.eclipse.jgit.transport.ReceiveCommand) IOException(java.io.IOException) RevWalk(org.eclipse.jgit.revwalk.RevWalk) BatchUpdate(com.google.gerrit.server.update.BatchUpdate) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) ObjectInserter(org.eclipse.jgit.lib.ObjectInserter) OrmException(com.google.gwtorm.server.OrmException) ObjectReader(org.eclipse.jgit.lib.ObjectReader) UpdateException(com.google.gerrit.server.update.UpdateException) RestApiException(com.google.gerrit.extensions.restapi.RestApiException)

Example 54 with RestApiException

use of com.google.gerrit.extensions.restapi.RestApiException in project gerrit by GerritCodeReview.

the class ReceiveCommits method autoCloseChanges.

private void autoCloseChanges(final ReceiveCommand cmd) {
    logDebug("Starting auto-closing of changes");
    String refName = cmd.getRefName();
    checkState(!MagicBranch.isMagicBranch(refName), "shouldn't be auto-closing changes on magic branch %s", refName);
    // insertChangesAndPatchSets.
    try (BatchUpdate bu = batchUpdateFactory.create(db, projectControl.getProject().getNameKey(), user, TimeUtil.nowTs());
        ObjectInserter ins = repo.newObjectInserter();
        ObjectReader reader = ins.newReader();
        RevWalk rw = new RevWalk(reader)) {
        bu.setRepository(repo, rw, ins).updateChangesInParallel();
        bu.setRequestId(receiveId);
        // TODO(dborowitz): Teach BatchUpdate to ignore missing changes.
        RevCommit newTip = rw.parseCommit(cmd.getNewId());
        Branch.NameKey branch = new Branch.NameKey(project.getNameKey(), refName);
        rw.reset();
        rw.markStart(newTip);
        if (!ObjectId.zeroId().equals(cmd.getOldId())) {
            rw.markUninteresting(rw.parseCommit(cmd.getOldId()));
        }
        ListMultimap<ObjectId, Ref> byCommit = changeRefsById();
        Map<Change.Key, ChangeNotes> byKey = null;
        List<ReplaceRequest> replaceAndClose = new ArrayList<>();
        int existingPatchSets = 0;
        int newPatchSets = 0;
        COMMIT: for (RevCommit c; (c = rw.next()) != null; ) {
            rw.parseBody(c);
            for (Ref ref : byCommit.get(c.copy())) {
                existingPatchSets++;
                PatchSet.Id psId = PatchSet.Id.fromRef(ref.getName());
                bu.addOp(psId.getParentKey(), mergedByPushOpFactory.create(requestScopePropagator, psId, refName));
                continue COMMIT;
            }
            for (String changeId : c.getFooterLines(CHANGE_ID)) {
                if (byKey == null) {
                    byKey = openChangesByBranch(branch);
                }
                ChangeNotes onto = byKey.get(new Change.Key(changeId.trim()));
                if (onto != null) {
                    newPatchSets++;
                    // Hold onto this until we're done with the walk, as the call to
                    // req.validate below calls isMergedInto which resets the walk.
                    ReplaceRequest req = new ReplaceRequest(onto.getChangeId(), c, cmd, false);
                    req.notes = onto;
                    replaceAndClose.add(req);
                    continue COMMIT;
                }
            }
        }
        for (final ReplaceRequest req : replaceAndClose) {
            Change.Id id = req.notes.getChangeId();
            if (!req.validate(true)) {
                logDebug("Not closing {} because validation failed", id);
                continue;
            }
            req.addOps(bu, null);
            bu.addOp(id, mergedByPushOpFactory.create(requestScopePropagator, req.psId, refName).setPatchSetProvider(new Provider<PatchSet>() {

                @Override
                public PatchSet get() {
                    return req.replaceOp.getPatchSet();
                }
            }));
            bu.addOp(id, new ChangeProgressOp(closeProgress));
        }
        logDebug("Auto-closing {} changes with existing patch sets and {} with new patch sets", existingPatchSets, newPatchSets);
        bu.execute();
    } catch (RestApiException e) {
        logError("Can't insert patchset", e);
    } catch (IOException | OrmException | UpdateException | PermissionBackendException e) {
        logError("Can't scan for changes to close", e);
    }
}
Also used : ArrayList(java.util.ArrayList) ChangeNotes(com.google.gerrit.server.notedb.ChangeNotes) BatchUpdate(com.google.gerrit.server.update.BatchUpdate) ObjectInserter(org.eclipse.jgit.lib.ObjectInserter) OrmException(com.google.gwtorm.server.OrmException) MagicBranch(com.google.gerrit.server.util.MagicBranch) Branch(com.google.gerrit.reviewdb.client.Branch) ObjectReader(org.eclipse.jgit.lib.ObjectReader) UpdateException(com.google.gerrit.server.update.UpdateException) RevCommit(org.eclipse.jgit.revwalk.RevCommit) ObjectId(org.eclipse.jgit.lib.ObjectId) PermissionBackendException(com.google.gerrit.server.permissions.PermissionBackendException) Change(com.google.gerrit.reviewdb.client.Change) IOException(java.io.IOException) RevWalk(org.eclipse.jgit.revwalk.RevWalk) Provider(com.google.inject.Provider) Ref(org.eclipse.jgit.lib.Ref) RequestId(com.google.gerrit.server.util.RequestId) ObjectId(org.eclipse.jgit.lib.ObjectId) RevId(com.google.gerrit.reviewdb.client.RevId) RestApiException(com.google.gerrit.extensions.restapi.RestApiException)

Example 55 with RestApiException

use of com.google.gerrit.extensions.restapi.RestApiException in project gerrit by GerritCodeReview.

the class DirectChangeByCommit method doGet.

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse rsp) throws IOException {
    String query = CharMatcher.is('/').trimTrailingFrom(req.getPathInfo());
    List<ChangeInfo> results;
    try {
        results = changes.query(query).withLimit(2).get();
    } catch (RestApiException e) {
        logger.atWarning().withCause(e).log("Cannot process query by URL: /r/%s", query);
        results = ImmutableList.of();
    }
    String token;
    if (results.size() == 1) {
        // If exactly one change matches, link to that change.
        // TODO Link to a specific patch set, if one matched.
        ChangeInfo ci = results.iterator().next();
        token = PageLinks.toChange(Project.nameKey(ci.project), Change.id(ci._number));
    } else {
        // Otherwise, link to the query page.
        token = PageLinks.toChangeQuery(query);
    }
    UrlModule.toGerrit(token, req, rsp);
}
Also used : ChangeInfo(com.google.gerrit.extensions.common.ChangeInfo) RestApiException(com.google.gerrit.extensions.restapi.RestApiException)

Aggregations

RestApiException (com.google.gerrit.extensions.restapi.RestApiException)93 ApiUtil.asRestApiException (com.google.gerrit.server.api.ApiUtil.asRestApiException)38 IOException (java.io.IOException)31 BadRequestException (com.google.gerrit.extensions.restapi.BadRequestException)24 UpdateException (com.google.gerrit.server.update.UpdateException)23 BatchUpdate (com.google.gerrit.server.update.BatchUpdate)22 ResourceConflictException (com.google.gerrit.extensions.restapi.ResourceConflictException)20 PermissionBackendException (com.google.gerrit.server.permissions.PermissionBackendException)19 AuthException (com.google.gerrit.extensions.restapi.AuthException)18 StorageException (com.google.gerrit.exceptions.StorageException)17 List (java.util.List)17 BatchUpdateOp (com.google.gerrit.server.update.BatchUpdateOp)16 Inject (com.google.inject.Inject)15 ArrayList (java.util.ArrayList)15 ResourceNotFoundException (com.google.gerrit.extensions.restapi.ResourceNotFoundException)14 ChangeNotes (com.google.gerrit.server.notedb.ChangeNotes)14 ChangeContext (com.google.gerrit.server.update.ChangeContext)14 ConfigInvalidException (org.eclipse.jgit.errors.ConfigInvalidException)14 Provider (com.google.inject.Provider)12 Change (com.google.gerrit.entities.Change)11