Example usage for io.netty.channel ChannelFutureListener ChannelFutureListener

List of usage examples for io.netty.channel ChannelFutureListener ChannelFutureListener

Introduction

In this page you can find the example usage for io.netty.channel ChannelFutureListener ChannelFutureListener.

Prototype

ChannelFutureListener

Source Link

Usage

From source file:io.nodyn.tcp.TCPWrap.java

License:Apache License

public void connect(String addr, int port) {
    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(this.process.getEventLoop().getEventLoopGroup());
    bootstrap.channel(NioSocketChannel.class);
    if (this.port >= 0) {
        if (this.addr != null) {
            bootstrap.localAddress(this.addr, this.port);
        } else {// w  w w. jav  a  2 s.c  om
            bootstrap.localAddress(this.port);
        }
    }

    bootstrap.handler(new ChannelInitializer<Channel>() {
        @Override
        protected void initChannel(Channel ch) throws Exception {
            ch.config().setAutoRead(false);
            //ch.pipeline().addLast("debug", new DebugHandler("client"));
            ch.pipeline().addLast("emit.afterConnect",
                    new AfterConnectEventHandler(TCPWrap.this.process, TCPWrap.this));
            ch.pipeline().addLast("emit.eof", new EOFEventHandler(TCPWrap.this.process, TCPWrap.this));
            ch.pipeline().addLast("handle", new UnrefHandler(TCPWrap.this));
        }
    });

    this.channelFuture = bootstrap.connect(addr, port);
    this.channelFuture.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            // TODO callback error
        }
    });
    ref();
}

From source file:io.pravega.client.netty.impl.ConnectionFactoryImpl.java

License:Open Source License

@Override
public CompletableFuture<ClientConnection> establishConnection(PravegaNodeUri location, ReplyProcessor rp) {
    Preconditions.checkNotNull(location);
    Exceptions.checkNotClosed(closed.get(), this);
    final SslContext sslCtx;
    if (ssl) {//  w  ww .  j  a v  a 2 s .  co  m
        try {
            sslCtx = SslContextBuilder.forClient().trustManager(FingerprintTrustManagerFactory
                    .getInstance(FingerprintTrustManagerFactory.getDefaultAlgorithm())).build();
        } catch (SSLException | NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    } else {
        sslCtx = null;
    }
    AppendBatchSizeTracker batchSizeTracker = new AppendBatchSizeTrackerImpl();
    ClientConnectionInboundHandler handler = new ClientConnectionInboundHandler(location.getEndpoint(), rp,
            batchSizeTracker);
    Bootstrap b = new Bootstrap();
    b.group(group).channel(nio ? NioSocketChannel.class : EpollSocketChannel.class)
            .option(ChannelOption.TCP_NODELAY, true).handler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline p = ch.pipeline();
                    if (sslCtx != null) {
                        p.addLast(sslCtx.newHandler(ch.alloc(), location.getEndpoint(), location.getPort()));
                    }
                    // p.addLast(new LoggingHandler(LogLevel.INFO));
                    p.addLast(new ExceptionLoggingHandler(location.getEndpoint()),
                            new CommandEncoder(batchSizeTracker),
                            new LengthFieldBasedFrameDecoder(WireCommands.MAX_WIRECOMMAND_SIZE, 4, 4),
                            new CommandDecoder(), handler);
                }
            });

    // Start the client.
    CompletableFuture<ClientConnection> result = new CompletableFuture<>();
    try {
        b.connect(location.getEndpoint(), location.getPort()).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) {
                if (future.isSuccess()) {
                    result.complete(handler);
                } else {
                    result.completeExceptionally(future.cause());
                }
            }
        });
    } catch (Exception e) {
        result.completeExceptionally(e);
    }
    return result;
}

From source file:io.reactivesocket.transport.websocket.client.ClientWebSocketDuplexConnection.java

License:Apache License

