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:me.ferrybig.javacoding.teamspeakconnector.util.FutureUtil.java

License:Open Source License

public static <T, I, R> Future<R> chainFutureFlat(Promise<R> result, Future<T> future,
        Function<T, Future<I>> mapping, Function<I, R> secondary) {
    future.addListener(ignored -> {//w  w w.  ja v  a2s  .c o  m
        assert ignored == future;
        try {
            if (future.isSuccess()) {
                delegateFutureResult(mapping.apply(future.getNow()), result, secondary);
            } else {
                result.setFailure(future.cause());
            }
        } catch (Throwable e) {
            result.setFailure(e);
        }
    });
    return result;
}

From source file:net.epsilony.utils.codec.modbus.ModbusClientMaster.java

License:Open Source License

public CompletableFuture<ModbusResponse> request(ModbusRequest req) {
    final CompletableFuture<ModbusResponse> result = new CompletableFuture<>();

    result.whenComplete((res, ex) -> {
        if (transectionIdDispatcher != null) {
            int transectionId = req.getTransectionId();
            if (transectionId >= 0) {
                transectionIdDispatcher.repay(transectionId);
            }//from ww  w  . j  a v a  2s  . co m
        }
    });

    lock.lock();
    try {
        if (connectFuture == null) {
            connectFuture = genConnectFuture();
            connectFuture.addListener(new GenericFutureListener<Future<? super Void>>() {

                @Override
                public void operationComplete(Future<? super Void> future) throws Exception {
                    lock.lock();
                    try {
                        if (future.isSuccess()) {
                            channel = connectFuture.channel();
                            channel.closeFuture()
                                    .addListener(new GenericFutureListener<Future<? super Void>>() {

                                        @Override
                                        public void operationComplete(Future<? super Void> future)
                                                throws Exception {
                                            lock.lock();
                                            try {
                                                connectFuture = null;
                                                initializer.clearExceptionally(
                                                        new ConnectException("connection is closed!"));
                                                transectionIdDispatcher.reset();
                                            } finally {
                                                lock.unlock();
                                            }
                                        }
                                    });
                        } else {
                            connectFuture = null;
                        }
                    } finally {
                        lock.unlock();
                    }
                }
            });
        }

        connectFuture.addListener(new GenericFutureListener<Future<? super Void>>() {

            @Override
            public void operationComplete(Future<? super Void> future) throws Exception {
                ChannelFuture channelFuture = (ChannelFuture) future;
                if (future.isSuccess()) {
                    if (null != transectionIdDispatcher) {
                        int transectionId = transectionIdDispatcher.borrow();
                        req.setTransectionId(transectionId);
                        if (transectionId < 0) {
                            result.completeExceptionally(new TransectionDispatcherEmptyException());
                            return;
                        }
                    }

                    try {
                        initializer.register(result, req);
                    } catch (Throwable ex) {
                        result.completeExceptionally(ex);
                        return;
                    }

                    ChannelFuture writeFuture = channelFuture.channel().writeAndFlush(req);
                    writeFuture.addListener(new GenericFutureListener<Future<? super Void>>() {

                        @Override
                        public void operationComplete(Future<? super Void> future) throws Exception {
                            if (!future.isSuccess()) {
                                if (future.isCancelled()) {
                                    initializer.removeExceptionally(req.getTransectionId(),
                                            new ConnectException("connection is canncelled"));
                                } else {
                                    initializer.removeExceptionally(req.getTransectionId(), future.cause());
                                }
                            }
                        }
                    });
                } else if (future.isCancelled()) {
                    result.completeExceptionally(new ConnectException("connection is canncelled"));
                } else {
                    result.completeExceptionally(future.cause());
                }
            }

        });
    } finally {
        lock.unlock();
    }

    return result;

}

From source file:org.aesh.terminal.http.netty.NettyWebsocketTtyBootstrap.java

License:Open Source License

public void stop(Consumer<Throwable> doneHandler) {
    CountDownLatch latch = new CountDownLatch(1);
    if (channel != null) {
        channel.close().addListener((Future<Void> f) -> latch.countDown());
    }/* w  w  w .  j a va2  s . c o  m*/
    channelGroup.close().addListener((Future<Void> f) -> {
        latch.await();
        doneHandler.accept(f.cause());
    });
}

From source file:org.apache.activemq.artemis.core.remoting.impl.netty.NettyConnector.java

License:Apache License

