Search in sources :

Example 6 with ResourceConflictException

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

the class DeletePrivate method applyImpl.

@Override
protected Response<String> applyImpl(BatchUpdate.Factory updateFactory, ChangeResource rsrc, SetPrivateOp.Input input) throws RestApiException, UpdateException {
    if (!canDeletePrivate(rsrc)) {
        throw new AuthException("not allowed to unmark private");
    }
    if (!rsrc.getChange().isPrivate()) {
        throw new ResourceConflictException("change is not private");
    }
    ChangeControl control = rsrc.getControl();
    SetPrivateOp op = new SetPrivateOp(cmUtil, false, input);
    try (BatchUpdate u = updateFactory.create(dbProvider.get(), control.getProject().getNameKey(), control.getUser(), TimeUtil.nowTs())) {
        u.addOp(control.getId(), op).execute();
    }
    return Response.none();
}
Also used : ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) ChangeControl(com.google.gerrit.server.project.ChangeControl) AuthException(com.google.gerrit.extensions.restapi.AuthException) BatchUpdate(com.google.gerrit.server.update.BatchUpdate)

Example 7 with ResourceConflictException

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

the class SetAccess method apply.

@Override
public ProjectAccessInfo apply(ProjectResource rsrc, ProjectAccessInput input) throws ResourceNotFoundException, ResourceConflictException, IOException, AuthException, BadRequestException, UnprocessableEntityException, PermissionBackendException {
    List<AccessSection> removals = getAccessSections(input.remove);
    List<AccessSection> additions = getAccessSections(input.add);
    MetaDataUpdate.User metaDataUpdateUser = metaDataUpdateFactory.get();
    ProjectControl projectControl = rsrc.getControl();
    ProjectConfig config;
    Project.NameKey newParentProjectName = input.parent == null ? null : new Project.NameKey(input.parent);
    try (MetaDataUpdate md = metaDataUpdateUser.create(rsrc.getNameKey())) {
        config = ProjectConfig.read(md);
        // Perform removal checks
        for (AccessSection section : removals) {
            boolean isGlobalCapabilities = AccessSection.GLOBAL_CAPABILITIES.equals(section.getName());
            if (isGlobalCapabilities) {
                checkGlobalCapabilityPermissions(config.getName());
            } else if (!projectControl.controlForRef(section.getName()).isOwner()) {
                throw new AuthException("You are not allowed to edit permissionsfor ref: " + section.getName());
            }
        }
        // Perform addition checks
        for (AccessSection section : additions) {
            String name = section.getName();
            boolean isGlobalCapabilities = AccessSection.GLOBAL_CAPABILITIES.equals(name);
            if (isGlobalCapabilities) {
                checkGlobalCapabilityPermissions(config.getName());
            } else {
                if (!AccessSection.isValid(name)) {
                    throw new BadRequestException("invalid section name");
                }
                if (!projectControl.controlForRef(name).isOwner()) {
                    throw new AuthException("You are not allowed to edit permissionsfor ref: " + name);
                }
                RefPattern.validate(name);
            }
            // Check all permissions for soundness
            for (Permission p : section.getPermissions()) {
                if (isGlobalCapabilities && !GlobalCapability.isCapability(p.getName())) {
                    throw new BadRequestException("Cannot add non-global capability " + p.getName() + " to global capabilities");
                }
            }
        }
        // Apply removals
        for (AccessSection section : removals) {
            if (section.getPermissions().isEmpty()) {
                // Remove entire section
                config.remove(config.getAccessSection(section.getName()));
            }
            // Remove specific permissions
            for (Permission p : section.getPermissions()) {
                if (p.getRules().isEmpty()) {
                    config.remove(config.getAccessSection(section.getName()), p);
                } else {
                    for (PermissionRule r : p.getRules()) {
                        config.remove(config.getAccessSection(section.getName()), p, r);
                    }
                }
            }
        }
        // Apply additions
        for (AccessSection section : additions) {
            AccessSection currentAccessSection = config.getAccessSection(section.getName());
            if (currentAccessSection == null) {
                // Add AccessSection
                config.replace(section);
            } else {
                for (Permission p : section.getPermissions()) {
                    Permission currentPermission = currentAccessSection.getPermission(p.getName());
                    if (currentPermission == null) {
                        // Add Permission
                        currentAccessSection.addPermission(p);
                    } else {
                        for (PermissionRule r : p.getRules()) {
                            // AddPermissionRule
                            currentPermission.add(r);
                        }
                    }
                }
            }
        }
        if (newParentProjectName != null && !config.getProject().getNameKey().equals(allProjects) && !config.getProject().getParent(allProjects).equals(newParentProjectName)) {
            try {
                setParent.get().validateParentUpdate(projectControl, MoreObjects.firstNonNull(newParentProjectName, allProjects).get(), true);
            } catch (UnprocessableEntityException e) {
                throw new ResourceConflictException(e.getMessage(), e);
            }
            config.getProject().setParentName(newParentProjectName);
        }
        if (!Strings.isNullOrEmpty(input.message)) {
            if (!input.message.endsWith("\n")) {
                input.message += "\n";
            }
            md.setMessage(input.message);
        } else {
            md.setMessage("Modify access rules\n");
        }
        config.commit(md);
        projectCache.evict(config.getProject());
    } catch (InvalidNameException e) {
        throw new BadRequestException(e.toString());
    } catch (ConfigInvalidException e) {
        throw new ResourceConflictException(rsrc.getName());
    }
    return getAccess.apply(rsrc.getNameKey());
}
Also used : UnprocessableEntityException(com.google.gerrit.extensions.restapi.UnprocessableEntityException) ConfigInvalidException(org.eclipse.jgit.errors.ConfigInvalidException) PermissionRule(com.google.gerrit.common.data.PermissionRule) AuthException(com.google.gerrit.extensions.restapi.AuthException) AccessSection(com.google.gerrit.common.data.AccessSection) ProjectConfig(com.google.gerrit.server.git.ProjectConfig) Project(com.google.gerrit.reviewdb.client.Project) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) InvalidNameException(com.google.gerrit.common.errors.InvalidNameException) GlobalPermission(com.google.gerrit.server.permissions.GlobalPermission) Permission(com.google.gerrit.common.data.Permission) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException) MetaDataUpdate(com.google.gerrit.server.git.MetaDataUpdate)

