Example usage for io.netty.channel ChannelFuture isSuccess

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

Introduction

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

Prototype

boolean isSuccess();

Source Link

Document

Returns true if and only if the I/O operation was completed successfully.

Usage

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

License:Apache License

@Override
public void shutdown() {
    if (channel == null || !channel.isOpen()) {
        // Already closed.
        return;/* w  ww. j a va 2 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.NettyServerHandlerTest.java

License:Apache License

@Test
public void sendFrameShouldSucceed() throws Exception {
    manualSetUp();/*  w ww  .j a  va2s .c o m*/
    createStream();

    // Send a frame and verify that it was written.
    ChannelFuture future = enqueue(new SendGrpcFrameCommand(stream.transportState(), content(), false));
    assertTrue(future.isSuccess());
    verifyWrite().writeData(eq(ctx()), eq(STREAM_ID), eq(content()), eq(0), eq(false),
            any(ChannelPromise.class));
}

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  ww w  .jav a  2 s .  com*/
            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   ww  w.j  av  a 2 s . 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}//  ww w .  ja v a 2 s .  co 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  .  ja v  a  2s.  co m
        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.  co 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 ww. ja  v a  2 s . c om*/

    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. jav a  2  s . 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());
            }
        }
    });
}

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

License:Open Source License

public HttpServer listen(int port, String host, final Handler<AsyncResult<HttpServer>> listenHandler) {
    if (requestHandler == null && wsHandler == null) {
        throw new IllegalStateException("Set request or websocket handler first");
    }/*  w w w.j  a  v a 2  s  . c  om*/
    if (listening) {
        throw new IllegalStateException("Listen already called");
    }
    listening = true;

    synchronized (async.sharedHttpServers()) {
        id = new ServerID(port, host);

        serverOrigin = (isSSL() ? "https" : "http") + "://" + host + ":" + port;

        DefaultHttpServer shared = async.sharedHttpServers().get(id);
        if (shared == null || port == 0) {
            serverChannelGroup = new DefaultChannelGroup("async-acceptor-channels",
                    GlobalEventExecutor.INSTANCE);
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(availableWorkers);
            bootstrap.channel(NioServerSocketChannel.class);
            tcpHelper.applyConnectionOptions(bootstrap);
            tcpHelper.checkSSL(async);
            bootstrap.childHandler(new ChannelInitializer<Channel>() {
                @Override
                protected void initChannel(Channel ch) throws Exception {
                    ChannelPipeline pipeline = ch.pipeline();
                    if (tcpHelper.isSSL()) {
                        pipeline.addLast("ssl", tcpHelper.createSslHandler(async, false));
                    }
                    pipeline.addLast("flashpolicy", new FlashPolicyHandler());
                    pipeline.addLast("httpDecoder", new HttpRequestDecoder(4096, 8192, 8192, false));
                    pipeline.addLast("httpEncoder", new AsyncHttpResponseEncoder());
                    if (compressionSupported) {
                        pipeline.addLast("deflater", new HttpChunkContentCompressor());
                    }
                    if (tcpHelper.isSSL() || compressionSupported) {
                        // only add ChunkedWriteHandler when SSL is enabled otherwise it is not needed as FileRegion is used.
                        pipeline.addLast("chunkedWriter", new ChunkedWriteHandler()); // For large file / sendfile support
                    }
                    pipeline.addLast("handler", new ServerHandler());
                }
            });

            addHandlers(this);
            try {
                bindFuture = bootstrap.bind(new InetSocketAddress(InetAddress.getByName(host), port));
                bindFuture.addListener(new ChannelFutureListener() {
                    @Override
                    public void operationComplete(ChannelFuture channelFuture) throws Exception {
                        if (!channelFuture.isSuccess()) {
                            async.sharedHttpServers().remove(id);
                        } else {
                            Channel channel = channelFuture.channel();
                            InetSocketAddress address = (InetSocketAddress) channel.localAddress();
                            DefaultHttpServer.this.actualPort = address.getPort();
                            serverChannelGroup.add(channel);
                        }
                    }
                });
            } catch (final Throwable t) {
                // Make sure we send the exception back through the handler (if any)
                if (listenHandler != null) {
                    async.runOnContext(new VoidHandler() {
                        @Override
                        protected void handle() {
                            listenHandler.handle(new DefaultFutureResult<HttpServer>(t));
                        }
                    });
                } else {
                    // No handler - log so user can see failure
                    actualCtx.reportException(t);
                }
                listening = false;
                return this;
            }
            async.sharedHttpServers().put(id, this);
            actualServer = this;
        } else {
            // Server already exists with that host/port - we will use that
            actualServer = shared;
            this.actualPort = shared.actualPort;
            addHandlers(actualServer);
        }
        actualServer.bindFuture.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(final ChannelFuture future) throws Exception {
                if (listenHandler != null) {
                    final AsyncResult<HttpServer> res;
                    if (future.isSuccess()) {
                        res = new DefaultFutureResult<HttpServer>(DefaultHttpServer.this);
                    } else {
                        res = new DefaultFutureResult<>(future.cause());
                        listening = false;
                    }
                    actualCtx.execute(future.channel().eventLoop(), new Runnable() {
                        @Override
                        public void run() {
                            listenHandler.handle(res);
                        }
                    });
                } else if (!future.isSuccess()) {
                    listening = false;
                    // No handler - log so user can see failure
                    actualCtx.reportException(future.cause());
                }
            }
        });
    }
    return this;
}