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:org.hawkular.metrics.clients.ptrans.backend.RestForwardingHandler.java

License:Apache License

private void sendToChannel(final Channel ch) {
    LOG.trace("Sending to channel {}", ch);

    final List<SingleMetric> metricsToSend = fifo.getList();

    String payload = Batcher.metricListToJson(metricsToSend);
    ByteBuf content = Unpooled.copiedBuffer(payload, CharsetUtil.UTF_8);
    FullHttpRequest request = new DefaultFullHttpRequest(HTTP_1_1, POST, restPrefix, content);
    HttpHeaders.setContentLength(request, content.readableBytes());
    HttpHeaders.setKeepAlive(request, true);
    HttpHeaders.setHeader(request, HttpHeaders.Names.CONTENT_TYPE, "application/json;charset=utf-8");
    // We need to send the list of metrics we are sending down the pipeline, so the status watcher
    // can later clean them out of the fifo
    ch.attr(listKey).set(metricsToSend);
    ch.writeAndFlush(request).addListener(new ChannelFutureListener() {
        @Override/* w  w  w  .  ja v  a 2 s.  co m*/
        public void operationComplete(ChannelFuture future) throws Exception {
            if (!future.isSuccess()) {
                // and remove from connection pool if you have one etc...
                ch.close();
                senderChannel = null;
                LOG.error("Sending to the hawkular-metrics server failed: " + future.cause());

            } else {
                sendCounter++;
                if (sendCounter >= restCloseAfterRequests) {
                    SingleMetric perfMetric = new SingleMetric(localHostName + ".ptrans.counter",
                            System.currentTimeMillis(), (double) (numberOfMetrics + metricsToSend.size()));
                    fifo.offer(perfMetric);
                    LOG.trace("Doing a periodic close after {} requests and {} items", restCloseAfterRequests,
                            numberOfMetrics);
                    numberOfMetrics = 0;
                    ch.close();
                    senderChannel = null;
                    sendCounter = 0;
                }
            }
        }
    });
}

From source file:org.hongxi.whatsmars.remoting.netty.NettyRemotingAbstract.java

License:Apache License

public RemotingCommand invokeSyncImpl(final Channel channel, final RemotingCommand request,
        final long timeoutMillis)
        throws InterruptedException, RemotingSendRequestException, RemotingTimeoutException {
    final int opaque = request.getOpaque();

    try {//w  ww .  ja  v  a2s.  co  m
        final ResponseFuture responseFuture = new ResponseFuture(channel, opaque, timeoutMillis, null, null);
        this.responseTable.put(opaque, responseFuture);
        final SocketAddress addr = channel.remoteAddress();
        channel.writeAndFlush(request).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture f) throws Exception {
                if (f.isSuccess()) {
                    responseFuture.setSendRequestOK(true);
                    return;
                } else {
                    responseFuture.setSendRequestOK(false);
                }

                responseTable.remove(opaque);
                responseFuture.setCause(f.cause());
                responseFuture.putResponse(null);
                log.warn("send a request command to channel <" + addr + "> failed.");
            }
        });

        RemotingCommand responseCommand = responseFuture.waitResponse(timeoutMillis);
        if (null == responseCommand) {
            if (responseFuture.isSendRequestOK()) {
                throw new RemotingTimeoutException(RemotingHelper.parseSocketAddressAddr(addr), timeoutMillis,
                        responseFuture.getCause());
            } else {
                throw new RemotingSendRequestException(RemotingHelper.parseSocketAddressAddr(addr),
                        responseFuture.getCause());
            }
        }

        return responseCommand;
    } finally {
        this.responseTable.remove(opaque);
    }
}

From source file:org.hongxi.whatsmars.remoting.netty.NettyRemotingClient.java

License:Apache License

