Search in sources :

Example 21 with NioClientSocketChannelFactory

use of org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory in project Protocol-Adapter-OSLP by OSGP.

the class OslpConfig method clientBootstrap.

@Bean(destroyMethod = "releaseExternalResources")
public ClientBootstrap clientBootstrap() {
    InternalLoggerFactory.setDefaultFactory(new Slf4JLoggerFactory());
    final ChannelFactory factory = new NioClientSocketChannelFactory(Executors.newCachedThreadPool(), Executors.newCachedThreadPool());
    final ChannelPipelineFactory pipelineFactory = new ChannelPipelineFactory() {

        @Override
        public ChannelPipeline getPipeline() throws ProtocolAdapterException {
            final ChannelPipeline pipeline = OslpConfig.this.createChannelPipeline(OslpConfig.this.oslpChannelHandlerClient());
            LOGGER.info("Created client new pipeline");
            return pipeline;
        }
    };
    final ClientBootstrap bootstrap = new ClientBootstrap(factory);
    bootstrap.setOption("tcpNoDelay", true);
    bootstrap.setOption("keepAlive", false);
    bootstrap.setOption("connectTimeoutMillis", this.connectionTimeout());
    bootstrap.setPipelineFactory(pipelineFactory);
    return bootstrap;
}
Also used : NioClientSocketChannelFactory(org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory) ClientBootstrap(org.jboss.netty.bootstrap.ClientBootstrap) NioClientSocketChannelFactory(org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory) NioServerSocketChannelFactory(org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory) ChannelFactory(org.jboss.netty.channel.ChannelFactory) ChannelPipelineFactory(org.jboss.netty.channel.ChannelPipelineFactory) ChannelPipeline(org.jboss.netty.channel.ChannelPipeline) Slf4JLoggerFactory(org.jboss.netty.logging.Slf4JLoggerFactory) Bean(org.springframework.context.annotation.Bean)

Example 22 with NioClientSocketChannelFactory

use of org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory in project camel by apache.

the class NettyProducer method setupTCPCommunication.

protected void setupTCPCommunication() throws Exception {
    if (channelFactory == null) {
        // prefer using explicit configured thread pools
        BossPool bp = configuration.getBossPool();
        WorkerPool wp = configuration.getWorkerPool();
        if (bp == null) {
            // create new pool which we should shutdown when stopping as its not shared
            bossPool = new NettyClientBossPoolBuilder().withTimer(getEndpoint().getTimer()).withBossCount(configuration.getBossCount()).withName("NettyClientTCPBoss").build();
            bp = bossPool;
        }
        if (wp == null) {
            // create new pool which we should shutdown when stopping as its not shared
            workerPool = new NettyWorkerPoolBuilder().withWorkerCount(configuration.getWorkerCount()).withName("NettyClientTCPWorker").build();
            wp = workerPool;
        }
        channelFactory = new NioClientSocketChannelFactory(bp, wp);
    }
}
Also used : BossPool(org.jboss.netty.channel.socket.nio.BossPool) WorkerPool(org.jboss.netty.channel.socket.nio.WorkerPool) NioDatagramWorkerPool(org.jboss.netty.channel.socket.nio.NioDatagramWorkerPool) NioClientSocketChannelFactory(org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory)

Example 23 with NioClientSocketChannelFactory

use of org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory in project vcell by virtualcell.

the class BeanUtils method downloadBytes.

/**
 * download bytes from URL; optionally provide progress reports; time out after 2 minutes. Note
 * returned string could be an error message from webserver
 * @param url not null
 * @param clientTaskStatusSupport could be null, in which case default status messages printed
 * @return downloadedString
 * @throws RuntimeException
 */
