Search in sources :

Example 21 with MethodNotAllowedException

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

the class QueryProjects method apply.

public List<ProjectInfo> apply() throws BadRequestException, MethodNotAllowedException {
    if (Strings.isNullOrEmpty(query)) {
        throw new BadRequestException("missing query field");
    }
    ProjectIndex searchIndex = indexes.getSearchIndex();
    if (searchIndex == null) {
        throw new MethodNotAllowedException("no project index");
    }
    ProjectQueryProcessor queryProcessor = queryProcessorProvider.get();
    if (start != 0) {
        queryProcessor.setStart(start);
    }
    if (limit != 0) {
        queryProcessor.setUserProvidedLimit(limit);
    }
    try {
        QueryResult<ProjectData> result = queryProcessor.query(queryBuilder.parse(query));
        List<ProjectData> pds = result.entities();
        ArrayList<ProjectInfo> projectInfos = Lists.newArrayListWithCapacity(pds.size());
        for (ProjectData pd : pds) {
            projectInfos.add(json.format(pd.getProject()));
        }
        return projectInfos;
    } catch (QueryParseException e) {
        throw new BadRequestException(e.getMessage());
    }
}
Also used : MethodNotAllowedException(com.google.gerrit.extensions.restapi.MethodNotAllowedException) ProjectQueryProcessor(com.google.gerrit.server.query.project.ProjectQueryProcessor) ProjectInfo(com.google.gerrit.extensions.common.ProjectInfo) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException) ProjectIndex(com.google.gerrit.index.project.ProjectIndex) ProjectData(com.google.gerrit.index.project.ProjectData) QueryParseException(com.google.gerrit.index.query.QueryParseException)

Example 22 with MethodNotAllowedException

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

the class DeleteEmail method apply.

public Response<?> apply(IdentifiedUser user, String email) throws ResourceNotFoundException, ResourceConflictException, MethodNotAllowedException, IOException, ConfigInvalidException {
    Account.Id accountId = user.getAccountId();
    if (realm.accountBelongsToRealm(externalIds.byAccount(accountId)) && !realm.allowsEdit(AccountFieldName.REGISTER_NEW_EMAIL)) {
        throw new MethodNotAllowedException("realm does not allow deleting emails");
    }
    Set<ExternalId> extIds = externalIds.byAccount(accountId).stream().filter(e -> email.equals(e.email())).collect(toSet());
    if (extIds.isEmpty()) {
        throw new ResourceNotFoundException(email);
    }
    if (realm.accountBelongsToRealm(extIds)) {
        String errorMsg = String.format("Cannot remove e-mail '%s' which is directly associated with %s authentication", email, authType);
        throw new ResourceConflictException(errorMsg);
    }
    try {
        accountManager.unlink(user.getAccountId(), extIds.stream().map(ExternalId::key).collect(toSet()));
    } catch (AccountException e) {
        throw new ResourceConflictException(e.getMessage());
    }
    return Response.none();
}
Also used : ResourceNotFoundException(com.google.gerrit.extensions.restapi.ResourceNotFoundException) AuthType(com.google.gerrit.extensions.client.AuthType) PermissionBackendException(com.google.gerrit.server.permissions.PermissionBackendException) ConfigInvalidException(org.eclipse.jgit.errors.ConfigInvalidException) Inject(com.google.inject.Inject) Input(com.google.gerrit.extensions.common.Input) Response(com.google.gerrit.extensions.restapi.Response) PermissionBackend(com.google.gerrit.server.permissions.PermissionBackend) RestModifyView(com.google.gerrit.extensions.restapi.RestModifyView) AuthException(com.google.gerrit.extensions.restapi.AuthException) Collectors.toSet(java.util.stream.Collectors.toSet) GlobalPermission(com.google.gerrit.server.permissions.GlobalPermission) CurrentUser(com.google.gerrit.server.CurrentUser) AccountResource(com.google.gerrit.server.account.AccountResource) Account(com.google.gerrit.entities.Account) Set(java.util.Set) AccountFieldName(com.google.gerrit.extensions.client.AccountFieldName) IOException(java.io.IOException) MethodNotAllowedException(com.google.gerrit.extensions.restapi.MethodNotAllowedException) AccountException(com.google.gerrit.server.account.AccountException) ExternalIds(com.google.gerrit.server.account.externalids.ExternalIds) Provider(com.google.inject.Provider) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) IdentifiedUser(com.google.gerrit.server.IdentifiedUser) ExternalId(com.google.gerrit.server.account.externalids.ExternalId) AuthConfig(com.google.gerrit.server.config.AuthConfig) Realm(com.google.gerrit.server.account.Realm) AccountManager(com.google.gerrit.server.account.AccountManager) Singleton(com.google.inject.Singleton) Account(com.google.gerrit.entities.Account) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) MethodNotAllowedException(com.google.gerrit.extensions.restapi.MethodNotAllowedException) AccountException(com.google.gerrit.server.account.AccountException) ExternalId(com.google.gerrit.server.account.externalids.ExternalId) ResourceNotFoundException(com.google.gerrit.extensions.restapi.ResourceNotFoundException)

