Search in sources :

Example 6 with ProcessingException

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

the class JettyHttpContainerFactory method createServer.

/**
     * Create a {@link Server} that registers an {@link org.eclipse.jetty.server.Handler} that
     * in turn manages all root resource and provider classes found by searching the
     * classes referenced in the java classpath.
     *
     * @param uri               the URI to create the http server. The URI scheme must be
     *                          equal to {@code https}. The URI user information and host
     *                          are ignored. If the URI port is not present then port
     *                          {@value org.glassfish.jersey.server.spi.Container#DEFAULT_HTTPS_PORT} will be
     *                          used. The URI path, query and fragment components are ignored.
     * @param sslContextFactory this is the SSL context factory used to configure SSL connector
     * @param handler           the container that handles all HTTP requests
     * @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 {@link Server}.
     *
     * @throws ProcessingException      in case of any failure when creating a new Jetty {@code Server} instance.
     * @throws IllegalArgumentException if {@code uri} is {@code null}.
     * @see JettyHttpContainer
     */
public static Server createServer(final URI uri, final SslContextFactory sslContextFactory, final JettyHttpContainer handler, final boolean start) {
    if (uri == null) {
        throw new IllegalArgumentException(LocalizationMessages.URI_CANNOT_BE_NULL());
    }
    final String scheme = uri.getScheme();
    int defaultPort = Container.DEFAULT_HTTP_PORT;
    if (sslContextFactory == null) {
        if (!"http".equalsIgnoreCase(scheme)) {
            throw new IllegalArgumentException(LocalizationMessages.WRONG_SCHEME_WHEN_USING_HTTP());
        }
    } else {
        if (!"https".equalsIgnoreCase(scheme)) {
            throw new IllegalArgumentException(LocalizationMessages.WRONG_SCHEME_WHEN_USING_HTTPS());
        }
        defaultPort = Container.DEFAULT_HTTPS_PORT;
    }
    final int port = (uri.getPort() == -1) ? defaultPort : uri.getPort();
    final Server server = new Server(new JettyConnectorThreadPool());
    final HttpConfiguration config = new HttpConfiguration();
    if (sslContextFactory != null) {
        config.setSecureScheme("https");
        config.setSecurePort(port);
        config.addCustomizer(new SecureRequestCustomizer());
        final ServerConnector https = new ServerConnector(server, new SslConnectionFactory(sslContextFactory, "http/1.1"), new HttpConnectionFactory(config));
        https.setPort(port);
        server.setConnectors(new Connector[] { https });
    } else {
        final ServerConnector http = new ServerConnector(server, new HttpConnectionFactory(config));
        http.setPort(port);
        server.setConnectors(new Connector[] { http });
    }
    if (handler != null) {
        server.setHandler(handler);
    }
    if (start) {
        try {
            // Start the server.
            server.start();
        } catch (final Exception e) {
            throw new ProcessingException(LocalizationMessages.ERROR_WHEN_CREATING_SERVER(), e);
        }
    }
    return server;
}
Also used : ServerConnector(org.eclipse.jetty.server.ServerConnector) SecureRequestCustomizer(org.eclipse.jetty.server.SecureRequestCustomizer) Server(org.eclipse.jetty.server.Server) HttpConnectionFactory(org.eclipse.jetty.server.HttpConnectionFactory) HttpConfiguration(org.eclipse.jetty.server.HttpConfiguration) SslConnectionFactory(org.eclipse.jetty.server.SslConnectionFactory) ProcessingException(javax.ws.rs.ProcessingException) ProcessingException(javax.ws.rs.ProcessingException)

Example 7 with ProcessingException

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

the class NettyHttpContainerProvider method createServer.

/**
     * Create and start Netty server.
     *
     * @param baseUri       base uri.
     * @param configuration Jersey configuration.
     * @param sslContext    Netty SSL context (can be null).
     * @param block         when {@code true}, this method will block until the server is stopped. When {@code false}, the
     *                      execution will
     *                      end immediately after the server is started.
     * @return Netty channel instance.
     * @throws ProcessingException when there is an issue with creating new container.
     */
public static Channel createServer(final URI baseUri, final ResourceConfig configuration, SslContext sslContext, final boolean block) throws ProcessingException {
    // Configure the server.
    final EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    final EventLoopGroup workerGroup = new NioEventLoopGroup();
    final NettyHttpContainer container = new NettyHttpContainer(configuration);
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.option(ChannelOption.SO_BACKLOG, 1024);
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).childHandler(new JerseyServerInitializer(baseUri, sslContext, container));
        int port = getPort(baseUri);
        Channel ch = b.bind(port).sync().channel();
        ch.closeFuture().addListener(new GenericFutureListener<Future<? super Void>>() {

            @Override
            public void operationComplete(Future<? super Void> future) throws Exception {
                container.getApplicationHandler().onShutdown(container);
                bossGroup.shutdownGracefully();
                workerGroup.shutdownGracefully();
            }
        });
        if (block) {
            ch.closeFuture().sync();
            return ch;
        } else {
            return ch;
        }
    } catch (InterruptedException e) {
        throw new ProcessingException(e);
    }
}
Also used : NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) Channel(io.netty.channel.Channel) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ProcessingException(javax.ws.rs.ProcessingException) EventLoopGroup(io.netty.channel.EventLoopGroup) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) Future(io.netty.util.concurrent.Future) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) ProcessingException(javax.ws.rs.ProcessingException)

Example 8 with ProcessingException

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

the class JdkHttpsServerTest method testHttpsServerNoSslContextDelayedStart.

/**
     * Test, that {@link HttpsServer} can be manually started even with (empty) SSLContext, but will throw an exception
     * on request.
     * @throws Exception
     */
