Search in sources :

Example 61 with BadRequestException

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

the class CreateGroup method apply.

@Override
public Response<GroupInfo> apply(TopLevelResource resource, IdString id, GroupInput input) throws AuthException, BadRequestException, UnprocessableEntityException, ResourceConflictException, IOException, ConfigInvalidException, ResourceNotFoundException, PermissionBackendException {
    String name = id.get();
    if (input == null) {
        input = new GroupInput();
    }
    if (input.name != null && !name.equals(input.name)) {
        throw new BadRequestException("name must match URL");
    }
    AccountGroup.UUID ownerUuid = owner(input);
    CreateGroupArgs args = new CreateGroupArgs();
    args.setGroupName(name);
    args.uuid = Strings.isNullOrEmpty(input.uuid) ? null : AccountGroup.UUID.parse(input.uuid);
    if (args.uuid != null) {
        if (!args.uuid.isInternalGroup()) {
            throw new BadRequestException(String.format("invalid group UUID '%s'", args.uuid.get()));
        }
        if (groupCache.get(args.uuid).isPresent()) {
            throw new ResourceConflictException(String.format("group with UUID '%s' already exists", args.uuid.get()));
        }
    }
    args.groupDescription = Strings.emptyToNull(input.description);
    args.visibleToAll = MoreObjects.firstNonNull(input.visibleToAll, defaultVisibleToAll);
    args.ownerGroupUuid = ownerUuid;
    if (input.members != null && !input.members.isEmpty()) {
        List<Account.Id> members = new ArrayList<>();
        for (String nameOrEmailOrId : input.members) {
            Account a = addMembers.findAccount(nameOrEmailOrId);
            if (!a.isActive()) {
                throw new UnprocessableEntityException(String.format("Account Inactive: %s", nameOrEmailOrId));
            }
            members.add(a.id());
        }
        args.initialMembers = members;
    } else {
        args.initialMembers = ownerUuid == null ? Collections.singleton(self.get().getAccountId()) : Collections.emptySet();
    }
    try {
        groupCreationValidationListeners.runEach(l -> l.validateNewGroup(args), ValidationException.class);
    } catch (ValidationException e) {
        throw new ResourceConflictException(e.getMessage(), e);
    }
    return Response.created(json.format(new InternalGroupDescription(createGroup(args))));
}
Also used : GroupInput(com.google.gerrit.extensions.api.groups.GroupInput) Account(com.google.gerrit.entities.Account) UnprocessableEntityException(com.google.gerrit.extensions.restapi.UnprocessableEntityException) InternalGroupDescription(com.google.gerrit.server.group.InternalGroupDescription) ValidationException(com.google.gerrit.server.validators.ValidationException) ArrayList(java.util.ArrayList) IdString(com.google.gerrit.extensions.restapi.IdString) CreateGroupArgs(com.google.gerrit.server.account.CreateGroupArgs) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) AccountGroup(com.google.gerrit.entities.AccountGroup) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException)

Example 62 with BadRequestException

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

the class CheckMergeability method apply.

