Example usage for io.netty.channel ChannelFuture cause

List of usage examples for io.netty.channel ChannelFuture cause

Introduction

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

Prototype

Throwable cause();

Source Link

Document

Returns the cause of the failed I/O operation if the I/O operation has failed.

Usage

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) {//from   w ww .  jav a 2s .c o  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.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();

    /**/*from   w ww  .java 2 s.  com*/
     * 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,//from  ww  w.j  a  v  a2s  . c o 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.client.ClientConnectionHandler.java

License:Apache License

@Override
public void operationComplete(ChannelFuture future) throws Exception {
    if (!future.isSuccess()) {
        connectionSub.onError(future.cause());
    } // onComplete() needs to be send after onNext(), calling it here will cause a race-condition between next & complete.
}

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 {/*w w w.j a 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  ww  w .j  a  v  a  2 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());
            }
        }
    });
}

From source file:io.reactivex.netty.protocol.http.MultipleFutureListener.java

License:Apache License

public MultipleFutureListener(final ChannelPromise completionPromise) {
    if (null == completionPromise) {
        throw new NullPointerException("Promise can not be null.");
    }/*w  ww  .  ja  v a 2  s  .  c o m*/
    this.completionPromise = completionPromise;
    completionObservable = Observable.create(new Observable.OnSubscribe<Void>() {
        @Override
        public void call(final Subscriber<? super Void> subscriber) {
            MultipleFutureListener.this.completionPromise.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.protocol.http.MultipleFutureListener.java

License:Apache License

@Override
public void operationComplete(ChannelFuture future) throws Exception {
    pendingFutures.remove(future);/*  w w w. j a  v  a  2  s.c  om*/
    int nowListeningTo = listeningToCount.decrementAndGet();
    /**
     * If any one of the future fails, we fail the subscribers.
     * If all complete (listen count == 0) we complete the subscribers.
     */
    if (!future.isSuccess()) {
        cancelPendingFutures(true);
        completionPromise.tryFailure(future.cause());
    } else if (nowListeningTo == 0) {
        completionPromise.trySuccess(null);
    }
}

From source file:io.reactivex.netty.protocol.http.server.ServerRequestResponseConverter.java

License:Apache License

private void addWriteCompleteEvents(ChannelPromise promise, final long startTimeMillis,
        final HttpServerMetricsEvent<HttpServerMetricsEvent.EventType> successEvent,
        final HttpServerMetricsEvent<HttpServerMetricsEvent.EventType> failureEvent) {
    promise.addListener(new ChannelFutureListener() {
        @Override//from w ww  .  j  av  a 2s  .com
        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());
            }
        }
    });
}

From source file:io.reactivex.netty.protocol.http.websocket.WebSocketServerHandler.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (msg instanceof FullHttpRequest) {
        ChannelFuture upgradeFuture = handleHttpRequest(ctx, (FullHttpRequest) msg);
        if (upgradeFuture != null) {
            updatePipeline(ctx);// w w  w  . jav  a2  s  . c o m
            upgradeFuture.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (future.isSuccess()) {
                        handshakeFuture.setSuccess();
                        eventsSubject.onEvent(WebSocketServerMetricsEvent.HANDSHAKE_PROCESSED);
                    } else {
                        handshakeFuture.setFailure(future.cause());
                        eventsSubject.onEvent(WebSocketServerMetricsEvent.HANDSHAKE_FAILURE);
                    }
                }
            });
        }
    } else {
        ctx.fireChannelRead(msg);
    }
}