Search in sources :

Example 6 with IdString

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

the class RobotComments method parse.

@Override
public RobotCommentResource parse(RevisionResource rev, IdString id) throws ResourceNotFoundException, OrmException {
    String uuid = id.get();
    ChangeNotes notes = rev.getNotes();
    for (RobotComment c : commentsUtil.robotCommentsByPatchSet(notes, rev.getPatchSet().getId())) {
        if (uuid.equals(c.key.uuid)) {
            return new RobotCommentResource(rev, c);
        }
    }
    throw new ResourceNotFoundException(id);
}
Also used : RobotComment(com.google.gerrit.reviewdb.client.RobotComment) IdString(com.google.gerrit.extensions.restapi.IdString) ChangeNotes(com.google.gerrit.server.notedb.ChangeNotes) ResourceNotFoundException(com.google.gerrit.extensions.restapi.ResourceNotFoundException)

Example 7 with IdString

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

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

the class RestApiServlet method splitPath.

private static List<IdString> splitPath(HttpServletRequest req) {
    String path = RequestUtil.getEncodedPathInfo(req);
    if (Strings.isNullOrEmpty(path)) {
        return Collections.emptyList();
    }
    List<IdString> out = new ArrayList<>();
    for (String p : Splitter.on('/').split(path)) {
        out.add(IdString.fromUrl(p));
    }
    if (out.size() > 0 && out.get(out.size() - 1).isEmpty()) {
        out.remove(out.size() - 1);
    }
    return out;
}
Also used : IdString(com.google.gerrit.extensions.restapi.IdString) ArrayList(java.util.ArrayList) IdString(com.google.gerrit.extensions.restapi.IdString)

Example 9 with IdString

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

the class RestApiServlet method view.

private ViewData view(RestResource rsrc, RestCollection<RestResource, RestResource> rc, String method, List<IdString> path) throws AmbiguousViewException, RestApiException {
    DynamicMap<RestView<RestResource>> views = rc.views();
    final IdString projection = path.isEmpty() ? IdString.fromUrl("/") : path.remove(0);
    if (!path.isEmpty()) {
        // If there are path components still remaining after this projection
        // is chosen, look for the projection based upon GET as the method as
        // the client thinks it is a nested collection.
        method = "GET";
    } else if ("HEAD".equals(method)) {
        method = "GET";
    }
    List<String> p = splitProjection(projection);
    if (p.size() == 2) {
        String viewname = p.get(1);
        if (Strings.isNullOrEmpty(viewname)) {
            viewname = "/";
        }
        RestView<RestResource> view = views.get(p.get(0), method + "." + viewname);
        if (view != null) {
            return new ViewData(p.get(0), view);
        }
        view = views.get(p.get(0), "GET." + viewname);
        if (view != null) {
            if (view instanceof AcceptsPost && "POST".equals(method)) {
                @SuppressWarnings("unchecked") AcceptsPost<RestResource> ap = (AcceptsPost<RestResource>) view;
                return new ViewData(p.get(0), ap.post(rsrc));
            }
        }
        throw new ResourceNotFoundException(projection);
    }
    String name = method + "." + p.get(0);
    RestView<RestResource> core = views.get("gerrit", name);
    if (core != null) {
        return new ViewData(null, core);
    }
    core = views.get("gerrit", "GET." + p.get(0));
    if (core instanceof AcceptsPost && "POST".equals(method)) {
        @SuppressWarnings("unchecked") AcceptsPost<RestResource> ap = (AcceptsPost<RestResource>) core;
        return new ViewData(null, ap.post(rsrc));
    }
    Map<String, RestView<RestResource>> r = new TreeMap<>();
    for (String plugin : views.plugins()) {
        RestView<RestResource> action = views.get(plugin, name);
        if (action != null) {
            r.put(plugin, action);
        }
    }
    if (r.size() == 1) {
        Map.Entry<String, RestView<RestResource>> entry = Iterables.getOnlyElement(r.entrySet());
        return new ViewData(entry.getKey(), entry.getValue());
    } else if (r.isEmpty()) {
        throw new ResourceNotFoundException(projection);
    } else {
        throw new AmbiguousViewException(String.format("Projection %s is ambiguous: %s", name, r.keySet().stream().map(in -> in + "~" + projection).collect(joining(", "))));
    }
}
Also used : RestResource(com.google.gerrit.extensions.restapi.RestResource) RestView(com.google.gerrit.extensions.restapi.RestView) AcceptsPost(com.google.gerrit.extensions.restapi.AcceptsPost) IdString(com.google.gerrit.extensions.restapi.IdString) TreeMap(java.util.TreeMap) IdString(com.google.gerrit.extensions.restapi.IdString) ResourceNotFoundException(com.google.gerrit.extensions.restapi.ResourceNotFoundException) Map(java.util.Map) TreeMap(java.util.TreeMap) DynamicMap(com.google.gerrit.extensions.registration.DynamicMap) HashMap(java.util.HashMap)

