Search in sources :

Example 61 with ProcessingException

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

the class InboundMessageContext method readEntity.

/**
     * Read entity from a context entity input stream.
     *
     * @param <T>                entity Java object type.
     * @param rawType            raw Java entity type.
     * @param type               generic Java entity type.
     * @param annotations        entity annotations.
     * @param propertiesDelegate request-scoped properties delegate.
     * @return entity read from a context entity input stream.
     */
@SuppressWarnings("unchecked")
public <T> T readEntity(Class<T> rawType, Type type, Annotation[] annotations, PropertiesDelegate propertiesDelegate) {
    final boolean buffered = entityContent.isBuffered();
    if (buffered) {
        entityContent.reset();
    }
    entityContent.ensureNotClosed();
    if (workers == null) {
        return null;
    }
    MediaType mediaType = getMediaType();
    mediaType = mediaType == null ? MediaType.APPLICATION_OCTET_STREAM_TYPE : mediaType;
    boolean shouldClose = !buffered;
    try {
        T t = (T) workers.readFrom(rawType, type, annotations, mediaType, headers, propertiesDelegate, entityContent.getWrappedStream(), entityContent.hasContent() ? getReaderInterceptors() : Collections.<ReaderInterceptor>emptyList(), translateNce);
        shouldClose = shouldClose && !(t instanceof Closeable) && !(t instanceof Source);
        return t;
    } catch (IOException ex) {
        throw new ProcessingException(LocalizationMessages.ERROR_READING_ENTITY_FROM_INPUT_STREAM(), ex);
    } finally {
        if (shouldClose) {
            // Workaround for JRFCAF-1344: the underlying stream close() implementation may be thread-unsafe
            // and as such the close() may result in an IOException at the socket input stream level,
            // if the close() gets called at once from multiple threads somehow.
            // We want to ignore these exceptions in the readEntity/bufferEntity operations though.
            ReaderWriter.safelyClose(entityContent);
        }
    }
}
Also used : Closeable(java.io.Closeable) MediaType(javax.ws.rs.core.MediaType) IOException(java.io.IOException) Source(javax.xml.transform.Source) ProcessingException(javax.ws.rs.ProcessingException)

Example 62 with ProcessingException

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

the class AbstractJavaResourceMethodDispatcher method invoke.

/**
     * Use the underlying invocation handler to invoke the underlying Java method
     * with the supplied input method argument values on a given resource instance.
     *
     * @param containerRequest container request.
     * @param resource         resource class instance.
     * @param args             input argument values for the invoked Java method.
     * @return invocation result.
     * @throws ProcessingException (possibly {@link MappableException mappable})
     *                             container exception in case the invocation failed.
     */
final Object invoke(final ContainerRequest containerRequest, final Object resource, final Object... args) throws ProcessingException {
    try {
        // Validate resource class & method input parameters.
        if (validator != null) {
            validator.validateResourceAndInputParams(resource, resourceMethod, args);
        }
        final PrivilegedAction invokeMethodAction = new PrivilegedAction() {

            @Override
            public Object run() {
                final TracingLogger tracingLogger = TracingLogger.getInstance(containerRequest);
                final long timestamp = tracingLogger.timestamp(ServerTraceEvent.METHOD_INVOKE);
                try {
                    return methodHandler.invoke(resource, method, args);
                } catch (IllegalAccessException | IllegalArgumentException | UndeclaredThrowableException ex) {
                    throw new ProcessingException(LocalizationMessages.ERROR_RESOURCE_JAVA_METHOD_INVOCATION(), ex);
                } catch (InvocationTargetException ex) {
                    throw mapTargetToRuntimeEx(ex.getCause());
                } catch (Throwable t) {
                    throw new ProcessingException(t);
                } finally {
                    tracingLogger.logDuration(ServerTraceEvent.METHOD_INVOKE, timestamp, resource, method);
                }
            }
        };
        final SecurityContext securityContext = containerRequest.getSecurityContext();
        final Object invocationResult = (securityContext instanceof SubjectSecurityContext) ? ((SubjectSecurityContext) securityContext).doAsSubject(invokeMethodAction) : invokeMethodAction.run();
        // Validate response entity.
        if (validator != null) {
            validator.validateResult(resource, resourceMethod, invocationResult);
        }
        return invocationResult;
    } catch (ValidationException ex) {
        // handle validation exceptions -> potentially mappable
        throw new MappableException(ex);
    }
}
Also used : MappableException(org.glassfish.jersey.server.internal.process.MappableException) ValidationException(javax.validation.ValidationException) TracingLogger(org.glassfish.jersey.message.internal.TracingLogger) InvocationTargetException(java.lang.reflect.InvocationTargetException) SubjectSecurityContext(org.glassfish.jersey.server.SubjectSecurityContext) PrivilegedAction(java.security.PrivilegedAction) UndeclaredThrowableException(java.lang.reflect.UndeclaredThrowableException) SecurityContext(javax.ws.rs.core.SecurityContext) SubjectSecurityContext(org.glassfish.jersey.server.SubjectSecurityContext) ProcessingException(javax.ws.rs.ProcessingException)