@Test(expected = IOException.class)
public void testHttpsServerNoSslContextDelayedStart() throws Throwable {
    server = JdkHttpServerFactory.createHttpServer(httpsUri, rc, null, false);
    assertThat(server, instanceOf(HttpsServer.class));
    server.start();
    final Client client = ClientBuilder.newBuilder().newClient();
    try {
        client.target(httpsUri).path("testHttps").request().get(String.class);
    } catch (final ProcessingException e) {
        throw e.getCause();
    }
}
Also used : Client(javax.ws.rs.client.Client) HttpsServer(com.sun.net.httpserver.HttpsServer) ProcessingException(javax.ws.rs.ProcessingException) Test(org.junit.Test)

Example 9 with ProcessingException

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

the class JerseyInvocation method invoke.

@Override
public <T> T invoke(final Class<T> responseType) throws ProcessingException, WebApplicationException {
    if (responseType == null) {
        throw new IllegalArgumentException(LocalizationMessages.RESPONSE_TYPE_IS_NULL());
    }
    final ClientRuntime runtime = request().getClientRuntime();
    final RequestScope requestScope = runtime.getRequestScope();
    //noinspection Duplicates
    return requestScope.runInScope(() -> {
        try {
            return translate(runtime.invoke(requestForCall(requestContext)), requestScope, responseType);
        } catch (final ProcessingException ex) {
            if (ex.getCause() instanceof WebApplicationException) {
                throw (WebApplicationException) ex.getCause();
            }
            throw ex;
        }
    });
}
Also used : WebApplicationException(javax.ws.rs.WebApplicationException) RequestScope(org.glassfish.jersey.process.internal.RequestScope) ProcessingException(javax.ws.rs.ProcessingException) ResponseProcessingException(javax.ws.rs.client.ResponseProcessingException)

Example 10 with ProcessingException

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

the class HttpUrlConnector method _apply.

private ClientResponse _apply(final ClientRequest request) throws IOException {
    final HttpURLConnection uc;
    uc = this.connectionFactory.getConnection(request.getUri().toURL());
    uc.setDoInput(true);
    final String httpMethod = request.getMethod();
    if (request.resolveProperty(HttpUrlConnectorProvider.SET_METHOD_WORKAROUND, setMethodWorkaround)) {
        setRequestMethodViaJreBugWorkaround(uc, httpMethod);
    } else {
        uc.setRequestMethod(httpMethod);
    }
    uc.setInstanceFollowRedirects(request.resolveProperty(ClientProperties.FOLLOW_REDIRECTS, true));
    uc.setConnectTimeout(request.resolveProperty(ClientProperties.CONNECT_TIMEOUT, uc.getConnectTimeout()));
    uc.setReadTimeout(request.resolveProperty(ClientProperties.READ_TIMEOUT, uc.getReadTimeout()));
    secureConnection(request.getClient(), uc);
    final Object entity = request.getEntity();
    if (entity != null) {
        RequestEntityProcessing entityProcessing = request.resolveProperty(ClientProperties.REQUEST_ENTITY_PROCESSING, RequestEntityProcessing.class);
        if (entityProcessing == null || entityProcessing != RequestEntityProcessing.BUFFERED) {
            final long length = request.getLengthLong();
            if (fixLengthStreaming && length > 0) {
                // uc.setFixedLengthStreamingMode(long) was introduced in JDK 1.7 and Jersey client supports 1.6+
                if ("1.6".equals(Runtime.class.getPackage().getSpecificationVersion())) {
                    uc.setFixedLengthStreamingMode(request.getLength());
                } else {
                    uc.setFixedLengthStreamingMode(length);
                }
            } else if (entityProcessing == RequestEntityProcessing.CHUNKED) {
                uc.setChunkedStreamingMode(chunkSize);
            }
        }
        uc.setDoOutput(true);
        if ("GET".equalsIgnoreCase(httpMethod)) {
            final Logger logger = Logger.getLogger(HttpUrlConnector.class.getName());
            if (logger.isLoggable(Level.INFO)) {
                logger.log(Level.INFO, LocalizationMessages.HTTPURLCONNECTION_REPLACES_GET_WITH_ENTITY());
            }
        }
        request.setStreamProvider(contentLength -> {
            setOutboundHeaders(request.getStringHeaders(), uc);
            return uc.getOutputStream();
        });
        request.writeEntity();
    } else {
        setOutboundHeaders(request.getStringHeaders(), uc);
    }
    final int code = uc.getResponseCode();
    final String reasonPhrase = uc.getResponseMessage();
    final Response.StatusType status = reasonPhrase == null ? Statuses.from(code) : Statuses.from(code, reasonPhrase);
    final URI resolvedRequestUri;
    try {
        resolvedRequestUri = uc.getURL().toURI();
    } catch (URISyntaxException e) {
        throw new ProcessingException(e);
    }
    ClientResponse responseContext = new ClientResponse(status, request, resolvedRequestUri);
    responseContext.headers(uc.getHeaderFields().entrySet().stream().filter(stringListEntry -> stringListEntry.getKey() != null).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)));
    responseContext.setEntityStream(getInputStream(uc));
    return responseContext;
}
Also used : ClientResponse(org.glassfish.jersey.client.ClientResponse) RequestEntityProcessing(org.glassfish.jersey.client.RequestEntityProcessing) URISyntaxException(java.net.URISyntaxException) Logger(java.util.logging.Logger) URI(java.net.URI) ClientResponse(org.glassfish.jersey.client.ClientResponse) Response(javax.ws.rs.core.Response) HttpURLConnection(java.net.HttpURLConnection) 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