Example 8 with ResourceConflictException

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

the class RevisionIT method postSubmitApproval.

@Test
public void postSubmitApproval() throws Exception {
    PushOneCommit.Result r = createChange();
    String changeId = project.get() + "~master~" + r.getChangeId();
    gApi.changes().id(changeId).current().review(ReviewInput.recommend());
    String label = "Code-Review";
    ApprovalInfo approval = getApproval(changeId, label);
    assertThat(approval.value).isEqualTo(1);
    assertThat(approval.postSubmit).isNull();
    // Submit by direct push.
    git().push().setRefSpecs(new RefSpec(r.getCommit().name() + ":refs/heads/master")).call();
    assertThat(gApi.changes().id(changeId).get().status).isEqualTo(ChangeStatus.MERGED);
    approval = getApproval(changeId, label);
    assertThat(approval.value).isEqualTo(1);
    assertThat(approval.postSubmit).isNull();
    assertPermitted(gApi.changes().id(changeId).get(EnumSet.of(DETAILED_LABELS)), "Code-Review", 1, 2);
    // Repeating the current label is allowed. Does not flip the postSubmit bit
    // due to deduplication codepath.
    gApi.changes().id(changeId).current().review(ReviewInput.recommend());
    approval = getApproval(changeId, label);
    assertThat(approval.value).isEqualTo(1);
    assertThat(approval.postSubmit).isNull();
    // Reducing vote is not allowed.
    try {
        gApi.changes().id(changeId).current().review(ReviewInput.dislike());
        fail("expected ResourceConflictException");
    } catch (ResourceConflictException e) {
        assertThat(e).hasMessageThat().isEqualTo("Cannot reduce vote on labels for closed change: Code-Review");
    }
    approval = getApproval(changeId, label);
    assertThat(approval.value).isEqualTo(1);
    assertThat(approval.postSubmit).isNull();
    // Increasing vote is allowed.
    gApi.changes().id(changeId).current().review(ReviewInput.approve());
    approval = getApproval(changeId, label);
    assertThat(approval.value).isEqualTo(2);
    assertThat(approval.postSubmit).isTrue();
    assertPermitted(gApi.changes().id(changeId).get(EnumSet.of(DETAILED_LABELS)), "Code-Review", 2);
    // Decreasing to previous post-submit vote is still not allowed.
    try {
        gApi.changes().id(changeId).current().review(ReviewInput.dislike());
        fail("expected ResourceConflictException");
    } catch (ResourceConflictException e) {
        assertThat(e).hasMessageThat().isEqualTo("Cannot reduce vote on labels for closed change: Code-Review");
    }
    approval = getApproval(changeId, label);
    assertThat(approval.value).isEqualTo(2);
    assertThat(approval.postSubmit).isTrue();
}
Also used : ApprovalInfo(com.google.gerrit.extensions.common.ApprovalInfo) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) RefSpec(org.eclipse.jgit.transport.RefSpec) PushOneCommit(com.google.gerrit.acceptance.PushOneCommit) AbstractDaemonTest(com.google.gerrit.acceptance.AbstractDaemonTest) Test(org.junit.Test)

Example 9 with ResourceConflictException

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

the class NoteDbOnlyIT method updateChangeFailureRollsBackRefUpdate.

