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:org.waarp.ftp.core.data.FtpTransferControl.java

License:Open Source License

/**
 * Wait for the client to be connected (Passive) or Wait for the server to be connected to the
 * client (Active)//from   w ww .  ja v a  2 s. c om
 * 
 * @return True if the connection is OK
 * @throws Reply425Exception
 */
public synchronized boolean openDataConnection() throws Reply425Exception {
    // Prepare this Data channel to be closed ;-)
    // In fact, prepare the future close op which should occur since it is
    // now opened
    FtpDataAsyncConn dataAsyncConn = session.getDataConn();
    if (!dataAsyncConn.isStreamFile()) {
        // FIXME isActive or isDNHReady ?
        if (dataAsyncConn.isActive()) {
            // Already connected
            logger.debug("Connection already open");
            session.setReplyCode(ReplyCode.REPLY_125_DATA_CONNECTION_ALREADY_OPEN,
                    dataAsyncConn.getType().name() + " mode data connection already open");
            return true;
        }
    } else {
        // Stream, Data Connection should not be opened
        if (dataAsyncConn.isActive()) {
            logger.error("Connection already open but should not since in Stream mode");
            setTransferAbortedFromInternal(false);
            throw new Reply425Exception("Connection already open but should not since in Stream mode");
        }
    }
    // Need to open connection
    session.setReplyCode(ReplyCode.REPLY_150_FILE_STATUS_OKAY,
            "Opening " + dataAsyncConn.getType().name() + " mode data connection");
    if (dataAsyncConn.isPassiveMode()) {
        if (!dataAsyncConn.isBind()) {
            // No passive connection prepared
            throw new Reply425Exception("No passive data connection prepared");
        }
        // Wait for the connection to be done by the client
        logger.debug("Passive mode standby");
        try {
            dataChannel = waitForOpenedDataChannel();
            dataAsyncConn.setNewOpenedDataChannel(dataChannel);
        } catch (InterruptedException e) {
            logger.warn("Connection abort in passive mode", e);
            // Cannot open connection
            throw new Reply425Exception("Cannot open passive data connection");
        }
        logger.debug("Passive mode connected");
    } else {
        // Wait for the server to be connected to the client
        InetAddress inetAddress = dataAsyncConn.getLocalAddress().getAddress();
        InetSocketAddress inetSocketAddress = dataAsyncConn.getRemoteAddress();
        if (session.getConfiguration().getFtpInternalConfiguration().hasFtpSession(inetAddress,
                inetSocketAddress)) {
            throw new Reply425Exception(
                    "Cannot open active data connection since remote address is already in use: "
                            + inetSocketAddress);
        }
        logger.debug("Active mode standby");
        Bootstrap bootstrap = session.getConfiguration().getFtpInternalConfiguration()
                .getActiveBootstrap(session.isDataSsl());
        session.getConfiguration().setNewFtpSession(inetAddress, inetSocketAddress, session);
        // Set the session for the future dataChannel
        String mylog = session.toString();
        logger.debug("DataConn for: " + session.getCurrentCommand().getCommand() + " to "
                + inetSocketAddress.toString());
        ChannelFuture future = bootstrap.connect(inetSocketAddress, dataAsyncConn.getLocalAddress());
        try {
            future.await();
        } catch (InterruptedException e1) {
        }
        if (!future.isSuccess()) {
            logger.warn("Connection abort in active mode from future while session: " + session.toString()
                    + "\nTrying connect to: " + inetSocketAddress.toString() + " From: "
                    + dataAsyncConn.getLocalAddress() + "\nWas: " + mylog, future.cause());
            // Cannot open connection
            session.getConfiguration().delFtpSession(inetAddress, inetSocketAddress);
            throw new Reply425Exception("Cannot open active data connection");
        }
        try {
            dataChannel = waitForOpenedDataChannel();
            dataAsyncConn.setNewOpenedDataChannel(dataChannel);
        } catch (InterruptedException e) {
            logger.warn("Connection abort in active mode", e);
            // Cannot open connection
            session.getConfiguration().delFtpSession(inetAddress, inetSocketAddress);
            throw new Reply425Exception("Cannot open active data connection");
        }
        // logger.debug("Active mode connected");
    }
    if (dataChannel == null) {
        // Cannot have a new Data connection since shutdown
        if (!dataAsyncConn.isPassiveMode()) {
            session.getConfiguration().getFtpInternalConfiguration().delFtpSession(
                    dataAsyncConn.getLocalAddress().getAddress(), dataAsyncConn.getRemoteAddress());
        }
        throw new Reply425Exception("Cannot open data connection, shuting down");
    }
    return true;
}

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
 * /*ww w  . j a v  a  2s  . com*/
 * @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.gateway.kernel.exec.LocalExecClient.java

