Search in sources :

Example 26 with UnprocessableEntityException

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

the class ImpersonationIT method submitOnBehalfOfInvalidUser.

@Test
public void submitOnBehalfOfInvalidUser() throws Exception {
    allowSubmitOnBehalfOf();
    PushOneCommit.Result r = createChange();
    String changeId = project.get() + "~master~" + r.getChangeId();
    gApi.changes().id(changeId).current().review(ReviewInput.approve());
    SubmitInput in = new SubmitInput();
    in.onBehalfOf = "doesnotexist";
    UnprocessableEntityException thrown = assertThrows(UnprocessableEntityException.class, () -> gApi.changes().id(changeId).current().submit(in));
    assertThat(thrown).hasMessageThat().contains("not found");
    assertThat(thrown).hasMessageThat().contains("doesnotexist");
}
Also used : SubmitInput(com.google.gerrit.extensions.api.changes.SubmitInput) UnprocessableEntityException(com.google.gerrit.extensions.restapi.UnprocessableEntityException) PushOneCommit(com.google.gerrit.acceptance.PushOneCommit) AbstractDaemonTest(com.google.gerrit.acceptance.AbstractDaemonTest) Test(org.junit.Test)

Example 27 with UnprocessableEntityException

use of com.google.gerrit.extensions.restapi.UnprocessableEntityException 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.
 */
public ObjectId findBaseRevision(PatchSet patchSet, BranchNameKey destBranch, Repository git, RevWalk rw) throws RestApiException, IOException {
    ObjectId baseId = null;
    RevCommit commit = rw.parseCommit(patchSet.commitId());
    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?).");
    }
    ObjectId parentId = commit.getParent(0);
    CHANGES: for (ChangeData cd : queryProvider.get().byBranchCommit(destBranch, parentId.name())) {
        for (PatchSet depPatchSet : cd.patchSets()) {
            if (!depPatchSet.commitId().equals(parentId)) {
                continue;
            }
            Change depChange = cd.change();
            if (depChange.isAbandoned()) {
                throw new ResourceConflictException("Cannot rebase a change with an abandoned parent: " + depChange.getKey());
            }
            if (depChange.isNew()) {
                if (depPatchSet.id().equals(depChange.currentPatchSetId())) {
                    throw new ResourceConflictException("Change is already based on the latest patch set of the dependent change.");
                }
                baseId = cd.currentPatchSet().commitId();
            }
            break CHANGES;
        }
    }
    if (baseId == null) {
        // We are dependent on a merged PatchSet or have no PatchSet
        // dependencies at all.
        Ref destRef = git.getRefDatabase().exactRef(destBranch.branch());
        if (destRef == null) {
            throw new UnprocessableEntityException("The destination branch does not exist: " + destBranch.branch());
        }
        baseId = destRef.getObjectId();
        if (baseId.equals(parentId)) {
            throw new ResourceConflictException("Change is already up to date.");
        }
    }
    return baseId;
}
Also used : UnprocessableEntityException(com.google.gerrit.extensions.restapi.UnprocessableEntityException) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) Ref(org.eclipse.jgit.lib.Ref) ObjectId(org.eclipse.jgit.lib.ObjectId) PatchSet(com.google.gerrit.entities.PatchSet) Change(com.google.gerrit.entities.Change) ChangeData(com.google.gerrit.server.query.change.ChangeData) RevCommit(org.eclipse.jgit.revwalk.RevCommit)

Example 28 with UnprocessableEntityException

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

the class SetHead method apply.