Example 23 with MethodNotAllowedException

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

the class QueryAccounts method apply.

@Override
public Response<List<AccountInfo>> apply(TopLevelResource rsrc) throws RestApiException, PermissionBackendException {
    if (Strings.isNullOrEmpty(query)) {
        throw new BadRequestException("missing query field");
    }
    if (suggest && (!suggestConfig || query.length() < suggestFrom)) {
        return Response.ok(Collections.emptyList());
    }
    Set<FillOptions> fillOptions = EnumSet.of(FillOptions.ID);
    if (options.contains(ListAccountsOption.DETAILS)) {
        fillOptions.addAll(AccountLoader.DETAILED_OPTIONS);
    }
    boolean modifyAccountCapabilityChecked = false;
    if (options.contains(ListAccountsOption.ALL_EMAILS)) {
        permissionBackend.currentUser().check(GlobalPermission.MODIFY_ACCOUNT);
        modifyAccountCapabilityChecked = true;
        fillOptions.add(FillOptions.EMAIL);
        fillOptions.add(FillOptions.SECONDARY_EMAILS);
    }
    if (suggest) {
        fillOptions.addAll(AccountLoader.DETAILED_OPTIONS);
        fillOptions.add(FillOptions.EMAIL);
        if (modifyAccountCapabilityChecked) {
            fillOptions.add(FillOptions.SECONDARY_EMAILS);
        } else {
            if (permissionBackend.currentUser().test(GlobalPermission.MODIFY_ACCOUNT)) {
                fillOptions.add(FillOptions.SECONDARY_EMAILS);
            }
        }
    }
    accountLoader = accountLoaderFactory.create(fillOptions);
    AccountQueryProcessor queryProcessor = queryProcessorProvider.get();
    if (queryProcessor.isDisabled()) {
        throw new MethodNotAllowedException("query disabled");
    }
    if (limit != null) {
        queryProcessor.setUserProvidedLimit(limit);
    }
    if (start != null) {
        queryProcessor.setStart(start);
    }
    Map<Account.Id, AccountInfo> matches = new LinkedHashMap<>();
    try {
        Predicate<AccountState> queryPred;
        if (suggest) {
            queryPred = queryBuilder.defaultQuery(query);
            queryProcessor.setUserProvidedLimit(suggestLimit);
        } else {
            queryPred = queryBuilder.parse(query);
        }
        if (!AccountPredicates.hasActive(queryPred)) {
            // if neither 'is:active' nor 'is:inactive' appears in the query only
            // active accounts should be queried
            queryPred = AccountPredicates.andActive(queryPred);
        }
        QueryResult<AccountState> result = queryProcessor.query(queryPred);
        for (AccountState accountState : result.entities()) {
            Account.Id id = accountState.account().id();
            matches.put(id, accountLoader.get(id));
        }
        accountLoader.fill();
        List<AccountInfo> sorted = AccountInfoComparator.ORDER_NULLS_LAST.sortedCopy(matches.values());
        if (!sorted.isEmpty() && result.more()) {
            sorted.get(sorted.size() - 1)._moreAccounts = true;
        }
        return Response.ok(sorted);
    } catch (QueryParseException e) {
        if (suggest) {
            return Response.ok(ImmutableList.of());
        }
        throw new BadRequestException(e.getMessage());
    }
}
Also used : Account(com.google.gerrit.entities.Account) MethodNotAllowedException(com.google.gerrit.extensions.restapi.MethodNotAllowedException) AccountQueryProcessor(com.google.gerrit.server.query.account.AccountQueryProcessor) AccountState(com.google.gerrit.server.account.AccountState) LinkedHashMap(java.util.LinkedHashMap) QueryParseException(com.google.gerrit.index.query.QueryParseException) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException) FillOptions(com.google.gerrit.server.account.AccountDirectory.FillOptions) AccountInfo(com.google.gerrit.extensions.common.AccountInfo)

Example 24 with MethodNotAllowedException

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

the class CreateChange method checkAndSanitizeChangeInput.

/**
 * Checks and sanitizes the user input, e.g. check whether the input is legal; clean the input so
 * that it meets the requirement for creating a change; set a field based on the global configs,
 * etc.
 *
 * @param input the {@code ChangeInput} from the request. Note this method modify the {@code
 *     ChangeInput} object so that it can be reused directly by follow-up code.
 * @param me the user who sent the current request to create a change.
 * @throws BadRequestException if the input is not legal.
 */
