Search in sources :

Example 26 with GenericFutureListener

use of io.netty.util.concurrent.GenericFutureListener in project vert.x by eclipse-vertx.

the class HttpServerWorker method handle.

@Override
public void handle(Channel ch) {
    if (HAProxyMessageCompletionHandler.canUseProxyProtocol(options.isUseProxyProtocol())) {
        IdleStateHandler idle;
        io.netty.util.concurrent.Promise<Channel> p = ch.eventLoop().newPromise();
        ch.pipeline().addLast(new HAProxyMessageDecoder());
        if (options.getProxyProtocolTimeout() > 0) {
            ch.pipeline().addLast("idle", idle = new IdleStateHandler(0, 0, options.getProxyProtocolTimeout(), options.getProxyProtocolTimeoutUnit()));
        } else {
            idle = null;
        }
        ch.pipeline().addLast(new HAProxyMessageCompletionHandler(p));
        p.addListener((GenericFutureListener<Future<Channel>>) future -> {
            if (future.isSuccess()) {
                if (idle != null) {
                    ch.pipeline().remove(idle);
                }
                configurePipeline(future.getNow());
            } else {
                handleException(future.cause());
            }
        });
    } else {
        configurePipeline(ch);
    }
}
Also used : HttpContentCompressor(io.netty.handler.codec.http.HttpContentCompressor) HAProxyMessageCompletionHandler(io.vertx.core.net.impl.HAProxyMessageCompletionHandler) SniHandler(io.netty.handler.ssl.SniHandler) LoggingHandler(io.netty.handler.logging.LoggingHandler) FlashPolicyHandler(io.vertx.core.http.impl.cgbystrom.FlashPolicyHandler) ContextInternal(io.vertx.core.impl.ContextInternal) SslHandshakeCompletionHandler(io.vertx.core.net.impl.SslHandshakeCompletionHandler) ChunkedWriteHandler(io.netty.handler.stream.ChunkedWriteHandler) Function(java.util.function.Function) Supplier(java.util.function.Supplier) Unpooled(io.netty.buffer.Unpooled) ArrayList(java.util.ArrayList) StandardCompressionOptions(io.netty.handler.codec.compression.StandardCompressionOptions) CompressionOptions(io.netty.handler.codec.compression.CompressionOptions) HttpServerMetrics(io.vertx.core.spi.metrics.HttpServerMetrics) IdleState(io.netty.handler.timeout.IdleState) io.netty.channel(io.netty.channel) VertxHandler(io.vertx.core.net.impl.VertxHandler) IdleStateEvent(io.netty.handler.timeout.IdleStateEvent) VertxInternal(io.vertx.core.impl.VertxInternal) GenericFutureListener(io.netty.util.concurrent.GenericFutureListener) SSLHelper(io.vertx.core.net.impl.SSLHelper) StandardCharsets(java.nio.charset.StandardCharsets) HAProxyMessageDecoder(io.netty.handler.codec.haproxy.HAProxyMessageDecoder) IdleStateHandler(io.netty.handler.timeout.IdleStateHandler) EventLoopContext(io.vertx.core.impl.EventLoopContext) List(java.util.List) SslHandler(io.netty.handler.ssl.SslHandler) HttpServerOptions(io.vertx.core.http.HttpServerOptions) HttpContentDecompressor(io.netty.handler.codec.http.HttpContentDecompressor) Future(io.netty.util.concurrent.Future) Handler(io.vertx.core.Handler) HAProxyMessageCompletionHandler(io.vertx.core.net.impl.HAProxyMessageCompletionHandler) IdleStateHandler(io.netty.handler.timeout.IdleStateHandler) HAProxyMessageDecoder(io.netty.handler.codec.haproxy.HAProxyMessageDecoder) Future(io.netty.util.concurrent.Future)

Example 27 with GenericFutureListener

use of io.netty.util.concurrent.GenericFutureListener in project vert.x by eclipse-vertx.

the class DatagramSocketImpl method send.