Example 10 with IdString

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

the class Fixes method parse.

@Override
public FixResource parse(RevisionResource revisionResource, IdString id) throws ResourceNotFoundException, OrmException {
    String fixId = id.get();
    ChangeNotes changeNotes = revisionResource.getNotes();
    List<RobotComment> robotComments = commentsUtil.robotCommentsByPatchSet(changeNotes, revisionResource.getPatchSet().getId());
    for (RobotComment robotComment : robotComments) {
        for (FixSuggestion fixSuggestion : robotComment.fixSuggestions) {
            if (Objects.equals(fixId, fixSuggestion.fixId)) {
                return new FixResource(revisionResource, fixSuggestion.replacements);
            }
        }
    }
    throw new ResourceNotFoundException(id);
}
Also used : FixSuggestion(com.google.gerrit.reviewdb.client.FixSuggestion) RobotComment(com.google.gerrit.reviewdb.client.RobotComment) IdString(com.google.gerrit.extensions.restapi.IdString) ChangeNotes(com.google.gerrit.server.notedb.ChangeNotes) ResourceNotFoundException(com.google.gerrit.extensions.restapi.ResourceNotFoundException)

Aggregations

IdString (com.google.gerrit.extensions.restapi.IdString)14 ResourceNotFoundException (com.google.gerrit.extensions.restapi.ResourceNotFoundException)12 ChangeNotes (com.google.gerrit.server.notedb.ChangeNotes)3 AcceptsPost (com.google.gerrit.extensions.restapi.AcceptsPost)2 RestResource (com.google.gerrit.extensions.restapi.RestResource)2 Comment (com.google.gerrit.reviewdb.client.Comment)2 RobotComment (com.google.gerrit.reviewdb.client.RobotComment)2 Cache (com.google.common.cache.Cache)1 ExtendedHttpAuditEvent (com.google.gerrit.audit.ExtendedHttpAuditEvent)1 GlobalOrPluginPermission (com.google.gerrit.extensions.api.access.GlobalOrPluginPermission)1 PluginPermission (com.google.gerrit.extensions.api.access.PluginPermission)1 BranchInfo (com.google.gerrit.extensions.api.projects.BranchInfo)1 DynamicMap (com.google.gerrit.extensions.registration.DynamicMap)1 AcceptsCreate (com.google.gerrit.extensions.restapi.AcceptsCreate)1 AcceptsDelete (com.google.gerrit.extensions.restapi.AcceptsDelete)1 AuthException (com.google.gerrit.extensions.restapi.AuthException)1 BadRequestException (com.google.gerrit.extensions.restapi.BadRequestException)1 BinaryResult (com.google.gerrit.extensions.restapi.BinaryResult)1 MethodNotAllowedException (com.google.gerrit.extensions.restapi.MethodNotAllowedException)1 NeedsParams (com.google.gerrit.extensions.restapi.NeedsParams)1