Search in sources :

Example 1 with ResourceConflictException

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

the class RebaseUtil method findBaseRevision.

/**
   * Find the commit onto which a patch set should be rebased.
   *
   * <p>This is defined as the latest patch set of the change corresponding to this commit's parent,
   * or the destination branch tip in the case where the parent's change is merged.
   *
   * @param patchSet patch set for which the new base commit should be found.
   * @param destBranch the destination branch.
   * @param git the repository.
   * @param rw the RevWalk.
   * @return the commit onto which the patch set should be rebased.
   * @throws RestApiException if rebase is not possible.
   * @throws IOException if accessing the repository fails.
   * @throws OrmException if accessing the database fails.
   */
ObjectId findBaseRevision(PatchSet patchSet, Branch.NameKey destBranch, Repository git, RevWalk rw) throws RestApiException, IOException, OrmException {
    String baseRev = null;
    RevCommit commit = rw.parseCommit(ObjectId.fromString(patchSet.getRevision().get()));
    if (commit.getParentCount() > 1) {
        throw new UnprocessableEntityException("Cannot rebase a change with multiple parents.");
    } else if (commit.getParentCount() == 0) {
        throw new UnprocessableEntityException("Cannot rebase a change without any parents (is this the initial commit?).");
    }
    RevId parentRev = new RevId(commit.getParent(0).name());
    CHANGES: for (ChangeData cd : queryProvider.get().byBranchCommit(destBranch, parentRev.get())) {
        for (PatchSet depPatchSet : cd.patchSets()) {
            if (!depPatchSet.getRevision().equals(parentRev)) {
                continue;
            }
            Change depChange = cd.change();
            if (depChange.getStatus() == Status.ABANDONED) {
                throw new ResourceConflictException("Cannot rebase a change with an abandoned parent: " + depChange.getKey());
            }
            if (depChange.getStatus().isOpen()) {
                if (depPatchSet.getId().equals(depChange.currentPatchSetId())) {
                    throw new ResourceConflictException("Change is already based on the latest patch set of the dependent change.");
                }
                baseRev = cd.currentPatchSet().getRevision().get();
            }
            break CHANGES;
        }
    }
    if (baseRev == null) {
        // We are dependent on a merged PatchSet or have no PatchSet
        // dependencies at all.
        Ref destRef = git.getRefDatabase().exactRef(destBranch.get());
        if (destRef == null) {
            throw new UnprocessableEntityException("The destination branch does not exist: " + destBranch.get());
        }
        baseRev = destRef.getObjectId().getName();
        if (baseRev.equals(parentRev.get())) {
            throw new ResourceConflictException("Change is already up to date.");
        }
    }
    return ObjectId.fromString(baseRev);
}
Also used : UnprocessableEntityException(com.google.gerrit.extensions.restapi.UnprocessableEntityException) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) Ref(org.eclipse.jgit.lib.Ref) PatchSet(com.google.gerrit.reviewdb.client.PatchSet) Change(com.google.gerrit.reviewdb.client.Change) RevId(com.google.gerrit.reviewdb.client.RevId) ChangeData(com.google.gerrit.server.query.change.ChangeData) RevCommit(org.eclipse.jgit.revwalk.RevCommit)

Example 2 with ResourceConflictException

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

the class Revert method revert.

