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.grpc.netty.NettyClientTransport.java

License:Apache License

/**
 * Convert ChannelFuture.cause() to a Status, taking into account that all handlers are removed
 * from the pipeline when the channel is closed. Since handlers are removed, you may get an
 * unhelpful exception like ClosedChannelException.
 *
 * <p>This method must only be called on the event loop.
 *//*from   ww  w  . j a  va 2  s.  co  m*/
private Status statusFromFailedFuture(ChannelFuture f) {
    Throwable t = f.cause();
    if (t instanceof ClosedChannelException
            // Exception thrown by the StreamBufferingEncoder if the channel is closed while there
            // are still streams buffered. This exception is not helpful. Replace it by the real
            // cause of the shutdown (if available).
            || t instanceof Http2ChannelClosedException) {
        Status shutdownStatus = lifecycleManager.getShutdownStatus();
        if (shutdownStatus == null) {
            return Status.UNKNOWN.withDescription("Channel closed but for unknown reason")
                    .withCause(new ClosedChannelException().initCause(t));
        }
        return shutdownStatus;
    }
    return Utils.statusFromThrowable(t);
}

From source file:io.grpc.netty.NettyServer.java

License:Apache License

@Override
public void start(ServerListener serverListener) throws IOException {
    listener = checkNotNull(serverListener, "serverListener");

    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup, workerGroup);/*from w ww  .j  a va 2  s  .  co  m*/
    b.channelFactory(channelFactory);
    // For non-socket based channel, the option will be ignored.
    b.option(SO_BACKLOG, 128);
    b.childOption(SO_KEEPALIVE, true);

    if (channelOptions != null) {
        for (Map.Entry<ChannelOption<?>, ?> entry : channelOptions.entrySet()) {
            @SuppressWarnings("unchecked")
            ChannelOption<Object> key = (ChannelOption<Object>) entry.getKey();
            b.childOption(key, entry.getValue());
        }
    }

    b.childHandler(new ChannelInitializer<Channel>() {
        @Override
        public void initChannel(Channel ch) {

            ChannelPromise channelDone = ch.newPromise();

            long maxConnectionAgeInNanos = NettyServer.this.maxConnectionAgeInNanos;
            if (maxConnectionAgeInNanos != MAX_CONNECTION_AGE_NANOS_DISABLED) {
                // apply a random jitter of +/-10% to max connection age
                maxConnectionAgeInNanos = (long) ((.9D + Math.random() * .2D) * maxConnectionAgeInNanos);
            }

            NettyServerTransport transport = new NettyServerTransport(ch, channelDone, protocolNegotiator,
                    streamTracerFactories, transportTracerFactory.create(), maxStreamsPerConnection,
                    flowControlWindow, maxMessageSize, maxHeaderListSize, keepAliveTimeInNanos,
                    keepAliveTimeoutInNanos, maxConnectionIdleInNanos, maxConnectionAgeInNanos,
                    maxConnectionAgeGraceInNanos, permitKeepAliveWithoutCalls, permitKeepAliveTimeInNanos);
            ServerTransportListener transportListener;
            // This is to order callbacks on the listener, not to guard access to channel.
            synchronized (NettyServer.this) {
                if (channel != null && !channel.isOpen()) {
                    // Server already shutdown.
                    ch.close();
                    return;
                }
                // `channel` shutdown can race with `ch` initialization, so this is only safe to increment
                // inside the lock.
                eventLoopReferenceCounter.retain();
                transportListener = listener.transportCreated(transport);
            }

            /**
             * Releases the event loop if the channel is "done", possibly due to the channel closing.
             */
            final class LoopReleaser implements ChannelFutureListener {
                private boolean done;

                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (!done) {
                        done = true;
                        eventLoopReferenceCounter.release();
                    }
                }
            }

            transport.start(transportListener);
            ChannelFutureListener loopReleaser = new LoopReleaser();
            channelDone.addListener(loopReleaser);
            ch.closeFuture().addListener(loopReleaser);
        }
    });
    // Bind and start to accept incoming connections.
    ChannelFuture future = b.bind(address);
    try {
        future.await();
    } catch (InterruptedException ex) {
        Thread.currentThread().interrupt();
        throw new RuntimeException("Interrupted waiting for bind");
    }
    if (!future.isSuccess()) {
        throw new IOException("Failed to bind", future.cause());
    }
    channel = future.channel();
    Future<?> channelzFuture = channel.eventLoop().submit(new Runnable() {
        @Override
        public void run() {
            InternalInstrumented<SocketStats> listenSocket = new ListenSocket(channel);
            listenSocketStats.set(listenSocket);
            channelz.addListenSocket(listenSocket);
        }
    });
    try {
        channelzFuture.await();
    } catch (InterruptedException ex) {
        throw new RuntimeException("Interrupted while registering listen socket to channelz", ex);
    }
}