License:Open Source License

/**
 * Connect to the Server/*w  w  w.  ja v a2 s  .  c o m*/
 */
public boolean connect() {
    // Start the connection attempt.
    ChannelFuture future = bootstrapLocalExec.connect(getAddress());

    // Wait until the connection attempt succeeds or fails.
    try {
        channel = future.await().sync().channel();
    } catch (InterruptedException e) {
    }
    if (!future.isSuccess()) {
        logger.error("Client Not Connected", future.cause());
        return false;
    }
    return true;
}

From source file:org.waarp.openr66.context.task.localexec.LocalExecClient.java

License:Open Source License

/**
 * Connect to the Server/*from www.  j av a  2 s  .  c o  m*/
 */
public boolean connect() {
    // Start the connection attempt.
    ChannelFuture future = bootstrapLocalExec.connect(address);

    // Wait until the connection attempt succeeds or fails.
    try {
        channel = future.await().sync().channel();
    } catch (InterruptedException e) {
    }
    if (!future.isSuccess()) {
        logger.error("Client Not Connected", future.cause());
        return false;
    }
    return true;
}

From source file:org.waarp.openr66.protocol.configuration.Configuration.java

License:Open Source License

public void r66Startup() throws WaarpDatabaseNoConnectionException, WaarpDatabaseSqlException, ServerException {
    logger.info(Messages.getString("Configuration.Start") + getSERVER_PORT() + ":" + isUseNOSSL() + ":" //$NON-NLS-1$
            + getHOST_ID() + " " + getSERVER_SSLPORT() + ":" + isUseSSL() + ":" + getHOST_SSLID());
    // add into configuration
    this.getConstraintLimitHandler().setServer(true);
    // Global Server
    serverChannelGroup = new DefaultChannelGroup("OpenR66", subTaskGroup.next());
    if (isUseNOSSL()) {
        serverBootstrap = new ServerBootstrap();
        WaarpNettyUtil.setServerBootstrap(serverBootstrap, bossGroup, workerGroup, (int) getTIMEOUTCON());
        networkServerInitializer = new NetworkServerInitializer(true);
        serverBootstrap.childHandler(networkServerInitializer);
        ChannelFuture future = serverBootstrap.bind(new InetSocketAddress(getSERVER_PORT()))
                .awaitUninterruptibly();
        if (future.isSuccess()) {
            bindNoSSL = future.channel();
            serverChannelGroup.add(bindNoSSL);
        } else {//from  w w  w . ja  v  a 2 s.  c  o  m
            throw new ServerException(Messages.getString("Configuration.R66NotBound"), future.cause());
        }
    } else {
        networkServerInitializer = null;
        logger.warn(Messages.getString("Configuration.NOSSLDeactivated")); //$NON-NLS-1$
    }

    if (isUseSSL() && getHOST_SSLID() != null) {
        serverSslBootstrap = new ServerBootstrap();
        WaarpNettyUtil.setServerBootstrap(serverSslBootstrap, bossGroup, workerGroup, (int) getTIMEOUTCON());
        networkSslServerInitializer = new NetworkSslServerInitializer(false);
        serverSslBootstrap.childHandler(networkSslServerInitializer);
        ChannelFuture future = serverSslBootstrap.bind(new InetSocketAddress(getSERVER_SSLPORT()))
                .awaitUninterruptibly();
        if (future.isSuccess()) {
            bindSSL = future.channel();
            serverChannelGroup.add(bindSSL);
        } else {
            throw new ServerException(Messages.getString("Configuration.R66SSLNotBound"), future.cause());
        }
    } else {
        networkSslServerInitializer = null;
        logger.warn(Messages.getString("Configuration.SSLMODEDeactivated")); //$NON-NLS-1$
    }

    // Factory for TrafficShapingHandler
    globalTrafficShapingHandler = new GlobalTrafficHandler(subTaskGroup, getServerGlobalWriteLimit(),
            getServerGlobalReadLimit(), getServerChannelWriteLimit(), getServerChannelReadLimit(),
            getDelayLimit());
    this.getConstraintLimitHandler().setHandler(globalTrafficShapingHandler);

    // Now start the InternalRunner
    internalRunner = new InternalRunner();

    if (getThriftport() > 0) {
        setThriftService(new R66ThriftServerService(new WaarpFuture(true), getThriftport()));
        execOtherWorker.execute(getThriftService());
        getThriftService().awaitInitialization();
    } else {
        setThriftService(null);
    }
}

