Example usage for io.netty.channel ChannelFuture isSuccess

List of usage examples for io.netty.channel ChannelFuture isSuccess

Introduction

In this page you can find the example usage for io.netty.channel ChannelFuture isSuccess.

Prototype

boolean isSuccess();

Source Link

Document

Returns true if and only if the I/O operation was completed successfully.

Usage

From source file:org.apache.camel.component.netty4.handlers.ServerResponseFutureListener.java

License:Apache License

@Override
public void operationComplete(ChannelFuture future) throws Exception {
    // if it was not a success then thrown an exception
    if (!future.isSuccess()) {
        Exception e = new CamelExchangeException("Cannot write response to " + remoteAddress, exchange,
                future.cause());//from   ww w  . j  av a2s. c o  m
        consumer.getExceptionHandler().handleException(e);
    }

    // should channel be closed after complete?
    Boolean close;
    if (exchange.hasOut()) {
        close = exchange.getOut().getHeader(NettyConstants.NETTY_CLOSE_CHANNEL_WHEN_COMPLETE, Boolean.class);
    } else {
        close = exchange.getIn().getHeader(NettyConstants.NETTY_CLOSE_CHANNEL_WHEN_COMPLETE, Boolean.class);
    }

    // should we disconnect, the header can override the configuration
    boolean disconnect = consumer.getConfiguration().isDisconnect();
    if (close != null) {
        disconnect = close;
    }
    if (disconnect) {
        if (LOG.isTraceEnabled()) {
            LOG.trace("Closing channel when complete at address: {}", remoteAddress);
        }
        NettyHelper.close(future.channel());
    }
}

From source file:org.apache.camel.component.netty4.NettyProducer.java

License:Apache License

public boolean process(final Exchange exchange, AsyncCallback callback) {
    if (!isRunAllowed()) {
        if (exchange.getException() == null) {
            exchange.setException(new RejectedExecutionException());
        }/* www  .  j  a  va  2 s.  c om*/
        callback.done(true);
        return true;
    }

    Object body;
    try {
        body = getRequestBody(exchange);
        if (body == null) {
            noReplyLogger.log("No payload to send for exchange: " + exchange);
            callback.done(true);
            return true;
        }
    } catch (Exception e) {
        exchange.setException(e);
        callback.done(true);
        return true;
    }

    // set the exchange encoding property
    if (getConfiguration().getCharsetName() != null) {
        exchange.setProperty(Exchange.CHARSET_NAME,
                IOHelper.normalizeCharset(getConfiguration().getCharsetName()));
    }

    if (LOG.isTraceEnabled()) {
        LOG.trace("Pool[active={}, idle={}]", pool.getNumActive(), pool.getNumIdle());
    }

    // get a channel from the pool
    Channel existing;
    try {
        existing = pool.borrowObject();
        if (existing != null) {
            LOG.trace("Got channel from pool {}", existing);
        }
    } catch (Exception e) {
        exchange.setException(e);
        callback.done(true);
        return true;
    }

    // we must have a channel
    if (existing == null) {
        exchange.setException(new CamelExchangeException("Cannot get channel from pool", exchange));
        callback.done(true);
        return true;
    }

    // need to declare as final
    final Channel channel = existing;
    final AsyncCallback producerCallback = new NettyProducerCallback(channel, callback);

    // setup state as attachment on the channel, so we can access the state later when needed
    putState(channel, new NettyCamelState(producerCallback, exchange));
    // here we need to setup the remote address information here
    InetSocketAddress remoteAddress = null;
    if (!isTcp()) {
        remoteAddress = new InetSocketAddress(configuration.getHost(), configuration.getPort());
    }

    // write body
    NettyHelper.writeBodyAsync(LOG, channel, remoteAddress, body, exchange, new ChannelFutureListener() {
        public void operationComplete(ChannelFuture channelFuture) throws Exception {
            LOG.trace("Operation complete {}", channelFuture);
            if (!channelFuture.isSuccess()) {
                // no success the set the caused exception and signal callback and break
                exchange.setException(channelFuture.cause());
                producerCallback.done(false);
                return;
            }

            // if we do not expect any reply then signal callback to continue routing
            if (!configuration.isSync()) {
                try {
                    // should channel be closed after complete?
                    Boolean close;
                    if (ExchangeHelper.isOutCapable(exchange)) {
                        close = exchange.getOut().getHeader(NettyConstants.NETTY_CLOSE_CHANNEL_WHEN_COMPLETE,
                                Boolean.class);
                    } else {
                        close = exchange.getIn().getHeader(NettyConstants.NETTY_CLOSE_CHANNEL_WHEN_COMPLETE,
                                Boolean.class);
                    }

                    // should we disconnect, the header can override the configuration
                    boolean disconnect = getConfiguration().isDisconnect();
                    if (close != null) {
                        disconnect = close;
                    }
                    if (disconnect) {
                        if (LOG.isTraceEnabled()) {
                            LOG.trace("Closing channel when complete at address: {}",
                                    getEndpoint().getConfiguration().getAddress());
                        }
                        NettyHelper.close(channel);
                    }
                } finally {
                    // signal callback to continue routing
                    producerCallback.done(false);
                }
            }
        }
    });

    // continue routing asynchronously
    return false;
}

