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:com.github.mrstampy.kitchensync.netty.Bootstrapper.java

License:Open Source License

private GenericFutureListener<ChannelFuture> getMulticastBindListener(final InetSocketAddress multicast,
        final CountDownLatch latch) {
    return new GenericFutureListener<ChannelFuture>() {

        @Override/*from w w  w  .  java 2 s . c  o  m*/
        public void operationComplete(ChannelFuture future) throws Exception {
            try {
                if (future.isSuccess()) {
                    log.debug("Multicast channel creation successful for {}", multicast);
                } else {
                    Throwable cause = future.cause();
                    if (cause == null) {
                        log.error("Could not create multicast channel for {}", multicast);
                    } else {
                        log.error("Could not create multicast channel for {}", multicast, cause);
                    }
                }
            } finally {
                latch.countDown();
            }
        }
    };
}

From source file:com.github.mrstampy.kitchensync.netty.channel.AbstractKiSyMulticastChannel.java

License:Open Source License

private GenericFutureListener<ChannelFuture> getJoinGroupListener(final InetSocketAddress multicast,
        final CountDownLatch latch) {
    return new GenericFutureListener<ChannelFuture>() {

        @Override//from www. ja  va  2s .c om
        public void operationComplete(ChannelFuture future) throws Exception {
            try {
                if (future.isSuccess()) {
                    log.debug("Multicast channel joined group {}", multicast);
                } else {
                    Throwable cause = future.cause();
                    if (cause == null) {
                        log.error("Could not join multicast group for {}", multicast);
                    } else {
                        log.error("Could not join multicast group for {}", multicast, cause);
                    }
                }
            } finally {
                latch.countDown();
            }
        }
    };
}

From source file:com.github.mrstampy.kitchensync.netty.channel.AbstractKiSyMulticastChannel.java

License:Open Source License

private GenericFutureListener<ChannelFuture> getLeaveGroupListener(final InetSocketAddress multicast,
        final CountDownLatch latch) {
    return new GenericFutureListener<ChannelFuture>() {

        @Override//from  ww  w  .j  a v  a  2  s  . c o  m
        public void operationComplete(ChannelFuture future) throws Exception {
            try {
                if (future.isSuccess()) {
                    log.debug("Multicast channel left group {}", multicast);
                } else {
                    Throwable cause = future.cause();
                    if (cause == null) {
                        log.error("Could not leave multicast group for {}", multicast);
                    } else {
                        log.error("Could not leave multicast group for {}", multicast, cause);
                    }
                }
            } finally {
                latch.countDown();
            }
        }
    };
}

From source file:com.github.mrstampy.kitchensync.netty.channel.AbstractKiSyMulticastChannel.java

License:Open Source License

private GenericFutureListener<ChannelFuture> getBlockListener(final InetSocketAddress multicast,
        final CountDownLatch latch, final InetAddress sourceToBlock) {
    return new GenericFutureListener<ChannelFuture>() {

        @Override/*from  w w  w.  ja v  a  2 s.co m*/
        public void operationComplete(ChannelFuture future) throws Exception {
            try {
                if (future.isSuccess()) {
                    log.debug("Multicast channel {} now blocking {}", multicast, sourceToBlock);
                } else {
                    Throwable cause = future.cause();
                    if (cause == null) {
                        log.error("Could not block {} from {}", sourceToBlock, multicast);
                    } else {
                        log.error("Could not block {} from {}", sourceToBlock, multicast, cause);
                    }
                }
            } finally {
                latch.countDown();
            }
        }
    };
}

From source file:com.github.sinsinpub.pero.backend.ConnectBackendHandler.java

License:Apache License

