Example usage for io.netty.util.concurrent Future cause

List of usage examples for io.netty.util.concurrent Future cause

Introduction

In this page you can find the example usage for io.netty.util.concurrent Future 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.hornetq.core.remoting.impl.netty.NettyConnector.java

License:Apache License

public Connection createConnection() {
    if (channelClazz == null) {
        return null;
    }/*from  w w w.ja v a2s. c o m*/

    // 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.jboss.aerogear.webpush.netty.WebPushFrameListener.java

License:Apache License

private static void logFutureError(final Future future) {
    if (!future.isSuccess()) {
        LOGGER.error("ChannelFuture failed. Cause:", future.cause());
    }// ww  w.java 2  s  . c o  m
}

From source file:org.jdiameter.client.impl.transport.tls.netty.StartTlsInitiator.java

License:Open Source License

@SuppressWarnings({ "unchecked", "rawtypes" })
@Override/*w w w  .  j  ava  2s .  c  om*/
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (msg instanceof IMessage) {
        IMessage m = (IMessage) msg;
        logger.debug("StartTlsInitiator");
        if (m.getCommandCode() == IMessage.CAPABILITIES_EXCHANGE_ANSWER
                && this.tlsTransportClient.getTlsHandshakingState() == TlsHandshakingState.INIT) {
            AvpSet set = m.getAvps();
            Avp inbandAvp = set.getAvp(Avp.INBAND_SECURITY_ID);
            if (inbandAvp != null && inbandAvp.getUnsigned32() == 1) {
                this.tlsTransportClient.setTlsHandshakingState(TlsHandshakingState.SHAKING);

                final ChannelPipeline pipeline = ctx.pipeline();
                pipeline.remove("decoder");
                pipeline.remove("msgHandler");
                pipeline.remove(this);
                pipeline.remove("encoder");
                pipeline.remove("inbandWriter");

                pipeline.addLast("startTlsClientHandler", new StartTlsClientHandler(this.tlsTransportClient));

                logger.debug("Sending StartTlsRequest");
                ctx.writeAndFlush(Unpooled.wrappedBuffer("StartTlsRequest".getBytes()))
                        .addListener(new GenericFutureListener() {

                            @Override
                            public void operationComplete(Future f) throws Exception {
                                if (!f.isSuccess()) {
                                    logger.error(f.cause().getMessage(), f.cause());
                                }
                            }
                        });

            }
        }
    }

    ReferenceCountUtil.release(msg);
}

From source file:org.jdiameter.client.impl.transport.tls.netty.StartTlsServerHandler.java

License:Open Source License

@SuppressWarnings({ "unchecked", "rawtypes" })
@Override/*from w w w. j  a  v a  2s .co m*/
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    logger.debug("StartTlsServerHandler");
    ByteBuf buf = (ByteBuf) msg;
    byte[] bytes = new byte[buf.readableBytes()];
    buf.getBytes(buf.readerIndex(), bytes);

    if ("StartTlsRequest".equals(new String(bytes))) {
        logger.debug("Received StartTlsRequest");
        SslContext sslContext = SslContextFactory.getSslContextForServer(this.tlsTransportClient.getConfig());
        SSLEngine sslEngine = sslContext.newEngine(ctx.alloc());
        sslEngine.setUseClientMode(false);
        SslHandler sslHandler = new SslHandler(sslEngine, false);

        final ChannelPipeline pipeline = ctx.pipeline();

        pipeline.remove("decoder");
        pipeline.remove("msgHandler");
        pipeline.remove("encoder");
        pipeline.remove("inbandWriter");
        pipeline.remove(this);

        pipeline.addLast("sslHandler", sslHandler);

        sslHandler.handshakeFuture().addListener(new GenericFutureListener() {

            @Override
            public void operationComplete(Future future) throws Exception {
                if (future.isSuccess()) {
                    logger.debug("StartTls server handshake succesfull");

                    tlsTransportClient.setTlsHandshakingState(TlsHandshakingState.SHAKEN);

                    logger.debug("restoring all handlers");

                    pipeline.addLast("decoder",
                            new DiameterMessageDecoder(
                                    StartTlsServerHandler.this.tlsTransportClient.getParent(),
                                    StartTlsServerHandler.this.tlsTransportClient.getParser()));
                    pipeline.addLast("msgHandler", new DiameterMessageHandler(
                            StartTlsServerHandler.this.tlsTransportClient.getParent(), true));

                    pipeline.addLast("encoder", new DiameterMessageEncoder(
                            StartTlsServerHandler.this.tlsTransportClient.getParser()));
                    pipeline.addLast("inbandWriter", new InbandSecurityHandler());

                }
            }
        });

        ReferenceCountUtil.release(msg);
        logger.debug("Sending StartTlsResponse");
        ctx.writeAndFlush(Unpooled.wrappedBuffer("StartTlsResponse".getBytes()))
                .addListener(new GenericFutureListener() {

                    @Override
                    public void operationComplete(Future f) throws Exception {
                        if (!f.isSuccess()) {
                            logger.error(f.cause().getMessage(), f.cause());
                        }

                    }
                });
    } else {
        ctx.fireChannelRead(msg);
    }

}

