Example usage for io.netty.channel ChannelFuture await

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

Introduction

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

Prototype

boolean await(long timeoutMillis) throws InterruptedException;

Source Link

Document

Waits for this future to be completed within the specified time limit.

Usage

From source file:org.waarp.commandexec.client.test.LocalExecClientTest.java

License:Open Source License

/**
 * Disconnect from the server/*from  w  ww  .jav  a  2  s .co  m*/
 */
private void disconnect() {
    // Close the connection. Make sure the close operation ends because
    // all I/O operations are asynchronous in Netty.
    try {
        ChannelFuture closeFuture = WaarpSslUtility.closingSslChannel(channel);
        closeFuture.await(30000);
    } catch (InterruptedException e) {
    }
}

From source file:org.waarp.common.crypto.ssl.WaarpSslUtility.java

License:Open Source License

/**
 * Waiting for the channel to be opened and ready (Client side) (blocking call)
 * //from w ww .  j  a  v  a  2  s .  c om
 * @param future
 *            a future on connect only
 * @return the channel if correctly associated, else return null
 */
public static Channel waitforChannelReady(ChannelFuture future) {
    // Wait until the connection attempt succeeds or fails.
    try {
        future.await(10000);
    } catch (InterruptedException e1) {
    }
    if (!future.isSuccess()) {
        logger.error("Channel not connected", future.cause());
        return null;
    }
    Channel channel = future.channel();
    if (waitForHandshake(channel)) {
        return channel;
    }
    return null;
}

From source file:org.waarp.ftp.core.config.FtpInternalConfiguration.java

License:Open Source License

/**
 * Try to add a Passive Channel listening to the specified local address
 * //ww  w.  j a  va  2 s  .c  o  m
 * @param address
 * @param ssl
 * @throws Reply425Exception
 *             in case the channel cannot be opened
 */
public void bindPassive(InetSocketAddress address, boolean ssl) throws Reply425Exception {
    configuration.bindLock();
    try {
        BindAddress bindAddress = hashBindPassiveDataConn.get(address);
        if (bindAddress == null) {
            logger.debug("Bind really to {}", address);
            Channel parentChannel = null;
            try {
                ChannelFuture future = null;
                if (ssl) {
                    future = passiveSslBootstrap.bind(address);
                } else {
                    future = passiveBootstrap.bind(address);
                }
                if (future.await(configuration.TIMEOUTCON)) {
                    parentChannel = future.sync().channel();
                } else {
                    logger.warn("Cannot open passive connection due to Timeout");
                    throw new Reply425Exception("Cannot open a Passive Connection due to Timeout");
                }
            } catch (ChannelException e) {
                logger.warn("Cannot open passive connection {}", e.getMessage());
                throw new Reply425Exception("Cannot open a Passive Connection");
            } catch (InterruptedException e) {
                logger.warn("Cannot open passive connection {}", e.getMessage());
                throw new Reply425Exception("Cannot open a Passive Connection");
            }
            bindAddress = new BindAddress(parentChannel);
            FtpChannelUtils.addDataChannel(parentChannel, configuration);
            hashBindPassiveDataConn.put(address, bindAddress);
        }
        bindAddress.nbBind++;
        logger.debug("Bind number to {} is {}", address, bindAddress.nbBind);
    } finally {
        configuration.bindUnlock();
    }
}

From source file:org.waarp.ftp.core.data.handler.DataNetworkHandler.java

License:Open Source License

/**
 * Write a simple message (like LIST) and wait for it
 * // www  .j  a  va  2s  .co m
 * @param message
 * @return True if the message is correctly written
 */
public boolean writeMessage(String message) {
    DataBlock dataBlock = new DataBlock();
    dataBlock.setEOF(true);
    ByteBuf buffer = Unpooled.wrappedBuffer(message.getBytes(WaarpStringUtils.UTF8));
    dataBlock.setBlock(buffer);
    ChannelFuture future;
    logger.debug("Will write: " + buffer.toString(WaarpStringUtils.UTF8));
    try {
        future = dataChannel.writeAndFlush(dataBlock);
        future.await(FtpConfiguration.DATATIMEOUTCON);
    } catch (InterruptedException e) {
        logger.debug("Interrupted", e);
        return false;
    }
    logger.debug("Write result: " + future.isSuccess(), future.cause());
    return future.isSuccess();
}