@Override
public void channelRead0(final ChannelHandlerContext ctx, final SocksCmdRequest request) throws Exception {
    final Channel inboundChannel = ctx.channel();
    final Promise<Channel> outboundPromise = newOutboundPromise(ctx, request);
    final int maxProxies = AppProps.PROPS.getInteger("upstream.socks5.count", 1);
    final AtomicBoolean isFinalSuccess = new AtomicBoolean(false);
    final AtomicBoolean isRetryOccured = new AtomicBoolean(false);
    for (int i = 1; i <= maxProxies; i++) {
        final boolean isFirstOne = (i == 1);
        final boolean isFinalOne = (i == maxProxies);
        if (!isFirstOne) {
            isRetryOccured.set(true);//from www . j a  va2 s .c o m
        }
        try {
            final ProxyHandler upstreamProxyHandler = newUpstreamProxyHandler(i);
            final Bootstrap b = newConnectionBootstrap(inboundChannel, outboundPromise, upstreamProxyHandler);
            logger.info(String.format("Connecting backend %s:%s via %s", request.host(), request.port(),
                    upstreamProxyHandler != null ? upstreamProxyHandler.proxyAddress() : "direct"));
            ChannelFuture connFuture = b.connect(request.host(), request.port());
            connFuture.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (future.isSuccess()) {
                        // Connection established use handler provided results
                        if (upstreamProxyHandler == null) {
                            logger.info("Backend connected directly");
                        } else {
                            logger.info("Backend connected via: " + upstreamProxyHandler.proxyAddress());
                        }
                    } else {
                        // Close the connection if the connection attempt has failed.
                        if (isFinalOne) {
                            logger.error("Backend connection failed: " + future.cause(), future.cause());
                            ctx.channel().writeAndFlush(
                                    new SocksCmdResponse(SocksCmdStatus.FAILURE, request.addressType()));
                            NettyChannelUtils.closeOnFlush(ctx.channel());
                        } else {
                            logger.warn("Backend connection failed: {}", future.cause().toString());
                        }
                    }
                }
            });
            connFuture.await(getConnectTimeoutMillis(), TimeUnit.MILLISECONDS);
            if (connFuture.isSuccess()) {
                isFinalSuccess.set(true);
                break;
            }
        } catch (Exception e) {
            logger.error("Connecting exception {} caught:", e);
        }
    }
    if (isFinalSuccess.get() && isRetryOccured.get()) {
        logger.warn("Protected from Error-Neko: {} times", nekoKilled.incrementAndGet());
    }
}

From source file:com.github.sparkfy.network.client.TransportClient.java

License:Apache License

/**
 * Requests a single chunk from the remote side, from the pre-negotiated streamId.
 * <p/>/*from   w w w  . j  av a 2s. c o  m*/
 * Chunk indices go from 0 onwards. It is valid to request the same chunk multiple times, though
 * some streams may not support this.
 * <p/>
 * Multiple fetchChunk requests may be outstanding simultaneously, and the chunks are guaranteed
 * to be returned in the same order that they were requested, assuming only a single
 * TransportClient is used to fetch the chunks.
 *
 * @param streamId   Identifier that refers to a stream in the remote StreamManager. This should
 *                   be agreed upon by client and server beforehand.
 * @param chunkIndex 0-based index of the chunk to fetch
 * @param callback   Callback invoked upon successful receipt of chunk, or upon any failure.
 */
public void fetchChunk(long streamId, final int chunkIndex, final ChunkReceivedCallback callback) {
    final String serverAddr = NettyUtils.getRemoteAddress(channel);
    final long startTime = System.currentTimeMillis();
    logger.debug("Sending fetch chunk request {} to {}", chunkIndex, serverAddr);

    final StreamChunkId streamChunkId = new StreamChunkId(streamId, chunkIndex);
    handler.addFetchRequest(streamChunkId, callback);

    channel.writeAndFlush(new ChunkFetchRequest(streamChunkId)).addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                long timeTaken = System.currentTimeMillis() - startTime;
                logger.trace("Sending request {} to {} took {} ms", streamChunkId, serverAddr, timeTaken);
            } else {
                String errorMsg = String.format("Failed to send request %s to %s: %s", streamChunkId,
                        serverAddr, future.cause());
                logger.error(errorMsg, future.cause());
                handler.removeFetchRequest(streamChunkId);
                channel.close();
                try {
                    callback.onFailure(chunkIndex, new IOException(errorMsg, future.cause()));
                } catch (Exception e) {
                    logger.error("Uncaught exception in RPC response callback handler!", e);
                }
            }
        }
    });
}