public static String downloadBytes(final URL url, final ClientTaskStatusSupport clientTaskStatusSupport) {
    final ChannelFuture[] connectFuture = new ChannelFuture[1];
    final ChannelFuture[] closeFuture = new ChannelFuture[1];
    final Exception[] exception = new Exception[1];
    final FLAG_STATE[] bFlag = new FLAG_STATE[] { FLAG_STATE.START };
    final HttpResponseHandler responseHandler = new HttpResponseHandler(clientTaskStatusSupport, url.getHost());
    final Thread readBytesThread = new Thread(new Runnable() {

        ClientBootstrap bootstrap = null;

        public void run() {
            try {
                bootstrap = new ClientBootstrap(new NioClientSocketChannelFactory(Executors.newCachedThreadPool(), Executors.newCachedThreadPool()));
                // Set up the event pipeline factory.
                bootstrap.setPipelineFactory(new HttpClientPipelineFactory(responseHandler));
                // int connectionTimeout = 1000 * 60 * 5;
                // bootstrap.setOption("connectTimeoutMillis", connectionTimeout);
                // Start the connection attempt.
                int port = url.getPort();
                if (port <= 0) {
                    port = 80;
                }
                String host = url.getHost();
                connectFuture[0] = bootstrap.connect(new InetSocketAddress(host, port));
                // Wait until the connection attempt succeeds or fails.
                connectFuture[0].awaitUninterruptibly();
                if (connectFuture[0].isCancelled()) {
                    bFlag[0] = FLAG_STATE.INTERRUPTED;
                    return;
                } else if (!connectFuture[0].isSuccess()) {
                    connectFuture[0].getCause().printStackTrace();
                    if (connectFuture[0].getCause() instanceof Exception) {
                        throw (Exception) connectFuture[0].getCause();
                    } else {
                        throw new RuntimeException(exceptionMessage(connectFuture[0].getCause()));
                    }
                } else {
                // Connection established successfully
                }
                // Prepare the HTTP request.
                HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, url.toURI().toASCIIString());
                request.setHeader(HttpHeaders.Names.HOST, host);
                request.setHeader(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE);
                request.setHeader(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP);
                Channel channel = connectFuture[0].getChannel();
                // Send the HTTP request.
                channel.write(request);
                // Wait for the server to close the connection.
                closeFuture[0] = channel.getCloseFuture();
                closeFuture[0].awaitUninterruptibly();
                if (closeFuture[0].isCancelled()) {
                    bFlag[0] = FLAG_STATE.INTERRUPTED;
                    return;
                } else if (!closeFuture[0].isSuccess()) {
                    closeFuture[0].getCause().printStackTrace();
                    if (closeFuture[0].getCause() instanceof Exception) {
                        throw (Exception) closeFuture[0].getCause();
                    } else {
                        throw new RuntimeException(exceptionMessage(closeFuture[0].getCause()));
                    }
                } else {
                // Connection established successfully
                }
                bFlag[0] = FLAG_STATE.FINISHED;
            } catch (Exception e) {
                e.printStackTrace();
                bFlag[0] = FLAG_STATE.FAILED;
                exception[0] = new RuntimeException("contacting outside server " + url.toString() + " failed.\n" + exceptionMessage(e));
            } finally {
                if (bootstrap != null) {
                    // Shut down executor threads to exit.
                    bootstrap.releaseExternalResources();
                }
            }
        }
    });
    readBytesThread.start();
    // Monitor content
    long maximumElapsedTime_ms = 1000 * 60 * 2;
    long startTime_ms = System.currentTimeMillis();
    while (true) {
        try {
            Thread.sleep(100);
        } catch (Exception e) {
        }
        long elapsedTime_ms = System.currentTimeMillis() - startTime_ms;
        if (clientTaskStatusSupport != null && clientTaskStatusSupport.isInterrupted()) {
            bFlag[0] = FLAG_STATE.INTERRUPTED;
            if (connectFuture[0] != null) {
                connectFuture[0].cancel();
            }
            if (closeFuture[0] != null) {
                closeFuture[0].cancel();
            }
            throw UserCancelException.CANCEL_GENERIC;
        } else if (elapsedTime_ms > maximumElapsedTime_ms) {
            bFlag[0] = FLAG_STATE.INTERRUPTED;
            if (connectFuture[0] != null) {
                connectFuture[0].cancel();
            }
            if (closeFuture[0] != null) {
                closeFuture[0].cancel();
            }
            readBytesThread.interrupt();
            throw new RuntimeException("Download timed out after " + (maximumElapsedTime_ms / 1000) + " seconds");
        }
        if (bFlag[0] == FLAG_STATE.FINISHED) {
            // finished normally
            break;
        }
        if (bFlag[0] == FLAG_STATE.FAILED) {
            // finished error
            if (connectFuture[0] != null) {
                connectFuture[0].cancel();
            }
            if (closeFuture[0] != null) {
                closeFuture[0].cancel();
            }
            if (exception[0] instanceof RuntimeException) {
                throw (RuntimeException) exception[0];
            }
            throw new RuntimeException(exception[0]);
        }
    }
    return responseHandler.getResponseContent().toString();
}
Also used : ChannelFuture(org.jboss.netty.channel.ChannelFuture) HttpRequest(org.jboss.netty.handler.codec.http.HttpRequest) DefaultHttpRequest(org.jboss.netty.handler.codec.http.DefaultHttpRequest) NioClientSocketChannelFactory(org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory) InetSocketAddress(java.net.InetSocketAddress) Channel(org.jboss.netty.channel.Channel) MessagingException(javax.mail.MessagingException) HeadlessException(java.awt.HeadlessException) AddressException(javax.mail.internet.AddressException) IOException(java.io.IOException) ClientBootstrap(org.jboss.netty.bootstrap.ClientBootstrap) DefaultHttpRequest(org.jboss.netty.handler.codec.http.DefaultHttpRequest)

Example 24 with NioClientSocketChannelFactory

use of org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory in project load-balancer by RestComm.

the class Client method switchover.