private Channel createChannel(final String addr) throws InterruptedException {
    ChannelWrapper cw = this.channelTables.get(addr);
    if (cw != null && cw.isOK()) {
        cw.getChannel().close();//  w  ww  .jav a2s  .c  om
        channelTables.remove(addr);
    }

    if (this.lockChannelTables.tryLock(LOCK_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS)) {
        try {
            boolean createNewConnection;
            cw = this.channelTables.get(addr);
            if (cw != null) {

                if (cw.isOK()) {
                    cw.getChannel().close();
                    this.channelTables.remove(addr);
                    createNewConnection = true;
                } else if (!cw.getChannelFuture().isDone()) {
                    createNewConnection = false;
                } else {
                    this.channelTables.remove(addr);
                    createNewConnection = true;
                }
            } else {
                createNewConnection = true;
            }

            if (createNewConnection) {
                ChannelFuture channelFuture = this.bootstrap.connect(RemotingHelper.string2SocketAddress(addr));
                log.info("createChannel: begin to connect remote host[{}] asynchronously", addr);
                cw = new ChannelWrapper(channelFuture);
                this.channelTables.put(addr, cw);
            }
        } catch (Exception e) {
            log.error("createChannel: create channel exception", e);
        } finally {
            this.lockChannelTables.unlock();
        }
    } else {
        log.warn("createChannel: try to lock channel table, but timeout, {}ms", LOCK_TIMEOUT_MILLIS);
    }

    if (cw != null) {
        ChannelFuture channelFuture = cw.getChannelFuture();
        if (channelFuture.awaitUninterruptibly(this.nettyClientConfig.getConnectTimeoutMillis())) {
            if (cw.isOK()) {
                log.info("createChannel: connect remote host[{}] success, {}", addr, channelFuture.toString());
                return cw.getChannel();
            } else {
                log.warn("createChannel: connect remote host[" + addr + "] failed, " + channelFuture.toString(),
                        channelFuture.cause());
            }
        } else {
            log.warn("createChannel: connect remote host[{}] timeout {}ms, {}", addr,
                    this.nettyClientConfig.getConnectTimeoutMillis(), channelFuture.toString());
        }
    }

    return null;
}

From source file:org.hornetq.core.protocol.stomp.WebSocketServerHandler.java

License:Apache License

private void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest req) throws Exception {
    // Allow only GET methods.
    if (req.getMethod() != GET) {
        sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN));
        return;//  www.  ja v  a  2s. com
    }

    // Handshake
    WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(
            this.getWebSocketLocation(req), "v10.stomp,v11.stomp", false);
    this.handshaker = wsFactory.newHandshaker(req);
    if (this.handshaker == null) {
        WebSocketServerHandshakerFactory.sendUnsupportedWebSocketVersionResponse(ctx.channel());
    } else {
        ChannelFuture handshake = this.handshaker.handshake(ctx.channel(), req);
        handshake.addListener(new ChannelFutureListener() {

            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (future.isSuccess()) {
                    // we need to insert an encoder that takes the underlying ChannelBuffer of a StompFrame.toHornetQBuffer and
                    // wrap it in a binary web socket frame before letting the wsencoder send it on the wire
                    future.channel().pipeline().addAfter("wsencoder", "binary-websocket-encoder",
                            BINARY_WEBSOCKET_ENCODER);
                } else {
                    // Handshake failed, fire an exceptionCaught event
                    future.channel().pipeline().fireExceptionCaught(future.cause());
                }
            }
        });
    }
}

From source file:org.hornetq.core.remoting.impl.netty.NettyConnector.java

License:Apache License