private Change.Id revert(BatchUpdate.Factory updateFactory, ChangeControl ctl, String message) throws OrmException, IOException, RestApiException, UpdateException {
    Change.Id changeIdToRevert = ctl.getChange().getId();
    PatchSet.Id patchSetId = ctl.getChange().currentPatchSetId();
    PatchSet patch = psUtil.get(db.get(), ctl.getNotes(), patchSetId);
    if (patch == null) {
        throw new ResourceNotFoundException(changeIdToRevert.toString());
    }
    Project.NameKey project = ctl.getProject().getNameKey();
    CurrentUser user = ctl.getUser();
    try (Repository git = repoManager.openRepository(project);
        ObjectInserter oi = git.newObjectInserter();
        ObjectReader reader = oi.newReader();
        RevWalk revWalk = new RevWalk(reader)) {
        RevCommit commitToRevert = revWalk.parseCommit(ObjectId.fromString(patch.getRevision().get()));
        if (commitToRevert.getParentCount() == 0) {
            throw new ResourceConflictException("Cannot revert initial commit");
        }
        Timestamp now = TimeUtil.nowTs();
        PersonIdent committerIdent = new PersonIdent(serverIdent, now);
        PersonIdent authorIdent = user.asIdentifiedUser().newCommitterIdent(now, committerIdent.getTimeZone());
        RevCommit parentToCommitToRevert = commitToRevert.getParent(0);
        revWalk.parseHeaders(parentToCommitToRevert);
        CommitBuilder revertCommitBuilder = new CommitBuilder();
        revertCommitBuilder.addParentId(commitToRevert);
        revertCommitBuilder.setTreeId(parentToCommitToRevert.getTree());
        revertCommitBuilder.setAuthor(authorIdent);
        revertCommitBuilder.setCommitter(authorIdent);
        Change changeToRevert = ctl.getChange();
        if (message == null) {
            message = MessageFormat.format(ChangeMessages.get().revertChangeDefaultMessage, changeToRevert.getSubject(), patch.getRevision().get());
        }
        ObjectId computedChangeId = ChangeIdUtil.computeChangeId(parentToCommitToRevert.getTree(), commitToRevert, authorIdent, committerIdent, message);
        revertCommitBuilder.setMessage(ChangeIdUtil.insertId(message, computedChangeId, true));
        Change.Id changeId = new Change.Id(seq.nextChangeId());
        ObjectId id = oi.insert(revertCommitBuilder);
        RevCommit revertCommit = revWalk.parseCommit(id);
        ChangeInserter ins = changeInserterFactory.create(changeId, revertCommit, ctl.getChange().getDest().get()).setTopic(changeToRevert.getTopic());
        ins.setMessage("Uploaded patch set 1.");
        Set<Account.Id> reviewers = new HashSet<>();
        reviewers.add(changeToRevert.getOwner());
        reviewers.addAll(approvalsUtil.getReviewers(db.get(), ctl.getNotes()).all());
        reviewers.remove(user.getAccountId());
        ins.setReviewers(reviewers);
        try (BatchUpdate bu = updateFactory.create(db.get(), project, user, now)) {
            bu.setRepository(git, revWalk, oi);
            bu.insertChange(ins);
            bu.addOp(changeId, new NotifyOp(ctl.getChange(), ins));
            bu.addOp(changeToRevert.getId(), new PostRevertedMessageOp(computedChangeId));
            bu.execute();
        }
        return changeId;
    } catch (RepositoryNotFoundException e) {
        throw new ResourceNotFoundException(changeIdToRevert.toString(), e);
    }
}
Also used : CurrentUser(com.google.gerrit.server.CurrentUser) CommitBuilder(org.eclipse.jgit.lib.CommitBuilder) Timestamp(java.sql.Timestamp) BatchUpdate(com.google.gerrit.server.update.BatchUpdate) ObjectInserter(org.eclipse.jgit.lib.ObjectInserter) ObjectReader(org.eclipse.jgit.lib.ObjectReader) ResourceNotFoundException(com.google.gerrit.extensions.restapi.ResourceNotFoundException) RevCommit(org.eclipse.jgit.revwalk.RevCommit) HashSet(java.util.HashSet) ObjectId(org.eclipse.jgit.lib.ObjectId) PatchSet(com.google.gerrit.reviewdb.client.PatchSet) Change(com.google.gerrit.reviewdb.client.Change) RepositoryNotFoundException(org.eclipse.jgit.errors.RepositoryNotFoundException) RevWalk(org.eclipse.jgit.revwalk.RevWalk) Project(com.google.gerrit.reviewdb.client.Project) Repository(org.eclipse.jgit.lib.Repository) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) PersonIdent(org.eclipse.jgit.lib.PersonIdent) GerritPersonIdent(com.google.gerrit.server.GerritPersonIdent) ObjectId(org.eclipse.jgit.lib.ObjectId)

Example 3 with ResourceConflictException

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

the class SetReadyForReview method applyImpl.

@Override
protected Response<?> applyImpl(BatchUpdate.Factory updateFactory, ChangeResource rsrc, Input input) throws RestApiException, UpdateException {
    Change change = rsrc.getChange();
    if (!rsrc.isUserOwner()) {
        throw new AuthException("not allowed to set ready for review");
    }
    if (change.getStatus() != Status.NEW) {
        throw new ResourceConflictException("change is " + ChangeUtil.status(change));
    }
    if (!change.isWorkInProgress()) {
        throw new ResourceConflictException("change is not work in progress");
    }
    try (BatchUpdate bu = updateFactory.create(db.get(), rsrc.getProject(), rsrc.getUser(), TimeUtil.nowTs())) {
        bu.addOp(rsrc.getChange().getId(), new WorkInProgressOp(cmUtil, false, input));
        bu.execute();
        return Response.ok("");
    }
}
Also used : ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) AuthException(com.google.gerrit.extensions.restapi.AuthException) Change(com.google.gerrit.reviewdb.client.Change) BatchUpdate(com.google.gerrit.server.update.BatchUpdate)

Example 4 with ResourceConflictException

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

the class DeleteActive method apply.

@Override
public Response<?> apply(AccountResource rsrc, Input input) throws RestApiException, OrmException, IOException {
    if (self.get() == rsrc.getUser()) {
        throw new ResourceConflictException("cannot deactivate own account");
    }
    AtomicBoolean alreadyInactive = new AtomicBoolean(false);
    Account a = dbProvider.get().accounts().atomicUpdate(rsrc.getUser().getAccountId(), new AtomicUpdate<Account>() {

        @Override
        public Account update(Account a) {
            if (!a.isActive()) {
                alreadyInactive.set(true);
            } else {
                a.setActive(false);
            }
            return a;
        }
    });
    if (a == null) {
        throw new ResourceNotFoundException("account not found");
    }
    if (alreadyInactive.get()) {
        throw new ResourceConflictException("account not active");
    }
    byIdCache.evict(a.getId());
    return Response.none();
}
Also used : AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Account(com.google.gerrit.reviewdb.client.Account) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) ResourceNotFoundException(com.google.gerrit.extensions.restapi.ResourceNotFoundException)