public Connection createConnection() {
    if (channelClazz == null) {
        return null;
    }//  ww  w .  ja va  2 s  . 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());
            }
        }
    }

    ActiveMQClientLogger.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();
                    ActiveMQChannelHandler channelHandler = channelPipeline.get(ActiveMQChannelHandler.class);
                    channelHandler.active = true;
                } else {
                    ch.close().awaitUninterruptibly();
                    ActiveMQClientLogger.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, ACTIVEMQ_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_ACTIVEMQ_REMOTING_KEY, key);
                ch.attr(REMOTING_KEY).set(key);

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

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

                if (!httpUpgradeHandler.awaitHandshake()) {
                    return null;
                }
            } catch (URISyntaxException e) {
                ActiveMQClientLogger.LOGGER.errorCreatingNettyConnection(e);
                return null;
            }
        } else {
            ChannelPipeline channelPipeline = ch.pipeline();
            ActiveMQChannelHandler channelHandler = channelPipeline.get(ActiveMQChannelHandler.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, protocolManager.getName());
        return conn;
    } else {
        Throwable t = future.cause();

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

        return null;
    }
}

From source file:org.apache.activemq.artemis.core.remoting.impl.netty.SharedEventLoopGroup.java

License:Apache License

@Override
public Future<?> shutdownGracefully(final long l, final long l2, final TimeUnit timeUnit) {
    if (channelFactoryCount.decrementAndGet() == 0) {
        shutdown.compareAndSet(null, next().scheduleAtFixedRate(new Runnable() {
            @Override//from  w  w  w .  j  ava 2 s . co  m
            public void run() {
                synchronized (SharedEventLoopGroup.class) {
                    if (shutdown.get() != null) {
                        Future<?> future = SharedEventLoopGroup.super.shutdownGracefully(l, l2, timeUnit);
                        future.addListener(new FutureListener<Object>() {
                            @Override
                            public void operationComplete(Future<Object> future) throws Exception {
                                if (future.isSuccess()) {
                                    terminationPromise.setSuccess(null);
                                } else {
                                    terminationPromise.setFailure(future.cause());
                                }
                            }
                        });
                        instance = null;
                    }
                }
            }

        }, 10, 10, TimeUnit.SECONDS));
    }
    return terminationPromise;
}

From source file:org.apache.activemq.artemis.core.remoting.impl.netty.SharedNioEventLoopGroup.java

License:Apache License

@Override
public Future<?> shutdownGracefully(final long l, final long l2, final TimeUnit timeUnit) {
    if (nioChannelFactoryCount.decrementAndGet() == 0) {
        shutdown.compareAndSet(null, next().scheduleAtFixedRate(new Runnable() {
            @Override/*from  www .ja  v  a2 s . c  o  m*/
            public void run() {
                synchronized (SharedNioEventLoopGroup.class) {
                    if (shutdown.get() != null) {
                        Future<?> future = SharedNioEventLoopGroup.super.shutdownGracefully(l, l2, timeUnit);
                        future.addListener(new FutureListener<Object>() {
                            @Override
                            public void operationComplete(Future future) throws Exception {
                                if (future.isSuccess()) {
                                    terminationPromise.setSuccess(null);
                                } else {
                                    terminationPromise.setFailure(future.cause());
                                }
                            }
                        });
                        instance = null;
                    }
                }
            }

        }, 10, 10, TimeUnit.SECONDS));
    }
    return terminationPromise;
}

From source file:org.apache.bookkeeper.proto.BookieRequestProcessor.java

License:Apache License