@Test
public void updateChangeFailureRollsBackRefUpdate() throws Exception {
    assume().that(notesMigration.fuseUpdates()).isTrue();
    PushOneCommit.Result r = createChange();
    Change.Id id = r.getChange().getId();
    String master = "refs/heads/master";
    String backup = "refs/backup/master";
    ObjectId master1 = getRef(master).get();
    assertThat(getRef(backup)).isEmpty();
    // Toy op that copies the value of refs/heads/master to refs/backup/master.
    BatchUpdateOp backupMasterOp = new BatchUpdateOp() {

        ObjectId newId;

        @Override
        public void updateRepo(RepoContext ctx) throws IOException {
            ObjectId oldId = ctx.getRepoView().getRef(backup).orElse(ObjectId.zeroId());
            newId = ctx.getRepoView().getRef(master).get();
            ctx.addRefUpdate(oldId, newId, backup);
        }

        @Override
        public boolean updateChange(ChangeContext ctx) {
            ctx.getUpdate(ctx.getChange().currentPatchSetId()).setChangeMessage("Backed up master branch to " + newId.name());
            return true;
        }
    };
    try (BatchUpdate bu = newBatchUpdate(batchUpdateFactory)) {
        bu.addOp(id, backupMasterOp);
        bu.execute();
    }
    // Ensure backupMasterOp worked.
    assertThat(getRef(backup)).hasValue(master1);
    assertThat(getMessages(id)).contains("Backed up master branch to " + master1.name());
    // Advance master by submitting the change.
    gApi.changes().id(id.get()).current().review(ReviewInput.approve());
    gApi.changes().id(id.get()).current().submit();
    ObjectId master2 = getRef(master).get();
    assertThat(master2).isNotEqualTo(master1);
    int msgCount = getMessages(id).size();
    try (BatchUpdate bu = newBatchUpdate(batchUpdateFactory)) {
        // This time, we attempt to back up master, but we fail during updateChange.
        bu.addOp(id, backupMasterOp);
        String msg = "Change is bad";
        bu.addOp(id, new BatchUpdateOp() {

            @Override
            public boolean updateChange(ChangeContext ctx) throws ResourceConflictException {
                throw new ResourceConflictException(msg);
            }
        });
        try {
            bu.execute();
            assert_().fail("expected ResourceConflictException");
        } catch (ResourceConflictException e) {
            assertThat(e).hasMessageThat().isEqualTo(msg);
        }
    }
    // If updateChange hadn't failed, backup would have been updated to master2.
    assertThat(getRef(backup)).hasValue(master1);
    assertThat(getMessages(id)).hasSize(msgCount);
}
Also used : RepoContext(com.google.gerrit.server.update.RepoContext) ChangeContext(com.google.gerrit.server.update.ChangeContext) ObjectId(org.eclipse.jgit.lib.ObjectId) Change(com.google.gerrit.reviewdb.client.Change) PushOneCommit(com.google.gerrit.acceptance.PushOneCommit) BatchUpdate(com.google.gerrit.server.update.BatchUpdate) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) BatchUpdateOp(com.google.gerrit.server.update.BatchUpdateOp) Test(org.junit.Test) AbstractDaemonTest(com.google.gerrit.acceptance.AbstractDaemonTest)

Example 10 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)

Aggregations

ResourceConflictException (com.google.gerrit.extensions.restapi.ResourceConflictException)75 AuthException (com.google.gerrit.extensions.restapi.AuthException)25 BadRequestException (com.google.gerrit.extensions.restapi.BadRequestException)21 Change (com.google.gerrit.reviewdb.client.Change)19 ResourceNotFoundException (com.google.gerrit.extensions.restapi.ResourceNotFoundException)18 Project (com.google.gerrit.reviewdb.client.Project)17 IOException (java.io.IOException)17 PatchSet (com.google.gerrit.reviewdb.client.PatchSet)14 Repository (org.eclipse.jgit.lib.Repository)14 UnprocessableEntityException (com.google.gerrit.extensions.restapi.UnprocessableEntityException)13 BatchUpdate (com.google.gerrit.server.update.BatchUpdate)12 OrmException (com.google.gwtorm.server.OrmException)12 ConfigInvalidException (org.eclipse.jgit.errors.ConfigInvalidException)12 ObjectId (org.eclipse.jgit.lib.ObjectId)12 RevWalk (org.eclipse.jgit.revwalk.RevWalk)12 AbstractDaemonTest (com.google.gerrit.acceptance.AbstractDaemonTest)10 ArrayList (java.util.ArrayList)10 RepositoryNotFoundException (org.eclipse.jgit.errors.RepositoryNotFoundException)10 ProjectConfig (com.google.gerrit.server.git.ProjectConfig)9 RevCommit (org.eclipse.jgit.revwalk.RevCommit)9