Search in sources :

Example 1 with Response

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

the class PostReview method apply.

public Response<ReviewResult> apply(BatchUpdate.Factory updateFactory, RevisionResource revision, ReviewInput input, Timestamp ts) throws RestApiException, UpdateException, OrmException, IOException, PermissionBackendException {
    // Respect timestamp, but truncate at change created-on time.
    ts = Ordering.natural().max(ts, revision.getChange().getCreatedOn());
    if (revision.getEdit().isPresent()) {
        throw new ResourceConflictException("cannot post review on edit");
    }
    if (input.onBehalfOf != null) {
        revision = onBehalfOf(revision, input);
    } else if (input.drafts == null) {
        input.drafts = DraftHandling.DELETE;
    }
    if (input.labels != null) {
        checkLabels(revision, input.strictLabels, input.labels);
    }
    if (input.comments != null) {
        cleanUpComments(input.comments);
        checkComments(revision, input.comments);
    }
    if (input.robotComments != null) {
        if (!migration.readChanges()) {
            throw new MethodNotAllowedException("robot comments not supported");
        }
        checkRobotComments(revision, input.robotComments);
    }
    if (input.notify == null) {
        log.warn("notify = null; assuming notify = NONE");
        input.notify = NotifyHandling.NONE;
    }
    ListMultimap<RecipientType, Account.Id> accountsToNotify = notifyUtil.resolveAccounts(input.notifyDetails);
    Map<String, AddReviewerResult> reviewerJsonResults = null;
    List<PostReviewers.Addition> reviewerResults = Lists.newArrayList();
    boolean hasError = false;
    boolean confirm = false;
    if (input.reviewers != null) {
        reviewerJsonResults = Maps.newHashMap();
        for (AddReviewerInput reviewerInput : input.reviewers) {
            // Prevent notifications because setting reviewers is batched.
            reviewerInput.notify = NotifyHandling.NONE;
            PostReviewers.Addition result = postReviewers.prepareApplication(revision.getChangeResource(), reviewerInput, true);
            reviewerJsonResults.put(reviewerInput.reviewer, result.result);
            if (result.result.error != null) {
                hasError = true;
                continue;
            }
            if (result.result.confirm != null) {
                confirm = true;
                continue;
            }
            reviewerResults.add(result);
        }
    }
    ReviewResult output = new ReviewResult();
    output.reviewers = reviewerJsonResults;
    if (hasError || confirm) {
        return Response.withStatusCode(SC_BAD_REQUEST, output);
    }
    output.labels = input.labels;
    try (BatchUpdate bu = updateFactory.create(db.get(), revision.getChange().getProject(), revision.getUser(), ts)) {
        Account.Id id = revision.getUser().getAccountId();
        boolean ccOrReviewer = false;
        if (input.labels != null && !input.labels.isEmpty()) {
            ccOrReviewer = input.labels.values().stream().filter(v -> v != 0).findFirst().isPresent();
        }
        if (!ccOrReviewer) {
            // Check if user was already CCed or reviewing prior to this review.
            ReviewerSet currentReviewers = approvalsUtil.getReviewers(db.get(), revision.getChangeResource().getNotes());
            ccOrReviewer = currentReviewers.all().contains(id);
        }
        // themselves as a reviewer or to the CC list.
        for (PostReviewers.Addition reviewerResult : reviewerResults) {
            bu.addOp(revision.getChange().getId(), reviewerResult.op);
            if (!ccOrReviewer && reviewerResult.result.reviewers != null) {
                for (ReviewerInfo reviewerInfo : reviewerResult.result.reviewers) {
                    if (Objects.equals(id.get(), reviewerInfo._accountId)) {
                        ccOrReviewer = true;
                        break;
                    }
                }
            }
            if (!ccOrReviewer && reviewerResult.result.ccs != null) {
                for (AccountInfo accountInfo : reviewerResult.result.ccs) {
                    if (Objects.equals(id.get(), accountInfo._accountId)) {
                        ccOrReviewer = true;
                        break;
                    }
                }
            }
        }
        if (!ccOrReviewer) {
            // User posting this review isn't currently in the reviewer or CC list,
            // isn't being explicitly added, and isn't voting on any label.
            // Automatically CC them on this change so they receive replies.
            PostReviewers.Addition selfAddition = postReviewers.ccCurrentUser(revision.getUser(), revision);
            bu.addOp(revision.getChange().getId(), selfAddition.op);
        }
        bu.addOp(revision.getChange().getId(), new Op(revision.getPatchSet().getId(), input, accountsToNotify));
        bu.execute();
        for (PostReviewers.Addition reviewerResult : reviewerResults) {
            reviewerResult.gatherResults();
        }
        emailReviewers(revision.getChange(), reviewerResults, input.notify, accountsToNotify);
    }
    return Response.ok(output);
}
Also used : ON_BEHALF_OF(com.google.gerrit.server.permissions.LabelPermission.ForUser.ON_BEHALF_OF) ListMultimap(com.google.common.collect.ListMultimap) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException) PermissionBackend(com.google.gerrit.server.permissions.PermissionBackend) ReviewResult(com.google.gerrit.extensions.api.changes.ReviewResult) PatchSetApproval(com.google.gerrit.reviewdb.client.PatchSetApproval) ReviewerSet(com.google.gerrit.server.ReviewerSet) Config(org.eclipse.jgit.lib.Config) Map(java.util.Map) RetryHelper(com.google.gerrit.server.update.RetryHelper) DraftHandling(com.google.gerrit.extensions.api.changes.ReviewInput.DraftHandling) Side(com.google.gerrit.extensions.client.Side) GerritServerConfig(com.google.gerrit.server.config.GerritServerConfig) ChangeMessage(com.google.gerrit.reviewdb.client.ChangeMessage) Set(java.util.Set) Collectors.joining(java.util.stream.Collectors.joining) StandardCharsets(java.nio.charset.StandardCharsets) NotifyHandling(com.google.gerrit.extensions.api.changes.NotifyHandling) CommentAdded(com.google.gerrit.server.extensions.events.CommentAdded) AutoValue(com.google.auto.value.AutoValue) LabelId(com.google.gerrit.reviewdb.client.LabelId) NotesMigration(com.google.gerrit.server.notedb.NotesMigration) ChangeMessagesUtil(com.google.gerrit.server.ChangeMessagesUtil) Singleton(com.google.inject.Singleton) ReviewDb(com.google.gerrit.reviewdb.server.ReviewDb) PermissionBackendException(com.google.gerrit.server.permissions.PermissionBackendException) Change(com.google.gerrit.reviewdb.client.Change) UnprocessableEntityException(com.google.gerrit.extensions.restapi.UnprocessableEntityException) Collectors.groupingBy(java.util.stream.Collectors.groupingBy) CommentsUtil(com.google.gerrit.server.CommentsUtil) Response(com.google.gerrit.extensions.restapi.Response) ArrayList(java.util.ArrayList) Strings(com.google.common.base.Strings) Lists(com.google.common.collect.Lists) RestApiException(com.google.gerrit.extensions.restapi.RestApiException) REVIEWER(com.google.gerrit.server.notedb.ReviewerStateInternal.REVIEWER) HashCode(com.google.common.hash.HashCode) PatchListCache(com.google.gerrit.server.patch.PatchListCache) TimeUtil(com.google.gerrit.common.TimeUtil) MoreObjects(com.google.common.base.MoreObjects) ChangeNotes(com.google.gerrit.server.notedb.ChangeNotes) IOException(java.io.IOException) CommentsUtil.setCommentRevId(com.google.gerrit.server.CommentsUtil.setCommentRevId) RobotCommentInput(com.google.gerrit.extensions.api.changes.ReviewInput.RobotCommentInput) ChangeUpdate(com.google.gerrit.server.notedb.ChangeUpdate) IdentifiedUser(com.google.gerrit.server.IdentifiedUser) ReviewInput(com.google.gerrit.extensions.api.changes.ReviewInput) PatchSet(com.google.gerrit.reviewdb.client.PatchSet) LabelVote(com.google.gerrit.server.util.LabelVote) SC_BAD_REQUEST(javax.servlet.http.HttpServletResponse.SC_BAD_REQUEST) ChangeControl(com.google.gerrit.server.project.ChangeControl) AddReviewerResult(com.google.gerrit.extensions.api.changes.AddReviewerResult) OrmException(com.google.gwtorm.server.OrmException) Inject(com.google.inject.Inject) LoggerFactory(org.slf4j.LoggerFactory) UpdateException(com.google.gerrit.server.update.UpdateException) Comment(com.google.gerrit.reviewdb.client.Comment) BatchUpdate(com.google.gerrit.server.update.BatchUpdate) AccountInfo(com.google.gerrit.extensions.common.AccountInfo) Gson(com.google.gson.Gson) AuthException(com.google.gerrit.extensions.restapi.AuthException) Context(com.google.gerrit.server.update.Context) RetryingRestModifyView(com.google.gerrit.server.update.RetryingRestModifyView) Collectors.toSet(java.util.stream.Collectors.toSet) ReviewerInfo(com.google.gerrit.extensions.api.changes.ReviewerInfo) Timestamp(java.sql.Timestamp) Collection(java.util.Collection) LabelType(com.google.gerrit.common.data.LabelType) MethodNotAllowedException(com.google.gerrit.extensions.restapi.MethodNotAllowedException) Preconditions.checkState(com.google.common.base.Preconditions.checkState) Objects(java.util.Objects) ChangeData(com.google.gerrit.server.query.change.ChangeData) List(java.util.List) Nullable(com.google.gerrit.common.Nullable) Status(com.google.gerrit.reviewdb.client.PatchLineComment.Status) AccountsCollection(com.google.gerrit.server.account.AccountsCollection) LabelTypes(com.google.gerrit.common.data.LabelTypes) AddReviewerInput(com.google.gerrit.extensions.api.changes.AddReviewerInput) FixSuggestionInfo(com.google.gerrit.extensions.common.FixSuggestionInfo) Url(com.google.gerrit.extensions.restapi.Url) BatchUpdateOp(com.google.gerrit.server.update.BatchUpdateOp) RobotComment(com.google.gerrit.reviewdb.client.RobotComment) LabelPermission(com.google.gerrit.server.permissions.LabelPermission) FixSuggestion(com.google.gerrit.reviewdb.client.FixSuggestion) ChangePermission(com.google.gerrit.server.permissions.ChangePermission) Hashing(com.google.common.hash.Hashing) ReviewerState(com.google.gerrit.extensions.client.ReviewerState) Patch(com.google.gerrit.reviewdb.client.Patch) HashMap(java.util.HashMap) OptionalInt(java.util.OptionalInt) HashSet(java.util.HashSet) CommentInput(com.google.gerrit.extensions.api.changes.ReviewInput.CommentInput) Range(com.google.gerrit.extensions.client.Comment.Range) Account(com.google.gerrit.reviewdb.client.Account) ChangeUtil(com.google.gerrit.server.ChangeUtil) OutputFormat(com.google.gerrit.server.OutputFormat) ChangeContext(com.google.gerrit.server.update.ChangeContext) FixReplacementInfo(com.google.gerrit.extensions.common.FixReplacementInfo) CurrentUser(com.google.gerrit.server.CurrentUser) Logger(org.slf4j.Logger) Iterator(java.util.Iterator) UTF_8(java.nio.charset.StandardCharsets.UTF_8) Preconditions.checkNotNull(com.google.common.base.Preconditions.checkNotNull) FixReplacement(com.google.gerrit.reviewdb.client.FixReplacement) Maps(com.google.common.collect.Maps) ApprovalsUtil(com.google.gerrit.server.ApprovalsUtil) Collectors.toList(java.util.stream.Collectors.toList) Address(com.google.gerrit.server.mail.Address) Provider(com.google.inject.Provider) Ordering(com.google.common.collect.Ordering) RecipientType(com.google.gerrit.extensions.api.changes.RecipientType) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) PatchSetUtil(com.google.gerrit.server.PatchSetUtil) Collections(java.util.Collections) Account(com.google.gerrit.reviewdb.client.Account) BatchUpdateOp(com.google.gerrit.server.update.BatchUpdateOp) MethodNotAllowedException(com.google.gerrit.extensions.restapi.MethodNotAllowedException) ReviewResult(com.google.gerrit.extensions.api.changes.ReviewResult) RecipientType(com.google.gerrit.extensions.api.changes.RecipientType) BatchUpdate(com.google.gerrit.server.update.BatchUpdate) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) AddReviewerResult(com.google.gerrit.extensions.api.changes.AddReviewerResult) ReviewerSet(com.google.gerrit.server.ReviewerSet) LabelId(com.google.gerrit.reviewdb.client.LabelId) CommentsUtil.setCommentRevId(com.google.gerrit.server.CommentsUtil.setCommentRevId) AccountInfo(com.google.gerrit.extensions.common.AccountInfo) AddReviewerInput(com.google.gerrit.extensions.api.changes.AddReviewerInput) ReviewerInfo(com.google.gerrit.extensions.api.changes.ReviewerInfo)