From source file:com.github.sparkfy.network.client.TransportClient.java

License:Apache License

/**
 * Request to stream the data with the given stream ID from the remote end.
 *
 * @param streamId The stream to fetch./*from   ww  w  .j  a  v a 2s  .  c om*/
 * @param callback Object to call with the stream data.
 */
public void stream(final String streamId, final StreamCallback callback) {
    final String serverAddr = NettyUtils.getRemoteAddress(channel);
    final long startTime = System.currentTimeMillis();
    logger.debug("Sending stream request for {} to {}", streamId, serverAddr);

    // Need to synchronize here so that the callback is added to the queue and the RPC is
    // written to the socket atomically, so that callbacks are called in the right order
    // when responses arrive.
    synchronized (this) {
        handler.addStreamCallback(callback);
        channel.writeAndFlush(new StreamRequest(streamId)).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (future.isSuccess()) {
                    long timeTaken = System.currentTimeMillis() - startTime;
                    logger.trace("Sending request for {} to {} took {} ms", streamId, serverAddr, timeTaken);
                } else {
                    String errorMsg = String.format("Failed to send request for %s to %s: %s", streamId,
                            serverAddr, future.cause());
                    logger.error(errorMsg, future.cause());
                    channel.close();
                    try {
                        callback.onFailure(streamId, new IOException(errorMsg, future.cause()));
                    } catch (Exception e) {
                        logger.error("Uncaught exception in RPC response callback handler!", e);
                    }
                }
            }
        });
    }
}

From source file:com.github.sparkfy.network.client.TransportClient.java

License:Apache License

/**
 * Sends an opaque message to the RpcHandler on the server-side. The callback will be invoked
 * with the server's response or upon any failure.
 *
 * @param message The message to send.//  ww  w .  j  av  a2  s. c  o  m
 * @return The RPC's id.
 */
public ByteBuffer sendRpcSyncSafely(ByteBuffer message, long timeoutMs) {
    final String serverAddr = NettyUtils.getRemoteAddress(channel);
    final long startTime = System.currentTimeMillis();
    logger.trace("Sending RPC to {}", serverAddr);

    final long requestId = Math.abs(UUID.randomUUID().getLeastSignificantBits());

    final SettableFuture<ByteBuffer> result = SettableFuture.create();
    final RpcResponseCallback callback = new RpcResponseCallback() {
        @Override
        public void onSuccess(ByteBuffer response) {
            result.set(response);
        }

        @Override
        public void onFailure(Throwable e) {
            result.setException(e);
        }
    };

    handler.addRpcRequest(requestId, callback);

    try {
        synchronized (this) {

            channel.writeAndFlush(new RpcRequest(requestId, new NioManagedBuffer(message)))
                    .addListener(new ChannelFutureListener() {
                        @Override
                        public void operationComplete(ChannelFuture future) throws Exception {
                            if (future.isSuccess()) {
                                long timeTaken = System.currentTimeMillis() - startTime;
                                logger.trace("Sending request {} to {} took {} ms", requestId, serverAddr,
                                        timeTaken);
                            } else {
                                String errorMsg = String.format("Failed to send RPC %s to %s: %s", requestId,
                                        serverAddr, future.cause());
                                logger.error(errorMsg, future.cause());
                                handler.removeRpcRequest(requestId);
                                channel.close();
                                try {
                                    callback.onFailure(new IOException(errorMsg, future.cause()));
                                } catch (Exception e) {
                                    logger.error("Uncaught exception in RPC response callback handler!", e);
                                }
                            }
                        }
                    }).get(timeoutMs, TimeUnit.MILLISECONDS);
        }
        return result.get(timeoutMs - (System.currentTimeMillis() - startTime), TimeUnit.MILLISECONDS);
    } catch (ExecutionException e) {
        channel.close();
        throw Throwables.propagate(e.getCause());
    } catch (Exception e) {
        channel.close();
        throw Throwables.propagate(e);
    }

}

From source file:com.github.sparkfy.network.client.TransportClient.java

License:Apache License

