Search in sources :

Example 76 with Consumes

use of javax.ws.rs.Consumes in project che by eclipse.

the class Service method generateLinkForMethod.

private Link generateLinkForMethod(UriInfo uriInfo, String linkRel, Method method, Object... pathParameters) {
    String httpMethod = null;
    final HttpMethod httpMethodAnnotation = getMetaAnnotation(method, HttpMethod.class);
    if (httpMethodAnnotation != null) {
        httpMethod = httpMethodAnnotation.value();
    }
    if (httpMethod == null) {
        throw new IllegalArgumentException(format("Method '%s' has not any HTTP method annotation and may not be used to produce link.", method.getName()));
    }
    final Consumes consumes = getAnnotation(method, Consumes.class);
    final Produces produces = getAnnotation(method, Produces.class);
    final UriBuilder baseUriBuilder = uriInfo.getBaseUriBuilder();
    final LinkedList<String> matchedURIs = new LinkedList<>(uriInfo.getMatchedURIs());
    // Get path to the root resource.
    if (uriInfo.getMatchedResources().size() < matchedURIs.size()) {
        matchedURIs.remove();
    }
    while (!matchedURIs.isEmpty()) {
        baseUriBuilder.path(matchedURIs.pollLast());
    }
    final Path path = method.getAnnotation(Path.class);
    if (path != null) {
        baseUriBuilder.path(path.value());
    }
    final Link link = DtoFactory.getInstance().createDto(Link.class).withRel(linkRel).withHref(baseUriBuilder.build(pathParameters).toString()).withMethod(httpMethod);
    if (consumes != null) {
        link.setConsumes(consumes.value()[0]);
    }
    if (produces != null) {
        link.setProduces(produces.value()[0]);
    }
    Class<?>[] parameterClasses = method.getParameterTypes();
    if (parameterClasses.length > 0) {
        Annotation[][] annotations = method.getParameterAnnotations();
        for (int i = 0; i < parameterClasses.length; i++) {
            if (annotations[i].length > 0) {
                boolean isBodyParameter = false;
                QueryParam queryParam = null;
                Description description = null;
                Required required = null;
                Valid valid = null;
                DefaultValue defaultValue = null;
                for (int j = 0; j < annotations[i].length; j++) {
                    Annotation annotation = annotations[i][j];
                    isBodyParameter |= !JAX_RS_ANNOTATIONS.contains(annotation.annotationType().getName());
                    Class<?> annotationType = annotation.annotationType();
                    if (annotationType == QueryParam.class) {
                        queryParam = (QueryParam) annotation;
                    } else if (annotationType == Description.class) {
                        description = (Description) annotation;
                    } else if (annotationType == Required.class) {
                        required = (Required) annotation;
                    } else if (annotationType == Valid.class) {
                        valid = (Valid) annotation;
                    } else if (annotationType == DefaultValue.class) {
                        defaultValue = (DefaultValue) annotation;
                    }
                }
                if (queryParam != null) {
                    LinkParameter parameter = DtoFactory.getInstance().createDto(LinkParameter.class).withName(queryParam.value()).withRequired(required != null).withType(getParameterType(parameterClasses[i]));
                    if (defaultValue != null) {
                        parameter.setDefaultValue(defaultValue.value());
                    }
                    if (description != null) {
                        parameter.setDescription(description.value());
                    }
                    if (valid != null) {
                        parameter.setValid(Arrays.asList(valid.value()));
                    }
                    link.getParameters().add(parameter);
                } else if (isBodyParameter) {
                    if (description != null) {
                        link.setRequestBody(DtoFactory.getInstance().createDto(RequestBodyDescriptor.class).withDescription(description.value()));
                    }
                }
            }
        }
    }
    return link;
}
Also used : Path(javax.ws.rs.Path) RequestBodyDescriptor(org.eclipse.che.api.core.rest.shared.dto.RequestBodyDescriptor) Description(org.eclipse.che.api.core.rest.annotations.Description) LinkParameter(org.eclipse.che.api.core.rest.shared.dto.LinkParameter) LinkedList(java.util.LinkedList) Annotation(java.lang.annotation.Annotation) DefaultValue(javax.ws.rs.DefaultValue) Required(org.eclipse.che.api.core.rest.annotations.Required) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces) QueryParam(javax.ws.rs.QueryParam) Valid(org.eclipse.che.api.core.rest.annotations.Valid) UriBuilder(javax.ws.rs.core.UriBuilder) HttpMethod(javax.ws.rs.HttpMethod) Link(org.eclipse.che.api.core.rest.shared.dto.Link) GenerateLink(org.eclipse.che.api.core.rest.annotations.GenerateLink)