From source file:org.apache.camel.component.netty4.NettyProducer.java

License:Apache License

protected Channel openChannel(ChannelFuture channelFuture) throws Exception {
    // blocking for channel to be done
    if (LOG.isTraceEnabled()) {
        LOG.trace("Waiting for operation to complete {} for {} millis", channelFuture,
                configuration.getConnectTimeout());
    }//from w w  w . ja v a  2s .c o  m
    // here we need to wait it in other thread
    final CountDownLatch channelLatch = new CountDownLatch(1);
    channelFuture.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture cf) throws Exception {
            channelLatch.countDown();
        }
    });

    try {
        channelLatch.await(configuration.getConnectTimeout(), TimeUnit.MILLISECONDS);
    } catch (InterruptedException ex) {
        throw new CamelException(
                "Interrupted while waiting for " + "connection to " + configuration.getAddress());
    }

    if (!channelFuture.isDone() || !channelFuture.isSuccess()) {
        ConnectException cause = new ConnectException("Cannot connect to " + configuration.getAddress());
        if (channelFuture.cause() != null) {
            cause.initCause(channelFuture.cause());
        }
        throw cause;
    }
    Channel answer = channelFuture.channel();
    // to keep track of all channels in use
    allChannels.add(answer);

    if (LOG.isDebugEnabled()) {
        LOG.debug("Creating connector to address: {}", configuration.getAddress());
    }
    return answer;
}

From source file:org.apache.camel.component.netty4.SingleTCPNettyServerBootstrapFactory.java

License:Apache License

@Override
protected void doResume() throws Exception {
    if (channel != null) {
        LOG.debug("ServerBootstrap binding to {}:{}", configuration.getHost(), configuration.getPort());
        ChannelFuture future = channel
                .bind(new InetSocketAddress(configuration.getHost(), configuration.getPort()));
        future.awaitUninterruptibly();//from  www.  jav a2 s. c o  m
        if (!future.isSuccess()) {
            // if we cannot bind, the re-create channel
            allChannels.remove(channel);
            future = serverBootstrap
                    .bind(new InetSocketAddress(configuration.getHost(), configuration.getPort()));
            future.awaitUninterruptibly();
            channel = future.channel();
            allChannels.add(channel);
        }
    }
}

From source file:org.apache.cassandra.transport.SimpleClient.java

License:Apache License

protected void establishConnection() throws IOException {
    // Configure the client.
    bootstrap = new Bootstrap().group(new NioEventLoopGroup())
            .channel(io.netty.channel.socket.nio.NioSocketChannel.class)
            .option(ChannelOption.TCP_NODELAY, true);

    // Configure the pipeline factory.
    if (encryptionOptions.enabled) {
        bootstrap.handler(new SecureInitializer());
    } else {/*w  w w  .java2 s .c  om*/
        bootstrap.handler(new Initializer());
    }
    ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port));

    // Wait until the connection attempt succeeds or fails.
    channel = future.awaitUninterruptibly().channel();
    if (!future.isSuccess()) {
        bootstrap.group().shutdownGracefully();
        throw new IOException("Connection Error", future.cause());
    }
}

From source file:org.apache.dubbo.remoting.transport.netty4.NettyClient.java

License:Apache License

@Override
protected void doConnect() throws Throwable {
    long start = System.currentTimeMillis();
    ChannelFuture future = bootstrap.connect(getConnectAddress());
    try {//from w  w  w. j  a  v a  2 s  .c o m
        boolean ret = future.awaitUninterruptibly(getConnectTimeout(), MILLISECONDS);

        if (ret && future.isSuccess()) {
            Channel newChannel = future.channel();
            try {
                // Close old channel
                // copy reference
                Channel oldChannel = NettyClient.this.channel;
                if (oldChannel != null) {
                    try {
                        if (logger.isInfoEnabled()) {
                            logger.info("Close old netty channel " + oldChannel
                                    + " on create new netty channel " + newChannel);
                        }
                        oldChannel.close();
                    } finally {
                        NettyChannel.removeChannelIfDisconnected(oldChannel);
                    }
                }
            } finally {
                if (NettyClient.this.isClosed()) {
                    try {
                        if (logger.isInfoEnabled()) {
                            logger.info(
                                    "Close new netty channel " + newChannel + ", because the client closed.");
                        }
                        newChannel.close();
                    } finally {
                        NettyClient.this.channel = null;
                        NettyChannel.removeChannelIfDisconnected(newChannel);
                    }
                } else {
                    NettyClient.this.channel = newChannel;
                }
            }
        } else if (future.cause() != null) {
            throw new RemotingException(this, "client(url: " + getUrl() + ") failed to connect to server "
                    + getRemoteAddress() + ", error message is:" + future.cause().getMessage(), future.cause());
        } else {
            throw new RemotingException(this,
                    "client(url: " + getUrl() + ") failed to connect to server " + getRemoteAddress()
                            + " client-side timeout " + getConnectTimeout() + "ms (elapsed: "
                            + (System.currentTimeMillis() - start) + "ms) from netty client "
                            + NetUtils.getLocalHost() + " using dubbo version " + Version.getVersion());
        }
    } finally {
        // just add new valid channel to NettyChannel's cache
        if (!isConnected()) {
            //future.cancel(true);
        }
    }
}

