Search in sources :

Example 36 with BadRequestException

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

the class RestApiServlet method parseRequest.

private Object parseRequest(HttpServletRequest req, Type type) throws IOException, BadRequestException, SecurityException, IllegalArgumentException, NoSuchMethodException, IllegalAccessException, InstantiationException, InvocationTargetException, MethodNotAllowedException {
    // 400). Consume the request body for all but raw input request types here.
    if (isType(JSON_TYPE, req.getContentType())) {
        try (BufferedReader br = req.getReader();
            JsonReader json = new JsonReader(br)) {
            try {
                json.setLenient(true);
                JsonToken first;
                try {
                    first = json.peek();
                } catch (EOFException e) {
                    throw new BadRequestException("Expected JSON object");
                }
                if (first == JsonToken.STRING) {
                    return parseString(json.nextString(), type);
                }
                return OutputFormat.JSON.newGson().fromJson(json, type);
            } finally {
                // Reader.close won't consume the rest of the input. Explicitly consume the request body.
                br.skip(Long.MAX_VALUE);
            }
        }
    } else if (rawInputRequest(req, type)) {
        return parseRawInput(req, type);
    } else if ("DELETE".equals(req.getMethod()) && hasNoBody(req)) {
        return null;
    } else if (hasNoBody(req)) {
        return createInstance(type);
    } else if (isType("text/plain", req.getContentType())) {
        try (BufferedReader br = req.getReader()) {
            char[] tmp = new char[256];
            StringBuilder sb = new StringBuilder();
            int n;
            while (0 < (n = br.read(tmp))) {
                sb.append(tmp, 0, n);
            }
            return parseString(sb.toString(), type);
        }
    } else if ("POST".equals(req.getMethod()) && isType(FORM_TYPE, req.getContentType())) {
        return OutputFormat.JSON.newGson().fromJson(ParameterParser.formToJson(req), type);
    } else {
        throw new BadRequestException("Expected Content-Type: " + JSON_TYPE);
    }
}
Also used : BufferedReader(java.io.BufferedReader) EOFException(java.io.EOFException) JsonReader(com.google.gson.stream.JsonReader) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException) JsonToken(com.google.gson.stream.JsonToken)

Example 37 with BadRequestException

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

the class PostWatchedProjects method asMap.

private Map<ProjectWatchKey, Set<NotifyType>> asMap(List<ProjectWatchInfo> input) throws BadRequestException, UnprocessableEntityException, IOException, PermissionBackendException {
    Map<ProjectWatchKey, Set<NotifyType>> m = new HashMap<>();
    for (ProjectWatchInfo info : input) {
        if (info.project == null) {
            throw new BadRequestException("project name must be specified");
        }
        ProjectWatchKey key = ProjectWatchKey.create(projectsCollection.parse(info.project).getNameKey(), info.filter);
        if (m.containsKey(key)) {
            throw new BadRequestException("duplicate entry for project " + format(info.project, info.filter));
        }
        Set<NotifyType> notifyValues = EnumSet.noneOf(NotifyType.class);
        if (toBoolean(info.notifyAbandonedChanges)) {
            notifyValues.add(NotifyType.ABANDONED_CHANGES);
        }
        if (toBoolean(info.notifyAllComments)) {
            notifyValues.add(NotifyType.ALL_COMMENTS);
        }
        if (toBoolean(info.notifyNewChanges)) {
            notifyValues.add(NotifyType.NEW_CHANGES);
        }
        if (toBoolean(info.notifyNewPatchSets)) {
            notifyValues.add(NotifyType.NEW_PATCHSETS);
        }
        if (toBoolean(info.notifySubmittedChanges)) {
            notifyValues.add(NotifyType.SUBMITTED_CHANGES);
        }
        m.put(key, notifyValues);
    }
    return m;
}
Also used : NotifyType(com.google.gerrit.server.account.WatchConfig.NotifyType) Set(java.util.Set) EnumSet(java.util.EnumSet) ProjectWatchInfo(com.google.gerrit.extensions.client.ProjectWatchInfo) HashMap(java.util.HashMap) ProjectWatchKey(com.google.gerrit.server.account.WatchConfig.ProjectWatchKey) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException)

Example 38 with BadRequestException

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

the class PutAgreement method apply.

@Override
public Response<String> apply(AccountResource resource, AgreementInput input) throws IOException, OrmException, RestApiException {
    if (!agreementsEnabled) {
        throw new MethodNotAllowedException("contributor agreements disabled");
    }
    if (self.get() != resource.getUser()) {
        throw new AuthException("not allowed to enter contributor agreement");
    }
    String agreementName = Strings.nullToEmpty(input.name);
    ContributorAgreement ca = projectCache.getAllProjects().getConfig().getContributorAgreement(agreementName);
    if (ca == null) {
        throw new UnprocessableEntityException("contributor agreement not found");
    }
    if (ca.getAutoVerify() == null) {
        throw new BadRequestException("cannot enter a non-autoVerify agreement");
    }
    AccountGroup.UUID uuid = ca.getAutoVerify().getUUID();
    if (uuid == null) {
        throw new ResourceConflictException("autoverify group uuid not found");
    }
    AccountGroup group = groupCache.get(uuid);
    if (group == null) {
        throw new ResourceConflictException("autoverify group not found");
    }
    Account account = self.get().getAccount();
    addMembers.addMembers(group.getId(), ImmutableList.of(account.getId()));
    agreementSignup.fire(account, agreementName);
    return Response.ok(agreementName);
}
Also used : UnprocessableEntityException(com.google.gerrit.extensions.restapi.UnprocessableEntityException) Account(com.google.gerrit.reviewdb.client.Account) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) MethodNotAllowedException(com.google.gerrit.extensions.restapi.MethodNotAllowedException) AccountGroup(com.google.gerrit.reviewdb.client.AccountGroup) ContributorAgreement(com.google.gerrit.common.data.ContributorAgreement) AuthException(com.google.gerrit.extensions.restapi.AuthException) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException)