Example 77 with Consumes

use of javax.ws.rs.Consumes in project druid by druid-io.

the class LookupCoordinatorResource method updateAllLookups.

@POST
@Produces({ MediaType.APPLICATION_JSON, SmileMediaTypes.APPLICATION_JACKSON_SMILE })
@Consumes({ MediaType.APPLICATION_JSON, SmileMediaTypes.APPLICATION_JACKSON_SMILE })
public Response updateAllLookups(InputStream in, @HeaderParam(AuditManager.X_DRUID_AUTHOR) @DefaultValue("") final String author, @HeaderParam(AuditManager.X_DRUID_COMMENT) @DefaultValue("") final String comment, @Context HttpServletRequest req) {
    try {
        final boolean isSmile = SmileMediaTypes.APPLICATION_JACKSON_SMILE.equals(req.getContentType());
        final ObjectMapper mapper = isSmile ? smileMapper : jsonMapper;
        final Map<String, Map<String, Map<String, Object>>> map;
        try {
            map = mapper.readValue(in, new TypeReference<Map<String, Map<String, Map<String, Object>>>>() {
            });
        } catch (IOException e) {
            return Response.status(Response.Status.BAD_REQUEST).entity(ServletResourceUtils.sanitizeException(e)).build();
        }
        if (lookupCoordinatorManager.updateLookups(map, new AuditInfo(author, comment, req.getRemoteAddr()))) {
            return Response.status(Response.Status.ACCEPTED).entity(map).build();
        } else {
            throw new RuntimeException("Unknown error updating configuration");
        }
    } catch (Exception e) {
        LOG.error(e, "Error creating new lookups");
        return Response.serverError().entity(ServletResourceUtils.sanitizeException(e)).build();
    }
}
Also used : AuditInfo(io.druid.audit.AuditInfo) TypeReference(com.fasterxml.jackson.core.type.TypeReference) IOException(java.io.IOException) Map(java.util.Map) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) IOException(java.io.IOException) POST(javax.ws.rs.POST) Produces(javax.ws.rs.Produces) Consumes(javax.ws.rs.Consumes)

Example 78 with Consumes

use of javax.ws.rs.Consumes in project che by eclipse.

the class ClasspathUpdaterService method updateClasspath.

/**
     * Updates the information about classpath.
     *
     * @param projectPath
     *         path to the current project
     * @param entries
     *         list of classpath entries which need to set
     * @throws JavaModelException
     *         if JavaModel has a failure
     * @throws ServerException
     *         if some server error
     * @throws ForbiddenException
     *         if operation is forbidden
     * @throws ConflictException
     *         if update operation causes conflicts
     * @throws NotFoundException
     *         if Project with specified path doesn't exist in workspace
     * @throws IOException
     */
@POST
@Consumes(MediaType.APPLICATION_JSON)
public void updateClasspath(@QueryParam("projectpath") String projectPath, List<ClasspathEntryDto> entries) throws JavaModelException, ServerException, ForbiddenException, ConflictException, NotFoundException, IOException {
    IJavaProject javaProject = model.getJavaProject(projectPath);
    javaProject.setRawClasspath(createModifiedEntry(entries), javaProject.getOutputLocation(), new NullProgressMonitor());
    updateProjectConfig(projectPath);
}
Also used : NullProgressMonitor(org.eclipse.core.runtime.NullProgressMonitor) IJavaProject(org.eclipse.jdt.core.IJavaProject) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes)