Example 2 with Response

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

the class DeleteExternalIds method apply.

@Override
public Response<?> apply(AccountResource resource, List<String> extIds) throws RestApiException, IOException, OrmException, ConfigInvalidException {
    if (self.get() != resource.getUser() && !self.get().getCapabilities().canAccessDatabase()) {
        throw new AuthException("not allowed to delete external IDs");
    }
    if (extIds == null || extIds.size() == 0) {
        throw new BadRequestException("external IDs are required");
    }
    Map<ExternalId.Key, ExternalId> externalIdMap = externalIds.byAccount(resource.getUser().getAccountId()).stream().collect(toMap(i -> i.key(), i -> i));
    List<ExternalId> toDelete = new ArrayList<>();
    ExternalId.Key last = resource.getUser().getLastLoginExternalIdKey();
    for (String externalIdStr : extIds) {
        ExternalId id = externalIdMap.get(ExternalId.Key.parse(externalIdStr));
        if (id == null) {
            throw new UnprocessableEntityException(String.format("External id %s does not exist", externalIdStr));
        }
        if ((!id.isScheme(SCHEME_USERNAME)) && ((last == null) || (!last.get().equals(id.key().get())))) {
            toDelete.add(id);
        } else {
            throw new ResourceConflictException(String.format("External id %s cannot be deleted", externalIdStr));
        }
    }
    try {
        for (ExternalId extId : toDelete) {
            AuthRequest authRequest = new AuthRequest(extId.key());
            authRequest.setEmailAddress(extId.email());
            accountManager.unlink(extId.accountId(), authRequest);
        }
    } catch (AccountException e) {
        throw new ResourceConflictException(e.getMessage());
    }
    return Response.none();
}
Also used : CurrentUser(com.google.gerrit.server.CurrentUser) OrmException(com.google.gwtorm.server.OrmException) ConfigInvalidException(org.eclipse.jgit.errors.ConfigInvalidException) UnprocessableEntityException(com.google.gerrit.extensions.restapi.UnprocessableEntityException) Inject(com.google.inject.Inject) IOException(java.io.IOException) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException) Response(com.google.gerrit.extensions.restapi.Response) ExternalIds(com.google.gerrit.server.account.externalids.ExternalIds) ArrayList(java.util.ArrayList) RestModifyView(com.google.gerrit.extensions.restapi.RestModifyView) Provider(com.google.inject.Provider) List(java.util.List) Collectors.toMap(java.util.stream.Collectors.toMap) SCHEME_USERNAME(com.google.gerrit.server.account.externalids.ExternalId.SCHEME_USERNAME) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) Map(java.util.Map) AuthException(com.google.gerrit.extensions.restapi.AuthException) ExternalId(com.google.gerrit.server.account.externalids.ExternalId) RestApiException(com.google.gerrit.extensions.restapi.RestApiException) UnprocessableEntityException(com.google.gerrit.extensions.restapi.UnprocessableEntityException) ExternalId(com.google.gerrit.server.account.externalids.ExternalId) ArrayList(java.util.ArrayList) AuthException(com.google.gerrit.extensions.restapi.AuthException) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException)