From source file:org.waarp.ftp.filesystembased.FilesystemBasedFtpFile.java

License:Open Source License

/**
 * Launch retrieve operation (internal method, should not be called directly)
 * //from  www.  ja  v  a 2 s.c  o  m
 */
public void trueRetrieve() {
    retrieveLock.lock();
    try {
        if (!isReady) {
            return;
        }
        // First check if ready to run from Control
        try {
            ((FtpSession) session).getDataConn().getFtpTransferControl().waitForDataNetworkHandlerReady();
        } catch (InterruptedException e) {
            // bad thing
            logger.warn("DataNetworkHandler was not ready", e);
            return;
        }
        Channel channel = null;
        try {
            channel = ((FtpSession) session).getDataConn().getCurrentDataChannel();
        } catch (FtpNoConnectionException e) {
            if (this.isInReading()) {
                logger.error("Should not be", e);
                ((FtpSession) session).getDataConn().getFtpTransferControl()
                        .setTransferAbortedFromInternal(true);
            }
            logger.debug("Possible call while channel was on going to be closed once transfer was done", e);
            closeFile();
            ((FtpSession) session).getDataConn().getFtpTransferControl().setPreEndOfTransfer();
            return;
        }
        DataBlock block = null;
        try {
            block = readDataBlock();
        } catch (FileEndOfTransferException e) {
            // Last block (in fact, previous block was the last one,
            // but it could be aligned with the block size so not
            // detected)
            closeFile();
            ((FtpSession) session).getDataConn().getFtpTransferControl().setPreEndOfTransfer();
            return;
        }
        if (block == null) {
            // Last block (in fact, previous block was the last one,
            // but it could be aligned with the block size so not
            // detected)
            closeFile();
            ((FtpSession) session).getDataConn().getFtpTransferControl().setPreEndOfTransfer();
            return;
        }
        // While not last block
        ChannelFuture future = null;
        while (block != null && !block.isEOF()) {
            logger.debug("Write " + block.getByteCount());
            future = channel.writeAndFlush(block);
            // Test if channel is writable in order to prevent OOM
            if (channel.isWritable()) {
                try {
                    block = readDataBlock();
                } catch (FileEndOfTransferException e) {
                    closeFile();
                    // Wait for last write
                    try {
                        future.await(FtpConfiguration.DATATIMEOUTCON);
                    } catch (InterruptedException e1) {
                        throw new FileTransferException("Interruption catched");
                    }
                    if (future.isSuccess()) {
                        ((FtpSession) session).getDataConn().getFtpTransferControl().setPreEndOfTransfer();
                    } else {
                        throw new FileTransferException("File transfer in error");
                    }
                    return;
                }
            } else {
                return;// Wait for the next InterestChanged
            }
            try {
                future.await(FtpConfiguration.DATATIMEOUTCON);
            } catch (InterruptedException e) {
                closeFile();
                throw new FileTransferException("Interruption catched");
            }
            if (!future.isSuccess()) {
                closeFile();
                throw new FileTransferException("File transfer in error");
            }
        }
        // Last block
        closeFile();
        if (block != null) {
            logger.debug("Write " + block.getByteCount());
            future = channel.writeAndFlush(block);
        }
        // Wait for last write
        if (future != null) {
            try {
                future.await(FtpConfiguration.DATATIMEOUTCON);
            } catch (InterruptedException e) {
                throw new FileTransferException("Interruption catched");
            }
            if (future.isSuccess()) {
                ((FtpSession) session).getDataConn().getFtpTransferControl().setPreEndOfTransfer();
            } else {
                throw new FileTransferException("Write is not successful");
            }
        }
    } catch (FileTransferException e) {
        // An error occurs!
        ((FtpSession) session).getDataConn().getFtpTransferControl().setTransferAbortedFromInternal(true);
    } catch (CommandAbstractException e) {
        logger.error("Should not be", e);
        ((FtpSession) session).getDataConn().getFtpTransferControl().setTransferAbortedFromInternal(true);
    } finally {
        retrieveLock.unlock();
    }
}

From source file:org.waarp.openr66.protocol.networkhandler.NetworkTransaction.java

License:Open Source License