@Override
public Publisher<Void> close() {
    return s -> {
        if (channel.isOpen()) {
            channel.close().addListener(new ChannelFutureListener() {
                @Override/*from  w  w  w  . j  a v a  2s  .  c o  m*/
                public void operationComplete(ChannelFuture future) throws Exception {
                    s.onComplete();
                }
            });
        } else {
            onClose().subscribe(s);
        }
    };
}

From source file:io.reactivesocket.transport.websocket.client.ClientWebSocketDuplexConnection.java

License:Apache License

@Override
public Publisher<Void> onClose() {
    return s -> {
        channel.closeFuture().addListener(new ChannelFutureListener() {
            @Override/*from  w w w  . j  a v a  2 s .co m*/
            public void operationComplete(ChannelFuture future) throws Exception {
                s.onComplete();
            }
        });
    };
}

From source file:io.reactivesocket.transport.websocket.server.ServerWebSocketDuplexConnection.java

License:Apache License

@Override
public Publisher<Void> close() {
    return s -> {
        if (ctx.channel().isOpen()) {
            ctx.channel().close().addListener(new ChannelFutureListener() {
                @Override/*from   www  .j  a v a 2 s  .  c o  m*/
                public void operationComplete(ChannelFuture future) throws Exception {
                    s.onComplete();
                }
            });
        } else {
            onClose().subscribe(s);
        }
    };
}

From source file:io.reactivesocket.transport.websocket.server.ServerWebSocketDuplexConnection.java

License:Apache License

@Override
public Publisher<Void> onClose() {
    return s -> {
        ctx.channel().closeFuture().addListener(new ChannelFutureListener() {
            @Override/*  www  . ja v  a  2 s  .c  o m*/
            public void operationComplete(ChannelFuture future) throws Exception {
                s.onComplete();
            }
        });
    };
}

From source file:io.reactivex.netty.channel.ObservableConnection.java

License:Apache License

@SuppressWarnings("unchecked")
protected Observable<Void> _closeChannel() {
    closeStartTimeMillis = Clock.newStartTimeMillis();
    eventsSubject.onEvent(metricEventProvider.getChannelCloseStartEvent());

    final ChannelFuture closeFuture = getChannelHandlerContext().close();

    /**//  ww w  . j a  v  a  2 s . co m
     * This listener if added inside the returned Observable onSubscribe() function, would mean that the
     * metric events will only be fired if someone subscribed to the close() Observable. However, we need them to
     * fire independent of someone subscribing.
     */
    closeFuture.addListener(new ChannelFutureListener() {
        @SuppressWarnings("unchecked")
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                eventsSubject.onEvent(metricEventProvider.getChannelCloseSuccessEvent(),
                        Clock.onEndMillis(closeStartTimeMillis));
            } else {
                eventsSubject.onEvent(metricEventProvider.getChannelCloseFailedEvent(),
                        Clock.onEndMillis(closeStartTimeMillis), future.cause());
            }
        }
    });

    return Observable.create(new Observable.OnSubscribe<Void>() {
        @Override
        public void call(final Subscriber<? super Void> subscriber) {
            closeFuture.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (future.isSuccess()) {
                        subscriber.onCompleted();
                    } else {
                        subscriber.onError(future.cause());
                    }
                }
            });
        }
    });
}

From source file:io.reactivex.netty.client.ClientChannelFactoryImpl.java

License:Apache License

