Search in sources :

Example 96 with ChannelPromise

use of io.netty.channel.ChannelPromise in project netty by netty.

the class EmbeddedChannelTest method testHasNoDisconnectSkipDisconnect.

@Test
public void testHasNoDisconnectSkipDisconnect() throws InterruptedException {
    EmbeddedChannel channel = new EmbeddedChannel(false, new ChannelOutboundHandlerAdapter() {

        @Override
        public void close(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception {
            promise.tryFailure(new Throwable());
        }
    });
    assertFalse(channel.disconnect().isSuccess());
}
Also used : ChannelOutboundHandlerAdapter(io.netty.channel.ChannelOutboundHandlerAdapter) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ChannelPromise(io.netty.channel.ChannelPromise) ClosedChannelException(java.nio.channels.ClosedChannelException) Test(org.junit.jupiter.api.Test)

Example 97 with ChannelPromise

use of io.netty.channel.ChannelPromise in project netty by netty.

the class BootstrapTest method testLateRegisterSuccessBindFailed.

@Test
public void testLateRegisterSuccessBindFailed() throws Exception {
    TestEventLoopGroup group = new TestEventLoopGroup();
    try {
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(group);
        bootstrap.channelFactory(new ChannelFactory<ServerChannel>() {

            @Override
            public ServerChannel newChannel() {
                return new LocalServerChannel() {

                    @Override
                    public ChannelFuture bind(SocketAddress localAddress) {
                        // Close the Channel to emulate what NIO and others impl do on bind failure
                        // See https://github.com/netty/netty/issues/2586
                        close();
                        return newFailedFuture(new SocketException());
                    }

                    @Override
                    public ChannelFuture bind(SocketAddress localAddress, ChannelPromise promise) {
                        // Close the Channel to emulate what NIO and others impl do on bind failure
                        // See https://github.com/netty/netty/issues/2586
                        close();
                        return promise.setFailure(new SocketException());
                    }
                };
            }
        });
        bootstrap.childHandler(new DummyHandler());
        bootstrap.localAddress(new LocalAddress("1"));
        ChannelFuture future = bootstrap.bind();
        assertFalse(future.isDone());
        group.promise.setSuccess();
        final BlockingQueue<Boolean> queue = new LinkedBlockingQueue<Boolean>();
        future.addListener(new ChannelFutureListener() {

            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                queue.add(future.channel().eventLoop().inEventLoop(Thread.currentThread()));
                queue.add(future.isSuccess());
            }
        });
        assertTrue(queue.take());
        assertFalse(queue.take());
    } finally {
        group.shutdownGracefully();
        group.terminationFuture().sync();
    }
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) SocketException(java.net.SocketException) LocalAddress(io.netty.channel.local.LocalAddress) ChannelPromise(io.netty.channel.ChannelPromise) LocalServerChannel(io.netty.channel.local.LocalServerChannel) ServerChannel(io.netty.channel.ServerChannel) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) ChannelFutureListener(io.netty.channel.ChannelFutureListener) SocketException(java.net.SocketException) ConnectException(java.net.ConnectException) UnknownHostException(java.net.UnknownHostException) LocalServerChannel(io.netty.channel.local.LocalServerChannel) SocketAddress(java.net.SocketAddress) Test(org.junit.jupiter.api.Test)

Example 98 with ChannelPromise

use of io.netty.channel.ChannelPromise in project netty by netty.

the class HttpResponseHandler method channelRead0.

@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpResponse msg) throws Exception {
    Integer streamId = msg.headers().getInt(HttpConversionUtil.ExtensionHeaderNames.STREAM_ID.text());
    if (streamId == null) {
        System.err.println("HttpResponseHandler unexpected message received: " + msg);
        return;
    }
    Entry<ChannelFuture, ChannelPromise> entry = streamidPromiseMap.get(streamId);
    if (entry == null) {
        System.err.println("Message received for unknown stream id " + streamId);
    } else {
        // Do stuff with the message (for now just print it)
        ByteBuf content = msg.content();
        if (content.isReadable()) {
            int contentLength = content.readableBytes();
            byte[] arr = new byte[contentLength];
            content.readBytes(arr);
            System.out.println(new String(arr, 0, contentLength, CharsetUtil.UTF_8));
        }
        entry.getValue().setSuccess();
    }
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) ChannelPromise(io.netty.channel.ChannelPromise) ByteBuf(io.netty.buffer.ByteBuf)

