Search in sources :

Example 16 with MethodNotAllowedException

use of com.google.gerrit.extensions.restapi.MethodNotAllowedException 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 17 with MethodNotAllowedException

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

the class AgreementsIT method agreementsDisabledList.

@Test
public void agreementsDisabledList() throws Exception {
    assume().that(isContributorAgreementsEnabled()).isFalse();
    MethodNotAllowedException thrown = assertThrows(MethodNotAllowedException.class, () -> gApi.accounts().self().listAgreements());
    assertThat(thrown).hasMessageThat().contains("contributor agreements disabled");
}
Also used : MethodNotAllowedException(com.google.gerrit.extensions.restapi.MethodNotAllowedException) Test(org.junit.Test) AbstractDaemonTest(com.google.gerrit.acceptance.AbstractDaemonTest)

Example 18 with MethodNotAllowedException

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

the class GetArchiveIT method zipFormatIsDisabled.

@Test
public void zipFormatIsDisabled() throws Exception {
    MethodNotAllowedException ex = assertThrows(MethodNotAllowedException.class, () -> gApi.changes().id(changeId).current().getArchive(ArchiveFormat.ZIP));
    assertThat(ex).hasMessageThat().isEqualTo("zip format is disabled");
}
Also used : MethodNotAllowedException(com.google.gerrit.extensions.restapi.MethodNotAllowedException) Test(org.junit.Test) AbstractDaemonTest(com.google.gerrit.acceptance.AbstractDaemonTest)

Example 19 with MethodNotAllowedException

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

the class RevisionReviewers method parse.

@Override
public ReviewerResource parse(RevisionResource rsrc, IdString id) throws ResourceNotFoundException, AuthException, MethodNotAllowedException, IOException, ConfigInvalidException {
    if (!rsrc.isCurrent()) {
        throw new MethodNotAllowedException("Cannot access on non-current patch set");
    }
    Address address = Address.tryParse(id.get());
    Account.Id accountId = null;
    try {
        accountId = accounts.parse(TopLevelResource.INSTANCE, id).getUser().getAccountId();
    } catch (ResourceNotFoundException e) {
        if (address == null) {
            throw e;
        }
    }
    Collection<Account.Id> reviewers = approvalsUtil.getReviewers(rsrc.getNotes()).all();
    // See if the id exists as a reviewer for this change
    if (reviewers.contains(accountId)) {
        return resourceFactory.create(rsrc, accountId);
    }
    // See if the address exists as a reviewer on the change
    if (address != null && rsrc.getNotes().getReviewersByEmail().all().contains(address)) {
        return new ReviewerResource(rsrc, address);
    }
    throw new ResourceNotFoundException(id);
}
Also used : Account(com.google.gerrit.entities.Account) ReviewerResource(com.google.gerrit.server.change.ReviewerResource) MethodNotAllowedException(com.google.gerrit.extensions.restapi.MethodNotAllowedException) Address(com.google.gerrit.entities.Address) ResourceNotFoundException(com.google.gerrit.extensions.restapi.ResourceNotFoundException)

Example 20 with MethodNotAllowedException

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

the class MergeUtil method createCherryPickFromCommit.