@Override
public Future<Void> send(Buffer packet, int port, String host) {
    Objects.requireNonNull(packet, "no null packet accepted");
    Objects.requireNonNull(host, "no null host accepted");
    if (port < 0 || port > 65535) {
        throw new IllegalArgumentException("port out of range:" + port);
    }
    AddressResolver resolver = context.owner().addressResolver();
    PromiseInternal<Void> promise = context.promise();
    io.netty.util.concurrent.Future<InetSocketAddress> f1 = resolver.resolveHostname(context.nettyEventLoop(), host);
    f1.addListener((GenericFutureListener<io.netty.util.concurrent.Future<InetSocketAddress>>) res1 -> {
        if (res1.isSuccess()) {
            ChannelFuture f2 = channel.writeAndFlush(new DatagramPacket(packet.getByteBuf(), new InetSocketAddress(f1.getNow().getAddress(), port)));
            if (metrics != null) {
                f2.addListener(fut -> {
                    if (fut.isSuccess()) {
                        metrics.bytesWritten(null, SocketAddress.inetSocketAddress(port, host), packet.length());
                    }
                });
            }
            f2.addListener(promise);
        } else {
            promise.fail(res1.cause());
        }
    });
    return promise.future();
}
Also used : ChannelOption(io.netty.channel.ChannelOption) LoggingHandler(io.netty.handler.logging.LoggingHandler) DatagramSocket(io.vertx.core.datagram.DatagramSocket) Arguments(io.vertx.core.impl.Arguments) ContextInternal(io.vertx.core.impl.ContextInternal) ConnectionBase(io.vertx.core.net.impl.ConnectionBase) InetAddress(java.net.InetAddress) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) DatagramChannel(io.netty.channel.socket.DatagramChannel) ByteBuf(io.netty.buffer.ByteBuf) WriteStream(io.vertx.core.streams.WriteStream) DatagramPacket(io.netty.channel.socket.DatagramPacket) InternetProtocolFamily(io.netty.channel.socket.InternetProtocolFamily) AsyncResult(io.vertx.core.AsyncResult) DatagramSocketOptions(io.vertx.core.datagram.DatagramSocketOptions) MaxMessagesRecvByteBufAllocator(io.netty.channel.MaxMessagesRecvByteBufAllocator) SocketAddress(io.vertx.core.net.SocketAddress) VertxHandler(io.vertx.core.net.impl.VertxHandler) Closeable(io.vertx.core.Closeable) PromiseInternal(io.vertx.core.impl.future.PromiseInternal) VertxInternal(io.vertx.core.impl.VertxInternal) Transport(io.vertx.core.net.impl.transport.Transport) Promise(io.vertx.core.Promise) AddressResolver(io.vertx.core.impl.AddressResolver) NetworkInterface(java.net.NetworkInterface) GenericFutureListener(io.netty.util.concurrent.GenericFutureListener) Future(io.vertx.core.Future) InetSocketAddress(java.net.InetSocketAddress) UnknownHostException(java.net.UnknownHostException) ChannelFuture(io.netty.channel.ChannelFuture) Nullable(io.vertx.codegen.annotations.Nullable) Objects(java.util.Objects) Buffer(io.vertx.core.buffer.Buffer) CloseFuture(io.vertx.core.impl.CloseFuture) io.vertx.core.spi.metrics(io.vertx.core.spi.metrics) Handler(io.vertx.core.Handler) ChannelFuture(io.netty.channel.ChannelFuture) AddressResolver(io.vertx.core.impl.AddressResolver) InetSocketAddress(java.net.InetSocketAddress) DatagramPacket(io.netty.channel.socket.DatagramPacket) Future(io.vertx.core.Future) ChannelFuture(io.netty.channel.ChannelFuture) CloseFuture(io.vertx.core.impl.CloseFuture)

Example 28 with GenericFutureListener

use of io.netty.util.concurrent.GenericFutureListener in project netconf by opendaylight.

the class DefaultCloseSessionTest method testDefaultCloseSession.

