Search in sources :

Example 6 with Future

use of io.netty.util.concurrent.Future in project jersey by jersey.

the class JerseyClientHandler method channelRead0.

@Override
public void channelRead0(ChannelHandlerContext ctx, HttpObject msg) {
    if (msg instanceof HttpResponse) {
        final HttpResponse response = (HttpResponse) msg;
        final ClientResponse jerseyResponse = new ClientResponse(new Response.StatusType() {

            @Override
            public int getStatusCode() {
                return response.status().code();
            }

            @Override
            public Response.Status.Family getFamily() {
                return Response.Status.Family.familyOf(response.status().code());
            }

            @Override
            public String getReasonPhrase() {
                return response.status().reasonPhrase();
            }
        }, jerseyRequest);
        for (Map.Entry<String, String> entry : response.headers().entries()) {
            jerseyResponse.getHeaders().add(entry.getKey(), entry.getValue());
        }
        // request entity handling.
        if ((response.headers().contains(HttpHeaderNames.CONTENT_LENGTH) && HttpUtil.getContentLength(response) > 0) || HttpUtil.isTransferEncodingChunked(response)) {
            ctx.channel().closeFuture().addListener(new GenericFutureListener<Future<? super Void>>() {

                @Override
                public void operationComplete(Future<? super Void> future) throws Exception {
                    isList.add(NettyInputStream.END_OF_INPUT_ERROR);
                }
            });
            jerseyResponse.setEntityStream(new NettyInputStream(isList));
        } else {
            jerseyResponse.setEntityStream(new InputStream() {

                @Override
                public int read() throws IOException {
                    return -1;
                }
            });
        }
        if (asyncConnectorCallback != null) {
            connector.executorService.execute(new Runnable() {

                @Override
                public void run() {
                    asyncConnectorCallback.response(jerseyResponse);
                    future.complete(jerseyResponse);
                }
            });
        }
    }
    if (msg instanceof HttpContent) {
        HttpContent httpContent = (HttpContent) msg;
        ByteBuf content = httpContent.content();
        if (content.isReadable()) {
            // copy bytes - when netty reads last chunk, it automatically closes the channel, which invalidates all
            // relates ByteBuffs.
            byte[] bytes = new byte[content.readableBytes()];
            content.getBytes(content.readerIndex(), bytes);
            isList.add(new ByteArrayInputStream(bytes));
        }
        if (msg instanceof LastHttpContent) {
            isList.add(NettyInputStream.END_OF_INPUT);
        }
    }
}
Also used : ClientResponse(org.glassfish.jersey.client.ClientResponse) ByteArrayInputStream(java.io.ByteArrayInputStream) NettyInputStream(org.glassfish.jersey.netty.connector.internal.NettyInputStream) InputStream(java.io.InputStream) HttpResponse(io.netty.handler.codec.http.HttpResponse) IOException(java.io.IOException) NettyInputStream(org.glassfish.jersey.netty.connector.internal.NettyInputStream) ByteBuf(io.netty.buffer.ByteBuf) LastHttpContent(io.netty.handler.codec.http.LastHttpContent) IOException(java.io.IOException) ClientResponse(org.glassfish.jersey.client.ClientResponse) Response(javax.ws.rs.core.Response) HttpResponse(io.netty.handler.codec.http.HttpResponse) ByteArrayInputStream(java.io.ByteArrayInputStream) CompletableFuture(java.util.concurrent.CompletableFuture) Future(io.netty.util.concurrent.Future) Map(java.util.Map) HttpContent(io.netty.handler.codec.http.HttpContent) LastHttpContent(io.netty.handler.codec.http.LastHttpContent)

Example 7 with Future

use of io.netty.util.concurrent.Future in project netty by netty.

the class ReentrantChannelTest method testCloseInFlush.

@Test
public void testCloseInFlush() throws Exception {
    LocalAddress addr = new LocalAddress("testCloseInFlush");
    ServerBootstrap sb = getLocalServerBootstrap();
    sb.bind(addr).sync().channel();
    Bootstrap cb = getLocalClientBootstrap();
    setInterest(Event.WRITE, Event.FLUSH, Event.CLOSE, Event.EXCEPTION);
    Channel clientChannel = cb.connect(addr).sync().channel();
    clientChannel.pipeline().addLast(new ChannelOutboundHandlerAdapter() {

        @Override
        public void write(final ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
            promise.addListener(new GenericFutureListener<Future<? super Void>>() {

                @Override
                public void operationComplete(Future<? super Void> future) throws Exception {
                    ctx.channel().close();
                }
            });
            super.write(ctx, msg, promise);
            ctx.channel().flush();
        }
    });
    clientChannel.write(createTestBuf(2000)).sync();
    clientChannel.closeFuture().sync();
    assertLog("WRITE\nFLUSH\nCLOSE\n");
}
Also used : LocalAddress(io.netty.channel.local.LocalAddress) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ClosedChannelException(java.nio.channels.ClosedChannelException) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) Future(io.netty.util.concurrent.Future) GenericFutureListener(io.netty.util.concurrent.GenericFutureListener) Test(org.junit.Test)

