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.apache.hadoop.hbase.ipc.AsyncRpcClient.java

License:Apache License

/**
 * Call method async/*  w ww .  j  av  a2 s. c o m*/
 */
private void callMethod(Descriptors.MethodDescriptor md, final PayloadCarryingRpcController pcrc, Message param,
        Message returnType, User ticket, InetSocketAddress addr, final RpcCallback<Message> done) {
    final AsyncRpcChannel connection;
    try {
        connection = createRpcChannel(md.getService().getName(), addr, ticket);

        connection.callMethod(md, pcrc, param, returnType)
                .addListener(new GenericFutureListener<Future<Message>>() {
                    @Override
                    public void operationComplete(Future<Message> future) throws Exception {
                        if (!future.isSuccess()) {
                            Throwable cause = future.cause();
                            if (cause instanceof IOException) {
                                pcrc.setFailed((IOException) cause);
                            } else {
                                pcrc.setFailed(new IOException(cause));
                            }
                        } else {
                            try {
                                done.run(future.get());
                            } catch (ExecutionException e) {
                                Throwable cause = e.getCause();
                                if (cause instanceof IOException) {
                                    pcrc.setFailed((IOException) cause);
                                } else {
                                    pcrc.setFailed(new IOException(cause));
                                }
                            } catch (InterruptedException e) {
                                pcrc.setFailed(new IOException(e));
                            }
                        }
                    }
                });
    } catch (StoppedRpcClientException | FailedServerException e) {
        pcrc.setFailed(e);
    }
}

From source file:org.apache.hadoop.hbase.ipc.NettyRpcConnection.java

License:Apache License

private void saslNegotiate(final Channel ch) {
    UserGroupInformation ticket = getUGI();
    if (ticket == null) {
        failInit(ch, new FatalConnectionException("ticket/user is null"));
        return;/*from w  w  w. j av  a  2 s .co  m*/
    }
    Promise<Boolean> saslPromise = ch.eventLoop().newPromise();
    final NettyHBaseSaslRpcClientHandler saslHandler;
    try {
        saslHandler = new NettyHBaseSaslRpcClientHandler(saslPromise, ticket, authMethod, token,
                serverPrincipal, rpcClient.fallbackAllowed, this.rpcClient.conf);
    } catch (IOException e) {
        failInit(ch, e);
        return;
    }
    ch.pipeline().addFirst(new SaslChallengeDecoder(), saslHandler);
    saslPromise.addListener(new FutureListener<Boolean>() {

        @Override
        public void operationComplete(Future<Boolean> future) throws Exception {
            if (future.isSuccess()) {
                ChannelPipeline p = ch.pipeline();
                p.remove(SaslChallengeDecoder.class);
                p.remove(NettyHBaseSaslRpcClientHandler.class);

                // check if negotiate with server for connection header is necessary
                if (saslHandler.isNeedProcessConnectionHeader()) {
                    Promise<Boolean> connectionHeaderPromise = ch.eventLoop().newPromise();
                    // create the handler to handle the connection header
                    ChannelHandler chHandler = new NettyHBaseRpcConnectionHeaderHandler(connectionHeaderPromise,
                            conf, connectionHeaderWithLength);

                    // add ReadTimeoutHandler to deal with server doesn't response connection header
                    // because of the different configuration in client side and server side
                    p.addFirst(new ReadTimeoutHandler(RpcClient.DEFAULT_SOCKET_TIMEOUT_READ,
                            TimeUnit.MILLISECONDS));
                    p.addLast(chHandler);
                    connectionHeaderPromise.addListener(new FutureListener<Boolean>() {
                        @Override
                        public void operationComplete(Future<Boolean> future) throws Exception {
                            if (future.isSuccess()) {
                                ChannelPipeline p = ch.pipeline();
                                p.remove(ReadTimeoutHandler.class);
                                p.remove(NettyHBaseRpcConnectionHeaderHandler.class);
                                // don't send connection header, NettyHbaseRpcConnectionHeaderHandler
                                // sent it already
                                established(ch);
                            } else {
                                final Throwable error = future.cause();
                                scheduleRelogin(error);
                                failInit(ch, toIOE(error));
                            }
                        }
                    });
                } else {
                    // send the connection header to server
                    ch.write(connectionHeaderWithLength.retainedDuplicate());
                    established(ch);
                }
            } else {
                final Throwable error = future.cause();
                scheduleRelogin(error);
                failInit(ch, toIOE(error));
            }
        }
    });
}

From source file:org.apache.pulsar.client.impl.ConsumerImpl.java

License:Apache License

