Search in sources :

Example 81 with Produces

use of javax.ws.rs.Produces in project OpenAttestation by OpenAttestation.

the class Host method get.

/**
     * Returns the trust status of a host.
     * 
     * Sample request:
     * GET http://localhost:8080/AttestationService/resources/hosts/trust?hostName=Some+TXT+Host
     * 
     * Sample output for untrusted host:
     * BIOS:0,VMM:0
     * 
     * Sample output for trusted host:
     * BIOS:1,VMM:1
     * 
     * @param hostName unique name of the host to query
     * @return a string like BIOS:0,VMM:0 representing the trust status
     */
@GET
@Produces({ MediaType.APPLICATION_JSON })
@Path("/trust")
public HostTrustResponse get(@QueryParam("hostName") String hostName) {
    try {
        // 0.5.1 returned MediaType.TEXT_PLAIN string like "BIOS:0,VMM:0" :  return new HostTrustBO().getTrustStatusString(new Hostname(hostName)); // datatype.Hostname            
        Hostname hostname = new Hostname(hostName);
        HostTrustStatus trust = new ASComponentFactory().getHostTrustBO().getTrustStatus(hostname);
        return new HostTrustResponse(hostname, trust);
    } catch (ASException e) {
        throw e;
    } catch (Exception e) {
        throw new ASException(e);
    }
}
Also used : ASComponentFactory(com.intel.mtwilson.as.helper.ASComponentFactory) Hostname(com.intel.mtwilson.util.net.Hostname) ASException(com.intel.mountwilson.as.common.ASException) ASException(com.intel.mountwilson.as.common.ASException) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET)

Example 82 with Produces

use of javax.ws.rs.Produces in project feign by OpenFeign.

the class JAXRSContract method processAnnotationOnClass.

@Override
protected void processAnnotationOnClass(MethodMetadata data, Class<?> clz) {
    Path path = clz.getAnnotation(Path.class);
    if (path != null) {
        String pathValue = emptyToNull(path.value());
        checkState(pathValue != null, "Path.value() was empty on type %s", clz.getName());
        if (!pathValue.startsWith("/")) {
            pathValue = "/" + pathValue;
        }
        if (pathValue.endsWith("/")) {
            // Strip off any trailing slashes, since the template has already had slashes appropriately added
            pathValue = pathValue.substring(0, pathValue.length() - 1);
        }
        data.template().insert(0, pathValue);
    }
    Consumes consumes = clz.getAnnotation(Consumes.class);
    if (consumes != null) {
        handleConsumesAnnotation(data, consumes, clz.getName());
    }
    Produces produces = clz.getAnnotation(Produces.class);
    if (produces != null) {
        handleProducesAnnotation(data, produces, clz.getName());
    }
}
Also used : Path(javax.ws.rs.Path) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces)

Example 83 with Produces

use of javax.ws.rs.Produces in project jersey by jersey.

the class TemplateModelProcessor method createEnhancingMethods.

/**
     * Creates enhancing methods for given resource.
     *
     * @param resourceClass    resource class for which enhancing methods should be created.
     * @param resourceInstance resource instance for which enhancing methods should be created. May be {@code null}.
     * @param newMethods       list to store new methods into.
     */
private void createEnhancingMethods(final Class<?> resourceClass, final Object resourceInstance, final List<ModelProcessorUtil.Method> newMethods) {
    final Template template = resourceClass.getAnnotation(Template.class);
    if (template != null) {
        final Class<?> annotatedResourceClass = ModelHelper.getAnnotatedResourceClass(resourceClass);
        final List<MediaType> produces = MediaTypes.createQualitySourceMediaTypes(annotatedResourceClass.getAnnotation(Produces.class));
        final List<MediaType> consumes = MediaTypes.createFrom(annotatedResourceClass.getAnnotation(Consumes.class));
        final TemplateInflectorImpl inflector = new TemplateInflectorImpl(template.name(), resourceClass, resourceInstance);
        newMethods.add(new ModelProcessorUtil.Method(HttpMethod.GET, consumes, produces, inflector));
        newMethods.add(new ModelProcessorUtil.Method(IMPLICIT_VIEW_PATH_PARAMETER_TEMPLATE, HttpMethod.GET, consumes, produces, inflector));
    }
}
Also used : ModelProcessorUtil(org.glassfish.jersey.server.model.internal.ModelProcessorUtil) Produces(javax.ws.rs.Produces) Consumes(javax.ws.rs.Consumes) MediaType(javax.ws.rs.core.MediaType) Template(org.glassfish.jersey.server.mvc.Template)

Example 84 with Produces

use of javax.ws.rs.Produces in project jersey by jersey.

the class WebResourceFactory method invoke.