From source file:org.apache.flink.runtime.io.network.netty.PartitionRequestClient.java

License:Apache License

/**
 * Requests a remote intermediate result partition queue.
 * <p>/*from   w ww  .ja  v a2 s  .  c om*/
 * The request goes to the remote producer, for which this partition
 * request client instance has been created.
 */
public ChannelFuture requestSubpartition(final ResultPartitionID partitionId, final int subpartitionIndex,
        final RemoteInputChannel inputChannel, int delayMs) throws IOException {

    checkNotClosed();

    LOG.debug("Requesting subpartition {} of partition {} with {} ms delay.", subpartitionIndex, partitionId,
            delayMs);

    partitionRequestHandler.addInputChannel(inputChannel);

    final PartitionRequest request = new PartitionRequest(partitionId, subpartitionIndex,
            inputChannel.getInputChannelId());

    final ChannelFutureListener listener = new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (!future.isSuccess()) {
                partitionRequestHandler.removeInputChannel(inputChannel);
                inputChannel.onError(new LocalTransportException("Sending the partition request failed.",
                        future.channel().localAddress(), future.cause()));
            }
        }
    };

    if (delayMs == 0) {
        ChannelFuture f = tcpChannel.writeAndFlush(request);
        f.addListener(listener);
        return f;
    } else {
        final ChannelFuture[] f = new ChannelFuture[1];
        tcpChannel.eventLoop().schedule(new Runnable() {
            @Override
            public void run() {
                f[0] = tcpChannel.writeAndFlush(request);
                f[0].addListener(listener);
            }
        }, delayMs, TimeUnit.MILLISECONDS);

        return f[0];
    }
}

From source file:org.apache.flink.runtime.io.network.netty.PartitionRequestClient.java

License:Apache License

/**
 * Sends a task event backwards to an intermediate result partition producer.
 * <p>/*from   w  w  w . j a  v  a  2  s . c  om*/
 * Backwards task events flow between readers and writers and therefore
 * will only work when both are running at the same time, which is only
 * guaranteed to be the case when both the respective producer and
 * consumer task run pipelined.
 */
public void sendTaskEvent(ResultPartitionID partitionId, TaskEvent event, final RemoteInputChannel inputChannel)
        throws IOException {
    checkNotClosed();

    tcpChannel.writeAndFlush(new TaskEventRequest(event, partitionId, inputChannel.getInputChannelId()))
            .addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (!future.isSuccess()) {
                        inputChannel.onError(new LocalTransportException("Sending the task event failed.",
                                future.channel().localAddress(), future.cause()));
                    }
                }
            });
}

From source file:org.apache.giraph.comm.netty.NettyClient.java

License:Apache License

/**
 * Connect to a collection of tasks servers
 *
 * @param tasks Tasks to connect to (if haven't already connected)
 *///  www . jav a2 s. c  om
