Search in sources :

Example 1 with ProcessingException

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

the class AbstractParamConverterProvider method getConverter.

@Override
public <T> ParamConverter<T> getConverter(Class<T> rawType, Type genericType, Annotation[] annotations) {
    if (AbstractParam.class.isAssignableFrom(rawType)) {
        final String parameterName = JerseyParameterNameProvider.getParameterNameFromAnnotations(annotations).orElse("Parameter");
        final Constructor<T> constructor;
        try {
            constructor = rawType.getConstructor(String.class, String.class);
        } catch (NoSuchMethodException ignored) {
            // leaving Jersey to handle these parameters as it normally would.
            return null;
        }
        return new ParamConverter<T>() {

            @Override
            @SuppressWarnings("unchecked")
            public T fromString(String value) {
                if (rawType != NonEmptyStringParam.class && Strings.isNullOrEmpty(value)) {
                    return null;
                }
                try {
                    return _fromString(value);
                } catch (InvocationTargetException ex) {
                    final Throwable cause = ex.getCause();
                    if (cause instanceof WebApplicationException) {
                        throw (WebApplicationException) cause;
                    } else {
                        throw new ExtractorException(cause);
                    }
                } catch (final Exception ex) {
                    throw new ProcessingException(ex);
                }
            }

            protected T _fromString(String value) throws Exception {
                return constructor.newInstance(value, parameterName);
            }

            @Override
            public String toString(T value) throws IllegalArgumentException {
                if (value == null) {
                    throw new IllegalArgumentException(LocalizationMessages.METHOD_PARAMETER_CANNOT_BE_NULL("value"));
                }
                return value.toString();
            }
        };
    }
    return null;
}
Also used : WebApplicationException(javax.ws.rs.WebApplicationException) ParamConverter(javax.ws.rs.ext.ParamConverter) InvocationTargetException(java.lang.reflect.InvocationTargetException) ProcessingException(javax.ws.rs.ProcessingException) WebApplicationException(javax.ws.rs.WebApplicationException) ExtractorException(org.glassfish.jersey.internal.inject.ExtractorException) InvocationTargetException(java.lang.reflect.InvocationTargetException) ExtractorException(org.glassfish.jersey.internal.inject.ExtractorException) ProcessingException(javax.ws.rs.ProcessingException)

Example 2 with ProcessingException

use of javax.ws.rs.ProcessingException in project metrics by dropwizard.

the class SingletonMetricsExceptionMeteredPerClassJerseyTest method subresourcesFromLocatorsRegisterMetrics.

@Test
public void subresourcesFromLocatorsRegisterMetrics() {
    final Meter meter = registry.meter(name(InstrumentedSubResourceExceptionMeteredPerClass.class, "exceptionMetered", "exceptions"));
    assertThat(target("subresource/exception-metered").request().get(String.class)).isEqualTo("fuh");
    assertThat(meter.getCount()).isZero();
    try {
        target("subresource/exception-metered").queryParam("splode", true).request().get(String.class);
        failBecauseExceptionWasNotThrown(ProcessingException.class);
    } catch (ProcessingException e) {
        assertThat(e.getCause()).isInstanceOf(IOException.class);
    }
    assertThat(meter.getCount()).isEqualTo(1);
}
Also used : Meter(com.codahale.metrics.Meter) InstrumentedSubResourceExceptionMeteredPerClass(com.codahale.metrics.jersey2.resources.InstrumentedSubResourceExceptionMeteredPerClass) IOException(java.io.IOException) ProcessingException(javax.ws.rs.ProcessingException) Test(org.junit.Test) JerseyTest(org.glassfish.jersey.test.JerseyTest)

Example 3 with ProcessingException

use of javax.ws.rs.ProcessingException in project metrics by dropwizard.

the class SingletonMetricsJerseyTest method exceptionMeteredMethodsAreExceptionMetered.

@Test
public void exceptionMeteredMethodsAreExceptionMetered() {
    final Meter meter = registry.meter(name(InstrumentedResource.class, "exceptionMetered", "exceptions"));
    assertThat(target("exception-metered").request().get(String.class)).isEqualTo("fuh");
    assertThat(meter.getCount()).isZero();
    try {
        target("exception-metered").queryParam("splode", true).request().get(String.class);
        failBecauseExceptionWasNotThrown(ProcessingException.class);
    } catch (ProcessingException e) {
        assertThat(e.getCause()).isInstanceOf(IOException.class);
    }
    assertThat(meter.getCount()).isEqualTo(1);
}
Also used : Meter(com.codahale.metrics.Meter) IOException(java.io.IOException) InstrumentedResource(com.codahale.metrics.jersey2.resources.InstrumentedResource) ProcessingException(javax.ws.rs.ProcessingException) Test(org.junit.Test) JerseyTest(org.glassfish.jersey.test.JerseyTest)

Example 4 with ProcessingException

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

the class DropwizardApacheConnector method apply.

/**
     * {@inheritDoc}
     */