From source file:org.waarp.openr66.protocol.localhandler.LocalTransaction.java

License:Open Source License

/**
 * Create a new Client// w w w .j av  a 2 s .c  om
 * 
 * @param networkChannelReference
 * @param remoteId
 *            might be set to ChannelUtils.NOCHANNEL (real creation)
 * @param futureRequest
 *            might be null (from NetworkChannel Startup)
 * @return the LocalChannelReference
 * @throws OpenR66ProtocolSystemException
 * @throws OpenR66ProtocolRemoteShutdownException
 * @throws OpenR66ProtocolNoConnectionException
 */
public LocalChannelReference createNewClient(NetworkChannelReference networkChannelReference, Integer remoteId,
        R66Future futureRequest) throws OpenR66ProtocolSystemException, OpenR66ProtocolRemoteShutdownException,
        OpenR66ProtocolNoConnectionException {
    ChannelFuture channelFuture = null;
    logger.debug("Status LocalChannelServer: {} {}", serverChannel.getClass().getName(),
            serverChannel.config().getConnectTimeoutMillis() + " " + serverChannel.isOpen());
    for (int i = 0; i < Configuration.RETRYNB; i++) {
        if (R66ShutdownHook.isShutdownStarting()) {
            // Do not try since already locally in shutdown
            throw new OpenR66ProtocolNoConnectionException("Cannot connect to local handler: "
                    + socketLocalServerAddress + " " + serverChannel.isOpen() + " " + serverChannel
                    + " since the local server is in shutdown.");
        }
        channelFuture = clientBootstrap.connect(socketLocalServerAddress);
        try {
            channelFuture.await();
            //channelFuture.await(Configuration.configuration.TIMEOUTCON/3);
        } catch (InterruptedException e1) {
            logger.error("LocalChannelServer Interrupted: " + serverChannel.getClass().getName() + " "
                    + serverChannel.config().getConnectTimeoutMillis() + " " + serverChannel.isOpen());
            throw new OpenR66ProtocolSystemException("Interruption - Cannot connect to local handler: "
                    + socketLocalServerAddress + " " + serverChannel.isOpen() + " " + serverChannel, e1);
        }
        if (channelFuture.isSuccess()) {
            final LocalChannel channel = (LocalChannel) channelFuture.channel();
            localChannelGroup.add(channel);
            logger.debug(
                    "Will start localChannelReference and eventually generate a new Db Connection if not-thread-safe");
            final LocalChannelReference localChannelReference = new LocalChannelReference(channel,
                    networkChannelReference, remoteId, futureRequest);
            localChannelHashMap.put(channel.id().hashCode(), localChannelReference);
            logger.debug("Db connection done and Create LocalChannel entry: " + i + " {}",
                    localChannelReference);
            logger.info("Add one localChannel to a Network Channel: " + channel.id());
            // Now send first a Startup message
            StartupPacket startup = new StartupPacket(localChannelReference.getLocalId());
            channel.writeAndFlush(startup);
            return localChannelReference;
        } else {
            logger.error("Can't connect to local server " + i + " (Done: " + channelFuture.isDone() + ")");
        }
        try {
            Thread.sleep(Configuration.RETRYINMS * 10);
        } catch (InterruptedException e) {
            throw new OpenR66ProtocolSystemException("Cannot connect to local handler", e);
        }
    }
    logger.error("LocalChannelServer: " + serverChannel.getClass().getName() + " "
            + serverChannel.config().getConnectTimeoutMillis() + " " + serverChannel.isOpen());
    throw new OpenR66ProtocolSystemException("Cannot connect to local handler: " + socketLocalServerAddress
            + " " + serverChannel.isOpen() + " " + serverChannel, channelFuture.cause());
}

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