public void connectAllAddresses(Collection<? extends TaskInfo> tasks) {
    List<ChannelFutureAddress> waitingConnectionList = Lists
            .newArrayListWithCapacity(tasks.size() * channelsPerServer);
    for (TaskInfo taskInfo : tasks) {
        context.progress();
        InetSocketAddress address = taskIdAddressMap.get(taskInfo.getTaskId());
        if (address == null || !address.getHostName().equals(taskInfo.getHostname())
                || address.getPort() != taskInfo.getPort()) {
            address = resolveAddress(maxResolveAddressAttempts, taskInfo.getInetSocketAddress());
            taskIdAddressMap.put(taskInfo.getTaskId(), address);
        }
        if (address == null || address.getHostName() == null || address.getHostName().isEmpty()) {
            throw new IllegalStateException("connectAllAddresses: Null address " + "in addresses " + tasks);
        }
        if (address.isUnresolved()) {
            throw new IllegalStateException("connectAllAddresses: Unresolved " + "address " + address);
        }

        if (addressChannelMap.containsKey(address)) {
            continue;
        }

        // Start connecting to the remote server up to n time
        for (int i = 0; i < channelsPerServer; ++i) {
            ChannelFuture connectionFuture = bootstrap.connect(address);

            waitingConnectionList
                    .add(new ChannelFutureAddress(connectionFuture, address, taskInfo.getTaskId()));
        }
    }

    // Wait for all the connections to succeed up to n tries
    int failures = 0;
    int connected = 0;
    while (failures < maxConnectionFailures) {
        List<ChannelFutureAddress> nextCheckFutures = Lists.newArrayList();
        for (ChannelFutureAddress waitingConnection : waitingConnectionList) {
            context.progress();
            ChannelFuture future = waitingConnection.future;
            ProgressableUtils.awaitChannelFuture(future, context);
            if (!future.isSuccess()) {
                LOG.warn("connectAllAddresses: Future failed " + "to connect with " + waitingConnection.address
                        + " with " + failures + " failures because of " + future.cause());

                ChannelFuture connectionFuture = bootstrap.connect(waitingConnection.address);
                nextCheckFutures.add(new ChannelFutureAddress(connectionFuture, waitingConnection.address,
                        waitingConnection.taskId));
                ++failures;
            } else {
                Channel channel = future.channel();
                if (LOG.isDebugEnabled()) {
                    LOG.debug("connectAllAddresses: Connected to " + channel.remoteAddress() + ", open = "
                            + channel.isOpen());
                }

                if (channel.remoteAddress() == null) {
                    throw new IllegalStateException("connectAllAddresses: Null remote address!");
                }

                ChannelRotater rotater = addressChannelMap.get(waitingConnection.address);
                if (rotater == null) {
                    ChannelRotater newRotater = new ChannelRotater(waitingConnection.taskId);
                    rotater = addressChannelMap.putIfAbsent(waitingConnection.address, newRotater);
                    if (rotater == null) {
                        rotater = newRotater;
                    }
                }
                rotater.addChannel(future.channel());
                ++connected;
            }
        }
        LOG.info("connectAllAddresses: Successfully added "
                + (waitingConnectionList.size() - nextCheckFutures.size()) + " connections, (" + connected
                + " total connected) " + nextCheckFutures.size() + " failed, " + failures + " failures total.");
        if (nextCheckFutures.isEmpty()) {
            break;
        }
        waitingConnectionList = nextCheckFutures;
    }
    if (failures >= maxConnectionFailures) {
        throw new IllegalStateException("connectAllAddresses: Too many failures (" + failures + ").");
    }
}

From source file:org.apache.giraph.comm.netty.NettyClient.java

License:Apache License

/**
 * Get the next available channel, reconnecting if necessary
 *
 * @param remoteServer Remote server to get a channel for
 * @return Available channel for this remote server
 *//*  ww  w . j  a va 2s .  c  o  m*/
private Channel getNextChannel(InetSocketAddress remoteServer) {
    Channel channel = addressChannelMap.get(remoteServer).nextChannel();
    if (channel == null) {
        throw new IllegalStateException("getNextChannel: No channel exists for " + remoteServer);
    }

    // Return this channel if it is connected
    if (channel.isActive()) {
        return channel;
    }

    // Get rid of the failed channel
    if (addressChannelMap.get(remoteServer).removeChannel(channel)) {
        LOG.warn("getNextChannel: Unlikely event that the channel " + channel + " was already removed!");
    }
    if (LOG.isInfoEnabled()) {
        LOG.info("getNextChannel: Fixing disconnected channel to " + remoteServer + ", open = "
                + channel.isOpen() + ", " + "bound = " + channel.isRegistered());
    }
    int reconnectFailures = 0;
    while (reconnectFailures < maxConnectionFailures) {
        ChannelFuture connectionFuture = bootstrap.connect(remoteServer);
        ProgressableUtils.awaitChannelFuture(connectionFuture, context);
        if (connectionFuture.isSuccess()) {
            if (LOG.isInfoEnabled()) {
                LOG.info("getNextChannel: Connected to " + remoteServer + "!");
            }
            addressChannelMap.get(remoteServer).addChannel(connectionFuture.channel());
            return connectionFuture.channel();
        }
        ++reconnectFailures;
        LOG.warn(
                "getNextChannel: Failed to reconnect to " + remoteServer + " on attempt " + reconnectFailures
                        + " out of " + maxConnectionFailures + " max attempts, sleeping for 5 secs",
                connectionFuture.cause());
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            LOG.warn("getNextChannel: Unexpected interrupted exception", e);
        }
    }
    throw new IllegalStateException("getNextChannel: Failed to connect " + "to " + remoteServer + " in "
            + reconnectFailures + " connect attempts");
}