@Override
@SuppressWarnings("unchecked")
public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
    if (args == null && method.getName().equals("toString")) {
        return toString();
    }
    if (args == null && method.getName().equals("hashCode")) {
        //unique instance in the JVM, and no need to override
        return hashCode();
    }
    if (args != null && args.length == 1 && method.getName().equals("equals")) {
        //unique instance in the JVM, and no need to override
        return equals(args[0]);
    }
    // get the interface describing the resource
    final Class<?> proxyIfc = proxy.getClass().getInterfaces()[0];
    // response type
    final Class<?> responseType = method.getReturnType();
    // determine method name
    String httpMethod = getHttpMethodName(method);
    if (httpMethod == null) {
        for (final Annotation ann : method.getAnnotations()) {
            httpMethod = getHttpMethodName(ann.annotationType());
            if (httpMethod != null) {
                break;
            }
        }
    }
    // create a new UriBuilder appending the @Path attached to the method
    WebTarget newTarget = addPathFromAnnotation(method, target);
    if (httpMethod == null) {
        if (newTarget == target) {
            // no path annotation on the method -> fail
            throw new UnsupportedOperationException("Not a resource method.");
        } else if (!responseType.isInterface()) {
            // not interface - can't help here
            throw new UnsupportedOperationException("Return type not an interface");
        }
    }
    // process method params (build maps of (Path|Form|Cookie|Matrix|Header..)Params
    // and extract entity type
    final MultivaluedHashMap<String, Object> headers = new MultivaluedHashMap<String, Object>(this.headers);
    final LinkedList<Cookie> cookies = new LinkedList<>(this.cookies);
    final Form form = new Form();
    form.asMap().putAll(this.form.asMap());
    final Annotation[][] paramAnns = method.getParameterAnnotations();
    Object entity = null;
    Type entityType = null;
    for (int i = 0; i < paramAnns.length; i++) {
        final Map<Class, Annotation> anns = new HashMap<>();
        for (final Annotation ann : paramAnns[i]) {
            anns.put(ann.annotationType(), ann);
        }
        Annotation ann;
        Object value = args[i];
        if (!hasAnyParamAnnotation(anns)) {
            entityType = method.getGenericParameterTypes()[i];
            entity = value;
        } else {
            if (value == null && (ann = anns.get(DefaultValue.class)) != null) {
                value = ((DefaultValue) ann).value();
            }
            if (value != null) {
                if ((ann = anns.get(PathParam.class)) != null) {
                    newTarget = newTarget.resolveTemplate(((PathParam) ann).value(), value);
                } else if ((ann = anns.get((QueryParam.class))) != null) {
                    if (value instanceof Collection) {
                        newTarget = newTarget.queryParam(((QueryParam) ann).value(), convert((Collection) value));
                    } else {
                        newTarget = newTarget.queryParam(((QueryParam) ann).value(), value);
                    }
                } else if ((ann = anns.get((HeaderParam.class))) != null) {
                    if (value instanceof Collection) {
                        headers.addAll(((HeaderParam) ann).value(), convert((Collection) value));
                    } else {
                        headers.addAll(((HeaderParam) ann).value(), value);
                    }
                } else if ((ann = anns.get((CookieParam.class))) != null) {
                    final String name = ((CookieParam) ann).value();
                    Cookie c;
                    if (value instanceof Collection) {
                        for (final Object v : ((Collection) value)) {
                            if (!(v instanceof Cookie)) {
                                c = new Cookie(name, v.toString());
                            } else {
                                c = (Cookie) v;
                                if (!name.equals(((Cookie) v).getName())) {
                                    // is this the right thing to do? or should I fail? or ignore the difference?
                                    c = new Cookie(name, c.getValue(), c.getPath(), c.getDomain(), c.getVersion());
                                }
                            }
                            cookies.add(c);
                        }
                    } else {
                        if (!(value instanceof Cookie)) {
                            cookies.add(new Cookie(name, value.toString()));
                        } else {
                            c = (Cookie) value;
                            if (!name.equals(((Cookie) value).getName())) {
                                // is this the right thing to do? or should I fail? or ignore the difference?
                                cookies.add(new Cookie(name, c.getValue(), c.getPath(), c.getDomain(), c.getVersion()));
                            }
                        }
                    }
                } else if ((ann = anns.get((MatrixParam.class))) != null) {
                    if (value instanceof Collection) {
                        newTarget = newTarget.matrixParam(((MatrixParam) ann).value(), convert((Collection) value));
                    } else {
                        newTarget = newTarget.matrixParam(((MatrixParam) ann).value(), value);
                    }
                } else if ((ann = anns.get((FormParam.class))) != null) {
                    if (value instanceof Collection) {
                        for (final Object v : ((Collection) value)) {
                            form.param(((FormParam) ann).value(), v.toString());
                        }
                    } else {
                        form.param(((FormParam) ann).value(), value.toString());
                    }
                }
            }
        }
    }
    if (httpMethod == null) {
        // the method is a subresource locator
        return WebResourceFactory.newResource(responseType, newTarget, true, headers, cookies, form);
    }
    // accepted media types
    Produces produces = method.getAnnotation(Produces.class);
    if (produces == null) {
        produces = proxyIfc.getAnnotation(Produces.class);
    }
    final String[] accepts = (produces == null) ? EMPTY : produces.value();
    // determine content type
    String contentType = null;
    if (entity != null) {
        final List<Object> contentTypeEntries = headers.get(HttpHeaders.CONTENT_TYPE);
        if ((contentTypeEntries != null) && (!contentTypeEntries.isEmpty())) {
            contentType = contentTypeEntries.get(0).toString();
        } else {
            Consumes consumes = method.getAnnotation(Consumes.class);
            if (consumes == null) {
                consumes = proxyIfc.getAnnotation(Consumes.class);
            }
            if (consumes != null && consumes.value().length > 0) {
                contentType = consumes.value()[0];
            }
        }
    }
    Invocation.Builder builder = newTarget.request().headers(// this resets all headers so do this first
    headers).accept(// if @Produces is defined, propagate values into Accept header; empty array is NO-OP
    accepts);
    for (final Cookie c : cookies) {
        builder = builder.cookie(c);
    }
    final Object result;
    if (entity == null && !form.asMap().isEmpty()) {
        entity = form;
        contentType = MediaType.APPLICATION_FORM_URLENCODED;
    } else {
        if (contentType == null) {
            contentType = MediaType.APPLICATION_OCTET_STREAM;
        }
        if (!form.asMap().isEmpty()) {
            if (entity instanceof Form) {
                ((Form) entity).asMap().putAll(form.asMap());
            } else {
            // TODO: should at least log some warning here
            }
        }
    }
    final GenericType responseGenericType = new GenericType(method.getGenericReturnType());
    if (entity != null) {
        if (entityType instanceof ParameterizedType) {
            entity = new GenericEntity(entity, entityType);
        }
        result = builder.method(httpMethod, Entity.entity(entity, contentType), responseGenericType);
    } else {
        result = builder.method(httpMethod, responseGenericType);
    }
    return result;
}
Also used : MatrixParam(javax.ws.rs.MatrixParam) Invocation(javax.ws.rs.client.Invocation) Form(javax.ws.rs.core.Form) HashMap(java.util.HashMap) MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) ParameterizedType(java.lang.reflect.ParameterizedType) Consumes(javax.ws.rs.Consumes) PathParam(javax.ws.rs.PathParam) Cookie(javax.ws.rs.core.Cookie) GenericType(javax.ws.rs.core.GenericType) Annotation(java.lang.annotation.Annotation) LinkedList(java.util.LinkedList) CookieParam(javax.ws.rs.CookieParam) MediaType(javax.ws.rs.core.MediaType) GenericType(javax.ws.rs.core.GenericType) ParameterizedType(java.lang.reflect.ParameterizedType) Type(java.lang.reflect.Type) QueryParam(javax.ws.rs.QueryParam) Produces(javax.ws.rs.Produces) GenericEntity(javax.ws.rs.core.GenericEntity) Collection(java.util.Collection) WebTarget(javax.ws.rs.client.WebTarget) FormParam(javax.ws.rs.FormParam)