public Connection createConnection() {
    if (channelClazz == null) {
        return null;
    }// w w  w .ja  v  a2  s .com

    // HORNETQ-907 - strip off IPv6 scope-id (if necessary)
    SocketAddress remoteDestination = new InetSocketAddress(host, port);
    InetAddress inetAddress = ((InetSocketAddress) remoteDestination).getAddress();
    if (inetAddress instanceof Inet6Address) {
        Inet6Address inet6Address = (Inet6Address) inetAddress;
        if (inet6Address.getScopeId() != 0) {
            try {
                remoteDestination = new InetSocketAddress(InetAddress.getByAddress(inet6Address.getAddress()),
                        ((InetSocketAddress) remoteDestination).getPort());
            } catch (UnknownHostException e) {
                throw new IllegalArgumentException(e.getMessage());
            }
        }
    }

    HornetQClientLogger.LOGGER.debug("Remote destination: " + remoteDestination);

    ChannelFuture future;
    //port 0 does not work so only use local address if set
    if (localPort != 0) {
        SocketAddress localDestination;
        if (localAddress != null) {
            localDestination = new InetSocketAddress(localAddress, localPort);
        } else {
            localDestination = new InetSocketAddress(localPort);
        }
        future = bootstrap.connect(remoteDestination, localDestination);
    } else {
        future = bootstrap.connect(remoteDestination);
    }

    future.awaitUninterruptibly();

    if (future.isSuccess()) {
        final Channel ch = future.channel();
        SslHandler sslHandler = ch.pipeline().get(SslHandler.class);
        if (sslHandler != null) {
            Future<Channel> handshakeFuture = sslHandler.handshakeFuture();
            if (handshakeFuture.awaitUninterruptibly(30000)) {
                if (handshakeFuture.isSuccess()) {
                    ChannelPipeline channelPipeline = ch.pipeline();
                    HornetQChannelHandler channelHandler = channelPipeline.get(HornetQChannelHandler.class);
                    channelHandler.active = true;
                } else {
                    ch.close().awaitUninterruptibly();
                    HornetQClientLogger.LOGGER.errorCreatingNettyConnection(handshakeFuture.cause());
                    return null;
                }
            } else {
                //handshakeFuture.setFailure(new SSLException("Handshake was not completed in 30 seconds"));
                ch.close().awaitUninterruptibly();
                return null;
            }

        }
        if (httpUpgradeEnabled) {
            // Send a HTTP GET + Upgrade request that will be handled by the http-upgrade handler.
            try {
                //get this first incase it removes itself
                HttpUpgradeHandler httpUpgradeHandler = (HttpUpgradeHandler) ch.pipeline().get("http-upgrade");
                URI uri = new URI("http", null, host, port, null, null, null);
                HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET,
                        uri.getRawPath());
                request.headers().set(HttpHeaders.Names.HOST, host);
                request.headers().set(HttpHeaders.Names.UPGRADE, HORNETQ_REMOTING);
                request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.UPGRADE);

                final String endpoint = ConfigurationHelper.getStringProperty(
                        TransportConstants.HTTP_UPGRADE_ENDPOINT_PROP_NAME, null, configuration);
                if (endpoint != null) {
                    request.headers().set(TransportConstants.HTTP_UPGRADE_ENDPOINT_PROP_NAME, endpoint);
                }

                // Get 16 bit nonce and base 64 encode it
                byte[] nonce = randomBytes(16);
                String key = base64(nonce);
                request.headers().set(SEC_HORNETQ_REMOTING_KEY, key);
                ch.attr(REMOTING_KEY).set(key);

                HornetQClientLogger.LOGGER.debugf("Sending HTTP request %s", request);

                // Send the HTTP request.
                ch.writeAndFlush(request);

                if (!httpUpgradeHandler.awaitHandshake()) {
                    return null;
                }
            } catch (URISyntaxException e) {
                HornetQClientLogger.LOGGER.errorCreatingNettyConnection(e);
                return null;
            }
        } else {
            ChannelPipeline channelPipeline = ch.pipeline();
            HornetQChannelHandler channelHandler = channelPipeline.get(HornetQChannelHandler.class);
            channelHandler.active = true;
        }

        // No acceptor on a client connection
        Listener connectionListener = new Listener();
        NettyConnection conn = new NettyConnection(configuration, ch, connectionListener,
                !httpEnabled && batchDelay > 0, false);
        connectionListener.connectionCreated(null, conn, HornetQClient.DEFAULT_CORE_PROTOCOL);
        return conn;
    } else {
        Throwable t = future.cause();

        if (t != null && !(t instanceof ConnectException)) {
            HornetQClientLogger.LOGGER.errorCreatingNettyConnection(future.cause());
        }

        return null;
    }
}

From source file:org.infinispan.rest.http2.HttpResponseHandler.java