Example 5 with ResourceConflictException

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

the class DeleteExternalIds method apply.

@Override
public Response<?> apply(AccountResource resource, List<String> extIds) throws RestApiException, IOException, OrmException, ConfigInvalidException {
    if (self.get() != resource.getUser() && !self.get().getCapabilities().canAccessDatabase()) {
        throw new AuthException("not allowed to delete external IDs");
    }
    if (extIds == null || extIds.size() == 0) {
        throw new BadRequestException("external IDs are required");
    }
    Map<ExternalId.Key, ExternalId> externalIdMap = externalIds.byAccount(resource.getUser().getAccountId()).stream().collect(toMap(i -> i.key(), i -> i));
    List<ExternalId> toDelete = new ArrayList<>();
    ExternalId.Key last = resource.getUser().getLastLoginExternalIdKey();
    for (String externalIdStr : extIds) {
        ExternalId id = externalIdMap.get(ExternalId.Key.parse(externalIdStr));
        if (id == null) {
            throw new UnprocessableEntityException(String.format("External id %s does not exist", externalIdStr));
        }
        if ((!id.isScheme(SCHEME_USERNAME)) && ((last == null) || (!last.get().equals(id.key().get())))) {
            toDelete.add(id);
        } else {
            throw new ResourceConflictException(String.format("External id %s cannot be deleted", externalIdStr));
        }
    }
    try {
        for (ExternalId extId : toDelete) {
            AuthRequest authRequest = new AuthRequest(extId.key());
            authRequest.setEmailAddress(extId.email());
            accountManager.unlink(extId.accountId(), authRequest);
        }
    } catch (AccountException e) {
        throw new ResourceConflictException(e.getMessage());
    }
    return Response.none();
}
Also used : CurrentUser(com.google.gerrit.server.CurrentUser) OrmException(com.google.gwtorm.server.OrmException) ConfigInvalidException(org.eclipse.jgit.errors.ConfigInvalidException) UnprocessableEntityException(com.google.gerrit.extensions.restapi.UnprocessableEntityException) Inject(com.google.inject.Inject) IOException(java.io.IOException) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException) Response(com.google.gerrit.extensions.restapi.Response) ExternalIds(com.google.gerrit.server.account.externalids.ExternalIds) ArrayList(java.util.ArrayList) RestModifyView(com.google.gerrit.extensions.restapi.RestModifyView) Provider(com.google.inject.Provider) List(java.util.List) Collectors.toMap(java.util.stream.Collectors.toMap) SCHEME_USERNAME(com.google.gerrit.server.account.externalids.ExternalId.SCHEME_USERNAME) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) Map(java.util.Map) AuthException(com.google.gerrit.extensions.restapi.AuthException) ExternalId(com.google.gerrit.server.account.externalids.ExternalId) RestApiException(com.google.gerrit.extensions.restapi.RestApiException) UnprocessableEntityException(com.google.gerrit.extensions.restapi.UnprocessableEntityException) ExternalId(com.google.gerrit.server.account.externalids.ExternalId) ArrayList(java.util.ArrayList) AuthException(com.google.gerrit.extensions.restapi.AuthException) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException)

Aggregations

ResourceConflictException (com.google.gerrit.extensions.restapi.ResourceConflictException)252 Test (org.junit.Test)106 AbstractDaemonTest (com.google.gerrit.acceptance.AbstractDaemonTest)102 BadRequestException (com.google.gerrit.extensions.restapi.BadRequestException)57 AuthException (com.google.gerrit.extensions.restapi.AuthException)46 PushOneCommit (com.google.gerrit.acceptance.PushOneCommit)44 ResourceNotFoundException (com.google.gerrit.extensions.restapi.ResourceNotFoundException)42 IOException (java.io.IOException)39 ObjectId (org.eclipse.jgit.lib.ObjectId)36 Repository (org.eclipse.jgit.lib.Repository)34 Change (com.google.gerrit.entities.Change)29 UnprocessableEntityException (com.google.gerrit.extensions.restapi.UnprocessableEntityException)28 RevCommit (org.eclipse.jgit.revwalk.RevCommit)27 ConfigInvalidException (org.eclipse.jgit.errors.ConfigInvalidException)26 RevWalk (org.eclipse.jgit.revwalk.RevWalk)25 BatchUpdate (com.google.gerrit.server.update.BatchUpdate)23 ArrayList (java.util.ArrayList)21 PatchSet (com.google.gerrit.entities.PatchSet)20 PermissionBackendException (com.google.gerrit.server.permissions.PermissionBackendException)20 ProjectState (com.google.gerrit.server.project.ProjectState)19