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

@Override
    ChannelFuture await() throws InterruptedException;

Source Link

Usage

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

License:Open Source License

/**
 * Connect to the Server//  w w  w  .  ja  va 2  s.c  o  m
 */
private boolean connect() {
    // Start the connection attempt.
    ChannelFuture future = bootstrap.connect(address);

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

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 ww  w.jav a 2  s.co m
 * 
 * @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.gateway.kernel.exec.LocalExecClient.java

License:Open Source License

/**
 * Connect to the Server//from  www .  j a  v  a2  s . co 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.gateway.kernel.rest.HttpRestHandlerTest.java

License:Open Source License

/**
 * Initialize the REST service (server side) for one restConfiguration
 * /*from w  ww  . j a  va  2s.c  o  m*/
 * @param restConfiguration
 */
public static void initializeService(RestConfiguration restConfiguration) {
    instantiateHandlers(restConfiguration);
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    // Configure the server.
    ServerBootstrap httpBootstrap = new ServerBootstrap();
    WaarpNettyUtil.setServerBootstrap(httpBootstrap, bossGroup, workerGroup, 30000);

    // Configure the pipeline factory.
    httpBootstrap.childHandler(new HttpRestInitializer(restConfiguration));
    // Bind and start to accept incoming connections.
    ChannelFuture future = null;
    if (restConfiguration != null && !restConfiguration.REST_ADDRESS.isEmpty()) {
        future = httpBootstrap
                .bind(new InetSocketAddress(restConfiguration.REST_ADDRESS, restConfiguration.REST_PORT));
    } else {
        future = httpBootstrap.bind(new InetSocketAddress(restConfiguration.REST_PORT));
    }
    try {
        future.await();
        group.add(future.channel());
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:org.waarp.openr66.context.filesystem.R66File.java

License:Open Source License

/**
 * Start the retrieve (send to the remote host the local file)
 * //from   w  w w.  jav  a  2 s  .  c o  m
 * @param running
 *            When false, should stop the runner
 * @throws OpenR66RunnerErrorException
 * @throws OpenR66ProtocolSystemException
 */
public void retrieveBlocking(AtomicBoolean running)
        throws OpenR66RunnerErrorException, OpenR66ProtocolSystemException {
    boolean retrieveDone = false;
    LocalChannelReference localChannelReference = getSession().getLocalChannelReference();
    FilesystemBasedDigest digest = null;
    logger.debug("File to retrieve: " + this.toString());
    try {
        if (!isReady) {
            return;
        }
        DataBlock block = null;
        try {
            block = readDataBlock();
        } catch (FileEndOfTransferException e) {
            // Last block (in fact, no data to read)
            retrieveDone = true;
            return;
        }
        if (block == null) {
            // Last block (in fact, no data to read)
            retrieveDone = true;
            return;
        }
        if (Configuration.configuration.isGlobalDigest()) {
            try {
                digest = new FilesystemBasedDigest(Configuration.configuration.getDigest());
            } catch (NoSuchAlgorithmException e2) {
                // ignore
            }
        }
        ChannelFuture future1 = null, future2 = null;
        if ((block != null && (running.get()))) {
            block.getBlock().retain();
            future1 = RetrieveRunner.writeWhenPossible(block, localChannelReference);
            if (Configuration.configuration.isGlobalDigest()) {
                FileUtils.computeGlobalHash(digest, block.getBlock());
            }
        }
        // While not last block
        while (block != null && (!block.isEOF()) && (running.get())) {
            try {
                future1.await();
            } catch (InterruptedException e) {
            }
            if (!future1.isSuccess()) {
                return;
            }
            try {
                block = readDataBlock();
            } catch (FileEndOfTransferException e) {
                // Wait for last write
                try {
                    future1.await();
                } catch (InterruptedException e1) {
                }
                if (future1.isSuccess()) {
                    retrieveDone = true;
                }
                return;
            }
            block.getBlock().retain();
            future2 = RetrieveRunner.writeWhenPossible(block, localChannelReference);
            if (Configuration.configuration.isGlobalDigest()) {
                FileUtils.computeGlobalHash(digest, block.getBlock());
            }
            future1 = future2;
        }
        if (!running.get()) {
            // stopped
            return;
        }
        // Wait for last write
        if (future1 != null) {
            try {
                future1.await();
            } catch (InterruptedException e) {
            }
            if (!future1.isSuccess()) {
                return;
            }
        }
        if (block != null) {
            block.getBlock().release();
            block.clear();
        }
        retrieveDone = true;
        return;
    } catch (FileTransferException e) {
        // An error occurs!
        getSession().setFinalizeTransfer(false, new R66Result(new OpenR66ProtocolSystemException(e),
                getSession(), false, ErrorCode.TransferError, getSession().getRunner()));
    } catch (OpenR66ProtocolPacketException e) {
        // An error occurs!
        getSession().setFinalizeTransfer(false,
                new R66Result(e, getSession(), false, ErrorCode.Internal, getSession().getRunner()));
    } finally {
        if (retrieveDone) {
            String hash = null;
            if (digest != null) {
                hash = FilesystemBasedDigest.getHex(digest.Final());
            }
            try {
                if (hash == null) {
                    ChannelUtils.writeEndTransfer(localChannelReference);
                } else {
                    ChannelUtils.writeEndTransfer(localChannelReference, hash);
                }
            } catch (OpenR66ProtocolPacketException e) {
                // An error occurs!
                getSession().setFinalizeTransfer(false,
                        new R66Result(e, getSession(), false, ErrorCode.Internal, getSession().getRunner()));
            }
        } else {
            // An error occurs!
            getSession().setFinalizeTransfer(false,
                    new R66Result(new OpenR66ProtocolSystemException("Transfer in error"), getSession(), false,
                            ErrorCode.TransferError, getSession().getRunner()));
        }
    }
}

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

License:Open Source License

/**
 * Connect to the Server/*from ww  w  .j  a  va2  s . com*/
 */
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.http.rest.HttpRestR66Handler.java

License:Open Source License

/**
 * Initialize the REST service (server side) for one restConfiguration
 * // w ww.  j av a  2s.  co  m
 * @param restConfiguration
 */
public static void initializeService(RestConfiguration restConfiguration) {
    instantiateHandlers(restConfiguration);
    if (group == null) {
        group = Configuration.configuration.getHttpChannelGroup();
    }
    // Configure the server.
    ServerBootstrap httpBootstrap = new ServerBootstrap();
    WaarpNettyUtil.setServerBootstrap(httpBootstrap, Configuration.configuration.getHttpBossGroup(),
            Configuration.configuration.getHttpWorkerGroup(),
            (int) Configuration.configuration.getTIMEOUTCON());
    // Set up the event pipeline factory.
    if (restConfiguration.REST_SSL) {
        httpBootstrap.childHandler(new HttpRestR66Initializer(false, Configuration.getWaarpSslContextFactory(),
                restConfiguration));
    } else {
        httpBootstrap.childHandler(new HttpRestR66Initializer(false, null, restConfiguration));
    }
    // Bind and start to accept incoming connections.
    ChannelFuture future;
    if (restConfiguration != null && restConfiguration.REST_ADDRESS != null
            && !restConfiguration.REST_ADDRESS.isEmpty()) {
        future = httpBootstrap
                .bind(new InetSocketAddress(restConfiguration.REST_ADDRESS, restConfiguration.REST_PORT));
    } else {
        future = httpBootstrap.bind(new InetSocketAddress(restConfiguration.REST_PORT));
    }
    try {
        future.await();
    } catch (InterruptedException e) {
    }
    if (future.isSuccess()) {
        group.add(future.channel());
    }
}

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

License:Open Source License

/**
 * Create a new Client/*from w ww  .  j  a  va  2s.  c o m*/
 * 
 * @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.test.TestSendThroughClient.java

License:Open Source License

public boolean sendFile() {
    R66File r66file = localChannelReference.getSession().getFile();
    boolean retrieveDone = false;
    try {/*from w  ww . j a  va 2  s  .  c om*/
        DataBlock block = null;
        try {
            block = r66file.readDataBlock();
        } catch (FileEndOfTransferException e) {
            // Last block (in fact, no data to read)
            retrieveDone = true;
            return retrieveDone;
        }
        if (block == null) {
            // Last block (in fact, no data to read)
            retrieveDone = true;
            return retrieveDone;
        }
        ChannelFuture future1 = null, future2 = null;
        if (block != null) {
            block.getBlock().retain();
            future1 = this.writeWhenPossible(block);
        }
        // While not last block
        while (block != null && !block.isEOF()) {
            try {
                future1.await();
            } catch (InterruptedException e) {
            }
            if (!future1.isSuccess()) {
                return false;
            }
            try {
                block = r66file.readDataBlock();
            } catch (FileEndOfTransferException e) {
                // Wait for last write
                retrieveDone = true;
                try {
                    future1.await();
                } catch (InterruptedException e1) {
                }
                return future1.isSuccess();
            }
            block.getBlock().retain();
            future2 = this.writeWhenPossible(block);
            future1 = future2;
        }
        // Wait for last write
        if (future1 != null) {
            try {
                future1.await();
            } catch (InterruptedException e) {
            }
            return future1.isSuccess();
        }
        retrieveDone = true;
        return retrieveDone;
    } catch (FileTransferException e) {
        // An error occurs!
        this.transferInError(new OpenR66ProtocolSystemException(e));
        return false;
    } catch (OpenR66ProtocolPacketException e) {
        // An error occurs!
        this.transferInError(e);
        return false;
    } catch (OpenR66RunnerErrorException e) {
        // An error occurs!
        this.transferInError(e);
        return false;
    } catch (OpenR66ProtocolSystemException e) {
        // An error occurs!
        this.transferInError(e);
        return false;
    }
}

From source file:org.wso2.carbon.tcp.transport.TcpNettyClient.java

License:Open Source License

/**
 * @param args/*from  w  w  w .  ja v  a 2s .c  om*/
 */
public static void main(String[] args) {

    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ChannelPipeline p = ch.pipeline();
                p.addLast(new EventEncoder());
            }
        });

        // Start the connection attempt.
        Channel ch = b.connect("localhost", 8080).sync().channel();
        List<SiddhiEventComposite> eventList = new ArrayList<SiddhiEventComposite>();
        ChannelFuture cf;
        for (int i = 0; i < 1; i++) {
            for (int j = 0; j < 5; j++) {
                Event event = new Event(System.currentTimeMillis(), new Object[] { "WSO2", i, 10 });
                eventList.add(new SiddhiEventComposite(event, "StockStream"));
                Event event1 = new Event(System.currentTimeMillis(), new Object[] { "IBM", i, 10 });
                eventList.add(new SiddhiEventComposite(event1, "StockStream"));
            }
            cf = ch.write(eventList);
            ch.flush();
            cf.await();
            eventList = new ArrayList<SiddhiEventComposite>();

            if (i * 10 % 10000 == 0) {
                log.info("Done Sending " + i * 10 + " events..");
            }
        }

        ch.close().sync();
    } catch (InterruptedException e) {
        log.error("Error sending messages " + e.getMessage(), e);
    } finally {
        group.shutdownGracefully();
    }

}