private void processStartTLSRequestV3(final BookkeeperProtocol.Request r, final Channel c) {
    BookkeeperProtocol.Response.Builder response = BookkeeperProtocol.Response.newBuilder();
    BookkeeperProtocol.BKPacketHeader.Builder header = BookkeeperProtocol.BKPacketHeader.newBuilder();
    header.setVersion(BookkeeperProtocol.ProtocolVersion.VERSION_THREE);
    header.setOperation(r.getHeader().getOperation());
    header.setTxnId(r.getHeader().getTxnId());
    response.setHeader(header.build());//from  w ww . java2  s  . co  m
    if (shFactory == null) {
        LOG.error("Got StartTLS request but TLS not configured");
        response.setStatus(BookkeeperProtocol.StatusCode.EBADREQ);
        c.writeAndFlush(response.build());
    } else {
        // there is no need to execute in a different thread as this operation is light
        SslHandler sslHandler = shFactory.newTLSHandler();
        c.pipeline().addFirst("tls", sslHandler);

        response.setStatus(BookkeeperProtocol.StatusCode.EOK);
        BookkeeperProtocol.StartTLSResponse.Builder builder = BookkeeperProtocol.StartTLSResponse.newBuilder();
        response.setStartTLSResponse(builder.build());
        sslHandler.handshakeFuture().addListener(new GenericFutureListener<Future<Channel>>() {
            @Override
            public void operationComplete(Future<Channel> future) throws Exception {
                // notify the AuthPlugin the completion of the handshake, even in case of failure
                AuthHandler.ServerSideHandler authHandler = c.pipeline()
                        .get(AuthHandler.ServerSideHandler.class);
                authHandler.authProvider.onProtocolUpgrade();
                if (future.isSuccess()) {
                    LOG.info("Session is protected by: {}", sslHandler.engine().getSession().getCipherSuite());
                } else {
                    LOG.error("TLS Handshake failure: {}", future.cause());
                    BookkeeperProtocol.Response.Builder errResponse = BookkeeperProtocol.Response.newBuilder()
                            .setHeader(r.getHeader()).setStatus(BookkeeperProtocol.StatusCode.EIO);
                    c.writeAndFlush(errResponse.build());
                    if (statsEnabled) {
                        bkStats.getOpStats(BKStats.STATS_UNKNOWN).incrementFailedOps();
                    }
                }
            }
        });
        c.writeAndFlush(response.build());
    }
}

From source file:org.apache.bookkeeper.proto.PerChannelBookieClient.java

License:Apache License

void initTLSHandshake() {
    // create TLS handler
    PerChannelBookieClient parentObj = PerChannelBookieClient.this;
    SslHandler handler = parentObj.shFactory.newTLSHandler();
    channel.pipeline().addFirst(parentObj.shFactory.getHandlerName(), handler);
    handler.handshakeFuture().addListener(new GenericFutureListener<Future<Channel>>() {
        @Override/*from   ww w  . jav a 2s .  co m*/
        public void operationComplete(Future<Channel> future) throws Exception {
            int rc;
            Queue<GenericCallback<PerChannelBookieClient>> oldPendingOps;

            synchronized (PerChannelBookieClient.this) {
                if (future.isSuccess() && state == ConnectionState.CONNECTING) {
                    LOG.error("Connection state changed before TLS handshake completed {}/{}", addr, state);
                    rc = BKException.Code.BookieHandleNotAvailableException;
                    closeChannel(channel);
                    channel = null;
                    if (state != ConnectionState.CLOSED) {
                        state = ConnectionState.DISCONNECTED;
                    }
                } else if (future.isSuccess() && state == ConnectionState.START_TLS) {
                    rc = BKException.Code.OK;
                    LOG.info("Successfully connected to bookie using TLS: " + addr);

                    state = ConnectionState.CONNECTED;
                    AuthHandler.ClientSideHandler authHandler = future.get().pipeline()
                            .get(AuthHandler.ClientSideHandler.class);
                    authHandler.authProvider.onProtocolUpgrade();
                    activeTlsChannelCounter.inc();
                } else if (future.isSuccess()
                        && (state == ConnectionState.CLOSED || state == ConnectionState.DISCONNECTED)) {
                    LOG.warn("Closed before TLS handshake completed, clean up: {}, current state {}", channel,
                            state);
                    closeChannel(channel);
                    rc = BKException.Code.BookieHandleNotAvailableException;
                    channel = null;
                } else if (future.isSuccess() && state == ConnectionState.CONNECTED) {
                    LOG.debug("Already connected with another channel({}), so close the new channel({})",
                            channel, channel);
                    closeChannel(channel);
                    return; // pendingOps should have been completed when other channel connected
                } else {
                    LOG.error("TLS handshake failed with bookie: {}/{}, current state {} : ", channel, addr,
                            state, future.cause());
                    rc = BKException.Code.SecurityException;
                    closeChannel(channel);
                    channel = null;
                    if (state != ConnectionState.CLOSED) {
                        state = ConnectionState.DISCONNECTED;
                    }
                    failedTlsHandshakeCounter.inc();
                }

                // trick to not do operations under the lock, take the list
                // of pending ops and assign it to a new variable, while
                // emptying the pending ops by just assigning it to a new
                // list
                oldPendingOps = pendingOps;
                pendingOps = new ArrayDeque<>();
            }

            makeWritable();

            for (GenericCallback<PerChannelBookieClient> pendingOp : oldPendingOps) {
                pendingOp.operationComplete(rc, PerChannelBookieClient.this);
            }
        }
    });
}