@Override
public Response<String> apply(ProjectResource rsrc, HeadInput input) throws AuthException, ResourceNotFoundException, BadRequestException, UnprocessableEntityException, IOException, PermissionBackendException {
    if (input == null || Strings.isNullOrEmpty(input.ref)) {
        throw new BadRequestException("ref required");
    }
    String ref = RefNames.fullName(input.ref);
    permissionBackend.user(rsrc.getUser()).project(rsrc.getNameKey()).ref(ref).check(RefPermission.SET_HEAD);
    try (Repository repo = repoManager.openRepository(rsrc.getNameKey())) {
        Map<String, Ref> cur = repo.getRefDatabase().exactRef(Constants.HEAD, ref);
        if (!cur.containsKey(ref)) {
            throw new UnprocessableEntityException(String.format("Ref Not Found: %s", ref));
        }
        final String oldHead = cur.get(Constants.HEAD).getTarget().getName();
        final String newHead = ref;
        if (!oldHead.equals(newHead)) {
            final RefUpdate u = repo.updateRef(Constants.HEAD, true);
            u.setRefLogIdent(identifiedUser.get().newRefLogIdent());
            RefUpdate.Result res = u.link(newHead);
            switch(res) {
                case NO_CHANGE:
                case RENAMED:
                case FORCED:
                case NEW:
                    break;
                case LOCK_FAILURE:
                    throw new LockFailureException("Setting HEAD failed", u);
                case FAST_FORWARD:
                case IO_FAILURE:
                case NOT_ATTEMPTED:
                case REJECTED:
                case REJECTED_CURRENT_BRANCH:
                case REJECTED_MISSING_OBJECT:
                case REJECTED_OTHER_REASON:
                default:
                    throw new IOException("Setting HEAD failed with " + res);
            }
            fire(rsrc.getNameKey(), oldHead, newHead);
        }
        return Response.ok(ref);
    } catch (RepositoryNotFoundException e) {
        throw new ResourceNotFoundException(rsrc.getName(), e);
    }
}
Also used : UnprocessableEntityException(com.google.gerrit.extensions.restapi.UnprocessableEntityException) Repository(org.eclipse.jgit.lib.Repository) Ref(org.eclipse.jgit.lib.Ref) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException) IOException(java.io.IOException) RepositoryNotFoundException(org.eclipse.jgit.errors.RepositoryNotFoundException) ResourceNotFoundException(com.google.gerrit.extensions.restapi.ResourceNotFoundException) LockFailureException(com.google.gerrit.git.LockFailureException) RefUpdate(org.eclipse.jgit.lib.RefUpdate)

Example 29 with UnprocessableEntityException

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

the class SetParent method validateParentUpdate.

public void validateParentUpdate(Project.NameKey project, IdentifiedUser user, String newParent, boolean checkIfAdmin) throws AuthException, ResourceConflictException, UnprocessableEntityException, PermissionBackendException, BadRequestException {
    if (checkIfAdmin) {
        if (allowProjectOwnersToChangeParent) {
            permissionBackend.user(user).project(project).check(ProjectPermission.WRITE_CONFIG);
        } else {
            permissionBackend.user(user).check(GlobalPermission.ADMINISTRATE_SERVER);
        }
    }
    if (project.equals(allUsers) && !allProjects.get().equals(newParent)) {
        throw new BadRequestException(String.format("%s must inherit from %s", allUsers.get(), allProjects.get()));
    }
    if (project.equals(allProjects)) {
        throw new ResourceConflictException("cannot set parent of " + allProjects.get());
    }
    if (allUsers.get().equals(newParent)) {
        throw new ResourceConflictException(String.format("Cannot inherit from '%s' project", allUsers.get()));
    }
    newParent = Strings.emptyToNull(newParent);
    if (newParent != null) {
        Project.NameKey newParentNameKey = Project.nameKey(newParent);
        ProjectState parent = cache.get(newParentNameKey).orElseThrow(() -> new UnprocessableEntityException("parent project " + newParentNameKey + " not found"));
        if (parent.getName().equals(project.get())) {
            throw new ResourceConflictException("cannot set parent to self");
        }
        if (Iterables.tryFind(parent.tree(), p -> p.getNameKey().equals(project)).isPresent()) {
            throw new ResourceConflictException("cycle exists between " + project.get() + " and " + parent.getName());
        }
    }
}
Also used : ResourceNotFoundException(com.google.gerrit.extensions.restapi.ResourceNotFoundException) AllUsersName(com.google.gerrit.server.config.AllUsersName) Iterables(com.google.common.collect.Iterables) PermissionBackendException(com.google.gerrit.server.permissions.PermissionBackendException) ProjectConfig(com.google.gerrit.server.project.ProjectConfig) ConfigInvalidException(org.eclipse.jgit.errors.ConfigInvalidException) ProjectCache(com.google.gerrit.server.project.ProjectCache) UnprocessableEntityException(com.google.gerrit.extensions.restapi.UnprocessableEntityException) GerritConfigListener(com.google.gerrit.server.config.GerritConfigListener) RepositoryNotFoundException(org.eclipse.jgit.errors.RepositoryNotFoundException) Inject(com.google.inject.Inject) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException) Multimap(com.google.common.collect.Multimap) Response(com.google.gerrit.extensions.restapi.Response) PermissionBackend(com.google.gerrit.server.permissions.PermissionBackend) ConfigUpdateEntry(com.google.gerrit.server.config.ConfigUpdatedEvent.ConfigUpdateEntry) RestModifyView(com.google.gerrit.extensions.restapi.RestModifyView) Strings(com.google.common.base.Strings) Config(org.eclipse.jgit.lib.Config) ParentInput(com.google.gerrit.extensions.api.projects.ParentInput) Objects.requireNonNull(java.util.Objects.requireNonNull) AuthException(com.google.gerrit.extensions.restapi.AuthException) ConfigUpdatedEvent(com.google.gerrit.server.config.ConfigUpdatedEvent) GlobalPermission(com.google.gerrit.server.permissions.GlobalPermission) GerritServerConfig(com.google.gerrit.server.config.GerritServerConfig) ProjectState(com.google.gerrit.server.project.ProjectState) MoreObjects(com.google.common.base.MoreObjects) ProjectResource(com.google.gerrit.server.project.ProjectResource) IOException(java.io.IOException) UpdateResult(com.google.gerrit.server.config.ConfigUpdatedEvent.UpdateResult) ConfigKey(com.google.gerrit.server.config.ConfigKey) ProjectPermission(com.google.gerrit.server.permissions.ProjectPermission) Provider(com.google.inject.Provider) AllProjectsName(com.google.gerrit.server.config.AllProjectsName) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) IdentifiedUser(com.google.gerrit.server.IdentifiedUser) Project(com.google.gerrit.entities.Project) MetaDataUpdate(com.google.gerrit.server.git.meta.MetaDataUpdate) Singleton(com.google.inject.Singleton) Project(com.google.gerrit.entities.Project) UnprocessableEntityException(com.google.gerrit.extensions.restapi.UnprocessableEntityException) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException) ProjectState(com.google.gerrit.server.project.ProjectState)