public CodeReviewCommit createCherryPickFromCommit(ObjectInserter inserter, Config repoConfig, RevCommit mergeTip, RevCommit originalCommit, PersonIdent cherryPickCommitterIdent, String commitMsg, CodeReviewRevWalk rw, int parentIndex, boolean ignoreIdenticalTree, boolean allowConflicts) throws IOException, MergeIdenticalTreeException, MergeConflictException, MethodNotAllowedException, InvalidMergeStrategyException {
    ThreeWayMerger m = newThreeWayMerger(inserter, repoConfig);
    m.setBase(originalCommit.getParent(parentIndex));
    DirCache dc = DirCache.newInCore();
    if (allowConflicts && m instanceof ResolveMerger) {
        // The DirCache must be set on ResolveMerger before calling
        // ResolveMerger#merge(AnyObjectId...) otherwise the entries in DirCache don't get populated.
        ((ResolveMerger) m).setDirCache(dc);
    }
    ObjectId tree;
    ImmutableSet<String> filesWithGitConflicts;
    if (m.merge(mergeTip, originalCommit)) {
        filesWithGitConflicts = null;
        tree = m.getResultTreeId();
        if (tree.equals(mergeTip.getTree()) && !ignoreIdenticalTree) {
            throw new MergeIdenticalTreeException("identical tree");
        }
    } else {
        if (!allowConflicts) {
            throw new MergeConflictException(String.format("merge conflict while merging commits %s and %s", mergeTip.toObjectId(), originalCommit.toObjectId()));
        }
        if (!useContentMerge) {
            // conflict markers.
            throw new MethodNotAllowedException("Cherry-pick with allow conflicts requires that content merge is enabled.");
        }
        // For merging with conflict markers we need a ResolveMerger, double-check that we have one.
        checkState(m instanceof ResolveMerger, "allow conflicts is not supported");
        Map<String, MergeResult<? extends Sequence>> mergeResults = ((ResolveMerger) m).getMergeResults();
        filesWithGitConflicts = mergeResults.entrySet().stream().filter(e -> e.getValue().containsConflicts()).map(Map.Entry::getKey).collect(toImmutableSet());
        tree = mergeWithConflicts(rw, inserter, dc, "HEAD", mergeTip, "CHANGE", originalCommit, mergeResults);
    }
    CommitBuilder cherryPickCommit = new CommitBuilder();
    cherryPickCommit.setTreeId(tree);
    cherryPickCommit.setParentId(mergeTip);
    cherryPickCommit.setAuthor(originalCommit.getAuthorIdent());
    cherryPickCommit.setCommitter(cherryPickCommitterIdent);
    cherryPickCommit.setMessage(commitMsg);
    matchAuthorToCommitterDate(project, cherryPickCommit);
    CodeReviewCommit commit = rw.parseCommit(inserter.insert(cherryPickCommit));
    commit.setFilesWithGitConflicts(filesWithGitConflicts);
    return commit;
}
Also used : ResourceNotFoundException(com.google.gerrit.extensions.restapi.ResourceNotFoundException) RevisionSyntaxException(org.eclipse.jgit.errors.RevisionSyntaxException) Comparator.naturalOrder(java.util.Comparator.naturalOrder) ObjectInserter(org.eclipse.jgit.lib.ObjectInserter) DynamicItem(com.google.gerrit.extensions.registration.DynamicItem) MissingObjectException(org.eclipse.jgit.errors.MissingObjectException) ThreeWayMergeStrategy(org.eclipse.jgit.merge.ThreeWayMergeStrategy) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException) Merger(org.eclipse.jgit.merge.Merger) Assisted(com.google.inject.assistedinject.Assisted) FooterKey(org.eclipse.jgit.revwalk.FooterKey) RevWalk(org.eclipse.jgit.revwalk.RevWalk) PatchSetApproval(com.google.gerrit.entities.PatchSetApproval) Config(org.eclipse.jgit.lib.Config) Preconditions.checkArgument(com.google.common.base.Preconditions.checkArgument) InvalidMergeStrategyException(com.google.gerrit.exceptions.InvalidMergeStrategyException) MergeConflictException(com.google.gerrit.extensions.restapi.MergeConflictException) FooterLine(org.eclipse.jgit.revwalk.FooterLine) LabelType(com.google.gerrit.entities.LabelType) Map(java.util.Map) AssistedInject(com.google.inject.assistedinject.AssistedInject) UrlFormatter(com.google.gerrit.server.config.UrlFormatter) ImmutableSortedSet.toImmutableSortedSet(com.google.common.collect.ImmutableSortedSet.toImmutableSortedSet) ImmutableSet(com.google.common.collect.ImmutableSet) Sequence(org.eclipse.jgit.diff.Sequence) GerritServerConfig(com.google.gerrit.server.config.GerritServerConfig) Collection(java.util.Collection) LargeObjectException(org.eclipse.jgit.errors.LargeObjectException) Account(com.google.gerrit.entities.Account) Set(java.util.Set) RevSort(org.eclipse.jgit.revwalk.RevSort) Constants(org.eclipse.jgit.lib.Constants) MethodNotAllowedException(com.google.gerrit.extensions.restapi.MethodNotAllowedException) Collectors.joining(java.util.stream.Collectors.joining) Sets(com.google.common.collect.Sets) BranchNameKey(com.google.gerrit.entities.BranchNameKey) ApprovalsUtil(com.google.gerrit.server.approval.ApprovalsUtil) MergeIdenticalTreeException(com.google.gerrit.server.submit.MergeIdenticalTreeException) MergeStrategy(org.eclipse.jgit.merge.MergeStrategy) Preconditions.checkState(com.google.common.base.Preconditions.checkState) Objects(java.util.Objects) PersonIdent(org.eclipse.jgit.lib.PersonIdent) List(java.util.List) Nullable(com.google.gerrit.common.Nullable) BooleanProjectConfig(com.google.gerrit.entities.BooleanProjectConfig) DirCache(org.eclipse.jgit.dircache.DirCache) Optional(java.util.Optional) FluentLogger(com.google.common.flogger.FluentLogger) AmbiguousObjectException(org.eclipse.jgit.errors.AmbiguousObjectException) Iterables(com.google.common.collect.Iterables) LabelId(com.google.gerrit.entities.LabelId) CodeReviewRevWalk(com.google.gerrit.server.git.CodeReviewCommit.CodeReviewRevWalk) RevCommit(org.eclipse.jgit.revwalk.RevCommit) CommitMergeStatus(com.google.gerrit.server.submit.CommitMergeStatus) IncorrectObjectTypeException(org.eclipse.jgit.errors.IncorrectObjectTypeException) RevFlag(org.eclipse.jgit.revwalk.RevFlag) DirCacheEntry(org.eclipse.jgit.dircache.DirCacheEntry) HashMap(java.util.HashMap) DirCacheBuilder(org.eclipse.jgit.dircache.DirCacheBuilder) MergeBaseFailureReason(org.eclipse.jgit.errors.NoMergeBaseException.MergeBaseFailureReason) ChangeAlreadyMergedException(com.google.gerrit.server.submit.ChangeAlreadyMergedException) ArrayList(java.util.ArrayList) Strings(com.google.common.base.Strings) ImmutableList(com.google.common.collect.ImmutableList) CommitBuilder(org.eclipse.jgit.lib.CommitBuilder) ResolveMerger(org.eclipse.jgit.merge.ResolveMerger) ImmutableSet.toImmutableSet(com.google.common.collect.ImmutableSet.toImmutableSet) MergeWithConflictsNotSupportedException(com.google.gerrit.exceptions.MergeWithConflictsNotSupportedException) Change(com.google.gerrit.entities.Change) PatchSet(com.google.gerrit.entities.PatchSet) ChangeUtil(com.google.gerrit.server.ChangeUtil) NoMergeBaseException(org.eclipse.jgit.errors.NoMergeBaseException) ImmutableSortedSet(com.google.common.collect.ImmutableSortedSet) TemporaryBuffer(org.eclipse.jgit.util.TemporaryBuffer) Iterator(java.util.Iterator) ObjectIds.abbreviateName(com.google.gerrit.git.ObjectIds.abbreviateName) UTF_8(java.nio.charset.StandardCharsets.UTF_8) StorageException(com.google.gerrit.exceptions.StorageException) ProjectState(com.google.gerrit.server.project.ProjectState) ChangeNotes(com.google.gerrit.server.notedb.ChangeNotes) IOException(java.io.IOException) ThreeWayMerger(org.eclipse.jgit.merge.ThreeWayMerger) ObjectId(org.eclipse.jgit.lib.ObjectId) MergeResult(org.eclipse.jgit.merge.MergeResult) MergeSorter(com.google.gerrit.server.submit.MergeSorter) MergeFormatter(org.eclipse.jgit.merge.MergeFormatter) IdentifiedUser(com.google.gerrit.server.IdentifiedUser) FooterConstants(com.google.gerrit.common.FooterConstants) Collections(java.util.Collections) Repository(org.eclipse.jgit.lib.Repository) InputStream(java.io.InputStream) MethodNotAllowedException(com.google.gerrit.extensions.restapi.MethodNotAllowedException) ObjectId(org.eclipse.jgit.lib.ObjectId) MergeResult(org.eclipse.jgit.merge.MergeResult) CommitBuilder(org.eclipse.jgit.lib.CommitBuilder) ThreeWayMerger(org.eclipse.jgit.merge.ThreeWayMerger) Sequence(org.eclipse.jgit.diff.Sequence) ResolveMerger(org.eclipse.jgit.merge.ResolveMerger) MergeIdenticalTreeException(com.google.gerrit.server.submit.MergeIdenticalTreeException) DirCache(org.eclipse.jgit.dircache.DirCache) MergeConflictException(com.google.gerrit.extensions.restapi.MergeConflictException) DirCacheEntry(org.eclipse.jgit.dircache.DirCacheEntry)