Example 3 with Response

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

the class RestApiServlet method service.

@Override
protected final void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    final long startNanos = System.nanoTime();
    long auditStartTs = TimeUtil.nowMs();
    res.setHeader("Content-Disposition", "attachment");
    res.setHeader("X-Content-Type-Options", "nosniff");
    int status = SC_OK;
    long responseBytes = -1;
    Object result = null;
    ListMultimap<String, String> params = MultimapBuilder.hashKeys().arrayListValues().build();
    ListMultimap<String, String> config = MultimapBuilder.hashKeys().arrayListValues().build();
    Object inputRequestBody = null;
    RestResource rsrc = TopLevelResource.INSTANCE;
    ViewData viewData = null;
    try {
        if (isCorsPreflight(req)) {
            doCorsPreflight(req, res);
            return;
        }
        checkCors(req, res);
        checkUserSession(req);
        ParameterParser.splitQueryString(req.getQueryString(), config, params);
        List<IdString> path = splitPath(req);
        RestCollection<RestResource, RestResource> rc = members.get();
        globals.permissionBackend.user(globals.currentUser).checkAny(GlobalPermission.fromAnnotation(rc.getClass()));
        viewData = new ViewData(null, null);
        if (path.isEmpty()) {
            if (rc instanceof NeedsParams) {
                ((NeedsParams) rc).setParams(params);
            }
            if (isRead(req)) {
                viewData = new ViewData(null, rc.list());
            } else if (rc instanceof AcceptsPost && "POST".equals(req.getMethod())) {
                @SuppressWarnings("unchecked") AcceptsPost<RestResource> ac = (AcceptsPost<RestResource>) rc;
                viewData = new ViewData(null, ac.post(rsrc));
            } else {
                throw new MethodNotAllowedException();
            }
        } else {
            IdString id = path.remove(0);
            try {
                rsrc = rc.parse(rsrc, id);
                if (path.isEmpty()) {
                    checkPreconditions(req);
                }
            } catch (ResourceNotFoundException e) {
                if (rc instanceof AcceptsCreate && path.isEmpty() && ("POST".equals(req.getMethod()) || "PUT".equals(req.getMethod()))) {
                    @SuppressWarnings("unchecked") AcceptsCreate<RestResource> ac = (AcceptsCreate<RestResource>) rc;
                    viewData = new ViewData(null, ac.create(rsrc, id));
                    status = SC_CREATED;
                } else {
                    throw e;
                }
            }
            if (viewData.view == null) {
                viewData = view(rsrc, rc, req.getMethod(), path);
            }
        }
        checkRequiresCapability(viewData);
        while (viewData.view instanceof RestCollection<?, ?>) {
            @SuppressWarnings("unchecked") RestCollection<RestResource, RestResource> c = (RestCollection<RestResource, RestResource>) viewData.view;
            if (path.isEmpty()) {
                if (isRead(req)) {
                    viewData = new ViewData(null, c.list());
                } else if (c instanceof AcceptsPost && "POST".equals(req.getMethod())) {
                    @SuppressWarnings("unchecked") AcceptsPost<RestResource> ac = (AcceptsPost<RestResource>) c;
                    viewData = new ViewData(null, ac.post(rsrc));
                } else if (c instanceof AcceptsDelete && "DELETE".equals(req.getMethod())) {
                    @SuppressWarnings("unchecked") AcceptsDelete<RestResource> ac = (AcceptsDelete<RestResource>) c;
                    viewData = new ViewData(null, ac.delete(rsrc, null));
                } else {
                    throw new MethodNotAllowedException();
                }
                break;
            }
            IdString id = path.remove(0);
            try {
                rsrc = c.parse(rsrc, id);
                checkPreconditions(req);
                viewData = new ViewData(null, null);
            } catch (ResourceNotFoundException e) {
                if (c instanceof AcceptsCreate && path.isEmpty() && ("POST".equals(req.getMethod()) || "PUT".equals(req.getMethod()))) {
                    @SuppressWarnings("unchecked") AcceptsCreate<RestResource> ac = (AcceptsCreate<RestResource>) c;
                    viewData = new ViewData(viewData.pluginName, ac.create(rsrc, id));
                    status = SC_CREATED;
                } else if (c instanceof AcceptsDelete && path.isEmpty() && "DELETE".equals(req.getMethod())) {
                    @SuppressWarnings("unchecked") AcceptsDelete<RestResource> ac = (AcceptsDelete<RestResource>) c;
                    viewData = new ViewData(viewData.pluginName, ac.delete(rsrc, id));
                    status = SC_NO_CONTENT;
                } else {
                    throw e;
                }
            }
            if (viewData.view == null) {
                viewData = view(rsrc, c, req.getMethod(), path);
            }
            checkRequiresCapability(viewData);
        }
        if (notModified(req, rsrc, viewData.view)) {
            res.sendError(SC_NOT_MODIFIED);
            return;
        }
        if (!globals.paramParser.get().parse(viewData.view, params, req, res)) {
            return;
        }
        if (viewData.view instanceof RestReadView<?> && isRead(req)) {
            result = ((RestReadView<RestResource>) viewData.view).apply(rsrc);
        } else if (viewData.view instanceof RestModifyView<?, ?>) {
            @SuppressWarnings("unchecked") RestModifyView<RestResource, Object> m = (RestModifyView<RestResource, Object>) viewData.view;
            Type type = inputType(m);
            inputRequestBody = parseRequest(req, type);
            result = m.apply(rsrc, inputRequestBody);
            consumeRawInputRequestBody(req, type);
        } else {
            throw new ResourceNotFoundException();
        }
        if (result instanceof Response) {
            @SuppressWarnings("rawtypes") Response<?> r = (Response) result;
            status = r.statusCode();
            configureCaching(req, res, rsrc, viewData.view, r.caching());
        } else if (result instanceof Response.Redirect) {
            CacheHeaders.setNotCacheable(res);
            res.sendRedirect(((Response.Redirect) result).location());
            return;
        } else if (result instanceof Response.Accepted) {
            CacheHeaders.setNotCacheable(res);
            res.setStatus(SC_ACCEPTED);
            res.setHeader(HttpHeaders.LOCATION, ((Response.Accepted) result).location());
            return;
        } else {
            CacheHeaders.setNotCacheable(res);
        }
        res.setStatus(status);
        if (result != Response.none()) {
            result = Response.unwrap(result);
            if (result instanceof BinaryResult) {
                responseBytes = replyBinaryResult(req, res, (BinaryResult) result);
            } else {
                responseBytes = replyJson(req, res, config, result);
            }
        }
    } catch (MalformedJsonException e) {
        responseBytes = replyError(req, res, status = SC_BAD_REQUEST, "Invalid " + JSON_TYPE + " in request", e);
    } catch (JsonParseException e) {
        responseBytes = replyError(req, res, status = SC_BAD_REQUEST, "Invalid " + JSON_TYPE + " in request", e);
    } catch (BadRequestException e) {
        responseBytes = replyError(req, res, status = SC_BAD_REQUEST, messageOr(e, "Bad Request"), e.caching(), e);
    } catch (AuthException e) {
        responseBytes = replyError(req, res, status = SC_FORBIDDEN, messageOr(e, "Forbidden"), e.caching(), e);
    } catch (AmbiguousViewException e) {
        responseBytes = replyError(req, res, status = SC_NOT_FOUND, messageOr(e, "Ambiguous"), e);
    } catch (ResourceNotFoundException e) {
        responseBytes = replyError(req, res, status = SC_NOT_FOUND, messageOr(e, "Not Found"), e.caching(), e);
    } catch (MethodNotAllowedException e) {
        responseBytes = replyError(req, res, status = SC_METHOD_NOT_ALLOWED, messageOr(e, "Method Not Allowed"), e.caching(), e);
    } catch (ResourceConflictException e) {
        responseBytes = replyError(req, res, status = SC_CONFLICT, messageOr(e, "Conflict"), e.caching(), e);
    } catch (PreconditionFailedException e) {
        responseBytes = replyError(req, res, status = SC_PRECONDITION_FAILED, messageOr(e, "Precondition Failed"), e.caching(), e);
    } catch (UnprocessableEntityException e) {
        responseBytes = replyError(req, res, status = SC_UNPROCESSABLE_ENTITY, messageOr(e, "Unprocessable Entity"), e.caching(), e);
    } catch (NotImplementedException e) {
        responseBytes = replyError(req, res, status = SC_NOT_IMPLEMENTED, messageOr(e, "Not Implemented"), e);
    } catch (Exception e) {
        status = SC_INTERNAL_SERVER_ERROR;
        responseBytes = handleException(e, req, res);
    } finally {
        String metric = viewData != null && viewData.view != null ? globals.metrics.view(viewData) : "_unknown";
        globals.metrics.count.increment(metric);
        if (status >= SC_BAD_REQUEST) {
            globals.metrics.errorCount.increment(metric, status);
        }
        if (responseBytes != -1) {
            globals.metrics.responseBytes.record(metric, responseBytes);
        }
        globals.metrics.serverLatency.record(metric, System.nanoTime() - startNanos, TimeUnit.NANOSECONDS);
        globals.auditService.dispatch(new ExtendedHttpAuditEvent(globals.webSession.get().getSessionId(), globals.currentUser.get(), req, auditStartTs, params, inputRequestBody, status, result, rsrc, viewData == null ? null : viewData.view));
    }
}
Also used : RestCollection(com.google.gerrit.extensions.restapi.RestCollection) RestResource(com.google.gerrit.extensions.restapi.RestResource) AcceptsDelete(com.google.gerrit.extensions.restapi.AcceptsDelete) NotImplementedException(com.google.gerrit.extensions.restapi.NotImplementedException) AuthException(com.google.gerrit.extensions.restapi.AuthException) ExtendedHttpAuditEvent(com.google.gerrit.audit.ExtendedHttpAuditEvent) IdString(com.google.gerrit.extensions.restapi.IdString) JsonParseException(com.google.gson.JsonParseException) PreconditionFailedException(com.google.gerrit.extensions.restapi.PreconditionFailedException) ResourceNotFoundException(com.google.gerrit.extensions.restapi.ResourceNotFoundException) MalformedJsonException(com.google.gson.stream.MalformedJsonException) UnprocessableEntityException(com.google.gerrit.extensions.restapi.UnprocessableEntityException) RestModifyView(com.google.gerrit.extensions.restapi.RestModifyView) MethodNotAllowedException(com.google.gerrit.extensions.restapi.MethodNotAllowedException) AcceptsPost(com.google.gerrit.extensions.restapi.AcceptsPost) ResourceNotFoundException(com.google.gerrit.extensions.restapi.ResourceNotFoundException) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException) InvocationTargetException(java.lang.reflect.InvocationTargetException) PermissionBackendException(com.google.gerrit.server.permissions.PermissionBackendException) UnprocessableEntityException(com.google.gerrit.extensions.restapi.UnprocessableEntityException) RestApiException(com.google.gerrit.extensions.restapi.RestApiException) PreconditionFailedException(com.google.gerrit.extensions.restapi.PreconditionFailedException) IOException(java.io.IOException) MalformedJsonException(com.google.gson.stream.MalformedJsonException) ServletException(javax.servlet.ServletException) AuthException(com.google.gerrit.extensions.restapi.AuthException) MethodNotAllowedException(com.google.gerrit.extensions.restapi.MethodNotAllowedException) EOFException(java.io.EOFException) JsonParseException(com.google.gson.JsonParseException) NotImplementedException(com.google.gerrit.extensions.restapi.NotImplementedException) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) Response(com.google.gerrit.extensions.restapi.Response) HttpServletResponse(javax.servlet.http.HttpServletResponse) ParameterizedType(java.lang.reflect.ParameterizedType) Type(java.lang.reflect.Type) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) IdString(com.google.gerrit.extensions.restapi.IdString) AcceptsCreate(com.google.gerrit.extensions.restapi.AcceptsCreate) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException) NeedsParams(com.google.gerrit.extensions.restapi.NeedsParams) BinaryResult(com.google.gerrit.extensions.restapi.BinaryResult)