/**
 * Sends an opaque message to the RpcHandler on the server-side. The callback will be invoked
 * with the server's response or upon any failure.
 *
 * @param message  The message to send./*from   w  w  w  . j  a v  a2s  .  c  o  m*/
 * @param callback Callback to handle the RPC's reply.
 * @return The RPC's id.
 */
public long sendRpc(ByteBuffer message, final RpcResponseCallback callback) {
    final String serverAddr = NettyUtils.getRemoteAddress(channel);
    final long startTime = System.currentTimeMillis();
    logger.trace("Sending RPC to {}", serverAddr);

    final long requestId = Math.abs(UUID.randomUUID().getLeastSignificantBits());
    handler.addRpcRequest(requestId, callback);

    channel.writeAndFlush(new RpcRequest(requestId, new NioManagedBuffer(message)))
            .addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (future.isSuccess()) {
                        long timeTaken = System.currentTimeMillis() - startTime;
                        logger.trace("Sending request {} to {} took {} ms", requestId, serverAddr, timeTaken);
                    } else {
                        String errorMsg = String.format("Failed to send RPC %s to %s: %s", requestId,
                                serverAddr, future.cause());
                        logger.error(errorMsg, future.cause());
                        handler.removeRpcRequest(requestId);
                        channel.close();
                        try {
                            callback.onFailure(new IOException(errorMsg, future.cause()));
                        } catch (Exception e) {
                            logger.error("Uncaught exception in RPC response callback handler!", e);
                        }
                    }
                }
            });

    return requestId;
}

From source file:com.github.sparkfy.network.client.TransportClientFactory.java

License:Apache License

/** Create a completely new {@link TransportClient} to the remote address. */
private TransportClient createClient(InetSocketAddress address) throws IOException {
    logger.debug("Creating new connection to " + address);

    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(workerGroup).channel(socketChannelClass)
            // Disable Nagle's Algorithm since we don't want packets to wait
            .option(ChannelOption.TCP_NODELAY, true).option(ChannelOption.SO_KEEPALIVE, true)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, conf.connectionTimeoutMs())
            .option(ChannelOption.ALLOCATOR, pooledAllocator);

    final AtomicReference<TransportClient> clientRef = new AtomicReference<TransportClient>();
    final AtomicReference<Channel> channelRef = new AtomicReference<Channel>();

    bootstrap.handler(new ChannelInitializer<SocketChannel>() {
        @Override/* w  ww. j  av  a 2 s .  c  om*/
        public void initChannel(SocketChannel ch) {
            TransportChannelHandler clientHandler = context.initializePipeline(ch);
            clientRef.set(clientHandler.getClient());
            channelRef.set(ch);
        }
    });

    // Connect to the remote server
    long preConnect = System.nanoTime();
    ChannelFuture cf = bootstrap.connect(address);
    if (!cf.awaitUninterruptibly(conf.connectionTimeoutMs())) {
        throw new IOException(
                String.format("Connecting to %s timed out (%s ms)", address, conf.connectionTimeoutMs()));
    } else if (cf.cause() != null) {
        throw new IOException(String.format("Failed to connect to %s", address), cf.cause());
    }

    TransportClient client = clientRef.get();
    Channel channel = channelRef.get();
    assert client != null : "Channel future completed successfully with null client";

    // Execute any client bootstraps synchronously before marking the Client as successful.
    long preBootstrap = System.nanoTime();
    logger.debug("Connection to {} successful, running bootstraps...", address);
    try {
        for (TransportClientBootstrap clientBootstrap : clientBootstraps) {
            clientBootstrap.doBootstrap(client, channel);
        }
    } catch (Exception e) { // catch non-RuntimeExceptions too as bootstrap may be written in Scala
        long bootstrapTimeMs = (System.nanoTime() - preBootstrap) / 1000000;
        logger.error("Exception while bootstrapping client after " + bootstrapTimeMs + " ms", e);
        client.close();
        throw Throwables.propagate(e);
    }
    long postBootstrap = System.nanoTime();

    logger.debug("Successfully created connection to {} after {} ms ({} ms spent in bootstraps)", address,
            (postBootstrap - preConnect) / 1000000, (postBootstrap - preBootstrap) / 1000000);

    return client;
}