Search in sources :

Example 1 with JerseyChunkedInput

use of org.glassfish.jersey.netty.connector.internal.JerseyChunkedInput in project jersey by jersey.

the class NettyResponseWriter method writeResponseStatusAndHeaders.

@Override
public synchronized OutputStream writeResponseStatusAndHeaders(long contentLength, ContainerResponse responseContext) throws ContainerException {
    if (responseWritten) {
        LOGGER.log(Level.FINE, "Response already written.");
        return null;
    }
    responseWritten = true;
    String reasonPhrase = responseContext.getStatusInfo().getReasonPhrase();
    int statusCode = responseContext.getStatus();
    HttpResponseStatus status = reasonPhrase == null ? HttpResponseStatus.valueOf(statusCode) : new HttpResponseStatus(statusCode, reasonPhrase);
    DefaultHttpResponse response;
    if (contentLength == 0) {
        response = new DefaultFullHttpResponse(req.protocolVersion(), status);
    } else {
        response = new DefaultHttpResponse(req.protocolVersion(), status);
    }
    for (final Map.Entry<String, List<String>> e : responseContext.getStringHeaders().entrySet()) {
        response.headers().add(e.getKey(), e.getValue());
    }
    if (contentLength == -1) {
        HttpUtil.setTransferEncodingChunked(response, true);
    } else {
        response.headers().set(HttpHeaderNames.CONTENT_LENGTH, contentLength);
    }
    if (HttpUtil.isKeepAlive(req)) {
        response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
    }
    ctx.writeAndFlush(response);
    if (req.method() != HttpMethod.HEAD && (contentLength > 0 || contentLength == -1)) {
        JerseyChunkedInput jerseyChunkedInput = new JerseyChunkedInput(ctx.channel());
        if (HttpUtil.isTransferEncodingChunked(response)) {
            ctx.write(new HttpChunkedInput(jerseyChunkedInput)).addListener(FLUSH_FUTURE);
        } else {
            ctx.write(new HttpChunkedInput(jerseyChunkedInput)).addListener(FLUSH_FUTURE);
        }
        return jerseyChunkedInput;
    } else {
        ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
        return null;
    }
}
Also used : DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) HttpChunkedInput(io.netty.handler.codec.http.HttpChunkedInput) HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) DefaultHttpResponse(io.netty.handler.codec.http.DefaultHttpResponse) List(java.util.List) Map(java.util.Map) JerseyChunkedInput(org.glassfish.jersey.netty.connector.internal.JerseyChunkedInput)

Example 2 with JerseyChunkedInput

use of org.glassfish.jersey.netty.connector.internal.JerseyChunkedInput in project jersey by jersey.

the class NettyConnector method apply.