/**
 * //w w  w.jav  a  2  s  .  com
 * @param socketServerAddress
 * @param isSSL
 * @return the NetworkChannelReference
 * @throws OpenR66ProtocolNetworkException
 * @throws OpenR66ProtocolRemoteShutdownException
 * @throws OpenR66ProtocolNoConnectionException
 */
private NetworkChannelReference createNewConnection(SocketAddress socketServerAddress, boolean isSSL)
        throws OpenR66ProtocolNetworkException, OpenR66ProtocolRemoteShutdownException,
        OpenR66ProtocolNoConnectionException {
    WaarpLock socketLock = getChannelLock(socketServerAddress);
    NetworkChannelReference networkChannelReference;
    socketLock.lock();
    try {
        try {
            networkChannelReference = getRemoteChannel(socketServerAddress);
        } catch (OpenR66ProtocolNoDataException e1) {
            networkChannelReference = null;
        }
        if (networkChannelReference != null) {
            networkChannelReference.use();
            logger.info("Already Connected: {}", networkChannelReference);
            return networkChannelReference;
        }
        logger.debug("NEW PHYSICAL CONNECTION REQUIRED");
        ChannelFuture channelFuture = null;
        for (int i = 0; i < Configuration.RETRYNB; i++) {
            if (R66ShutdownHook.isShutdownStarting()) {
                throw new OpenR66ProtocolNoConnectionException("Local system in shutdown");
            }
            try {
                if (isSSL) {
                    if (Configuration.configuration.getHOST_SSLID() != null) {
                        channelFuture = clientSslBootstrap.connect(socketServerAddress);
                    } else {
                        throw new OpenR66ProtocolNoConnectionException("No SSL support");
                    }
                } else {
                    channelFuture = clientBootstrap.connect(socketServerAddress);
                }
            } catch (ChannelPipelineException e) {
                throw new OpenR66ProtocolNoConnectionException(
                        "Cannot connect to remote server due to a channel exception");
            }
            try {
                channelFuture.await(Configuration.configuration.getTIMEOUTCON() / 3);
            } catch (InterruptedException e1) {
            }
            if (channelFuture.isSuccess()) {
                final Channel channel = channelFuture.channel();
                if (isSSL) {
                    if (!NetworkSslServerHandler.isSslConnectedChannel(channel)) {
                        logger.debug("KO CONNECT since SSL handshake is over");
                        channel.close();
                        throw new OpenR66ProtocolNoConnectionException(
                                "Cannot finish connect to remote server");
                    }
                }
                networkChannelGroup.add(channel);
                networkChannelReference = new NetworkChannelReference(channel, socketLock);
                addNCR(networkChannelReference);
                return networkChannelReference;
            } else {
                try {
                    Thread.sleep(Configuration.RETRYINMS);
                } catch (InterruptedException e) {
                }
                if (!channelFuture.isDone()) {
                    throw new OpenR66ProtocolNoConnectionException(
                            "Cannot connect to remote server due to interruption");
                }
                if (channelFuture.cause() instanceof ConnectException) {
                    logger.debug("KO CONNECT:" + channelFuture.cause().getMessage());
                    throw new OpenR66ProtocolNoConnectionException("Cannot connect to remote server",
                            channelFuture.cause());
                } else {
                    logger.debug("KO CONNECT but retry", channelFuture.cause());
                }
            }
        }
        throw new OpenR66ProtocolNetworkException("Cannot connect to remote server", channelFuture.cause());
    } finally {
        socketLock.unlock();
    }
}

From source file:org.waarp.openr66.protocol.utils.ChannelUtils.java

License:Open Source License

/**
 * Write an AbstractLocalPacket to the network Channel
 * /*ww  w  .ja v a2  s  . c o  m*/
 * @param localChannelReference
 * @param packet
 * @param wait
 * @return the ChannelFuture on write operation
 * @throws OpenR66ProtocolPacketException
 */