From source file:io.grpc.netty.NettyServer.java

License:Apache License

@Override
public void shutdown() {
    if (channel == null || !channel.isOpen()) {
        // Already closed.
        return;//from ww w  .  ja  v a2 s . c  o m
    }
    channel.close().addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (!future.isSuccess()) {
                log.log(Level.WARNING, "Error shutting down server", future.cause());
            }
            InternalInstrumented<SocketStats> stats = listenSocketStats.getAndSet(null);
            if (stats != null) {
                channelz.removeListenSocket(stats);
            }
            synchronized (NettyServer.this) {
                listener.serverShutdown();
            }
            eventLoopReferenceCounter.release();
        }
    });
    try {
        channel.closeFuture().await();
    } catch (InterruptedException e) {
        log.log(Level.FINE, "Interrupted while shutting down", e);
        Thread.currentThread().interrupt();
    }
}

From source file:io.grpc.netty.WriteBufferingAndExceptionHandler.java

License:Apache License

@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
    assert cause != null;
    Throwable previousFailure = failCause;
    Status status = Utils.statusFromThrowable(cause)
            .augmentDescription("Channel Pipeline: " + ctx.pipeline().names());
    failWrites(status.asRuntimeException());
    // Check to see if the channel is active and this is the first failure.  If a downstream
    // handler triggers an exception in close(), avoid being reentrant.  This is not obviously
    // correct, so here are the cases and how they are correctly handled:
    // 1. !active, prev==null: the channel is inactive, no-op
    // 2. !active, prev!=null: the channel is inactive, no-op
    // 3.  active, prev==null: this is the first error, close
    // 4a. active, prev!=null[channelInactive]: impossible, no-op
    // 4b. active, prev!=null[close]: close() cannot succeed, no point in calling ctx.close().
    // 4c. active, prev!=null[handlerRemoved]: channel will be closed out-of-band by buffered write.
    // 4d. active, prev!=null[connect]: impossible, channel can't be active after a failed connect.
    if (ctx.channel().isActive() && previousFailure == null) {
        final class LogOnFailure implements ChannelFutureListener {
            @Override/*from   www.  j a  v  a 2  s  .c  o m*/
            public void operationComplete(ChannelFuture future) {
                if (!future.isSuccess()) {
                    logger.log(Level.FINE, "Failed closing channel", future.cause());
                }
            }
        }

        ctx.close().addListener(new LogOnFailure());
    }
}

From source file:io.grpc.netty.WriteBufferingAndExceptionHandler.java

License:Apache License

/**
 * Connect failures do not show up as {@link #channelInactive} or {@link #exceptionCaught}, so
 * it needs to be watched.//from   w  ww .  ja v  a 2s.  co m
 */
@Override
public void connect(ChannelHandlerContext ctx, SocketAddress remoteAddress, SocketAddress localAddress,
        ChannelPromise promise) throws Exception {
    final class ConnectListener implements ChannelFutureListener {
        @Override
        public void operationComplete(ChannelFuture future) {
            if (!future.isSuccess()) {
                failWrites(future.cause());
            }
        }
    }

    super.connect(ctx, remoteAddress, localAddress, promise);
    promise.addListener(new ConnectListener());
}

From source file:io.horizondb.client.DefaultMsgChannel.java

License:Apache License

/**
  * {@inheritDoc}/*from w  ww  . j  ava2s . c o m*/
  */
@Override
public void sendRequest(Msg<?> request) {

    this.queue.clear();

    ChannelFuture future = this.channel.writeAndFlush(request);
    future.awaitUninterruptibly();

    if (!future.isSuccess()) {

        throw new HorizonDBException("", future.cause());
    }
}

From source file:io.hydramq.network.client.AbstractConnection.java

License:Open Source License

@Override
public CompletableFuture<Void> disconnect() {
    CompletableFuture<Void> future = new CompletableFuture<>();
    channel().close().addListener(new ChannelFutureListener() {
        @Override//from   w  w  w  .j ava  2s .  c  om
        public void operationComplete(final ChannelFuture closeFuture) throws Exception {
            if (closeFuture.isSuccess()) {
                future.complete(null);
                logger.info("Disconnected");
            } else {
                future.completeExceptionally(closeFuture.cause());
            }
        }
    });
    return future;
}

From source file:io.jsync.datagram.impl.DatagramChannelFutureListener.java

License:Open Source License

private void notifyHandler(ChannelFuture future) {
    if (future.isSuccess()) {
        handler.handle(new DefaultFutureResult<>(result));
    } else {/*from w  ww  . ja v a 2s  .  c  o  m*/
        handler.handle(new DefaultFutureResult<T>(future.cause()));
    }
}

From source file:io.jsync.http.impl.ClientConnection.java

License:Open Source License