@Override
public ChannelFuture connect(final Subscriber<? super ObservableConnection<I, O>> subscriber,
        RxClient.ServerInfo serverInfo,/*  w w  w.j a v  a  2 s  .  co  m*/
        final ClientConnectionFactory<I, O, ? extends ObservableConnection<I, O>> connectionFactory) {
    final long startTimeMillis = Clock.newStartTimeMillis();
    eventsSubject.onEvent(ClientMetricsEvent.CONNECT_START);
    final ChannelFuture connectFuture = clientBootstrap.connect(serverInfo.getHost(), serverInfo.getPort());

    subscriber.add(Subscriptions.create(new Action0() {
        @Override
        public void call() {
            if (!connectFuture.isDone()) {
                connectFuture.cancel(true); // Unsubscribe here means, no more connection is required. A close on connection is explicit.
            }
        }
    }));

    connectFuture.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            try {
                if (!future.isSuccess()) {
                    eventsSubject.onEvent(ClientMetricsEvent.CONNECT_FAILED, Clock.onEndMillis(startTimeMillis),
                            future.cause());
                    subscriber.onError(future.cause());
                } else {
                    eventsSubject.onEvent(ClientMetricsEvent.CONNECT_SUCCESS,
                            Clock.onEndMillis(startTimeMillis));
                    ChannelPipeline pipeline = future.channel().pipeline();
                    ChannelHandlerContext ctx = pipeline.lastContext(); // The connection uses the context for write which should always start from the tail.
                    final ObservableConnection<I, O> newConnection = connectionFactory.newConnection(ctx);
                    ChannelHandler lifecycleHandler = pipeline
                            .get(RxRequiredConfigurator.CONN_LIFECYCLE_HANDLER_NAME);
                    if (null == lifecycleHandler) {
                        onNewConnection(newConnection, subscriber);
                    } else {
                        @SuppressWarnings("unchecked")
                        ConnectionLifecycleHandler<I, O> handler = (ConnectionLifecycleHandler<I, O>) lifecycleHandler;
                        SslHandler sslHandler = pipeline.get(SslHandler.class);
                        if (null == sslHandler) {
                            handler.setConnection(newConnection);
                            onNewConnection(newConnection, subscriber);
                        } else {
                            sslHandler.handshakeFuture()
                                    .addListener(new GenericFutureListener<Future<? super Channel>>() {
                                        @Override
                                        public void operationComplete(Future<? super Channel> future)
                                                throws Exception {
                                            onNewConnection(newConnection, subscriber);
                                        }
                                    });
                        }
                    }
                }
            } catch (Throwable throwable) {
                subscriber.onError(throwable);
            }
        }
    });
    return connectFuture;
}

From source file:io.reactivex.netty.metrics.BytesInspector.java

License:Apache License

@Override
@SuppressWarnings("unchecked")
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
    try {/*from ww  w .ja  v a 2 s .c o m*/
        if (ByteBuf.class.isAssignableFrom(msg.getClass())) {
            final long startTimeMillis = Clock.newStartTimeMillis();
            final int bytesToWrite = ((ByteBuf) msg).readableBytes();
            eventsSubject.onEvent(metricEventProvider.getWriteStartEvent(), (Object) bytesToWrite);
            promise.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (future.isSuccess()) {
                        eventsSubject.onEvent(metricEventProvider.getWriteSuccessEvent(),
                                Clock.onEndMillis(startTimeMillis), bytesToWrite);
                    } else {
                        eventsSubject.onEvent(metricEventProvider.getWriteFailedEvent(),
                                Clock.onEndMillis(startTimeMillis), future.cause(), bytesToWrite);
                    }
                }
            });
        }
    } catch (Exception e) {
        logger.warn(
                "Failed to publish bytes write metrics event. This does *not* stop the pipeline processing.",
                e);
    } finally {
        super.write(ctx, msg, promise);
    }
}

From source file:io.reactivex.netty.protocol.http.client.ClientRequestResponseConverter.java

License:Apache License

private void addWriteCompleteEvents(ChannelFuture future, final long startTimeMillis,
        final HttpClientMetricsEvent<HttpClientMetricsEvent.EventType> successEvent,
        final HttpClientMetricsEvent<HttpClientMetricsEvent.EventType> failureEvent) {
    future.addListener(new ChannelFutureListener() {
        @Override//from  w w  w  .  j  a v a2  s.c om
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                eventsSubject.onEvent(successEvent, Clock.onEndMillis(startTimeMillis));
            } else {
                eventsSubject.onEvent(failureEvent, Clock.onEndMillis(startTimeMillis), future.cause());
            }
        }
    });
}