Example 63 with ProcessingException

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

the class WadlResource method getExternalGrammar.

@Produces({ "application/xml" })
@GET
@Path("{path}")
public synchronized Response getExternalGrammar(@Context UriInfo uriInfo, @PathParam("path") String path) {
    try {
        // Fail if wadl generation is disabled
        if (!wadlContext.isWadlGenerationEnabled()) {
            return Response.status(Response.Status.NOT_FOUND).build();
        }
        ApplicationDescription applicationDescription = wadlContext.getApplication(uriInfo, WadlUtils.isDetailedWadlRequested(uriInfo));
        // Fail is we don't have any metadata for this path
        ApplicationDescription.ExternalGrammar externalMetadata = applicationDescription.getExternalGrammar(path);
        if (externalMetadata == null) {
            return Response.status(Response.Status.NOT_FOUND).build();
        }
        // Return the data
        return Response.ok().type(externalMetadata.getType()).entity(externalMetadata.getContent()).build();
    } catch (Exception e) {
        throw new ProcessingException(LocalizationMessages.ERROR_WADL_RESOURCE_EXTERNAL_GRAMMAR(), e);
    }
}
Also used : ProcessingException(javax.ws.rs.ProcessingException) ProcessingException(javax.ws.rs.ProcessingException) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET)

Example 64 with ProcessingException

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

the class WadlUtils method unmarshall.

/**
     * Unmarshal a jaxb bean into a type of {@code resultClass} from the given {@code inputStream}.
     *
     * @param inputStream Input stream that contains input xml that should be processed.
     * @param saxParserFactory Sax parser factory for unmarshalling xml.
     * @param resultClass Class of the result bean into which the content of {@code inputStream} should be unmarshalled.
     * @param <T> Type of the result jaxb bean.
     * @return Unmarshalled jaxb bean.
     *
     * @throws JAXBException In case of jaxb problem.
     * @throws ParserConfigurationException In case of problem with parsing xml.
     * @throws SAXException In case of problem with parsing xml.
     */
public static <T> T unmarshall(InputStream inputStream, SAXParserFactory saxParserFactory, Class<T> resultClass) throws JAXBException, ParserConfigurationException, SAXException {
    JAXBContext jaxbContext = null;
    try {
        jaxbContext = JAXBContext.newInstance(resultClass);
    } catch (JAXBException ex) {
        throw new ProcessingException(LocalizationMessages.ERROR_WADL_JAXB_CONTEXT(), ex);
    }
    final SAXParser saxParser = saxParserFactory.newSAXParser();
    SAXSource source = new SAXSource(saxParser.getXMLReader(), new InputSource(inputStream));
    final Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
    final Object result = unmarshaller.unmarshal(source);
    return resultClass.cast(result);
}
Also used : InputSource(org.xml.sax.InputSource) SAXSource(javax.xml.transform.sax.SAXSource) JAXBException(javax.xml.bind.JAXBException) SAXParser(javax.xml.parsers.SAXParser) JAXBContext(javax.xml.bind.JAXBContext) Unmarshaller(javax.xml.bind.Unmarshaller) ProcessingException(javax.ws.rs.ProcessingException)

Example 65 with ProcessingException

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

the class ServletContainer method service.

/**
     * Receives standard HTTP requests from the public {@code service} method and dispatches
     * them to the {@code do}<i>XXX</i> methods defined in
     * this class. This method is an HTTP-specific version of the
     * {@link javax.servlet.Servlet#service} method. There's no
     * need to override this method.
     *
     * @param request  the {@link HttpServletRequest} object that
     *                 contains the request the client made of
     *                 the servlet
     * @param response the {@link HttpServletResponse} object that
     *                 contains the response the servlet returns
     *                 to the client
     * @throws IOException      if an input or output error occurs
     *                          while the servlet is handling the
     *                          HTTP request
     * @throws ServletException if the HTTP request
     *                          cannot be handled
     * @see javax.servlet.Servlet#service
     */