private void checkAndSanitizeChangeInput(ChangeInput input, IdentifiedUser me) throws RestApiException, PermissionBackendException, IOException {
    if (Strings.isNullOrEmpty(input.branch)) {
        throw new BadRequestException("branch must be non-empty");
    }
    input.branch = RefNames.fullName(input.branch);
    if (!isBranchAllowed(input.branch)) {
        throw new BadRequestException("Cannot create a change on ref " + input.branch + ". Gerrit internal refs and refs/tags/* are not allowed.");
    }
    String subject = Strings.nullToEmpty(input.subject);
    subject = subject.replaceAll("(?m)^#.*$\n?", "").trim();
    if (subject.isEmpty()) {
        throw new BadRequestException("commit message must be non-empty");
    }
    input.subject = subject;
    Optional<String> changeId = getChangeIdFromMessage(input.subject);
    if (changeId.isPresent()) {
        if (!queryProvider.get().setLimit(1).byBranchKey(BranchNameKey.create(input.project, input.branch), Change.key(changeId.get())).isEmpty()) {
            throw new ResourceConflictException(String.format("A change with Change-Id %s already exists for this branch.", changeId.get()));
        }
    }
    if (input.topic != null) {
        input.topic = Strings.emptyToNull(input.topic.trim());
    }
    if (input.status != null && input.status != ChangeStatus.NEW) {
        throw new BadRequestException("unsupported change status");
    }
    if (input.baseChange != null && input.baseCommit != null) {
        throw new BadRequestException("only provide one of base_change or base_commit");
    }
    ProjectResource projectResource = projectsCollection.parse(input.project);
    // Checks whether the change to be created should be a private change.
    boolean privateByDefault = projectResource.getProjectState().is(BooleanProjectConfig.PRIVATE_BY_DEFAULT);
    boolean isPrivate = input.isPrivate == null ? privateByDefault : input.isPrivate;
    if (isPrivate && disablePrivateChanges) {
        throw new MethodNotAllowedException("private changes are disabled");
    }
    input.isPrivate = isPrivate;
    ProjectState projectState = projectResource.getProjectState();
    if (input.workInProgress == null) {
        if (projectState.is(BooleanProjectConfig.WORK_IN_PROGRESS_BY_DEFAULT)) {
            input.workInProgress = true;
        } else {
            input.workInProgress = firstNonNull(me.state().generalPreferences().workInProgressByDefault, false);
        }
    }
    if (input.merge != null) {
        if (!(submitType.equals(SubmitType.MERGE_ALWAYS) || submitType.equals(SubmitType.MERGE_IF_NECESSARY))) {
            throw new BadRequestException("Submit type: " + submitType + " is not supported");
        }
    }
    if (input.author != null && (Strings.isNullOrEmpty(input.author.email) || Strings.isNullOrEmpty(input.author.name))) {
        throw new BadRequestException("Author must specify name and email");
    }
}
Also used : ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) MethodNotAllowedException(com.google.gerrit.extensions.restapi.MethodNotAllowedException) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException) ProjectResource(com.google.gerrit.server.project.ProjectResource) ProjectState(com.google.gerrit.server.project.ProjectState)

Example 25 with MethodNotAllowedException

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

the class DeleteVote method apply.

@Override
public Response<Object> apply(VoteResource rsrc, DeleteVoteInput input) throws RestApiException, UpdateException, IOException, ConfigInvalidException {
    if (input == null) {
        input = new DeleteVoteInput();
    }
    if (input.label != null && !rsrc.getLabel().equals(input.label)) {
        throw new BadRequestException("label must match URL");
    }
    if (input.notify == null) {
        input.notify = NotifyHandling.ALL;
    }
    ReviewerResource r = rsrc.getReviewer();
    Change change = r.getChange();
    if (r.getRevisionResource() != null && !r.getRevisionResource().isCurrent()) {
        throw new MethodNotAllowedException("Cannot delete vote on non-current patch set");
    }
    try (BatchUpdate bu = updateFactory.create(change.getProject(), r.getChangeResource().getUser(), TimeUtil.now())) {
        bu.setNotify(notifyResolver.resolve(firstNonNull(input.notify, NotifyHandling.ALL), input.notifyDetails));
        bu.addOp(change.getId(), new Op(projectCache.get(r.getChange().getProject()).orElseThrow(illegalState(r.getChange().getProject())), r.getReviewerUser().state(), rsrc.getLabel(), input));
        if (!input.ignoreAutomaticAttentionSetRules && !r.getReviewerUser().getAccountId().equals(currentUserProvider.get().getAccountId())) {
            bu.addOp(change.getId(), attentionSetOpFactory.create(r.getReviewerUser().getAccountId(), /* reason= */
            "Their vote was deleted", /* notify= */
            false));
        }
        if (input.ignoreAutomaticAttentionSetRules) {
            bu.addOp(change.getId(), new AttentionSetUnchangedOp());
        }
        bu.execute();
    }
    return Response.none();
}
Also used : DeleteVoteInput(com.google.gerrit.extensions.api.changes.DeleteVoteInput) BatchUpdateOp(com.google.gerrit.server.update.BatchUpdateOp) AddToAttentionSetOp(com.google.gerrit.server.change.AddToAttentionSetOp) AttentionSetUnchangedOp(com.google.gerrit.server.change.AttentionSetUnchangedOp) ReviewerResource(com.google.gerrit.server.change.ReviewerResource) MethodNotAllowedException(com.google.gerrit.extensions.restapi.MethodNotAllowedException) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException) AttentionSetUnchangedOp(com.google.gerrit.server.change.AttentionSetUnchangedOp) Change(com.google.gerrit.entities.Change) BatchUpdate(com.google.gerrit.server.update.BatchUpdate)

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