void toWebSocket(String uri, final WebSocketVersion wsVersion, final MultiMap headers,
        int maxWebSocketFrameSize, final Set<String> subProtocols, final Handler<WebSocket> wsConnect) {
    if (ws != null) {
        throw new IllegalStateException("Already websocket");
    }//from w w w.j av  a  2  s.c o  m

    try {
        URI wsuri = new URI(uri);
        if (!wsuri.isAbsolute()) {
            // Netty requires an absolute url
            wsuri = new URI((ssl ? "https:" : "http:") + "//" + host + ":" + port + uri);
        }
        io.netty.handler.codec.http.websocketx.WebSocketVersion version;
        if (wsVersion == WebSocketVersion.HYBI_00) {
            version = io.netty.handler.codec.http.websocketx.WebSocketVersion.V00;
        } else if (wsVersion == WebSocketVersion.HYBI_08) {
            version = io.netty.handler.codec.http.websocketx.WebSocketVersion.V08;
        } else if (wsVersion == WebSocketVersion.RFC6455) {
            version = io.netty.handler.codec.http.websocketx.WebSocketVersion.V13;
        } else {
            throw new IllegalArgumentException("Invalid version");
        }
        HttpHeaders nettyHeaders;
        if (headers != null) {
            nettyHeaders = new DefaultHttpHeaders();
            for (Map.Entry<String, String> entry : headers) {
                nettyHeaders.add(entry.getKey(), entry.getValue());
            }
        } else {
            nettyHeaders = null;
        }
        String wsSubProtocols = null;
        if (subProtocols != null && !subProtocols.isEmpty()) {
            StringBuilder sb = new StringBuilder();

            Iterator<String> protocols = subProtocols.iterator();
            while (protocols.hasNext()) {
                sb.append(protocols.next());
                if (protocols.hasNext()) {
                    sb.append(",");
                }
            }
            wsSubProtocols = sb.toString();
        }
        handshaker = WebSocketClientHandshakerFactory.newHandshaker(wsuri, version, wsSubProtocols, false,
                nettyHeaders, maxWebSocketFrameSize);
        final ChannelPipeline p = channel.pipeline();
        p.addBefore("handler", "handshakeCompleter", new HandshakeInboundHandler(wsConnect));
        handshaker.handshake(channel).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (!future.isSuccess()) {
                    client.handleException((Exception) future.cause());
                }
            }
        });
        upgradedConnection = true;

    } catch (Exception e) {
        handleException(e);
    }
}

From source file:io.jsync.http.impl.DefaultHttpClient.java

License:Open Source License

void internalConnect(final Handler<ClientConnection> connectHandler,
        final Handler<Throwable> connectErrorHandler) {
    if (bootstrap == null) {
        // Share the event loop thread to also serve the HttpClient's network traffic.
        AsyncEventLoopGroup pool = new AsyncEventLoopGroup();
        pool.addWorker(actualCtx.getEventLoop());
        bootstrap = new Bootstrap();
        bootstrap.group(pool);//from w w  w .  ja va2s.  c om
        bootstrap.channel(NioSocketChannel.class);
        tcpHelper.checkSSL(async);

        bootstrap.handler(new ChannelInitializer<Channel>() {
            @Override
            protected void initChannel(Channel ch) throws Exception {
                ChannelPipeline pipeline = ch.pipeline();
                if (tcpHelper.isSSL()) {
                    pipeline.addLast("ssl", tcpHelper.createSslHandler(async, true, host, port));
                }
                pipeline.addLast("codec", new HttpClientCodec(4096, 8192, 8192, false, false));
                if (tryUseCompression) {
                    pipeline.addLast("inflater", new HttpContentDecompressor(true));
                }
                pipeline.addLast("handler", new ClientHandler());
            }
        });
    }
    tcpHelper.applyConnectionOptions(bootstrap);
    ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port));
    future.addListener(new ChannelFutureListener() {
        public void operationComplete(ChannelFuture channelFuture) throws Exception {
            final Channel ch = channelFuture.channel();
            if (channelFuture.isSuccess()) {
                if (tcpHelper.isSSL()) {
                    // TCP connected, so now we must do the SSL handshake

                    SslHandler sslHandler = ch.pipeline().get(SslHandler.class);

                    Future<Channel> fut = sslHandler.handshakeFuture();
                    fut.addListener(new GenericFutureListener<Future<Channel>>() {
                        @Override
                        public void operationComplete(Future<Channel> future) throws Exception {
                            if (future.isSuccess()) {
                                connected(ch, connectHandler);
                            } else {
                                connectionFailed(ch, connectErrorHandler,
                                        new SSLHandshakeException("Failed to create SSL connection"));
                            }
                        }
                    });
                } else {
                    connected(ch, connectHandler);
                }
            } else {
                connectionFailed(ch, connectErrorHandler, channelFuture.cause());
            }
        }
    });
}