@Override
protected void service(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
    /**
         * There is an annoying edge case where the service method is
         * invoked for the case when the URI is equal to the deployment URL
         * minus the '/', for example http://locahost:8080/HelloWorldWebApp
         */
    final String servletPath = request.getServletPath();
    final StringBuffer requestUrl = request.getRequestURL();
    final String requestURI = request.getRequestURI();
    //        final String pathInfo = request.getPathInfo();
    //        final boolean checkPathInfo = pathInfo == null || pathInfo.isEmpty() || pathInfo.equals("/");
    //        if (checkPathInfo && !request.getRequestURI().endsWith("/")) {
    // Only do this if the last segment of the servlet path does not contain '.'
    // This handles the case when the extension mapping is used with the servlet
    // see issue 506
    // This solution does not require parsing the deployment descriptor,
    // however still leaves it broken for the very rare case if a standard path
    // servlet mapping would include dot in the last segment (e.g. /.webresources/*)
    // and somebody would want to hit the root resource without the trailing slash
    //            final int i = servletPath.lastIndexOf('/');
    //            if (servletPath.substring(i + 1).indexOf('.') < 0) {
    // TODO (+ handle request URL with invalid characters - see the creation of absoluteUriBuilder below)
    //                if (webComponent.getResourceConfig().getFeature(ResourceConfig.FEATURE_REDIRECT)) {
    //                    URI l = UriBuilder.fromUri(request.getRequestURL().toString()).
    //                            path("/").
    //                            replaceQuery(request.getQueryString()).build();
    //
    //                    response.setStatus(307);
    //                    response.setHeader("Location", l.toASCIIString());
    //                    return;
    //                } else {
    //                pathInfo = "/";
    //                requestURL.append("/");
    //                requestURI += "/";
    //                }
    //            }
    //        }
    /**
         * The HttpServletRequest.getRequestURL() contains the complete URI
         * minus the query and fragment components.
         */
    final UriBuilder absoluteUriBuilder;
    try {
        absoluteUriBuilder = UriBuilder.fromUri(requestUrl.toString());
    } catch (final IllegalArgumentException iae) {
        setResponseForInvalidUri(response, iae);
        return;
    }
    /**
         * The HttpServletRequest.getPathInfo() and
         * HttpServletRequest.getServletPath() are in decoded form.
         *
         * On some servlet implementations the getPathInfo() removed
         * contiguous '/' characters. This is problematic if URIs
         * are embedded, for example as the last path segment.
         * We need to work around this and not use getPathInfo
         * for the decodedPath.
         */
    final String decodedBasePath = request.getContextPath() + servletPath + "/";
    final String encodedBasePath = UriComponent.encode(decodedBasePath, UriComponent.Type.PATH);
    if (!decodedBasePath.equals(encodedBasePath)) {
        throw new ProcessingException("The servlet context path and/or the " + "servlet path contain characters that are percent encoded");
    }
    final URI baseUri;
    final URI requestUri;
    try {
        baseUri = absoluteUriBuilder.replacePath(encodedBasePath).build();
        String queryParameters = ContainerUtils.encodeUnsafeCharacters(request.getQueryString());
        if (queryParameters == null) {
            queryParameters = "";
        }
        requestUri = absoluteUriBuilder.replacePath(requestURI).replaceQuery(queryParameters).build();
    } catch (final UriBuilderException | IllegalArgumentException ex) {
        setResponseForInvalidUri(response, ex);
        return;
    }
    service(baseUri, requestUri, request, response);
}
Also used : UriBuilderException(javax.ws.rs.core.UriBuilderException) UriBuilder(javax.ws.rs.core.UriBuilder) URI(java.net.URI) ProcessingException(javax.ws.rs.ProcessingException)

Aggregations

ProcessingException (javax.ws.rs.ProcessingException)91 Test (org.junit.Test)32 IOException (java.io.IOException)26 Response (javax.ws.rs.core.Response)20 WebTarget (javax.ws.rs.client.WebTarget)19 JerseyTest (org.glassfish.jersey.test.JerseyTest)16 WebApplicationException (javax.ws.rs.WebApplicationException)11 CountDownLatch (java.util.concurrent.CountDownLatch)9 Client (javax.ws.rs.client.Client)9 ResponseProcessingException (javax.ws.rs.client.ResponseProcessingException)9 ByteArrayOutputStream (java.io.ByteArrayOutputStream)8 ClientRequest (org.glassfish.jersey.client.ClientRequest)8 ClientResponse (org.glassfish.jersey.client.ClientResponse)8 ByteArrayInputStream (java.io.ByteArrayInputStream)6 URI (java.net.URI)6 NoContentException (javax.ws.rs.core.NoContentException)6 OutputStream (java.io.OutputStream)5 Map (java.util.Map)5 CompletableFuture (java.util.concurrent.CompletableFuture)5 EventSource (org.glassfish.jersey.media.sse.EventSource)5