@Override
public ClientResponse apply(ClientRequest jerseyRequest) {
    try {
        final HttpUriRequest apacheRequest = buildApacheRequest(jerseyRequest);
        final CloseableHttpResponse apacheResponse = client.execute(apacheRequest);
        final StatusLine statusLine = apacheResponse.getStatusLine();
        final Response.StatusType status = Statuses.from(statusLine.getStatusCode(), firstNonNull(statusLine.getReasonPhrase(), ""));
        final ClientResponse jerseyResponse = new ClientResponse(status, jerseyRequest);
        for (Header header : apacheResponse.getAllHeaders()) {
            final List<String> headerValues = jerseyResponse.getHeaders().get(header.getName());
            if (headerValues == null) {
                jerseyResponse.getHeaders().put(header.getName(), Lists.newArrayList(header.getValue()));
            } else {
                headerValues.add(header.getValue());
            }
        }
        final HttpEntity httpEntity = apacheResponse.getEntity();
        jerseyResponse.setEntityStream(httpEntity != null ? httpEntity.getContent() : new ByteArrayInputStream(new byte[0]));
        return jerseyResponse;
    } catch (Exception e) {
        throw new ProcessingException(e);
    }
}
Also used : HttpUriRequest(org.apache.http.client.methods.HttpUriRequest) ClientResponse(org.glassfish.jersey.client.ClientResponse) AbstractHttpEntity(org.apache.http.entity.AbstractHttpEntity) HttpEntity(org.apache.http.HttpEntity) IOException(java.io.IOException) ProcessingException(javax.ws.rs.ProcessingException) StatusLine(org.apache.http.StatusLine) ClientResponse(org.glassfish.jersey.client.ClientResponse) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) Response(javax.ws.rs.core.Response) Header(org.apache.http.Header) ByteArrayInputStream(java.io.ByteArrayInputStream) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) ProcessingException(javax.ws.rs.ProcessingException)

Example 5 with ProcessingException

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

the class GrizzlyHttpServerFactory method createHttpServer.

/**
     * Create new {@link HttpServer} instance.
     *
     * @param uri                   uri on which the {@link ApplicationHandler} will be deployed. Only first path
     *                              segment will be used as context path, the rest will be ignored.
     * @param handler               {@link HttpHandler} instance.
     * @param secure                used for call {@link NetworkListener#setSecure(boolean)}.
     * @param sslEngineConfigurator Ssl settings to be passed to {@link NetworkListener#setSSLEngineConfig}.
     * @param start                 if set to false, server will not get started, this allows end users to set
     *                              additional properties on the underlying listener.
     * @return newly created {@code HttpServer}.
     * @throws ProcessingException in case of any failure when creating a new {@code HttpServer} instance.
     * @see GrizzlyHttpContainer
     */
public static HttpServer createHttpServer(final URI uri, final GrizzlyHttpContainer handler, final boolean secure, final SSLEngineConfigurator sslEngineConfigurator, final boolean start) {
    final String host = (uri.getHost() == null) ? NetworkListener.DEFAULT_NETWORK_HOST : uri.getHost();
    final int port = (uri.getPort() == -1) ? (secure ? Container.DEFAULT_HTTPS_PORT : Container.DEFAULT_HTTP_PORT) : uri.getPort();
    final NetworkListener listener = new NetworkListener("grizzly", host, port);
    listener.getTransport().getWorkerThreadPoolConfig().setThreadFactory(new ThreadFactoryBuilder().setNameFormat("grizzly-http-server-%d").setUncaughtExceptionHandler(new JerseyProcessingUncaughtExceptionHandler()).build());
    listener.setSecure(secure);
    if (sslEngineConfigurator != null) {
        listener.setSSLEngineConfig(sslEngineConfigurator);
    }
    final HttpServer server = new HttpServer();
    server.addListener(listener);
    // Map the path to the processor.
    final ServerConfiguration config = server.getServerConfiguration();
    if (handler != null) {
        final String path = uri.getPath().replaceAll("/{2,}", "/");
        final String contextPath = path.endsWith("/") ? path.substring(0, path.length() - 1) : path;
        config.addHttpHandler(handler, HttpHandlerRegistration.bulder().contextPath(contextPath).build());
    }
    config.setPassTraceRequest(true);
    config.setDefaultQueryEncoding(Charsets.UTF8_CHARSET);
    if (start) {
        try {
            // Start the server.
            server.start();
        } catch (final IOException ex) {
            server.shutdownNow();
            throw new ProcessingException(LocalizationMessages.FAILED_TO_START_SERVER(ex.getMessage()), ex);
        }
    }
    return server;
}
Also used : JerseyProcessingUncaughtExceptionHandler(org.glassfish.jersey.process.JerseyProcessingUncaughtExceptionHandler) ServerConfiguration(org.glassfish.grizzly.http.server.ServerConfiguration) HttpServer(org.glassfish.grizzly.http.server.HttpServer) ThreadFactoryBuilder(org.glassfish.jersey.internal.guava.ThreadFactoryBuilder) IOException(java.io.IOException) NetworkListener(org.glassfish.grizzly.http.server.NetworkListener) 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