@Test
public void testDefaultCloseSession() throws Exception {
    AutoCloseable res = mock(AutoCloseable.class);
    doNothing().when(res).close();
    DefaultCloseSession close = new DefaultCloseSession("", res);
    final Document doc = XmlUtil.newDocument();
    final XmlElement elem = XmlElement.fromDomElement(XmlUtil.readXmlToElement("<elem/>"));
    final Channel channel = mock(Channel.class);
    doReturn("channel").when(channel).toString();
    mockEventLoop(channel);
    final ChannelFuture channelFuture = mock(ChannelFuture.class);
    doReturn(channelFuture).when(channel).close();
    doReturn(channelFuture).when(channelFuture).addListener(any(GenericFutureListener.class));
    final ChannelPromise sendFuture = mock(ChannelPromise.class);
    doAnswer(invocation -> {
        invocation.<GenericFutureListener>getArgument(0).operationComplete(sendFuture);
        return null;
    }).when(sendFuture).addListener(any(GenericFutureListener.class));
    doReturn(sendFuture).when(channel).newPromise();
    doReturn(sendFuture).when(channel).writeAndFlush(any(), any());
    doReturn(true).when(sendFuture).isSuccess();
    final NetconfServerSessionListener listener = mock(NetconfServerSessionListener.class);
    doNothing().when(listener).onSessionTerminated(any(NetconfServerSession.class), any(NetconfTerminationReason.class));
    final NetconfServerSession session = new NetconfServerSession(listener, channel, 1L, NetconfHelloMessageAdditionalHeader.fromString("[netconf;10.12.0.102:48528;ssh;;;;;;]"));
    close.setNetconfSession(session);
    close.handleWithNoSubsequentOperations(doc, elem);
    // Fake close response to trigger delayed close
    session.sendMessage(new NetconfMessage(XmlUtil.readXmlToDocument("<rpc-reply message-id=\"101\"\n" + "xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n" + "<ok/>\n" + "</rpc-reply>")));
    verify(channel).close();
    verify(listener).onSessionTerminated(any(NetconfServerSession.class), any(NetconfTerminationReason.class));
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) NetconfTerminationReason(org.opendaylight.netconf.api.NetconfTerminationReason) NetconfServerSessionListener(org.opendaylight.netconf.impl.NetconfServerSessionListener) NetconfMessage(org.opendaylight.netconf.api.NetconfMessage) Channel(io.netty.channel.Channel) NetconfServerSession(org.opendaylight.netconf.impl.NetconfServerSession) XmlElement(org.opendaylight.netconf.api.xml.XmlElement) ChannelPromise(io.netty.channel.ChannelPromise) Document(org.w3c.dom.Document) GenericFutureListener(io.netty.util.concurrent.GenericFutureListener) Test(org.junit.Test)

Example 29 with GenericFutureListener

use of io.netty.util.concurrent.GenericFutureListener in project netconf by opendaylight.

the class NetconfDeviceCommunicatorTest method testSendRequest.

@SuppressWarnings({ "rawtypes", "unchecked" })
@Test
public void testSendRequest() throws Exception {
    setupSession();
    NetconfMessage message = new NetconfMessage(UntrustedXML.newDocumentBuilder().newDocument());
    QName rpc = QName.create("", "mockRpc");
    ArgumentCaptor<GenericFutureListener> futureListener = ArgumentCaptor.forClass(GenericFutureListener.class);
    ChannelFuture mockChannelFuture = mock(ChannelFuture.class);
    doReturn(mockChannelFuture).when(mockChannelFuture).addListener(futureListener.capture());
    doReturn(mockChannelFuture).when(mockSession).sendMessage(same(message));
    ListenableFuture<RpcResult<NetconfMessage>> resultFuture = communicator.sendRequest(message, rpc);
    verify(mockSession).sendMessage(same(message));
    assertNotNull("ListenableFuture is null", resultFuture);
    verify(mockChannelFuture).addListener(futureListener.capture());
    Future<Void> operationFuture = mock(Future.class);
    doReturn(true).when(operationFuture).isSuccess();
    futureListener.getValue().operationComplete(operationFuture);
    try {
        // verify it's not cancelled or has an error set
        resultFuture.get(1, TimeUnit.MILLISECONDS);
    } catch (TimeoutException e) {
        LOG.info("Operation failed due timeout.");
    }
// expected
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) NetconfMessage(org.opendaylight.netconf.api.NetconfMessage) QName(org.opendaylight.yangtools.yang.common.QName) RpcResult(org.opendaylight.yangtools.yang.common.RpcResult) GenericFutureListener(io.netty.util.concurrent.GenericFutureListener) TimeoutException(java.util.concurrent.TimeoutException) Test(org.junit.Test)

Example 30 with GenericFutureListener

use of io.netty.util.concurrent.GenericFutureListener in project cdap by cdapio.

the class AbstractSocksServerConnectHandler method handleConnectRequest.

/**
 * Handles the CONNECT socks request.
 *
 * @param ctx the context object for the channel
 * @param destAddress the destination address
 * @param destPort the destination port that the remote {@code localhost} is listening to
 * @param responseFunc a {@link Function} for creating a {@link SocksMessage} to send back to client
 *                     once the relay channel has been established
 */