Example 4 with Response

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

the class DeleteEmail method apply.

public Response<?> apply(IdentifiedUser user, String email) throws ResourceNotFoundException, ResourceConflictException, MethodNotAllowedException, OrmException, IOException, ConfigInvalidException {
    if (!realm.allowsEdit(AccountFieldName.REGISTER_NEW_EMAIL)) {
        throw new MethodNotAllowedException("realm does not allow deleting emails");
    }
    Set<ExternalId> extIds = externalIds.byAccount(user.getAccountId()).stream().filter(e -> email.equals(e.email())).collect(toSet());
    if (extIds.isEmpty()) {
        throw new ResourceNotFoundException(email);
    }
    try {
        for (ExternalId extId : extIds) {
            AuthRequest authRequest = new AuthRequest(extId.key());
            authRequest.setEmailAddress(email);
            accountManager.unlink(user.getAccountId(), authRequest);
        }
    } catch (AccountException e) {
        throw new ResourceConflictException(e.getMessage());
    }
    return Response.none();
}
Also used : ResourceNotFoundException(com.google.gerrit.extensions.restapi.ResourceNotFoundException) GlobalPermission(com.google.gerrit.server.permissions.GlobalPermission) PermissionBackendException(com.google.gerrit.server.permissions.PermissionBackendException) CurrentUser(com.google.gerrit.server.CurrentUser) OrmException(com.google.gwtorm.server.OrmException) ConfigInvalidException(org.eclipse.jgit.errors.ConfigInvalidException) Input(com.google.gerrit.server.account.DeleteEmail.Input) Inject(com.google.inject.Inject) Set(java.util.Set) AccountFieldName(com.google.gerrit.extensions.client.AccountFieldName) IOException(java.io.IOException) Response(com.google.gerrit.extensions.restapi.Response) PermissionBackend(com.google.gerrit.server.permissions.PermissionBackend) MethodNotAllowedException(com.google.gerrit.extensions.restapi.MethodNotAllowedException) ExternalIds(com.google.gerrit.server.account.externalids.ExternalIds) RestModifyView(com.google.gerrit.extensions.restapi.RestModifyView) Provider(com.google.inject.Provider) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) IdentifiedUser(com.google.gerrit.server.IdentifiedUser) AuthException(com.google.gerrit.extensions.restapi.AuthException) ExternalId(com.google.gerrit.server.account.externalids.ExternalId) Collectors.toSet(java.util.stream.Collectors.toSet) Singleton(com.google.inject.Singleton) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) MethodNotAllowedException(com.google.gerrit.extensions.restapi.MethodNotAllowedException) ExternalId(com.google.gerrit.server.account.externalids.ExternalId) ResourceNotFoundException(com.google.gerrit.extensions.restapi.ResourceNotFoundException)