Example 39 with BadRequestException

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

the class QueryAccounts method apply.

@Override
public List<AccountInfo> apply(TopLevelResource rsrc) throws OrmException, BadRequestException, MethodNotAllowedException {
    if (Strings.isNullOrEmpty(query)) {
        throw new BadRequestException("missing query field");
    }
    if (suggest && (!suggestConfig || query.length() < suggestFrom)) {
        return Collections.emptyList();
    }
    Set<FillOptions> fillOptions = EnumSet.of(FillOptions.ID);
    if (options.contains(ListAccountsOption.DETAILS)) {
        fillOptions.addAll(AccountLoader.DETAILED_OPTIONS);
    }
    if (options.contains(ListAccountsOption.ALL_EMAILS)) {
        fillOptions.add(FillOptions.EMAIL);
        fillOptions.add(FillOptions.SECONDARY_EMAILS);
    }
    if (suggest) {
        fillOptions.addAll(AccountLoader.DETAILED_OPTIONS);
        fillOptions.add(FillOptions.EMAIL);
        fillOptions.add(FillOptions.SECONDARY_EMAILS);
    }
    accountLoader = accountLoaderFactory.create(fillOptions);
    if (queryProcessor.isDisabled()) {
        throw new MethodNotAllowedException("query disabled");
    }
    if (start != null) {
        queryProcessor.setStart(start);
    }
    Map<Account.Id, AccountInfo> matches = new LinkedHashMap<>();
    try {
        Predicate<AccountState> queryPred;
        if (suggest) {
            queryPred = queryBuilder.defaultQuery(query);
            queryProcessor.setLimit(suggestLimit);
        } else {
            queryPred = queryBuilder.parse(query);
        }
        QueryResult<AccountState> result = queryProcessor.query(queryPred);
        for (AccountState accountState : result.entities()) {
            Account.Id id = accountState.getAccount().getId();
            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 sorted;
    } catch (QueryParseException e) {
        if (suggest) {
            return ImmutableList.of();
        }
        throw new BadRequestException(e.getMessage());
    }
}
Also used : Account(com.google.gerrit.reviewdb.client.Account) MethodNotAllowedException(com.google.gerrit.extensions.restapi.MethodNotAllowedException) LinkedHashMap(java.util.LinkedHashMap) QueryParseException(com.google.gerrit.server.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 40 with BadRequestException

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

the class AddSshKey method apply.

public Response<SshKeyInfo> apply(IdentifiedUser user, Input input) throws BadRequestException, IOException, ConfigInvalidException {
    if (input == null) {
        input = new Input();
    }
    if (input.raw == null) {
        throw new BadRequestException("SSH public key missing");
    }
    final RawInput rawKey = input.raw;
    String sshPublicKey = new ByteSource() {

        @Override
        public InputStream openStream() throws IOException {
            return rawKey.getInputStream();
        }
    }.asCharSource(UTF_8).read();
    try {
        AccountSshKey sshKey = authorizedKeys.addKey(user.getAccountId(), sshPublicKey);
        try {
            addKeyFactory.create(user, sshKey).send();
        } catch (EmailException e) {
            log.error("Cannot send SSH key added message to " + user.getAccount().getPreferredEmail(), e);
        }
        sshKeyCache.evict(user.getUserName());
        return Response.<SshKeyInfo>created(GetSshKeys.newSshKeyInfo(sshKey));
    } catch (InvalidSshKeyException e) {
        throw new BadRequestException(e.getMessage());
    }
}
Also used : RawInput(com.google.gerrit.extensions.restapi.RawInput) Input(com.google.gerrit.server.account.AddSshKey.Input) InvalidSshKeyException(com.google.gerrit.common.errors.InvalidSshKeyException) SshKeyInfo(com.google.gerrit.extensions.common.SshKeyInfo) AccountSshKey(com.google.gerrit.reviewdb.client.AccountSshKey) RawInput(com.google.gerrit.extensions.restapi.RawInput) EmailException(com.google.gerrit.common.errors.EmailException) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException) ByteSource(com.google.common.io.ByteSource)

Aggregations

BadRequestException (com.google.gerrit.extensions.restapi.BadRequestException)65 AuthException (com.google.gerrit.extensions.restapi.AuthException)22 ResourceConflictException (com.google.gerrit.extensions.restapi.ResourceConflictException)21 MethodNotAllowedException (com.google.gerrit.extensions.restapi.MethodNotAllowedException)15 ResourceNotFoundException (com.google.gerrit.extensions.restapi.ResourceNotFoundException)13 Repository (org.eclipse.jgit.lib.Repository)13 Project (com.google.gerrit.reviewdb.client.Project)12 UnprocessableEntityException (com.google.gerrit.extensions.restapi.UnprocessableEntityException)11 ArrayList (java.util.ArrayList)11 IOException (java.io.IOException)10 RevCommit (org.eclipse.jgit.revwalk.RevCommit)10 Account (com.google.gerrit.reviewdb.client.Account)9 Change (com.google.gerrit.reviewdb.client.Change)8 IdentifiedUser (com.google.gerrit.server.IdentifiedUser)8 BatchUpdate (com.google.gerrit.server.update.BatchUpdate)8 Map (java.util.Map)8 AccountGroup (com.google.gerrit.reviewdb.client.AccountGroup)7 ConfigInvalidException (org.eclipse.jgit.errors.ConfigInvalidException)7 RevWalk (org.eclipse.jgit.revwalk.RevWalk)7 RestApiException (com.google.gerrit.extensions.restapi.RestApiException)6