Java Code Examples for io.netty.channel.Channel#newPromise()

The following examples show how to use io.netty.channel.Channel#newPromise() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Bootstrap.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
/**
 * @see {@link #connect()}
 */
private ChannelFuture doConnect(final SocketAddress remoteAddress, final SocketAddress localAddress) {
    final ChannelFuture regFuture = initAndRegister();
    final Channel channel = regFuture.channel();
    if (regFuture.cause() != null) {
        return regFuture;
    }

    final ChannelPromise promise = channel.newPromise();
    if (regFuture.isDone()) {
        doConnect0(regFuture, channel, remoteAddress, localAddress, promise);
    } else {
        regFuture.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                doConnect0(regFuture, channel, remoteAddress, localAddress, promise);
            }
        });
    }

    return promise;
}
 
Example 2
Source File: Http2MultiplexCodecTest.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Ignore("not supported anymore atm")
@Test
public void cancellingWritesBeforeFlush() {
    LastInboundHandler inboundHandler = streamActiveAndWriteHeaders(inboundStream);
    Channel childChannel = inboundHandler.channel();

    Http2HeadersFrame headers1 = new DefaultHttp2HeadersFrame(new DefaultHttp2Headers());
    Http2HeadersFrame headers2 = new DefaultHttp2HeadersFrame(new DefaultHttp2Headers());
    ChannelPromise writePromise = childChannel.newPromise();
    childChannel.write(headers1, writePromise);
    childChannel.write(headers2);
    assertTrue(writePromise.cancel(false));
    childChannel.flush();

    Http2HeadersFrame headers = parentChannel.readOutbound();
    assertSame(headers, headers2);
}
 
Example 3
Source File: ClientConnectionImpl.java    From pravega with Apache License 2.0 6 votes vote down vote up
private void write(Append cmd) throws ConnectionFailedException {
    Channel channel = nettyHandler.getChannel();
    EventLoop eventLoop = channel.eventLoop();
    ChannelPromise promise = channel.newPromise();
    promise.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) {
            throttle.release(cmd.getDataLength());
            nettyHandler.setRecentMessage();
            if (!future.isSuccess()) {
                future.channel().pipeline().fireExceptionCaught(future.cause());
            }
        }
    });
    // Work around for https://github.com/netty/netty/issues/3246
    eventLoop.execute(() -> {
        try {
            if (!closed.get()) {
                channel.write(cmd, promise);
            }
        } catch (Exception e) {
            channel.pipeline().fireExceptionCaught(e);
        }
    });
    Exceptions.handleInterrupted(() -> throttle.acquire(cmd.getDataLength()));
}
 
Example 4
Source File: ClientConnectionImpl.java    From pravega with Apache License 2.0 6 votes vote down vote up
private void write(WireCommand cmd) throws ConnectionFailedException {
    Channel channel = nettyHandler.getChannel();
    EventLoop eventLoop = channel.eventLoop();
    ChannelPromise promise = channel.newPromise();
    promise.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) {
            nettyHandler.setRecentMessage();
            if (!future.isSuccess()) {
                future.channel().pipeline().fireExceptionCaught(future.cause());
            }
        }
    });
    // Work around for https://github.com/netty/netty/issues/3246
    eventLoop.execute(() -> {
        try {
            if (!closed.get()) {
                channel.write(cmd, promise);
            }
        } catch (Exception e) {
            channel.pipeline().fireExceptionCaught(e);
        }
    });
}
 
Example 5
Source File: ClientConnectionImpl.java    From pravega with Apache License 2.0 6 votes vote down vote up
@Override
public void sendAsync(List<Append> appends, CompletedCallback callback) {
    Channel ch;
    try {
        checkClientConnectionClosed();
        ch = nettyHandler.getChannel();
    } catch (ConnectionFailedException e) {
        callback.complete(new ConnectionFailedException("Connection to " + connectionName + " is not established."));
        return;
    }
    PromiseCombiner combiner = new PromiseCombiner(ImmediateEventExecutor.INSTANCE);
    for (Append append : appends) {
        combiner.add(ch.write(append));
    }
    ch.flush();
    ChannelPromise promise = ch.newPromise();
    promise.addListener(future -> {
        nettyHandler.setRecentMessage();
        Throwable cause = future.cause();
        callback.complete(cause == null ? null : new ConnectionFailedException(cause));
    });
    combiner.finish(promise);
}
 
Example 6
Source File: Bootstrap.java    From netty4.0.27Learn with Apache License 2.0 6 votes vote down vote up
/**
 * @see {@link #connect()}
 */
private ChannelFuture doConnect(final SocketAddress remoteAddress, final SocketAddress localAddress) {
    final ChannelFuture regFuture = initAndRegister();
    final Channel channel = regFuture.channel();
    if (regFuture.cause() != null) {
        return regFuture;
    }

    final ChannelPromise promise = channel.newPromise();
    if (regFuture.isDone()) {
        doConnect0(regFuture, channel, remoteAddress, localAddress, promise);
    } else {
        regFuture.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                doConnect0(regFuture, channel, remoteAddress, localAddress, promise);
            }
        });
    }

    return promise;
}
 