Example 99 with ChannelPromise

use of io.netty.channel.ChannelPromise in project netty by netty.

the class HttpResponseHandler method awaitResponses.

/**
 * Wait (sequentially) for a time duration for each anticipated response
 *
 * @param timeout Value of time to wait for each response
 * @param unit Units associated with {@code timeout}
 * @see HttpResponseHandler#put(int, io.netty.channel.ChannelFuture, io.netty.channel.ChannelPromise)
 */
public void awaitResponses(long timeout, TimeUnit unit) {
    Iterator<Entry<Integer, Entry<ChannelFuture, ChannelPromise>>> itr = streamidPromiseMap.entrySet().iterator();
    while (itr.hasNext()) {
        Entry<Integer, Entry<ChannelFuture, ChannelPromise>> entry = itr.next();
        ChannelFuture writeFuture = entry.getValue().getKey();
        if (!writeFuture.awaitUninterruptibly(timeout, unit)) {
            throw new IllegalStateException("Timed out waiting to write for stream id " + entry.getKey());
        }
        if (!writeFuture.isSuccess()) {
            throw new RuntimeException(writeFuture.cause());
        }
        ChannelPromise promise = entry.getValue().getValue();
        if (!promise.awaitUninterruptibly(timeout, unit)) {
            throw new IllegalStateException("Timed out waiting for response on stream id " + entry.getKey());
        }
        if (!promise.isSuccess()) {
            throw new RuntimeException(promise.cause());
        }
        System.out.println("---Stream id: " + entry.getKey() + " received---");
        itr.remove();
    }
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) Entry(java.util.Map.Entry) SimpleEntry(java.util.AbstractMap.SimpleEntry) ChannelPromise(io.netty.channel.ChannelPromise)

Example 100 with ChannelPromise

use of io.netty.channel.ChannelPromise in project netty by netty.

the class WebSocketServerProtocolHandler method decode.

@Override
protected void decode(ChannelHandlerContext ctx, WebSocketFrame frame, List<Object> out) throws Exception {
    if (serverConfig.handleCloseFrames() && frame instanceof CloseWebSocketFrame) {
        WebSocketServerHandshaker handshaker = getHandshaker(ctx.channel());
        if (handshaker != null) {
            frame.retain();
            ChannelPromise promise = ctx.newPromise();
            closeSent(promise);
            handshaker.close(ctx, (CloseWebSocketFrame) frame, promise);
        } else {
            ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
        }
        return;
    }
    super.decode(ctx, frame, out);
}
Also used : ChannelPromise(io.netty.channel.ChannelPromise)

Aggregations

ChannelPromise (io.netty.channel.ChannelPromise)218 Test (org.junit.jupiter.api.Test)87 ChannelFuture (io.netty.channel.ChannelFuture)62 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)59 DefaultChannelPromise (io.netty.channel.DefaultChannelPromise)57 ByteBuf (io.netty.buffer.ByteBuf)54 ChannelOutboundHandlerAdapter (io.netty.channel.ChannelOutboundHandlerAdapter)27 Test (org.junit.Test)24 EmbeddedChannel (io.netty.channel.embedded.EmbeddedChannel)22 FullHttpRequest (io.netty.handler.codec.http.FullHttpRequest)22 Channel (io.netty.channel.Channel)21 DefaultFullHttpRequest (io.netty.handler.codec.http.DefaultFullHttpRequest)21 ClosedChannelException (java.nio.channels.ClosedChannelException)20 ChannelFutureListener (io.netty.channel.ChannelFutureListener)19 HttpHeaders (io.netty.handler.codec.http.HttpHeaders)18 InvocationOnMock (org.mockito.invocation.InvocationOnMock)18 AsciiString (io.netty.util.AsciiString)15 IOException (java.io.IOException)13 Bootstrap (io.netty.bootstrap.Bootstrap)12 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)12