From source file:org.kaaproject.kaa.server.transports.http.transport.netty.DefaultHandler.java

License:Apache License

@Override
protected void channelRead0(final ChannelHandlerContext ctx, final AbstractCommand msg) throws Exception {
    Callable<AbstractCommand> callable = msg;

    final Future<AbstractCommand> future = executor.submit(callable);

    future.addListener(new GenericFutureListener<Future<Object>>() {
        @Override//w w  w. j  a  v a  2  s. com
        public void operationComplete(final Future<Object> future) throws Exception {
            LOG.trace("DefaultHandler().operationComplete...");
            if (future.isSuccess()) {
                ctx.writeAndFlush(future.get());
            } else {
                ctx.fireExceptionCaught(future.cause());
            }
        }
    });
}

From source file:org.opendaylight.bgpcep.pcep.topology.provider.AbstractTopologySessionListener.java

License:Open Source License

protected final synchronized ListenableFuture<OperationResult> sendMessage(final Message message,
        final S requestId, final Metadata metadata) {
    final io.netty.util.concurrent.Future<Void> f = this.session.sendMessage(message);
    this.listenerState.updateStatefulSentMsg(message);
    final PCEPRequest req = new PCEPRequest(metadata);
    this.requests.put(requestId, req);
    final int rpcTimeout = serverSessionManager.getRpcTimeout();
    LOG.trace("RPC response timeout value is {} seconds", rpcTimeout);
    if (rpcTimeout > 0) {
        setupTimeoutHandler(requestId, req, rpcTimeout);
    }//from  ww w. j a v  a 2  s.co  m

    f.addListener(new FutureListener<Void>() {
        @Override
        public void operationComplete(final io.netty.util.concurrent.Future<Void> future) {
            if (!future.isSuccess()) {
                synchronized (AbstractTopologySessionListener.this) {
                    AbstractTopologySessionListener.this.requests.remove(requestId);
                }
                req.done(OperationResults.UNSENT);
                LOG.info("Failed to send request {}, instruction cancelled", requestId, future.cause());
            } else {
                req.sent();
                LOG.trace("Request {} sent to peer (object {})", requestId, req);
            }
        }
    });

    return req.getFuture();
}

From source file:org.opendaylight.controller.sal.connect.netconf.listener.NetconfDeviceCommunicator.java

License:Open Source License

public void initializeRemoteConnection(final NetconfClientDispatcher dispatcher,
        final NetconfClientConfiguration config) {
    // TODO 2313 extract listener from configuration
    if (config instanceof NetconfReconnectingClientConfiguration) {
        initFuture = dispatcher.createReconnectingClient((NetconfReconnectingClientConfiguration) config);
    } else {/*from   ww w.j ava2  s . c o m*/
        initFuture = dispatcher.createClient(config);
    }

    initFuture.addListener(new GenericFutureListener<Future<Object>>() {

        @Override
        public void operationComplete(Future<Object> future) throws Exception {
            if (!future.isSuccess() && !future.isCancelled()) {
                logger.debug("{}: Connection failed", id, future.cause());
                NetconfDeviceCommunicator.this.remoteDevice.onRemoteSessionFailed(future.cause());
            }
        }
    });

}

From source file:org.opendaylight.controller.sal.connect.netconf.listener.NetconfDeviceCommunicator.java

License:Open Source License

private ListenableFuture<RpcResult<NetconfMessage>> sendRequestWithLock(final NetconfMessage message,
        final QName rpc) {
    if (logger.isTraceEnabled()) {
        logger.trace("{}: Sending message {}", id, msgToS(message));
    }// ww  w .  j av a 2s.c  o  m

    if (session == null) {
        logger.warn("{}: Session is disconnected, failing RPC request {}", id, message);
        return Futures.immediateFuture(createSessionDownRpcResult());
    }

    final Request req = new Request(new UncancellableFuture<RpcResult<NetconfMessage>>(true), message);
    requests.add(req);

    session.sendMessage(req.request).addListener(new FutureListener<Void>() {
        @Override
        public void operationComplete(final Future<Void> future) throws Exception {
            if (!future.isSuccess()) {
                // We expect that a session down will occur at this point
                logger.debug("{}: Failed to send request {}", id, XmlUtil.toString(req.request.getDocument()),
                        future.cause());

                if (future.cause() != null) {
                    req.future.set(createErrorRpcResult(RpcError.ErrorType.TRANSPORT,
                            future.cause().getLocalizedMessage()));
                } else {
                    req.future.set(createSessionDownRpcResult()); // assume session is down
                }
                req.future.setException(future.cause());
            } else {
                logger.trace("Finished sending request {}", req.request);
            }
        }
    });

    return req.future;
}