public static ChannelFuture writeAbstractLocalPacket(LocalChannelReference localChannelReference,
        AbstractLocalPacket packet, boolean wait) throws OpenR66ProtocolPacketException {
    final NetworkPacket networkPacket;
    try {
        networkPacket = new NetworkPacket(localChannelReference.getLocalId(),
                localChannelReference.getRemoteId(), packet, localChannelReference);
    } catch (OpenR66ProtocolPacketException e) {
        logger.error(Messages.getString("ChannelUtils.6") + packet.toString(), //$NON-NLS-1$
                e);
        throw e;
    }
    if (wait) {
        ChannelFuture future = localChannelReference.getNetworkChannel().writeAndFlush(networkPacket);
        localChannelReference.getNetworkChannelObject().use();
        try {
            future.await(Configuration.configuration.getTIMEOUTCON());
            return future;
        } catch (InterruptedException e) {
            return future;
        }
    } else {
        return localChannelReference.getNetworkChannel().writeAndFlush(networkPacket);
    }
}

From source file:org.waarp.openr66.proxy.network.NetworkTransaction.java

License:Open Source License

/**
 * /*from w  ww . ja  v a2  s  .  c  o m*/
 * @param socketServerAddress
 * @param isSSL
 * @return the channel
 * @throws OpenR66ProtocolNetworkException
 * @throws OpenR66ProtocolRemoteShutdownException
 * @throws OpenR66ProtocolNoConnectionException
 */
private Channel createNewConnection(SocketAddress socketServerAddress, boolean isSSL)
        throws OpenR66ProtocolNetworkException, OpenR66ProtocolRemoteShutdownException,
        OpenR66ProtocolNoConnectionException {
    ChannelFuture channelFuture = null;
    for (int i = 0; i < Configuration.RETRYNB; i++) {
        try {
            if (isSSL) {
                if (Configuration.configuration.getHOST_SSLID() != null) {
                    channelFuture = clientSslBootstrap.connect(socketServerAddress);
                } else {
                    throw new OpenR66ProtocolNoConnectionException("No SSL support");
                }
            } else {
                channelFuture = clientBootstrap.connect(socketServerAddress);
            }
        } catch (ChannelPipelineException e) {
            throw new OpenR66ProtocolNoConnectionException(
                    "Cannot connect to remote server due to a channel exception");
        }
        try {
            channelFuture.await(Configuration.configuration.getTIMEOUTCON() / 3);
        } catch (InterruptedException e1) {
        }
        if (channelFuture.isSuccess()) {
            final Channel channel = channelFuture.channel();
            if (isSSL) {
                if (!NetworkSslServerHandler.isSslConnectedChannel(channel)) {
                    logger.debug("KO CONNECT since SSL handshake is over");
                    channel.close();
                    throw new OpenR66ProtocolNoConnectionException("Cannot finish connect to remote server");
                }
            }
            networkChannelGroup.add(channel);
            return channel;
        } else {
            try {
                Thread.sleep(Configuration.WAITFORNETOP * 2);
            } catch (InterruptedException e) {
            }
            if (!channelFuture.isDone()) {
                throw new OpenR66ProtocolNoConnectionException(
                        "Cannot connect to remote server due to interruption");
            }
            if (channelFuture.cause() instanceof ConnectException) {
                logger.debug("KO CONNECT:" + channelFuture.cause().getMessage());
                throw new OpenR66ProtocolNoConnectionException("Cannot connect to remote server",
                        channelFuture.cause());
            } else {
                logger.debug("KO CONNECT but retry", channelFuture.cause());
            }
        }
    }
    throw new OpenR66ProtocolNetworkException("Cannot connect to remote server", channelFuture.cause());
}

From source file:pub.vrtech.monkey.transport.netty.NettyChannel.java

License:Apache License

/***
 * ?????//  w ww.j  a  v  a2  s  .  c  o  m
 * @param  message  ???
 * @param  sent   ????
 */
public void send(Object message, boolean sent) throws RemotingException {
    super.send(message, sent);

    boolean success = true;
    int timeout = 0;
    try {
        ChannelFuture future = channel.write(message);
        if (sent) {
            timeout = getUrl().getPositiveParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT);
            success = future.await(timeout);
        }
        Throwable cause = future.cause();
        if (cause != null) {
            throw cause;
        }
    } catch (Throwable e) {
        throw new RemotingException(this, "Failed to send message " + message + " to " + getRemoteAddress()
                + ", cause: " + e.getMessage(), e);
    }

    if (!success) {
        throw new RemotingException(this, "Failed to send message " + message + " to " + getRemoteAddress()
                + "in timeout(" + timeout + "ms) limit");
    }
}