From source file:org.apache.hadoop.hbase.io.asyncfs.FanOutOneBlockAsyncDFSOutput.java

License:Apache License

private <A> void flush0(final A attachment, final CompletionHandler<Long, ? super A> handler,
        boolean syncBlock) {
    if (state != State.STREAMING) {
        handler.failed(new IOException("stream already broken"), attachment);
        return;/*from  www . j  a  v  a  2  s. co  m*/
    }
    int dataLen = buf.readableBytes();
    final long ackedLength = nextPacketOffsetInBlock + dataLen;
    if (ackedLength == locatedBlock.getBlock().getNumBytes()) {
        // no new data, just return
        handler.completed(locatedBlock.getBlock().getNumBytes(), attachment);
        return;
    }
    Promise<Void> promise = eventLoop.newPromise();
    promise.addListener(new FutureListener<Void>() {

        @Override
        public void operationComplete(Future<Void> future) throws Exception {
            if (future.isSuccess()) {
                locatedBlock.getBlock().setNumBytes(ackedLength);
                handler.completed(ackedLength, attachment);
            } else {
                handler.failed(future.cause(), attachment);
            }
        }
    });
    Callback c = waitingAckQueue.peekLast();
    if (c != null && ackedLength == c.ackedLength) {
        // just append it to the tail of waiting ack queue,, do not issue new hflush request.
        waitingAckQueue.addLast(new Callback(promise, ackedLength, Collections.<Channel>emptyList()));
        return;
    }
    int chunkLen = summer.getBytesPerChecksum();
    int trailingPartialChunkLen = dataLen % chunkLen;
    int numChecks = dataLen / chunkLen + (trailingPartialChunkLen != 0 ? 1 : 0);
    int checksumLen = numChecks * summer.getChecksumSize();
    ByteBuf checksumBuf = alloc.directBuffer(checksumLen);
    summer.calculateChunkedSums(buf.nioBuffer(), checksumBuf.nioBuffer(0, checksumLen));
    checksumBuf.writerIndex(checksumLen);
    PacketHeader header = new PacketHeader(4 + checksumLen + dataLen, nextPacketOffsetInBlock, nextPacketSeqno,
            false, dataLen, syncBlock);
    int headerLen = header.getSerializedSize();
    ByteBuf headerBuf = alloc.buffer(headerLen);
    header.putInBuffer(headerBuf.nioBuffer(0, headerLen));
    headerBuf.writerIndex(headerLen);

    waitingAckQueue.addLast(new Callback(promise, ackedLength, datanodeList));
    for (Channel ch : datanodeList) {
        ch.write(headerBuf.duplicate().retain());
        ch.write(checksumBuf.duplicate().retain());
        ch.writeAndFlush(buf.duplicate().retain());
    }
    checksumBuf.release();
    headerBuf.release();
    ByteBuf newBuf = alloc.directBuffer().ensureWritable(trailingPartialChunkLen);
    if (trailingPartialChunkLen != 0) {
        buf.readerIndex(dataLen - trailingPartialChunkLen).readBytes(newBuf, trailingPartialChunkLen);
    }
    buf.release();
    this.buf = newBuf;
    nextPacketOffsetInBlock += dataLen - trailingPartialChunkLen;
    nextPacketSeqno++;
}

From source file:org.apache.hadoop.hbase.io.asyncfs.FanOutOneBlockAsyncDFSOutputHelper.java

License:Apache License

private static void initialize(Configuration conf, final Channel channel, final DatanodeInfo dnInfo,
        final Enum<?> storageType, final OpWriteBlockProto.Builder writeBlockProtoBuilder, final int timeoutMs,
        DFSClient client, Token<BlockTokenIdentifier> accessToken, final Promise<Channel> promise) {
    Promise<Void> saslPromise = channel.eventLoop().newPromise();
    trySaslNegotiate(conf, channel, dnInfo, timeoutMs, client, accessToken, saslPromise);
    saslPromise.addListener(new FutureListener<Void>() {

        @Override/*ww  w.  j  a va  2  s .c om*/
        public void operationComplete(Future<Void> future) throws Exception {
            if (future.isSuccess()) {
                // setup response processing pipeline first, then send request.
                processWriteBlockResponse(channel, dnInfo, promise, timeoutMs);
                requestWriteBlock(channel, storageType, writeBlockProtoBuilder);
            } else {
                promise.tryFailure(future.cause());
            }
        }
    });
}