private CompletableFuture<Void> sendAcknowledge(MessageId messageId, AckType ackType) {
    MessageIdImpl msgId = (MessageIdImpl) messageId;
    final ByteBuf cmd = Commands.newAck(consumerId, msgId.getLedgerId(), msgId.getEntryId(), ackType, null);

    // There's no actual response from ack messages
    final CompletableFuture<Void> ackFuture = new CompletableFuture<Void>();

    if (isConnected()) {
        cnx().ctx().writeAndFlush(cmd).addListener(new GenericFutureListener<Future<Void>>() {
            @Override/*from  www . j  av  a2  s.  c o m*/
            public void operationComplete(Future<Void> future) throws Exception {
                if (future.isSuccess()) {
                    if (ackType == AckType.Individual) {
                        unAckedMessageTracker.remove(msgId);
                        // increment counter by 1 for non-batch msg
                        if (!(messageId instanceof BatchMessageIdImpl)) {
                            stats.incrementNumAcksSent(1);
                        }
                    } else if (ackType == AckType.Cumulative) {
                        stats.incrementNumAcksSent(unAckedMessageTracker.removeMessagesTill(msgId));
                    }
                    if (log.isDebugEnabled()) {
                        log.debug("[{}] [{}] [{}] Successfully acknowledged message - {}, acktype {}",
                                subscription, topic, consumerName, messageId, ackType);
                    }
                    ackFuture.complete(null);
                } else {
                    stats.incrementNumAcksFailed();
                    ackFuture.completeExceptionally(new PulsarClientException(future.cause()));
                }
            }
        });
    } else {
        stats.incrementNumAcksFailed();
        ackFuture.completeExceptionally(
                new PulsarClientException("Not connected to broker. State: " + getState()));
    }

    return ackFuture;
}

From source file:org.apache.pulsar.proxy.server.ProxyConnection.java

License:Apache License

@Override
public void operationComplete(Future<Void> future) throws Exception {
    // This is invoked when the write operation on the paired connection is
    // completed// www. j a  v  a 2  s  . c  o  m
    if (future.isSuccess()) {
        ctx.read();
    } else {
        LOG.warn("[{}] Error in writing to inbound channel. Closing", remoteAddress, future.cause());
        directProxyHandler.outboundChannel.close();
    }
}

From source file:org.apache.qpid.jms.transports.netty.NettySslTransport.java

License:Apache License

@Override
protected void handleConnected(final Channel channel) throws Exception {
    SslHandler sslHandler = channel.pipeline().get(SslHandler.class);

    Future<Channel> channelFuture = sslHandler.handshakeFuture();
    channelFuture.addListener(new GenericFutureListener<Future<Channel>>() {
        @Override//from   w  w w  .  j  av a 2  s . co m
        public void operationComplete(Future<Channel> future) throws Exception {
            if (future.isSuccess()) {
                LOG.trace("SSL Handshake has completed: {}", channel);
                connectionEstablished(channel);
            } else {
                LOG.trace("SSL Handshake has failed: {}", channel);
                connectionFailed(IOExceptionSupport.create(future.cause()));
            }
        }
    });
}

From source file:org.asynchttpclient.netty.SimpleFutureListener.java

License:Open Source License

@Override
public final void operationComplete(Future<V> future) throws Exception {
    if (future.isSuccess()) {
        onSuccess(future.getNow());/*from   ww w .  ja v  a  2s . c  om*/
    } else {
        onFailure(future.cause());
    }
}

From source file:org.asynchttpclient.netty.SimpleGenericFutureListener.java

License:Open Source License

@Override
public final void operationComplete(Future<V> future) throws Exception {
    if (future.isSuccess()) {
        onSuccess(future.get());//from   w w w . j a v  a2s .co  m
    } else {
        onFailure(future.cause());
    }
}

From source file:org.asynchttpclient.providers.netty4.request.NettyConnectListener.java

License:Open Source License

private void onFutureSuccess(final Channel channel) throws ConnectException {
    Channels.setAttribute(channel, future);
    final HostnameVerifier hostnameVerifier = config.getHostnameVerifier();
    final SslHandler sslHandler = ChannelManager.getSslHandler(channel.pipeline());
    if (hostnameVerifier != null && sslHandler != null) {
        final String host = future.getUri().getHost();
        sslHandler.handshakeFuture().addListener(new GenericFutureListener<Future<? super Channel>>() {
            @Override//from   w  w  w  . j  a v  a 2s  .  com
            public void operationComplete(Future<? super Channel> handshakeFuture) throws Exception {
                if (handshakeFuture.isSuccess()) {
                    Channel channel = (Channel) handshakeFuture.getNow();
                    SSLEngine engine = sslHandler.engine();
                    SSLSession session = engine.getSession();

                    LOGGER.debug("onFutureSuccess: session = {}, id = {}, isValid = {}, host = {}",
                            session.toString(), Base64.encode(session.getId()), session.isValid(), host);
                    if (hostnameVerifier.verify(host, session)) {
                        final AsyncHandler<T> asyncHandler = future.getAsyncHandler();
                        if (asyncHandler instanceof AsyncHandlerExtensions)
                            AsyncHandlerExtensions.class.cast(asyncHandler).onSslHandshakeCompleted();

                        writeRequest(channel);
                    } else {
                        onFutureFailure(channel, new ConnectException("HostnameVerifier exception"));
                    }
                } else {
                    onFutureFailure(channel, handshakeFuture.cause());
                }
            }
        });
    } else {
        writeRequest(channel);
    }
}