Example 8 with Future

use of io.netty.util.concurrent.Future in project netty by netty.

the class Http2TestUtil method newVoidPromise.

static ChannelPromise newVoidPromise(final Channel channel) {
    return new DefaultChannelPromise(channel, ImmediateEventExecutor.INSTANCE) {

        @Override
        public ChannelPromise addListener(GenericFutureListener<? extends Future<? super Void>> listener) {
            throw new AssertionFailedError();
        }

        @Override
        public ChannelPromise addListeners(GenericFutureListener<? extends Future<? super Void>>... listeners) {
            throw new AssertionFailedError();
        }

        @Override
        public boolean isVoid() {
            return true;
        }

        @Override
        public boolean tryFailure(Throwable cause) {
            channel().pipeline().fireExceptionCaught(cause);
            return true;
        }

        @Override
        public ChannelPromise setFailure(Throwable cause) {
            tryFailure(cause);
            return this;
        }

        @Override
        public ChannelPromise unvoid() {
            ChannelPromise promise = new DefaultChannelPromise(channel, ImmediateEventExecutor.INSTANCE);
            promise.addListener(new ChannelFutureListener() {

                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (!future.isSuccess()) {
                        channel().pipeline().fireExceptionCaught(future.cause());
                    }
                }
            });
            return promise;
        }
    };
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) DefaultChannelPromise(io.netty.channel.DefaultChannelPromise) ChannelFuture(io.netty.channel.ChannelFuture) Future(io.netty.util.concurrent.Future) ChannelPromise(io.netty.channel.ChannelPromise) DefaultChannelPromise(io.netty.channel.DefaultChannelPromise) AssertionFailedError(junit.framework.AssertionFailedError) GenericFutureListener(io.netty.util.concurrent.GenericFutureListener) ChannelFutureListener(io.netty.channel.ChannelFutureListener)

Example 9 with Future

use of io.netty.util.concurrent.Future in project netty by netty.

the class DefaultHttp2ConnectionTest method removeAllStreamsWhileIteratingActiveStreamsAndExceptionOccurs.

@Test
public void removeAllStreamsWhileIteratingActiveStreamsAndExceptionOccurs() throws InterruptedException, Http2Exception {
    final Endpoint<Http2RemoteFlowController> remote = client.remote();
    final Endpoint<Http2LocalFlowController> local = client.local();
    for (int c = 3, s = 2; c < 5000; c += 2, s += 2) {
        local.createStream(c, false);
        remote.createStream(s, false);
    }
    final Promise<Void> promise = group.next().newPromise();
    final CountDownLatch latch = new CountDownLatch(1);
    try {
        client.forEachActiveStream(new Http2StreamVisitor() {

            @Override
            public boolean visit(Http2Stream stream) throws Http2Exception {
                // This close call is basically a noop, because the following statement will throw an exception.
                client.close(promise);
                // Do an invalid operation while iterating.
                remote.createStream(3, false);
                return true;
            }
        });
    } catch (Http2Exception ignored) {
        client.close(promise).addListener(new FutureListener<Void>() {

            @Override
            public void operationComplete(Future<Void> future) throws Exception {
                assertTrue(promise.isDone());
                latch.countDown();
            }
        });
    }
    assertTrue(latch.await(5, TimeUnit.SECONDS));
}
Also used : FutureListener(io.netty.util.concurrent.FutureListener) CountDownLatch(java.util.concurrent.CountDownLatch) Endpoint(io.netty.handler.codec.http2.Http2Connection.Endpoint) Future(io.netty.util.concurrent.Future) Test(org.junit.Test)

Example 10 with Future

use of io.netty.util.concurrent.Future in project netty by netty.

the class SslHandler method safeClose.