License:Open Source License

/**
 * /*from   ww  w . j ava 2 s .co  m*/
 * @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.proxy.network.NetworkTransaction.java

License:Open Source License

/**
 * /*from  ww w  . j ava  2s.  com*/
 * @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:org.wso2.carbon.gateway.internal.transport.sender.channel.ChannelUtils.java

License:Open Source License

/**
 * Open Channel for BE.//from  w ww.j  a  v a2s .c o  m
 *
 * @param channelFuture ChannelFuture Object
 * @param httpRoute     HttpRoute represents host and port for BE
 * @return Channel
 * @throws Exception Exception to notify any errors occur during opening the channel
 */
public static Channel openChannel(ChannelFuture channelFuture, HttpRoute httpRoute) throws Exception {

    BootstrapConfiguration bootstrapConfiguration = BootstrapConfiguration.getInstance();
    // blocking for channel to be done
    if (log.isTraceEnabled()) {
        log.trace("Waiting for operation to complete {} for {} millis", channelFuture,
                bootstrapConfiguration.getConnectTimeOut());
    }

    // here we need to wait it in other thread
    final CountDownLatch channelLatch = new CountDownLatch(1);
    channelFuture.addListener(cf -> channelLatch.countDown());

    try {
        boolean wait = channelLatch.await(bootstrapConfiguration.getConnectTimeOut(), TimeUnit.MILLISECONDS);
    } catch (InterruptedException ex) {
        throw new Exception("Interrupted while waiting for " + "connection to " + httpRoute.toString());
    }

    Channel channel = null;

    if (channelFuture.isDone() && channelFuture.isSuccess()) {
        channel = channelFuture.channel();
        if (log.isDebugEnabled()) {
            log.debug("Creating connector to address: {}", httpRoute.toString());
        }
    } else if (channelFuture.isDone() && channelFuture.isCancelled()) {
        ConnectException cause = new ConnectException("Request Cancelled, " + httpRoute.toString());
        if (channelFuture.cause() != null) {
            cause.initCause(channelFuture.cause());
        }
        throw cause;
    } else if (!channelFuture.isDone() && !channelFuture.isSuccess() && !channelFuture.isCancelled()
            && (channelFuture.cause() == null)) {
        throw new ConnectException("Connection timeout, " + httpRoute.toString());
    } else {
        ConnectException cause = new ConnectException("Connection refused, " + httpRoute.toString());
        if (channelFuture.cause() != null) {
            cause.initCause(channelFuture.cause());
        }
        throw cause;
    }
    return channel;
}

From source file:org.wso2.carbon.stream.processor.core.ha.transport.EventSyncConnection.java

License:Open Source License

public ChannelFuture send(final String channelId, final byte[] message) throws ConnectionUnavailableException {
    EventComposite eventComposite = new EventComposite(sessionId, channelId, message);
    ChannelFuture future = channel.writeAndFlush(eventComposite);
    future.addListener(new ChannelFutureListener() {
        @Override/*from   w  w  w.  j  a  va2s. co m*/
        public void operationComplete(ChannelFuture future) throws Exception {
            if (!future.isSuccess()) {
                log.error("Error sending events to '" + hostAndPort + "' on channel '" + channelId + "', "
                        + future.cause() + ", dropping events ", future.cause());
            }
        }
    });
    if (future.isDone() && !future.isSuccess()) {
        throw new ConnectionUnavailableException("Error sending events to '" + hostAndPort + "' on channel '"
                + channelId + "', " + hostAndPort + ", " + future.cause().getMessage(), future.cause());
    }
    return future;
}