Example 30 with UnprocessableEntityException

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

the class GroupsIT method getGroupsByOwner.

@Test
public void getGroupsByOwner() throws Exception {
    AccountGroup.UUID parent = groupOperations.newGroup().ownerGroupUuid(adminGroupUuid()).create();
    List<AccountGroup.UUID> children = Arrays.asList(groupOperations.newGroup().ownerGroupUuid(parent).create(), groupOperations.newGroup().ownerGroupUuid(parent).create());
    // By UUID
    List<GroupInfo> owned = gApi.groups().list().withOwnedBy(parent.get()).get();
    assertThat(owned.stream().map(g -> AccountGroup.uuid(g.id)).collect(toList())).containsExactlyElementsIn(children);
    // By name
    String parentName = groupOperations.group(parent).get().name();
    owned = gApi.groups().list().withOwnedBy(parentName).get();
    assertThat(owned.stream().map(g -> AccountGroup.uuid(g.id)).collect(toList())).containsExactlyElementsIn(children);
    // By group that does not own any others
    owned = gApi.groups().list().withOwnedBy(owned.get(0).id).get();
    assertThat(owned).isEmpty();
    // By non-existing group
    UnprocessableEntityException thrown = assertThrows(UnprocessableEntityException.class, () -> gApi.groups().list().withOwnedBy("does-not-exist").get());
    assertThat(thrown).hasMessageThat().contains("Group Not Found: does-not-exist");
}
Also used : ResourceNotFoundException(com.google.gerrit.extensions.restapi.ResourceNotFoundException) GroupBackend(com.google.gerrit.server.account.GroupBackend) Arrays(java.util.Arrays) GlobalCapability(com.google.gerrit.common.data.GlobalCapability) TestAccount(com.google.gerrit.acceptance.TestAccount) SystemGroupBackend(com.google.gerrit.server.group.SystemGroupBackend) REGISTERED_USERS(com.google.gerrit.server.group.SystemGroupBackend.REGISTERED_USERS) GroupIndexedListener(com.google.gerrit.extensions.events.GroupIndexedListener) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException) PushOneCommit(com.google.gerrit.acceptance.PushOneCommit) RevWalk(org.eclipse.jgit.revwalk.RevWalk) Config(org.eclipse.jgit.lib.Config) GroupAssert.assertGroupInfo(com.google.gerrit.acceptance.api.group.GroupAssert.assertGroupInfo) Registration(com.google.gerrit.acceptance.ExtensionRegistry.Registration) Map(java.util.Map) ListRequest(com.google.gerrit.extensions.api.groups.Groups.ListRequest) GroupOperations(com.google.gerrit.acceptance.testsuite.group.GroupOperations) TestProjectUpdate.allow(com.google.gerrit.acceptance.testsuite.project.TestProjectUpdate.allow) GitUtil.deleteRef(com.google.gerrit.acceptance.GitUtil.deleteRef) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) RefUpdate(org.eclipse.jgit.lib.RefUpdate) Constants(org.eclipse.jgit.lib.Constants) NoHttpd(com.google.gerrit.acceptance.NoHttpd) RequestScopeOperations(com.google.gerrit.acceptance.testsuite.request.RequestScopeOperations) PersonIdent(org.eclipse.jgit.lib.PersonIdent) UseClockStep(com.google.gerrit.acceptance.UseClockStep) Stream(java.util.stream.Stream) PushResult(org.eclipse.jgit.transport.PushResult) AbstractDaemonTest(com.google.gerrit.acceptance.AbstractDaemonTest) GerritJUnit.assertThrows(com.google.gerrit.testing.GerritJUnit.assertThrows) GitUtil.fetch(com.google.gerrit.acceptance.GitUtil.fetch) GroupInput(com.google.gerrit.extensions.api.groups.GroupInput) ThrowingRunnable(com.google.gerrit.testing.GerritJUnit.ThrowingRunnable) Iterables(com.google.common.collect.Iterables) RevCommit(org.eclipse.jgit.revwalk.RevCommit) UnprocessableEntityException(com.google.gerrit.extensions.restapi.UnprocessableEntityException) AccountOperations(com.google.gerrit.acceptance.testsuite.account.AccountOperations) GroupsSnapshotReader(com.google.gerrit.server.account.GroupsSnapshotReader) StalenessChecker(com.google.gerrit.server.index.group.StalenessChecker) FakeLdapGroupBackend(com.google.gerrit.auth.ldap.FakeLdapGroupBackend) GitUtil(com.google.gerrit.acceptance.GitUtil) ExtensionRegistry(com.google.gerrit.acceptance.ExtensionRegistry) ProjectResetter(com.google.gerrit.acceptance.ProjectResetter) AccountGroup(com.google.gerrit.entities.AccountGroup) MagicBranch(com.google.gerrit.server.util.MagicBranch) TestRepository(org.eclipse.jgit.junit.TestRepository) Sequences(com.google.gerrit.server.notedb.Sequences) IOException(java.io.IOException) Target(java.lang.annotation.Target) Test(org.junit.Test) ANONYMOUS_USERS(com.google.gerrit.server.group.SystemGroupBackend.ANONYMOUS_USERS) RUNTIME(java.lang.annotation.RetentionPolicy.RUNTIME) Correspondence(com.google.common.truth.Correspondence) METHOD(java.lang.annotation.ElementType.METHOD) ReviewInput(com.google.gerrit.extensions.api.changes.ReviewInput) Project(com.google.gerrit.entities.Project) DynamicSet(com.google.gerrit.extensions.registration.DynamicSet) PeriodicGroupIndexer(com.google.gerrit.server.group.PeriodicGroupIndexer) TimeUtil(com.google.gerrit.server.util.time.TimeUtil) GroupDelta(com.google.gerrit.server.group.db.GroupDelta) Repository(org.eclipse.jgit.lib.Repository) AbstractModule(com.google.inject.AbstractModule) Module(com.google.inject.Module) ObjectInserter(org.eclipse.jgit.lib.ObjectInserter) GroupMemberAuditEventInfo(com.google.gerrit.extensions.common.GroupAuditEventInfo.GroupMemberAuditEventInfo) Groups(com.google.gerrit.server.group.db.Groups) Date(java.util.Date) Inject(com.google.inject.Inject) GroupApi(com.google.gerrit.extensions.api.groups.GroupApi) MoreCollectors.onlyElement(com.google.common.collect.MoreCollectors.onlyElement) GroupsUpdate(com.google.gerrit.server.group.db.GroupsUpdate) Collectors.toMap(java.util.stream.Collectors.toMap) AccountInfo(com.google.gerrit.extensions.common.AccountInfo) InternalGroupCreation(com.google.gerrit.server.group.db.InternalGroupCreation) After(org.junit.After) RefNames(com.google.gerrit.entities.RefNames) AuthException(com.google.gerrit.extensions.restapi.AuthException) GroupsConsistencyChecker(com.google.gerrit.server.group.db.GroupsConsistencyChecker) AtomicLongMap(com.google.common.util.concurrent.AtomicLongMap) ImmutableSet(com.google.common.collect.ImmutableSet) Timestamp(java.sql.Timestamp) Collection(java.util.Collection) GroupAuditEventInfo(com.google.gerrit.extensions.common.GroupAuditEventInfo) Account(com.google.gerrit.entities.Account) Instant(java.time.Instant) GroupReference(com.google.gerrit.entities.GroupReference) List(java.util.List) Nullable(com.google.gerrit.common.Nullable) Ref(org.eclipse.jgit.lib.Ref) Url(com.google.gerrit.extensions.restapi.Url) MapSubject.assertThatMap(com.google.gerrit.truth.MapSubject.assertThatMap) UserMemberAuditEventInfo(com.google.gerrit.extensions.common.GroupAuditEventInfo.UserMemberAuditEventInfo) TestProjectUpdate.allowLabel(com.google.gerrit.acceptance.testsuite.project.TestProjectUpdate.allowLabel) InternalGroup(com.google.gerrit.entities.InternalGroup) LabelId(com.google.gerrit.entities.LabelId) InMemoryRepository(org.eclipse.jgit.internal.storage.dfs.InMemoryRepository) Retention(java.lang.annotation.Retention) GroupIndexer(com.google.gerrit.server.index.group.GroupIndexer) AccountAssert.assertAccountInfos(com.google.gerrit.acceptance.rest.account.AccountAssert.assertAccountInfos) GroupInfo(com.google.gerrit.extensions.common.GroupInfo) ImmutableList(com.google.common.collect.ImmutableList) CommitBuilder(org.eclipse.jgit.lib.CommitBuilder) GroupOptionsInfo(com.google.gerrit.extensions.common.GroupOptionsInfo) Truth8.assertThat(com.google.common.truth.Truth8.assertThat) TestProjectUpdate.allowCapability(com.google.gerrit.acceptance.testsuite.project.TestProjectUpdate.allowCapability) Sandboxed(com.google.gerrit.acceptance.Sandboxed) Permission(com.google.gerrit.entities.Permission) Truth.assertThat(com.google.common.truth.Truth.assertThat) GroupIncludeCache(com.google.gerrit.server.account.GroupIncludeCache) ObjectId(org.eclipse.jgit.lib.ObjectId) Collectors.toList(java.util.stream.Collectors.toList) ProjectOperations(com.google.gerrit.acceptance.testsuite.project.ProjectOperations) RemoteRefUpdate(org.eclipse.jgit.transport.RemoteRefUpdate) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) ServerInitiated(com.google.gerrit.server.ServerInitiated) GerritConfig(com.google.gerrit.acceptance.config.GerritConfig) NullAwareCorrespondence(com.google.gerrit.truth.NullAwareCorrespondence) ServiceUserClassifier(com.google.gerrit.server.account.ServiceUserClassifier) UnprocessableEntityException(com.google.gerrit.extensions.restapi.UnprocessableEntityException) AccountGroup(com.google.gerrit.entities.AccountGroup) GroupAssert.assertGroupInfo(com.google.gerrit.acceptance.api.group.GroupAssert.assertGroupInfo) GroupInfo(com.google.gerrit.extensions.common.GroupInfo) AbstractDaemonTest(com.google.gerrit.acceptance.AbstractDaemonTest) Test(org.junit.Test)