License:Apache License

/**
 * Wait (sequentially) for a time duration for each anticipated response
 *
 * @param timeout Value of time to wait for each response
 * @param unit Units associated with {@code timeout}
 * @see HttpResponseHandler#put(int, io.netty.channel.ChannelFuture, io.netty.channel.ChannelPromise)
 *///from www  .  j a v  a  2  s. co  m
public void awaitResponses(long timeout, TimeUnit unit) {
    Iterator<Entry<Integer, Entry<ChannelFuture, ChannelPromise>>> itr = streamidPromiseMap.entrySet()
            .iterator();
    while (itr.hasNext()) {
        Entry<Integer, Entry<ChannelFuture, ChannelPromise>> entry = itr.next();
        ChannelFuture writeFuture = entry.getValue().getKey();
        if (!writeFuture.awaitUninterruptibly(timeout, unit)) {
            throw new IllegalStateException("Timed out waiting to write for stream id " + entry.getKey());
        }
        if (!writeFuture.isSuccess()) {
            throw new RuntimeException(writeFuture.cause());
        }
        ChannelPromise promise = entry.getValue().getValue();
        if (!promise.awaitUninterruptibly(timeout, unit)) {
            throw new IllegalStateException("Timed out waiting for response on stream id " + entry.getKey());
        }
        if (!promise.isSuccess()) {
            throw new RuntimeException(promise.cause());
        }
        itr.remove();
    }
}

From source file:org.it4y.integration.IT_TProxyListenerTest.java

License:Apache License

@Test
public void testPerformanceMultibleClients() throws Exception {
    final Counter msgcnt = new Counter();
    final Counter errcnt = new Counter();

    LinkManager linkManager = null;/*from   w w  w.j a va 2s .c om*/
    TProxyListener proxy = null;

    try {
        linkManager = startLinkManager();
        //get interface with default gateway. this will be our source IP
        final NetworkInterface defaultGW = linkManager.getDefaultGateway();
        log.info("Default GW: {}", defaultGW);

        //Run a proxy to intercept port 80 . this requires setup-test.sh to setup iptables and routing
        proxy = startTProxyListener(new TProxyListener(InetAddress.getByName(bind), port, backlog) {
            public void newClient(TProxyInterceptedSocket client) throws IOException {
                //log.info("intercept client connection: {}", client);
                //check client connection parameters
                Assert.assertNotNull(client);
                //we should check local and remote address are unchanged (thats transparent proxy)
                Assert.assertEquals(0x08080404, client.getRemoteAddress());
                Assert.assertEquals(80, client.getRemotePort());
                Assert.assertTrue(client.getSocket().toString()
                        .contains(defaultGW.getIpv4AddressAsInetAddress().toString()));
                msgcnt.inc();
            }

            public void onIOError(IOException io) {
                errcnt.inc();
                log.info("oeps some error: {}", io.getMessage(), io);
            }
        });
        log.info("TProxy running...");

        //we use NETTY to generated massive tcp connections
        EventLoopGroup workerGroup = new NioEventLoopGroup(Runtime.getRuntime().availableProcessors() * 40);
        Bootstrap b = new Bootstrap(); // (1)
        b.group(workerGroup); // (2)
        b.channel(NioSocketChannel.class); // (3)
        b.option(ChannelOption.SO_KEEPALIVE, true); // (4)
        Bootstrap handler = b.handler(new ChannelInitializer<NioSocketChannel>() {
            @Override
            protected void initChannel(NioSocketChannel ch) throws Exception {
            }
        });

        // Start the client.
        int nrOfConnections = 1000; //going to high here will cause TO MANY FILES open, you should see man page ulimit ;-)
        log.info("Starting {} connections ....", nrOfConnections);
        long start = System.currentTimeMillis();
        int retry = 0;
        for (int i = 0; i < nrOfConnections; i++) {
            final ChannelFuture f = b.connect("8.8.4.4", 80);
            f.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    //close when connected
                    if (future.isSuccess()) {
                        future.channel().disconnect();
                    } else {
                        log.error("ooeps:", future.cause());
                    }
                }
            });
            Thread.sleep(0, 2000); //sleep a small bit else we see issues in VM's
        }

        //log.info("Started: {} msec", System.currentTimeMillis() - start);
        //wait until all are closed
        while (msgcnt.getCount() < nrOfConnections & retry < nrOfConnections) {
            Thread.sleep(100); //on vm's this can be slow
            retry++;
        }

        long end = System.currentTimeMillis();
        log.info("Done: {} msec", end - start);
        Assert.assertEquals(nrOfConnections, msgcnt.getCount());
        Assert.assertEquals(0, errcnt.getCount());
    } finally {
        if (linkManager != null)
            stopLinkManager(linkManager);
        if (proxy != null)
            stopTProxyListener(proxy);
    }
}