Example 85 with Produces

use of javax.ws.rs.Produces in project neo4j-clean-remote-db-addon by jexp.

the class DeleteDatabaseResource method cleanDb.

@DELETE
@Path("/{key}")
@Produces(MediaType.APPLICATION_JSON)
public Response cleanDb(@PathParam("key") String deleteKey) {
    GraphDatabaseAPI graph = database.getGraph();
    String configKey = config.getString(CONFIG_DELETE_AUTH_KEY);
    if (deleteKey == null || configKey == null || !deleteKey.equals(configKey)) {
        return Response.status(Status.UNAUTHORIZED).build();
    }
    try {
        Map<String, Object> result = new Neo4jDatabaseCleaner(graph).cleanDb(MAX_NODES_TO_DELETE);
        if ((Long) result.get("nodes") >= MAX_NODES_TO_DELETE) {
            result.putAll(cleanDbDirectory(database));
        }
        log.warning("Deleted Database: " + result);
        return Response.status(Status.OK).entity(JsonHelper.createJsonFrom(result)).build();
    } catch (Throwable e) {
        return Response.status(Status.INTERNAL_SERVER_ERROR).entity(JsonHelper.createJsonFrom(e.getMessage())).build();
    }
}
Also used : GraphDatabaseAPI(org.neo4j.kernel.GraphDatabaseAPI) Path(javax.ws.rs.Path) DELETE(javax.ws.rs.DELETE) Produces(javax.ws.rs.Produces)

Aggregations

Produces (javax.ws.rs.Produces)1150 Path (javax.ws.rs.Path)844 GET (javax.ws.rs.GET)724 Consumes (javax.ws.rs.Consumes)306 POST (javax.ws.rs.POST)304 ApiOperation (io.swagger.annotations.ApiOperation)275 ApiResponses (io.swagger.annotations.ApiResponses)218 IOException (java.io.IOException)143 Response (javax.ws.rs.core.Response)139 WebApplicationException (javax.ws.rs.WebApplicationException)115 URI (java.net.URI)110 TimedResource (org.killbill.commons.metrics.TimedResource)109 Timed (com.codahale.metrics.annotation.Timed)103 ArrayList (java.util.ArrayList)91 PUT (javax.ws.rs.PUT)89 ResponseBuilder (javax.ws.rs.core.Response.ResponseBuilder)85 HashMap (java.util.HashMap)68 Map (java.util.Map)63 UUID (java.util.UUID)63 DELETE (javax.ws.rs.DELETE)62