private void safeClose(final ChannelHandlerContext ctx, final ChannelFuture flushFuture, final ChannelPromise promise) {
    if (!ctx.channel().isActive()) {
        ctx.close(promise);
        return;
    }
    final ScheduledFuture<?> timeoutFuture;
    if (!flushFuture.isDone()) {
        long closeNotifyTimeout = closeNotifyFlushTimeoutMillis;
        if (closeNotifyTimeout > 0) {
            // Force-close the connection if close_notify is not fully sent in time.
            timeoutFuture = ctx.executor().schedule(new Runnable() {

                @Override
                public void run() {
                    // May be done in the meantime as cancel(...) is only best effort.
                    if (!flushFuture.isDone()) {
                        logger.warn("{} Last write attempt timed out; force-closing the connection.", ctx.channel());
                        addCloseListener(ctx.close(ctx.newPromise()), promise);
                    }
                }
            }, closeNotifyTimeout, TimeUnit.MILLISECONDS);
        } else {
            timeoutFuture = null;
        }
    } else {
        timeoutFuture = null;
    }
    // Close the connection if close_notify is sent in time.
    flushFuture.addListener(new ChannelFutureListener() {

        @Override
        public void operationComplete(ChannelFuture f) throws Exception {
            if (timeoutFuture != null) {
                timeoutFuture.cancel(false);
            }
            final long closeNotifyReadTimeout = closeNotifyReadTimeoutMillis;
            if (closeNotifyReadTimeout <= 0) {
                // Trigger the close in all cases to make sure the promise is notified
                // See https://github.com/netty/netty/issues/2358
                addCloseListener(ctx.close(ctx.newPromise()), promise);
            } else {
                final ScheduledFuture<?> closeNotifyReadTimeoutFuture;
                if (!sslClosePromise.isDone()) {
                    closeNotifyReadTimeoutFuture = ctx.executor().schedule(new Runnable() {

                        @Override
                        public void run() {
                            if (!sslClosePromise.isDone()) {
                                logger.debug("{} did not receive close_notify in {}ms; force-closing the connection.", ctx.channel(), closeNotifyReadTimeout);
                                // Do the close now...
                                addCloseListener(ctx.close(ctx.newPromise()), promise);
                            }
                        }
                    }, closeNotifyReadTimeout, TimeUnit.MILLISECONDS);
                } else {
                    closeNotifyReadTimeoutFuture = null;
                }
                // Do the close once the we received the close_notify.
                sslClosePromise.addListener(new FutureListener<Channel>() {

                    @Override
                    public void operationComplete(Future<Channel> future) throws Exception {
                        if (closeNotifyReadTimeoutFuture != null) {
                            closeNotifyReadTimeoutFuture.cancel(false);
                        }
                        addCloseListener(ctx.close(ctx.newPromise()), promise);
                    }
                });
            }
        }
    });
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) FutureListener(io.netty.util.concurrent.FutureListener) ChannelFutureListener(io.netty.channel.ChannelFutureListener) ScheduledFuture(java.util.concurrent.ScheduledFuture) ChannelFuture(io.netty.channel.ChannelFuture) Future(io.netty.util.concurrent.Future) ChannelFutureListener(io.netty.channel.ChannelFutureListener) ChannelException(io.netty.channel.ChannelException) SSLException(javax.net.ssl.SSLException) ClosedChannelException(java.nio.channels.ClosedChannelException) IOException(java.io.IOException) UnsupportedMessageTypeException(io.netty.handler.codec.UnsupportedMessageTypeException) ScheduledFuture(java.util.concurrent.ScheduledFuture)

Aggregations

Future (io.netty.util.concurrent.Future)46 FutureListener (io.netty.util.concurrent.FutureListener)29 RFuture (org.redisson.api.RFuture)22 ChannelFuture (io.netty.channel.ChannelFuture)15 ChannelFutureListener (io.netty.channel.ChannelFutureListener)11 Channel (io.netty.channel.Channel)9 IOException (java.io.IOException)9 ArrayList (java.util.ArrayList)9 Timeout (io.netty.util.Timeout)8 TimerTask (io.netty.util.TimerTask)8 AtomicReference (java.util.concurrent.atomic.AtomicReference)8 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)7 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)7 RedisException (org.redisson.client.RedisException)7 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)6 Collection (java.util.Collection)6 RedisConnection (org.redisson.client.RedisConnection)6 RedisConnectionException (org.redisson.client.RedisConnectionException)6 MasterSlaveEntry (org.redisson.connection.MasterSlaveEntry)6 EventLoopGroup (io.netty.channel.EventLoopGroup)5