@Override
public Response<MergeableInfo> apply(BranchResource resource) throws IOException, BadRequestException, ResourceNotFoundException, ResourceConflictException {
    if (!(submitType.equals(SubmitType.MERGE_ALWAYS) || submitType.equals(SubmitType.MERGE_IF_NECESSARY))) {
        throw new BadRequestException("Submit type: " + submitType + " is not supported");
    }
    MergeableInfo result = new MergeableInfo();
    result.submitType = submitType;
    result.strategy = strategy;
    try (Repository git = gitManager.openRepository(resource.getNameKey());
        RevWalk rw = new RevWalk(git);
        ObjectInserter inserter = new InMemoryInserter(git)) {
        Merger m = MergeUtil.newMerger(inserter, git.getConfig(), strategy);
        Ref destRef = git.getRefDatabase().exactRef(resource.getRef());
        if (destRef == null) {
            throw new ResourceNotFoundException(resource.getRef());
        }
        RevCommit targetCommit = rw.parseCommit(destRef.getObjectId());
        RevCommit sourceCommit = null;
        try {
            sourceCommit = MergeUtil.resolveCommit(git, rw, source);
            if (!commits.canRead(resource.getProjectState(), git, sourceCommit)) {
                throw new BadRequestException("do not have read permission for: " + source);
            }
        } catch (BadRequestException e) {
            // Throw a unified exception for permission denied and unresolvable commits.
            throw new BadRequestException("Error resolving: '" + source + "'. Do not have read permission, or failed to resolve to a commit.", e);
        }
        if (rw.isMergedInto(sourceCommit, targetCommit)) {
            result.mergeable = true;
            result.commitMerged = true;
            result.contentMerged = true;
            return Response.ok(result);
        }
        if (m.merge(false, targetCommit, sourceCommit)) {
            result.mergeable = true;
            result.commitMerged = false;
            result.contentMerged = m.getResultTreeId().equals(targetCommit.getTree());
        } else {
            result.mergeable = false;
            if (m instanceof ResolveMerger) {
                result.conflicts = ((ResolveMerger) m).getUnmergedPaths();
            }
        }
    } catch (InvalidMergeStrategyException e) {
        throw new BadRequestException(e.getMessage());
    } catch (NoMergeBaseException e) {
        // adapted to show the message to the user.
        throw new ResourceConflictException(String.format("Change cannot be merged: %s", e.getMessage()), e);
    }
    return Response.ok(result);
}
Also used : NoMergeBaseException(org.eclipse.jgit.errors.NoMergeBaseException) InMemoryInserter(com.google.gerrit.server.git.InMemoryInserter) RevWalk(org.eclipse.jgit.revwalk.RevWalk) ResolveMerger(org.eclipse.jgit.merge.ResolveMerger) Repository(org.eclipse.jgit.lib.Repository) Ref(org.eclipse.jgit.lib.Ref) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) Merger(org.eclipse.jgit.merge.Merger) ResolveMerger(org.eclipse.jgit.merge.ResolveMerger) ObjectInserter(org.eclipse.jgit.lib.ObjectInserter) MergeableInfo(com.google.gerrit.extensions.common.MergeableInfo) InvalidMergeStrategyException(com.google.gerrit.exceptions.InvalidMergeStrategyException) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException) ResourceNotFoundException(com.google.gerrit.extensions.restapi.ResourceNotFoundException) RevCommit(org.eclipse.jgit.revwalk.RevCommit)

Example 63 with BadRequestException

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

the class LabelDefinitionInputParser method parseValues.

public static List<LabelValue> parseValues(Map<String, String> values) throws BadRequestException {
    List<LabelValue> valueList = new ArrayList<>();
    Set<Short> allValues = new HashSet<>();
    for (Map.Entry<String, String> e : values.entrySet()) {
        short value;
        try {
            value = Shorts.checkedCast(PermissionRule.parseInt(e.getKey().trim()));
        } catch (NumberFormatException ex) {
            throw new BadRequestException("invalid value: " + e.getKey(), ex);
        }
        if (!allValues.add(value)) {
            throw new BadRequestException("duplicate value: " + value);
        }
        String valueDescription = e.getValue().trim();
        if (valueDescription.isEmpty()) {
            throw new BadRequestException("description for value '" + e.getKey() + "' cannot be empty");
        }
        valueList.add(LabelValue.create(value, valueDescription));
    }
    return valueList;
}
Also used : LabelValue(com.google.gerrit.entities.LabelValue) ArrayList(java.util.ArrayList) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException) Map(java.util.Map) HashSet(java.util.HashSet)

Example 64 with BadRequestException

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

the class CreateTag method apply.