Example 79 with Consumes

use of javax.ws.rs.Consumes in project hadoop by apache.

the class KMS method rolloverKey.

@POST
@Path(KMSRESTConstants.KEY_RESOURCE + "/{name:.*}")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON + "; " + JettyUtils.UTF_8)
public Response rolloverKey(@PathParam("name") final String name, Map jsonMaterial) throws Exception {
    try {
        LOG.trace("Entering rolloverKey Method.");
        KMSWebApp.getAdminCallsMeter().mark();
        UserGroupInformation user = HttpUserGroupInformation.get();
        assertAccess(KMSACLs.Type.ROLLOVER, user, KMSOp.ROLL_NEW_VERSION, name);
        KMSClientProvider.checkNotEmpty(name, "name");
        LOG.debug("Rolling key with name {}.", name);
        final String material = (String) jsonMaterial.get(KMSRESTConstants.MATERIAL_FIELD);
        if (material != null) {
            assertAccess(KMSACLs.Type.SET_KEY_MATERIAL, user, KMSOp.ROLL_NEW_VERSION, name);
        }
        KeyProvider.KeyVersion keyVersion = user.doAs(new PrivilegedExceptionAction<KeyVersion>() {

            @Override
            public KeyVersion run() throws Exception {
                KeyVersion keyVersion = (material != null) ? provider.rollNewVersion(name, Base64.decodeBase64(material)) : provider.rollNewVersion(name);
                provider.flush();
                return keyVersion;
            }
        });
        kmsAudit.ok(user, KMSOp.ROLL_NEW_VERSION, name, "UserProvidedMaterial:" + (material != null) + " NewVersion:" + keyVersion.getVersionName());
        if (!KMSWebApp.getACLs().hasAccess(KMSACLs.Type.GET, user)) {
            keyVersion = removeKeyMaterial(keyVersion);
        }
        Map json = KMSServerJSONUtils.toJSON(keyVersion);
        LOG.trace("Exiting rolloverKey Method.");
        return Response.ok().type(MediaType.APPLICATION_JSON).entity(json).build();
    } catch (Exception e) {
        LOG.debug("Exception in rolloverKey.", e);
        throw e;
    }
}
Also used : KeyProvider(org.apache.hadoop.crypto.key.KeyProvider) KeyVersion(org.apache.hadoop.crypto.key.KeyProvider.KeyVersion) KeyVersion(org.apache.hadoop.crypto.key.KeyProvider.KeyVersion) EncryptedKeyVersion(org.apache.hadoop.crypto.key.KeyProviderCryptoExtension.EncryptedKeyVersion) Map(java.util.Map) IOException(java.io.IOException) AccessControlException(org.apache.hadoop.security.AccessControlException) UserGroupInformation(org.apache.hadoop.security.UserGroupInformation) HttpUserGroupInformation(org.apache.hadoop.security.token.delegation.web.HttpUserGroupInformation) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces)

Example 80 with Consumes

use of javax.ws.rs.Consumes in project hadoop by apache.

the class HttpFSServer method post.

/**
   * Binding to handle POST requests.
   *
   * @param is the inputstream for the request payload.
   * @param uriInfo the of the request.
   * @param path the path for operation.
   * @param op the HttpFS operation of the request.
   * @param params the HttpFS parameters of the request.
   *
   * @return the request response.
   *
   * @throws IOException thrown if an IO error occurred. Thrown exceptions are
   * handled by {@link HttpFSExceptionProvider}.
   * @throws FileSystemAccessException thrown if a FileSystemAccess releated
   * error occurred. Thrown exceptions are handled by
   * {@link HttpFSExceptionProvider}.
   */