private void handleConnectRequest(ChannelHandlerContext ctx, String destAddress, int destPort, Function<InetSocketAddress, SocksMessage> responseFunc, Supplier<SocksMessage> failureResponseSupplier) {
    // Create a forwarding channel handler, which returns a Future.
    // When that handler future completed successfully, responds with a Socks success response.
    // After the success response completed successfully, add the relay handler to the pipeline.
    Channel inboundChannel = ctx.channel();
    createForwardingChannelHandler(inboundChannel, destAddress, destPort).addListener((GenericFutureListener<Future<RelayChannelHandler>>) handlerFuture -> {
        if (handlerFuture.isSuccess()) {
            RelayChannelHandler handler = handlerFuture.get();
            SocketAddress relayAddress = handler.getRelayAddress();
            if (!(relayAddress instanceof InetSocketAddress)) {
                LOG.warn("Relay address is not InetSocketAddress: {} {}", relayAddress.getClass(), relayAddress);
                inboundChannel.writeAndFlush(failureResponseSupplier.get()).addListener(channelFuture -> Channels.closeOnFlush(inboundChannel));
            } else {
                inboundChannel.writeAndFlush(responseFunc.apply((InetSocketAddress) relayAddress)).addListener(channelFuture -> {
                    if (channelFuture.isSuccess()) {
                        ctx.pipeline().remove(AbstractSocksServerConnectHandler.this);
                        ctx.pipeline().addLast(handler);
                    } else {
                        Channels.closeOnFlush(inboundChannel);
                    }
                });
            }
        } else {
            Channels.closeOnFlush(inboundChannel);
        }
    });
}
Also used : SocketAddress(java.net.SocketAddress) Socks4CommandType(io.netty.handler.codec.socksx.v4.Socks4CommandType) LoggerFactory(org.slf4j.LoggerFactory) Loggers(io.cdap.cdap.common.logging.Loggers) Channels(io.cdap.cdap.common.http.Channels) Socks5CommandType(io.netty.handler.codec.socksx.v5.Socks5CommandType) DefaultSocks5CommandResponse(io.netty.handler.codec.socksx.v5.DefaultSocks5CommandResponse) Function(java.util.function.Function) Supplier(java.util.function.Supplier) Socks5CommandRequest(io.netty.handler.codec.socksx.v5.Socks5CommandRequest) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) Socks5CommandStatus(io.netty.handler.codec.socksx.v5.Socks5CommandStatus) ChannelFutureListener(io.netty.channel.ChannelFutureListener) Socks4CommandRequest(io.netty.handler.codec.socksx.v4.Socks4CommandRequest) Logger(org.slf4j.Logger) Socks5AddressType(io.netty.handler.codec.socksx.v5.Socks5AddressType) Socks4CommandStatus(io.netty.handler.codec.socksx.v4.Socks4CommandStatus) GenericFutureListener(io.netty.util.concurrent.GenericFutureListener) ChannelPipeline(io.netty.channel.ChannelPipeline) Inet4Address(java.net.Inet4Address) InetSocketAddress(java.net.InetSocketAddress) Channel(io.netty.channel.Channel) TimeUnit(java.util.concurrent.TimeUnit) DefaultSocks4CommandResponse(io.netty.handler.codec.socksx.v4.DefaultSocks4CommandResponse) SimpleChannelInboundHandler(io.netty.channel.SimpleChannelInboundHandler) LogSamplers(io.cdap.cdap.common.logging.LogSamplers) ChannelHandler(io.netty.channel.ChannelHandler) SocksMessage(io.netty.handler.codec.socksx.SocksMessage) Future(io.netty.util.concurrent.Future) InetSocketAddress(java.net.InetSocketAddress) Channel(io.netty.channel.Channel) Future(io.netty.util.concurrent.Future) SocketAddress(java.net.SocketAddress) InetSocketAddress(java.net.InetSocketAddress)

Aggregations

GenericFutureListener (io.netty.util.concurrent.GenericFutureListener)70 Future (io.netty.util.concurrent.Future)44 ChannelFuture (io.netty.channel.ChannelFuture)32 Channel (io.netty.channel.Channel)19 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)18 IOException (java.io.IOException)18 List (java.util.List)15 InetSocketAddress (java.net.InetSocketAddress)13 ArrayList (java.util.ArrayList)13 Map (java.util.Map)12 ChannelOption (io.netty.channel.ChannelOption)10 Future (io.vertx.core.Future)10 Handler (io.vertx.core.Handler)10 ContextInternal (io.vertx.core.impl.ContextInternal)10 VertxInternal (io.vertx.core.impl.VertxInternal)10 Logger (org.slf4j.Logger)10 LoggerFactory (org.slf4j.LoggerFactory)9 Bootstrap (io.netty.bootstrap.Bootstrap)8 LoggingHandler (io.netty.handler.logging.LoggingHandler)8 AsyncResult (io.vertx.core.AsyncResult)8