@Override
public void switchover(String fromJvmRoute, String toJvmRoute) {
    Packet packet = new SwitchoverRequestPacket(fromJvmRoute, toJvmRoute);
    ClientBootstrap clientBootstrap = new ClientBootstrap(new NioClientSocketChannelFactory(executor, executor));
    clientBootstrap.setPipelineFactory(new ClientPipelineFactory(clientListener));
    ChannelFuture future = clientBootstrap.connect(new InetSocketAddress(lbAddress, lbPort));
    future.awaitUninterruptibly();
    future.getChannel().write(createRequest(Protocol.SWITCHOVER, packet));
}
Also used : ChannelFuture(org.jboss.netty.channel.ChannelFuture) NodeStopRequestPacket(org.mobicents.tools.heartbeat.api.NodeStopRequestPacket) NodeShutdownRequestPacket(org.mobicents.tools.heartbeat.api.NodeShutdownRequestPacket) StartRequestPacket(org.mobicents.tools.heartbeat.api.StartRequestPacket) Packet(org.mobicents.tools.heartbeat.api.Packet) SwitchoverRequestPacket(org.mobicents.tools.heartbeat.packets.SwitchoverRequestPacket) HeartbeatRequestPacket(org.mobicents.tools.heartbeat.api.HeartbeatRequestPacket) NioClientSocketChannelFactory(org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory) ClientBootstrap(org.jboss.netty.bootstrap.ClientBootstrap) InetSocketAddress(java.net.InetSocketAddress) SwitchoverRequestPacket(org.mobicents.tools.heartbeat.packets.SwitchoverRequestPacket) ClientPipelineFactory(org.mobicents.tools.heartbeat.client.ClientPipelineFactory)

Example 25 with NioClientSocketChannelFactory

use of org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory in project databus by linkedin.

the class TestDatabusRelayMain method testClient.

private void testClient(int relayPort, int fetchSize, long scn, HttpResponseHandler handler) throws Exception {
    Checkpoint ckpt = Checkpoint.createOnlineConsumptionCheckpoint(scn);
    // TODO why is this needed
    // ckpt.setCatchupSource("foo");
    String uristr = "/stream?sources=105&output=json&size=" + fetchSize + "&streamFromLatestScn=false&checkPoint=" + ckpt.toString();
    ClientBootstrap bootstrap = new ClientBootstrap(new NioClientSocketChannelFactory(Executors.newCachedThreadPool(), Executors.newCachedThreadPool()));
    bootstrap.setPipelineFactory(new HttpClientPipelineFactory(handler));
    ChannelFuture future = bootstrap.connect(new InetSocketAddress("localhost", relayPort));
    Channel channel = future.awaitUninterruptibly().getChannel();
    Assert.assertTrue(future.isSuccess(), "Cannot connect to relay at localhost:" + relayPort);
    HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uristr);
    request.setHeader(HttpHeaders.Names.HOST, "localhost");
    channel.write(request);
    channel.getCloseFuture().awaitUninterruptibly();
}
Also used : ChannelFuture(org.jboss.netty.channel.ChannelFuture) HttpRequest(org.jboss.netty.handler.codec.http.HttpRequest) DefaultHttpRequest(org.jboss.netty.handler.codec.http.DefaultHttpRequest) Checkpoint(com.linkedin.databus.core.Checkpoint) NioClientSocketChannelFactory(org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory) ClientBootstrap(org.jboss.netty.bootstrap.ClientBootstrap) InetSocketAddress(java.net.InetSocketAddress) DefaultHttpRequest(org.jboss.netty.handler.codec.http.DefaultHttpRequest) Channel(org.jboss.netty.channel.Channel)

Aggregations

NioClientSocketChannelFactory (org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory)25 ClientBootstrap (org.jboss.netty.bootstrap.ClientBootstrap)19 InetSocketAddress (java.net.InetSocketAddress)11 ChannelFuture (org.jboss.netty.channel.ChannelFuture)9 NioClientBossPool (org.jboss.netty.channel.socket.nio.NioClientBossPool)5 NioWorkerPool (org.jboss.netty.channel.socket.nio.NioWorkerPool)5 ChannelPipelineFactory (org.jboss.netty.channel.ChannelPipelineFactory)4 ExecutorService (java.util.concurrent.ExecutorService)3 ThreadFactory (java.util.concurrent.ThreadFactory)3 Channel (org.jboss.netty.channel.Channel)3 ChannelFactory (org.jboss.netty.channel.ChannelFactory)3 ChannelPipeline (org.jboss.netty.channel.ChannelPipeline)3 BossPool (org.jboss.netty.channel.socket.nio.BossPool)3 NioServerSocketChannelFactory (org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory)3 WorkerPool (org.jboss.netty.channel.socket.nio.WorkerPool)3 HashedWheelTimer (org.jboss.netty.util.HashedWheelTimer)3 ClientPipelineFactory (org.mobicents.tools.heartbeat.client.ClientPipelineFactory)3 DefaultHttpRequest (org.jboss.netty.handler.codec.http.DefaultHttpRequest)2 HttpRequest (org.jboss.netty.handler.codec.http.HttpRequest)2 Slf4JLoggerFactory (org.jboss.netty.logging.Slf4JLoggerFactory)2