@POST
@Path("{path:.*}")
@Consumes({ "*/*" })
@Produces({ MediaType.APPLICATION_JSON + "; " + JettyUtils.UTF_8 })
public Response post(InputStream is, @Context UriInfo uriInfo, @PathParam("path") String path, @QueryParam(OperationParam.NAME) OperationParam op, @Context Parameters params, @Context HttpServletRequest request) throws IOException, FileSystemAccessException {
    UserGroupInformation user = HttpUserGroupInformation.get();
    Response response;
    path = makeAbsolute(path);
    MDC.put(HttpFSFileSystem.OP_PARAM, op.value().name());
    MDC.put("hostname", request.getRemoteAddr());
    switch(op.value()) {
        case APPEND:
            {
                Boolean hasData = params.get(DataParam.NAME, DataParam.class);
                if (!hasData) {
                    response = Response.temporaryRedirect(createUploadRedirectionURL(uriInfo, HttpFSFileSystem.Operation.APPEND)).build();
                } else {
                    FSOperations.FSAppend command = new FSOperations.FSAppend(is, path);
                    fsExecute(user, command);
                    AUDIT_LOG.info("[{}]", path);
                    response = Response.ok().type(MediaType.APPLICATION_JSON).build();
                }
                break;
            }
        case CONCAT:
            {
                System.out.println("HTTPFS SERVER CONCAT");
                String sources = params.get(SourcesParam.NAME, SourcesParam.class);
                FSOperations.FSConcat command = new FSOperations.FSConcat(path, sources.split(","));
                fsExecute(user, command);
                AUDIT_LOG.info("[{}]", path);
                System.out.println("SENT RESPONSE");
                response = Response.ok().build();
                break;
            }
        case TRUNCATE:
            {
                Long newLength = params.get(NewLengthParam.NAME, NewLengthParam.class);
                FSOperations.FSTruncate command = new FSOperations.FSTruncate(path, newLength);
                JSONObject json = fsExecute(user, command);
                AUDIT_LOG.info("Truncate [{}] to length [{}]", path, newLength);
                response = Response.ok(json).type(MediaType.APPLICATION_JSON).build();
                break;
            }
        case UNSETSTORAGEPOLICY:
            {
                FSOperations.FSUnsetStoragePolicy command = new FSOperations.FSUnsetStoragePolicy(path);
                fsExecute(user, command);
                AUDIT_LOG.info("Unset storage policy [{}]", path);
                response = Response.ok().build();
                break;
            }
        default:
            {
                throw new IOException(MessageFormat.format("Invalid HTTP POST operation [{0}]", op.value()));
            }
    }
    return response;
}
Also used : IOException(java.io.IOException) DataParam(org.apache.hadoop.fs.http.server.HttpFSParametersProvider.DataParam) Response(javax.ws.rs.core.Response) JSONObject(org.json.simple.JSONObject) SourcesParam(org.apache.hadoop.fs.http.server.HttpFSParametersProvider.SourcesParam) UserGroupInformation(org.apache.hadoop.security.UserGroupInformation) HttpUserGroupInformation(org.apache.hadoop.security.token.delegation.web.HttpUserGroupInformation) NewLengthParam(org.apache.hadoop.fs.http.server.HttpFSParametersProvider.NewLengthParam) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces)

Aggregations

Consumes (javax.ws.rs.Consumes)1610 Path (javax.ws.rs.Path)1243 Produces (javax.ws.rs.Produces)1233 POST (javax.ws.rs.POST)917 ApiOperation (io.swagger.annotations.ApiOperation)508 ApiResponses (io.swagger.annotations.ApiResponses)445 PUT (javax.ws.rs.PUT)439 GET (javax.ws.rs.GET)224 CheckPermission (com.emc.storageos.security.authorization.CheckPermission)215 URI (java.net.URI)207 IOException (java.io.IOException)160 ArrayList (java.util.ArrayList)142 WebApplicationException (javax.ws.rs.WebApplicationException)142 Response (javax.ws.rs.core.Response)140 Authorizable (org.apache.nifi.authorization.resource.Authorizable)100 DELETE (javax.ws.rs.DELETE)87 TimedResource (org.killbill.commons.metrics.TimedResource)84 CallContext (org.killbill.billing.util.callcontext.CallContext)83 Timed (com.codahale.metrics.annotation.Timed)78 HashMap (java.util.HashMap)78