@Override
public Future<?> apply(final ClientRequest jerseyRequest, final AsyncConnectorCallback jerseyCallback) {
    final CompletableFuture<Object> settableFuture = new CompletableFuture<>();
    final URI requestUri = jerseyRequest.getUri();
    String host = requestUri.getHost();
    int port = requestUri.getPort() != -1 ? requestUri.getPort() : "https".equals(requestUri.getScheme()) ? 443 : 80;
    try {
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {

            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ChannelPipeline p = ch.pipeline();
                // Enable HTTPS if necessary.
                if ("https".equals(requestUri.getScheme())) {
                    // making client authentication optional for now; it could be extracted to configurable property
                    JdkSslContext jdkSslContext = new JdkSslContext(client.getSslContext(), true, ClientAuth.NONE);
                    p.addLast(jdkSslContext.newHandler(ch.alloc()));
                }
                // http proxy
                Configuration config = jerseyRequest.getConfiguration();
                final Object proxyUri = config.getProperties().get(ClientProperties.PROXY_URI);
                if (proxyUri != null) {
                    final URI u = getProxyUri(proxyUri);
                    final String userName = ClientProperties.getValue(config.getProperties(), ClientProperties.PROXY_USERNAME, String.class);
                    final String password = ClientProperties.getValue(config.getProperties(), ClientProperties.PROXY_PASSWORD, String.class);
                    p.addLast(new HttpProxyHandler(new InetSocketAddress(u.getHost(), u.getPort() == -1 ? 8080 : u.getPort()), userName, password));
                }
                p.addLast(new HttpClientCodec());
                p.addLast(new ChunkedWriteHandler());
                p.addLast(new HttpContentDecompressor());
                p.addLast(new JerseyClientHandler(NettyConnector.this, jerseyRequest, jerseyCallback, settableFuture));
            }
        });
        // connect timeout
        Integer connectTimeout = ClientProperties.getValue(jerseyRequest.getConfiguration().getProperties(), ClientProperties.CONNECT_TIMEOUT, 0);
        if (connectTimeout > 0) {
            b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeout);
        }
        // Make the connection attempt.
        final Channel ch = b.connect(host, port).sync().channel();
        // guard against prematurely closed channel
        final GenericFutureListener<io.netty.util.concurrent.Future<? super Void>> closeListener = new GenericFutureListener<io.netty.util.concurrent.Future<? super Void>>() {

            @Override
            public void operationComplete(io.netty.util.concurrent.Future<? super Void> future) throws Exception {
                if (!settableFuture.isDone()) {
                    settableFuture.completeExceptionally(new IOException("Channel closed."));
                }
            }
        };
        ch.closeFuture().addListener(closeListener);
        HttpRequest nettyRequest;
        if (jerseyRequest.hasEntity()) {
            nettyRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.valueOf(jerseyRequest.getMethod()), requestUri.getRawPath());
        } else {
            nettyRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.valueOf(jerseyRequest.getMethod()), requestUri.getRawPath());
        }
        // headers
        for (final Map.Entry<String, List<String>> e : jerseyRequest.getStringHeaders().entrySet()) {
            nettyRequest.headers().add(e.getKey(), e.getValue());
        }
        // host header - http 1.1
        nettyRequest.headers().add(HttpHeaderNames.HOST, jerseyRequest.getUri().getHost());
        if (jerseyRequest.hasEntity()) {
            if (jerseyRequest.getLengthLong() == -1) {
                HttpUtil.setTransferEncodingChunked(nettyRequest, true);
            } else {
                nettyRequest.headers().add(HttpHeaderNames.CONTENT_LENGTH, jerseyRequest.getLengthLong());
            }
        }
        if (jerseyRequest.hasEntity()) {
            // Send the HTTP request.
            ch.writeAndFlush(nettyRequest);
            final JerseyChunkedInput jerseyChunkedInput = new JerseyChunkedInput(ch);
            jerseyRequest.setStreamProvider(new OutboundMessageContext.StreamProvider() {

                @Override
                public OutputStream getOutputStream(int contentLength) throws IOException {
                    return jerseyChunkedInput;
                }
            });
            if (HttpUtil.isTransferEncodingChunked(nettyRequest)) {
                ch.write(new HttpChunkedInput(jerseyChunkedInput));
            } else {
                ch.write(jerseyChunkedInput);
            }
            executorService.execute(new Runnable() {

                @Override
                public void run() {
                    // close listener is not needed any more.
                    ch.closeFuture().removeListener(closeListener);
                    try {
                        jerseyRequest.writeEntity();
                    } catch (IOException e) {
                        jerseyCallback.failure(e);
                        settableFuture.completeExceptionally(e);
                    }
                }
            });
            ch.flush();
        } else {
            // close listener is not needed any more.
            ch.closeFuture().removeListener(closeListener);
            // Send the HTTP request.
            ch.writeAndFlush(nettyRequest);
        }
    } catch (InterruptedException e) {
        settableFuture.completeExceptionally(e);
        return settableFuture;
    }
    return settableFuture;
}
Also used : NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) Configuration(javax.ws.rs.core.Configuration) InetSocketAddress(java.net.InetSocketAddress) OutputStream(java.io.OutputStream) HttpClientCodec(io.netty.handler.codec.http.HttpClientCodec) URI(java.net.URI) OutboundMessageContext(org.glassfish.jersey.message.internal.OutboundMessageContext) CompletableFuture(java.util.concurrent.CompletableFuture) HttpChunkedInput(io.netty.handler.codec.http.HttpChunkedInput) DefaultHttpRequest(io.netty.handler.codec.http.DefaultHttpRequest) Bootstrap(io.netty.bootstrap.Bootstrap) List(java.util.List) GenericFutureListener(io.netty.util.concurrent.GenericFutureListener) JerseyChunkedInput(org.glassfish.jersey.netty.connector.internal.JerseyChunkedInput) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) DefaultHttpRequest(io.netty.handler.codec.http.DefaultHttpRequest) HttpRequest(io.netty.handler.codec.http.HttpRequest) JdkSslContext(io.netty.handler.ssl.JdkSslContext) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) Channel(io.netty.channel.Channel) IOException(java.io.IOException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) ProcessingException(javax.ws.rs.ProcessingException) ChannelPipeline(io.netty.channel.ChannelPipeline) HttpContentDecompressor(io.netty.handler.codec.http.HttpContentDecompressor) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) ChunkedWriteHandler(io.netty.handler.stream.ChunkedWriteHandler) CompletableFuture(java.util.concurrent.CompletableFuture) Future(java.util.concurrent.Future) HttpProxyHandler(io.netty.handler.proxy.HttpProxyHandler) Map(java.util.Map)

Aggregations

HttpChunkedInput (io.netty.handler.codec.http.HttpChunkedInput)2 List (java.util.List)2 Map (java.util.Map)2 JerseyChunkedInput (org.glassfish.jersey.netty.connector.internal.JerseyChunkedInput)2 Bootstrap (io.netty.bootstrap.Bootstrap)1 Channel (io.netty.channel.Channel)1 ChannelPipeline (io.netty.channel.ChannelPipeline)1 SocketChannel (io.netty.channel.socket.SocketChannel)1 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)1 DefaultFullHttpRequest (io.netty.handler.codec.http.DefaultFullHttpRequest)1 DefaultFullHttpResponse (io.netty.handler.codec.http.DefaultFullHttpResponse)1 DefaultHttpRequest (io.netty.handler.codec.http.DefaultHttpRequest)1 DefaultHttpResponse (io.netty.handler.codec.http.DefaultHttpResponse)1 HttpClientCodec (io.netty.handler.codec.http.HttpClientCodec)1 HttpContentDecompressor (io.netty.handler.codec.http.HttpContentDecompressor)1 HttpRequest (io.netty.handler.codec.http.HttpRequest)1 HttpResponseStatus (io.netty.handler.codec.http.HttpResponseStatus)1 HttpProxyHandler (io.netty.handler.proxy.HttpProxyHandler)1 JdkSslContext (io.netty.handler.ssl.JdkSslContext)1 ChunkedWriteHandler (io.netty.handler.stream.ChunkedWriteHandler)1