From source file:org.opendaylight.controller.sal.connect.netconf.NetconfDeviceListener.java

License:Open Source License

synchronized ListenableFuture<RpcResult<CompositeNode>> sendRequest(final NetconfMessage message) {
    if (session == null) {
        LOG.debug("Session to {} is disconnected, failing RPC request {}", device.getName(), message);
        return Futures.<RpcResult<CompositeNode>>immediateFuture(new RpcResult<CompositeNode>() {
            @Override/*from   w w  w . ja va2 s  .  c  o  m*/
            public boolean isSuccessful() {
                return false;
            }

            @Override
            public CompositeNode getResult() {
                return null;
            }

            @Override
            public Collection<RpcError> getErrors() {
                // FIXME: indicate that the session is down
                return Collections.emptySet();
            }
        });
    }

    final Request req = new Request(new UncancellableFuture<RpcResult<CompositeNode>>(true), message);
    requests.add(req);

    session.sendMessage(req.request).addListener(new FutureListener<Void>() {
        @Override
        public void operationComplete(final Future<Void> future) throws Exception {
            if (!future.isSuccess()) {
                // We expect that a session down will occur at this point
                LOG.debug("Failed to send request {}", req.request, future.cause());
                req.future.setException(future.cause());
            } else {
                LOG.trace("Finished sending request {}", req.request);
            }
        }
    });

    return req.future;
}

From source file:org.opendaylight.netconf.client.TcpClientChannelInitializer.java

License:Open Source License

@Override
public void initialize(final Channel ch, final Promise<NetconfClientSession> promise) {
    final Future<NetconfClientSession> negotiationFuture = promise;

    //We have to add this channel outbound handler to channel pipeline, in order
    //to get notifications from netconf negotiatior. Set connection promise to
    //success only after successful negotiation.
    ch.pipeline().addFirst(new ChannelOutboundHandlerAdapter() {
        ChannelPromise connectPromise;//  w  w w .  j  a  v a2 s .c  o  m
        GenericFutureListener<Future<NetconfClientSession>> negotiationFutureListener;

        @Override
        public void connect(final ChannelHandlerContext ctx, final SocketAddress remoteAddress,
                final SocketAddress localAddress, final ChannelPromise channelPromise) throws Exception {
            connectPromise = channelPromise;
            ChannelPromise tcpConnectFuture = new DefaultChannelPromise(ch);

            negotiationFutureListener = new GenericFutureListener<Future<NetconfClientSession>>() {
                @Override
                public void operationComplete(final Future<NetconfClientSession> future) throws Exception {
                    if (future.isSuccess()) {
                        connectPromise.setSuccess();
                    }
                }
            };

            tcpConnectFuture.addListener(new GenericFutureListener<Future<? super Void>>() {
                @Override
                public void operationComplete(final Future<? super Void> future) throws Exception {
                    if (future.isSuccess()) {
                        //complete connection promise with netconf negotiation future
                        negotiationFuture.addListener(negotiationFutureListener);
                    } else {
                        connectPromise.setFailure(future.cause());
                    }
                }
            });
            ctx.connect(remoteAddress, localAddress, tcpConnectFuture);
        }

        @Override
        public void disconnect(final ChannelHandlerContext ctx, final ChannelPromise promise) throws Exception {
            // If we have already succeeded and the session was dropped after, we need to fire inactive to notify reconnect logic
            if (connectPromise.isSuccess()) {
                ctx.fireChannelInactive();
            }

            //If connection promise is not already set, it means negotiation failed
            //we must set connection promise to failure
            if (!connectPromise.isDone()) {
                connectPromise.setFailure(new IllegalStateException("Negotiation failed"));
            }

            //Remove listener from negotiation future, we don't want notifications
            //from negotiation anymore
            negotiationFuture.removeListener(negotiationFutureListener);

            super.disconnect(ctx, promise);
            promise.setSuccess();
        }
    });

    super.initialize(ch, promise);
}