@Override
public Response<TagInfo> apply(ProjectResource resource, IdString id, TagInput input) throws RestApiException, IOException, PermissionBackendException, NoSuchProjectException {
    String ref = id.get();
    if (input == null) {
        input = new TagInput();
    }
    if (input.ref != null && !ref.equals(input.ref)) {
        throw new BadRequestException("ref must match URL");
    }
    if (input.revision != null) {
        input.revision = input.revision.trim();
    }
    if (Strings.isNullOrEmpty(input.revision)) {
        input.revision = Constants.HEAD;
    }
    ref = RefUtil.normalizeTagRef(ref);
    PermissionBackend.ForRef perm = permissionBackend.currentUser().project(resource.getNameKey()).ref(ref);
    try (Repository repo = repoManager.openRepository(resource.getNameKey())) {
        ObjectId revid = RefUtil.parseBaseRevision(repo, resource.getNameKey(), input.revision);
        RevWalk rw = RefUtil.verifyConnected(repo, revid);
        // Reachability through tags does not influence a commit's visibility, so no need to check for
        // visibility.
        RevObject object = rw.parseAny(revid);
        rw.reset();
        boolean isAnnotated = Strings.emptyToNull(input.message) != null;
        boolean isSigned = isAnnotated && input.message.contains("-----BEGIN PGP SIGNATURE-----\n");
        if (isSigned) {
            throw new MethodNotAllowedException("Cannot create signed tag \"" + ref + "\"");
        } else if (isAnnotated) {
            if (!check(perm, RefPermission.CREATE_TAG)) {
                throw new AuthException("Cannot create annotated tag \"" + ref + "\"");
            }
        } else {
            perm.check(RefPermission.CREATE);
        }
        if (repo.getRefDatabase().exactRef(ref) != null) {
            throw new ResourceConflictException("tag \"" + ref + "\" already exists");
        }
        try (Git git = new Git(repo)) {
            TagCommand tag = git.tag().setObjectId(object).setName(ref.substring(R_TAGS.length())).setAnnotated(isAnnotated).setSigned(isSigned);
            if (isAnnotated) {
                tag.setMessage(input.message).setTagger(resource.getUser().asIdentifiedUser().newCommitterIdent(TimeUtil.now(), TimeZone.getDefault()));
            }
            Ref result = tag.call();
            tagCache.updateFastForward(resource.getNameKey(), ref, ObjectId.zeroId(), result.getObjectId());
            referenceUpdated.fire(resource.getNameKey(), ref, ObjectId.zeroId(), result.getObjectId(), resource.getUser().asIdentifiedUser().state());
            try (RevWalk w = new RevWalk(repo)) {
                return Response.created(ListTags.createTagInfo(perm, result, w, resource.getProjectState(), links));
            }
        }
    } catch (InvalidRevisionException e) {
        throw new BadRequestException("Invalid base revision", e);
    } catch (GitAPIException e) {
        logger.atSevere().withCause(e).log("Cannot create tag \"%s\"", ref);
        throw new IOException(e);
    }
}
Also used : MethodNotAllowedException(com.google.gerrit.extensions.restapi.MethodNotAllowedException) PermissionBackend(com.google.gerrit.server.permissions.PermissionBackend) ObjectId(org.eclipse.jgit.lib.ObjectId) RevObject(org.eclipse.jgit.revwalk.RevObject) AuthException(com.google.gerrit.extensions.restapi.AuthException) TagInput(com.google.gerrit.extensions.api.projects.TagInput) IdString(com.google.gerrit.extensions.restapi.IdString) IOException(java.io.IOException) RevWalk(org.eclipse.jgit.revwalk.RevWalk) TagCommand(org.eclipse.jgit.api.TagCommand) GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) Repository(org.eclipse.jgit.lib.Repository) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) Ref(org.eclipse.jgit.lib.Ref) Git(org.eclipse.jgit.api.Git) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException) InvalidRevisionException(com.google.gerrit.server.project.RefUtil.InvalidRevisionException)

Example 65 with BadRequestException

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

the class CreateProject method apply.