From source file:org.eclipse.californium.elements.tcp.TcpClientConnector.java

License:Open Source License

@Override
public void send(final RawData msg) {
    if (msg == null) {
        throw new NullPointerException("Message must not be null");
    }/*from   w  w w.  j av a2 s  . c o m*/
    if (msg.isMulticast()) {
        LOGGER.warn("TcpConnector drops {} bytes to multicast {}:{}", msg.getSize(), msg.getAddress(),
                msg.getPort());
        msg.onError(new MulticastNotSupportedException("TCP doesn't support multicast!"));
        return;
    }
    if (workerGroup == null) {
        msg.onError(new IllegalStateException("TCP client connector not running!"));
        return;
    }
    InetSocketAddress addressKey = msg.getInetSocketAddress();
    final boolean connected = poolMap.contains(addressKey);
    final EndpointContextMatcher endpointMatcher = getEndpointContextMatcher();
    /* check, if a new connection should be established */
    if (endpointMatcher != null && !connected && !endpointMatcher.isToBeSent(msg.getEndpointContext(), null)) {
        LOGGER.warn("TcpConnector drops {} bytes to new {}:{}", msg.getSize(), msg.getAddress(), msg.getPort());
        msg.onError(new EndpointMismatchException("no connection"));
        return;
    }
    if (!connected) {
        msg.onConnecting();
    }
    final ChannelPool channelPool = poolMap.get(addressKey);
    Future<Channel> acquire = channelPool.acquire();
    acquire.addListener(new GenericFutureListener<Future<Channel>>() {

        @Override
        public void operationComplete(Future<Channel> future) throws Exception {
            Throwable cause = null;
            if (future.isSuccess()) {
                Channel channel = future.getNow();
                try {
                    send(channel, endpointMatcher, msg);
                } catch (Throwable t) {
                    cause = t;
                } finally {
                    try {
                        channelPool.release(channel);
                    } catch (RejectedExecutionException e) {
                        LOGGER.debug("{}", e.getMessage());
                    }
                }
            } else if (future.isCancelled()) {
                cause = new CancellationException();
            } else {
                cause = future.cause();
            }
            if (cause != null) {
                if (cause instanceof ConnectTimeoutException) {
                    LOGGER.warn("{}", cause.getMessage());
                } else if (cause instanceof CancellationException) {
                    LOGGER.debug("{}", cause.getMessage());
                } else {
                    LOGGER.warn("Unable to open connection to {}", msg.getAddress(), future.cause());
                }
                msg.onError(future.cause());
            }
        }
    });
}

From source file:org.eclipse.californium.elements.tcp.TlsClientConnector.java

License:Open Source License

/**
 * {@inheritDoc}/*from w  w  w . j a  v  a  2  s  . co  m*/
 * 
 * Delay message sending after TLS handshake is completed.
 */
@Override
protected void send(final Channel channel, final EndpointContextMatcher endpointMatcher, final RawData msg) {
    final SslHandler sslHandler = channel.pipeline().get(SslHandler.class);
    if (sslHandler == null) {
        msg.onError(new IllegalStateException("Missing SslHandler"));
    } else {
        /*
         * Trigger handshake.
         */
        Future<Channel> handshakeFuture = sslHandler.handshakeFuture();
        handshakeFuture.addListener(new GenericFutureListener<Future<Channel>>() {

            @Override
            public void operationComplete(Future<Channel> future) throws Exception {
                if (future.isSuccess()) {
                    EndpointContext context = contextUtil.buildEndpointContext(channel);
                    if (context == null || context.get(TlsEndpointContext.KEY_SESSION_ID) == null) {
                        msg.onError(new IllegalStateException("Missing TlsEndpointContext " + context));
                        return;
                    }
                    /*
                     * Handshake succeeded! 
                     * Call super.send() to actually send the message.
                     */
                    TlsClientConnector.super.send(future.getNow(), endpointMatcher, msg);
                } else if (future.isCancelled()) {
                    msg.onError(new CancellationException());
                } else {
                    msg.onError(future.cause());
                }
            }
        });
    }
}