Aggregations

AuthException (com.google.gerrit.extensions.restapi.AuthException)4 ResourceConflictException (com.google.gerrit.extensions.restapi.ResourceConflictException)4 Response (com.google.gerrit.extensions.restapi.Response)4 IOException (java.io.IOException)4 BadRequestException (com.google.gerrit.extensions.restapi.BadRequestException)3 RestApiException (com.google.gerrit.extensions.restapi.RestApiException)3 UnprocessableEntityException (com.google.gerrit.extensions.restapi.UnprocessableEntityException)3 CurrentUser (com.google.gerrit.server.CurrentUser)3 OrmException (com.google.gwtorm.server.OrmException)3 Inject (com.google.inject.Inject)3 Provider (com.google.inject.Provider)3 MethodNotAllowedException (com.google.gerrit.extensions.restapi.MethodNotAllowedException)2 ResourceNotFoundException (com.google.gerrit.extensions.restapi.ResourceNotFoundException)2 RestModifyView (com.google.gerrit.extensions.restapi.RestModifyView)2 PermissionBackendException (com.google.gerrit.server.permissions.PermissionBackendException)2 ArrayList (java.util.ArrayList)2 List (java.util.List)2 Map (java.util.Map)2 AutoValue (com.google.auto.value.AutoValue)1 MoreObjects (com.google.common.base.MoreObjects)1