From source file:org.jfxvnc.net.rfb.codec.handshaker.RfbClientHandshaker.java

License:Apache License

public final ChannelFuture handshake(Channel channel, final ChannelPromise promise) {

    channel.writeAndFlush(Unpooled.wrappedBuffer(version.getBytes())).addListener((ChannelFuture future) -> {
        if (!future.isSuccess()) {
            promise.setFailure(future.cause());
            return;
        }//from  ww  w . ja v a  2  s.c  om

        ChannelPipeline p = future.channel().pipeline();
        ChannelHandlerContext ctx = p.context(ProtocolHandshakeHandler.class);
        p.addBefore(ctx.name(), "rfb-handshake-decoder", newRfbClientDecoder());
        p.addBefore(ctx.name(), "rfb-handshake-encoder", newRfbClientEncoder());
        promise.setSuccess();

    });
    return promise;
}

From source file:org.jfxvnc.ui.service.VncRenderService.java

License:Apache License

private boolean connect() throws Exception {
    connectProperty.set(true);//from w  w w.  ja  va2 s  .  co  m
    shutdown();
    workerGroup = new NioEventLoopGroup();

    String host = config.hostProperty().get();
    int port = config.portProperty().get() > 0 ? config.portProperty().get() : CONNECT_PORT;

    Bootstrap b = new Bootstrap();
    b.group(workerGroup);
    b.channel(NioSocketChannel.class);
    b.option(ChannelOption.SO_KEEPALIVE, true);
    b.option(ChannelOption.TCP_NODELAY, true);
    b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000);

    b.handler(new ProtocolInitializer(VncRenderService.this, config));

    logger.info("try to connect to {}:{}", host, port);
    ChannelFuture f = b.connect(host, port);
    f.await(5000);

    connectProperty.set(f.isSuccess());
    logger.info("connection {}", connectProperty.get() ? "established" : "failed");
    if (f.isCancelled()) {
        logger.warn("connection aborted");
    } else if (!f.isSuccess()) {
        logger.error("connection failed", f.cause());
        exceptionCaughtProperty.set(f.cause() != null ? f.cause()
                : new Exception("connection failed to host: " + host + ":" + port));
    }
    return connectProperty.get();
}

From source file:org.jupiter.registry.DefaultRegistry.java

License:Apache License

/**
 * Notify to registry server unpublish corresponding service.
 *//* w ww. j a va 2 s  .  c o m*/
public void doUnregister(final RegisterMeta meta) {
    registryService.registerMetaSet().remove(meta);

    Message msg = new Message(serializerType.value());
    msg.messageCode(JProtocolHeader.PUBLISH_CANCEL_SERVICE);
    msg.data(meta);

    channel.writeAndFlush(msg).addListener(new ChannelFutureListener() {

        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (!future.isSuccess()) {
                Channel ch = future.channel();
                if (ch.isActive()) {
                    ch.pipeline().fireExceptionCaught(future.cause());
                } else {
                    if (logger.isWarnEnabled()) {
                        logger.warn("Unregister {} fail because of channel is inactive: {}.", meta,
                                stackTrace(future.cause()));
                    }
                }
            }
        }
    });

    MessageNonAck msgNonAck = new MessageNonAck(msg, channel);
    messagesNonAck.put(msgNonAck.id, msgNonAck);
}