Aggregations

UnprocessableEntityException (com.google.gerrit.extensions.restapi.UnprocessableEntityException)78 AuthException (com.google.gerrit.extensions.restapi.AuthException)31 BadRequestException (com.google.gerrit.extensions.restapi.BadRequestException)27 ResourceConflictException (com.google.gerrit.extensions.restapi.ResourceConflictException)25 AbstractDaemonTest (com.google.gerrit.acceptance.AbstractDaemonTest)23 Test (org.junit.Test)23 IOException (java.io.IOException)13 ArrayList (java.util.ArrayList)13 Account (com.google.gerrit.entities.Account)12 Ref (org.eclipse.jgit.lib.Ref)10 PushOneCommit (com.google.gerrit.acceptance.PushOneCommit)9 CurrentUser (com.google.gerrit.server.CurrentUser)9 IdentifiedUser (com.google.gerrit.server.IdentifiedUser)9 PermissionBackend (com.google.gerrit.server.permissions.PermissionBackend)9 ConfigInvalidException (org.eclipse.jgit.errors.ConfigInvalidException)9 ResourceNotFoundException (com.google.gerrit.extensions.restapi.ResourceNotFoundException)8 Map (java.util.Map)8 ObjectId (org.eclipse.jgit.lib.ObjectId)8 RevCommit (org.eclipse.jgit.revwalk.RevCommit)8 Nullable (com.google.gerrit.common.Nullable)7