Example 7
Source File: ChannelMediator.java    From flashback with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private Future<Void> disconnect(final Channel channel) {
  if (channel == null) {
    return null;
  }
  final Promise<Void> promise = channel.newPromise();
  writeToChannel(channel, Unpooled.EMPTY_BUFFER).addListener(future -> closeChannel(promise, channel));
  return promise;
}
 
Example 8
Source File: LocalChannelTest.java    From netty-4.1.22 with Apache License 2.0 4 votes vote down vote up
@Test(timeout = 3000)
public void testConnectFutureBeforeChannelActive() throws Exception {
    Bootstrap cb = new Bootstrap();
    ServerBootstrap sb = new ServerBootstrap();

    cb.group(group1)
            .channel(LocalChannel.class)
            .handler(new ChannelInboundHandlerAdapter());

    sb.group(group2)
            .channel(LocalServerChannel.class)
            .childHandler(new ChannelInitializer<LocalChannel>() {
                @Override
                public void initChannel(LocalChannel ch) throws Exception {
                    ch.pipeline().addLast(new TestHandler());
                }
            });

    Channel sc = null;
    Channel cc = null;
    try {
        // Start server
        sc = sb.bind(TEST_ADDRESS).sync().channel();

        cc = cb.register().sync().channel();

        final ChannelPromise promise = cc.newPromise();
        final Promise<Void> assertPromise = cc.eventLoop().newPromise();

        cc.pipeline().addLast(new TestHandler() {
            @Override
            public void channelActive(ChannelHandlerContext ctx) throws Exception {
                // Ensure the promise was done before the handler method is triggered.
                if (promise.isDone()) {
                    assertPromise.setSuccess(null);
                } else {
                    assertPromise.setFailure(new AssertionError("connect promise should be done"));
                }
            }
        });
        // Connect to the server
        cc.connect(sc.localAddress(), promise).sync();

        assertPromise.syncUninterruptibly();
        assertTrue(promise.isSuccess());
    } finally {
        closeChannel(cc);
        closeChannel(sc);
    }
}
 
Example 9
Source File: BootstrapTest.java    From netty-4.1.22 with Apache License 2.0 4 votes vote down vote up
@Override
public ChannelFuture register(Channel channel) {
    super.register(channel).syncUninterruptibly();
    promise = channel.newPromise();
    return promise;
}
 
Example 10
Source File: WebsocketServerOperations.java    From reactor-netty with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("FutureReturnValueIgnored")
WebsocketServerOperations(String wsUrl, WebsocketServerSpec websocketServerSpec, HttpServerOperations replaced) {
	super(replaced);
	this.proxyPing = websocketServerSpec.handlePing();

	Channel channel = replaced.channel();
	onCloseState = MonoProcessor.create();

	// Handshake
	WebSocketServerHandshakerFactory wsFactory =
			new WebSocketServerHandshakerFactory(wsUrl, websocketServerSpec.protocols(), true, websocketServerSpec.maxFramePayloadLength());
	handshaker = wsFactory.newHandshaker(replaced.nettyRequest);
	if (handshaker == null) {
		//"FutureReturnValueIgnored" this is deliberate
		WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(channel);
		handshakerResult = null;
	}
	else {
		removeHandler(NettyPipeline.HttpTrafficHandler);
		removeHandler(NettyPipeline.AccessLogHandler);
		removeHandler(NettyPipeline.HttpMetricsHandler);

		handshakerResult = channel.newPromise();
		HttpRequest request = new DefaultFullHttpRequest(replaced.version(),
				replaced.method(),
				replaced.uri());

		request.headers()
		       .set(replaced.nettyRequest.headers());

		if (websocketServerSpec.compress()) {
			removeHandler(NettyPipeline.CompressionHandler);

			WebSocketServerCompressionHandler wsServerCompressionHandler =
					new WebSocketServerCompressionHandler();
			try {
				wsServerCompressionHandler.channelRead(channel.pipeline()
				                                              .context(NettyPipeline.ReactiveBridge),
						request);

				addHandlerFirst(NettyPipeline.WsCompressionHandler, wsServerCompressionHandler);
			} catch (Throwable e) {
				log.error(format(channel(), ""), e);
			}
		}

		handshaker.handshake(channel,
		                     request,
		                     replaced.responseHeaders
		                             .remove(HttpHeaderNames.TRANSFER_ENCODING),
		                     handshakerResult)
		          .addListener(f -> {
		              if (replaced.rebind(this)) {
		                  markPersistent(false);
		              }
		              else {
		                  log.debug("Cannot bind WebsocketServerOperations after the handshake.");
		              }
		          });
	}
}
 
Example 11
Source File: BootstrapTest.java    From netty4.0.27Learn with Apache License 2.0 4 votes vote down vote up
@Override
public ChannelFuture register(Channel channel) {
    super.register(channel).syncUninterruptibly();
    promise = channel.newPromise();
    return promise;
}
 
Example 12
Source File: WebSocketClientHandler.java    From blynk-server with GNU General Public License v3.0 4 votes vote down vote up
public void startHandshake(Channel channel) {
    handshaker.handshake(channel);
    handshakeFuture = channel.newPromise();
}
 
Example 13
Source File: AppWebSocketClientHandler.java    From blynk-server with GNU General Public License v3.0 4 votes vote down vote up
public void startHandshake(Channel channel) {
    handshaker.handshake(channel);
    handshakeFuture = channel.newPromise();
}