Aggregations

MethodNotAllowedException (com.google.gerrit.extensions.restapi.MethodNotAllowedException)66 BadRequestException (com.google.gerrit.extensions.restapi.BadRequestException)27 AuthException (com.google.gerrit.extensions.restapi.AuthException)23 AbstractDaemonTest (com.google.gerrit.acceptance.AbstractDaemonTest)16 ResourceNotFoundException (com.google.gerrit.extensions.restapi.ResourceNotFoundException)16 Test (org.junit.Test)16 ResourceConflictException (com.google.gerrit.extensions.restapi.ResourceConflictException)15 AccountGroup (com.google.gerrit.reviewdb.client.AccountGroup)11 IOException (java.io.IOException)11 ArrayList (java.util.ArrayList)11 IdentifiedUser (com.google.gerrit.server.IdentifiedUser)10 Account (com.google.gerrit.reviewdb.client.Account)9 UnprocessableEntityException (com.google.gerrit.extensions.restapi.UnprocessableEntityException)8 PermissionBackend (com.google.gerrit.server.permissions.PermissionBackend)7 BatchUpdate (com.google.gerrit.server.update.BatchUpdate)7 Account (com.google.gerrit.entities.Account)6 GroupInfo (com.google.gerrit.extensions.common.GroupInfo)5 Response (com.google.gerrit.extensions.restapi.Response)5 Change (com.google.gerrit.reviewdb.client.Change)5 CurrentUser (com.google.gerrit.server.CurrentUser)5