@Override
public Response<ProjectInfo> apply(TopLevelResource resource, IdString id, ProjectInput input) throws RestApiException, IOException, ConfigInvalidException, PermissionBackendException {
    String name = id.get();
    if (input == null) {
        input = new ProjectInput();
    }
    if (input.name != null && !name.equals(input.name)) {
        throw new BadRequestException("name must match URL");
    }
    CreateProjectArgs args = new CreateProjectArgs();
    args.setProjectName(ProjectUtil.sanitizeProjectName(name));
    String parentName = MoreObjects.firstNonNull(Strings.emptyToNull(input.parent), allProjects.get());
    args.newParent = projectsCollection.get().parse(parentName, false).getNameKey();
    if (args.newParent.equals(allUsers)) {
        throw new ResourceConflictException(String.format("Cannot inherit from '%s' project", allUsers.get()));
    }
    args.createEmptyCommit = input.createEmptyCommit;
    args.permissionsOnly = input.permissionsOnly;
    args.projectDescription = Strings.emptyToNull(input.description);
    args.submitType = input.submitType;
    args.branch = normalizeBranchNames(input.branches);
    if (input.owners == null || input.owners.isEmpty()) {
        args.ownerIds = new ArrayList<>(projectOwnerGroups.create(args.getProject()).get());
    } else {
        args.ownerIds = Lists.newArrayListWithCapacity(input.owners.size());
        for (String owner : input.owners) {
            args.ownerIds.add(groupResolver.get().parse(owner).getGroupUUID());
        }
    }
    args.contributorAgreements = MoreObjects.firstNonNull(input.useContributorAgreements, InheritableBoolean.INHERIT);
    args.signedOffBy = MoreObjects.firstNonNull(input.useSignedOffBy, InheritableBoolean.INHERIT);
    args.contentMerge = input.submitType == SubmitType.FAST_FORWARD_ONLY ? InheritableBoolean.FALSE : MoreObjects.firstNonNull(input.useContentMerge, InheritableBoolean.INHERIT);
    args.newChangeForAllNotInTarget = MoreObjects.firstNonNull(input.createNewChangeForAllNotInTarget, InheritableBoolean.INHERIT);
    args.changeIdRequired = MoreObjects.firstNonNull(input.requireChangeId, InheritableBoolean.INHERIT);
    args.rejectEmptyCommit = MoreObjects.firstNonNull(input.rejectEmptyCommit, InheritableBoolean.INHERIT);
    args.enableSignedPush = MoreObjects.firstNonNull(input.enableSignedPush, InheritableBoolean.INHERIT);
    args.requireSignedPush = MoreObjects.firstNonNull(input.requireSignedPush, InheritableBoolean.INHERIT);
    try {
        args.maxObjectSizeLimit = ProjectConfig.validMaxObjectSizeLimit(input.maxObjectSizeLimit);
    } catch (ConfigInvalidException e) {
        throw new BadRequestException(e.getMessage());
    }
    Lock nameLock = lockManager.call(lockManager -> lockManager.getLock(args.getProject()));
    nameLock.lock();
    try {
        try {
            projectCreationValidationListeners.runEach(l -> l.validateNewProject(args), ValidationException.class);
        } catch (ValidationException e) {
            throw new ResourceConflictException(e.getMessage(), e);
        }
        ProjectState projectState = projectCreator.createProject(args);
        requireNonNull(projectState, () -> String.format("failed to create project %s", args.getProject().get()));
        if (input.pluginConfigValues != null) {
            ConfigInput in = new ConfigInput();
            in.pluginConfigValues = input.pluginConfigValues;
            in.description = args.projectDescription;
            putConfig.get().apply(projectState, in);
        }
        return Response.created(json.format(projectState));
    } finally {
        nameLock.unlock();
    }
}
Also used : ProjectInput(com.google.gerrit.extensions.api.projects.ProjectInput) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) ValidationException(com.google.gerrit.server.validators.ValidationException) ConfigInvalidException(org.eclipse.jgit.errors.ConfigInvalidException) ConfigInput(com.google.gerrit.extensions.api.projects.ConfigInput) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException) ProjectState(com.google.gerrit.server.project.ProjectState) IdString(com.google.gerrit.extensions.restapi.IdString) CreateProjectArgs(com.google.gerrit.server.project.CreateProjectArgs) Lock(java.util.concurrent.locks.Lock)

Aggregations

BadRequestException (com.google.gerrit.extensions.restapi.BadRequestException)310 Test (org.junit.Test)154 AbstractDaemonTest (com.google.gerrit.acceptance.AbstractDaemonTest)146 ResourceConflictException (com.google.gerrit.extensions.restapi.ResourceConflictException)56 PushOneCommit (com.google.gerrit.acceptance.PushOneCommit)51 AuthException (com.google.gerrit.extensions.restapi.AuthException)46 Repository (org.eclipse.jgit.lib.Repository)30 IdString (com.google.gerrit.extensions.restapi.IdString)29 UnprocessableEntityException (com.google.gerrit.extensions.restapi.UnprocessableEntityException)29 LabelDefinitionInput (com.google.gerrit.extensions.common.LabelDefinitionInput)28 ArrayList (java.util.ArrayList)28 RevCommit (org.eclipse.jgit.revwalk.RevCommit)28 MethodNotAllowedException (com.google.gerrit.extensions.restapi.MethodNotAllowedException)27 ResourceNotFoundException (com.google.gerrit.extensions.restapi.ResourceNotFoundException)27 IOException (java.io.IOException)25 BatchUpdate (com.google.gerrit.server.update.BatchUpdate)24 RevWalk (org.eclipse.jgit.revwalk.RevWalk)22 ObjectId (org.eclipse.jgit.lib.ObjectId)20 Map (java.util.Map)19 Change (com.google.gerrit.entities.Change)18