Example usage for io.netty.channel ChannelInboundHandlerAdapter ChannelInboundHandlerAdapter

List of usage examples for io.netty.channel ChannelInboundHandlerAdapter ChannelInboundHandlerAdapter

Introduction

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

Prototype

ChannelInboundHandlerAdapter

Source Link

Usage

From source file:org.r358.poolnetty.test.funcobs.AsyncLeaseTest.java

License:Open Source License

@Test
public void testWithCallbackListener() throws Exception {
    final CountDownLatch startedLatch = new CountDownLatch(1);
    final CountDownLatch leaseRequestedLatch = new CountDownLatch(1);
    final CountDownLatch leaseGrantedLatch = new CountDownLatch(1);
    final CountDownLatch leaseYieldedLatch = new CountDownLatch(1);
    final CountDownLatch stopLatch = new CountDownLatch(1);
    final CountDownLatch connectionOpenedLatch = new CountDownLatch(1);
    final CountDownLatch connectionClosedLatch = new CountDownLatch(1);

    final AtomicReference<String> messageAtServer = new AtomicReference<>(); // I need to set the message into something!

    final List<Object> listOfUserObjectReports = new ArrayList<>();

    final String originalMessage = "The cat sat on the mat.";

    ///*  ww  w. ja  v a2  s .co m*/
    // Pool listener.
    //
    PoolProviderListener ppl = new PoolProviderListener() {
        @Override
        public void started(PoolProvider provider) {
            startedLatch.countDown();
        }

        @Override
        public void stopped(PoolProvider provider) {
            stopLatch.countDown();
        }

        @Override
        public void leaseRequested(PoolProvider provider, int leaseTime, TimeUnit units, Object userObject) {
            leaseRequestedLatch.countDown();
            listOfUserObjectReports.add(userObject.toString() + ".request");
        }

        @Override
        public void leaseGranted(PoolProvider provider, Channel channel, Object userObject) {
            leaseGrantedLatch.countDown();
            listOfUserObjectReports.add(userObject.toString() + ".granted");
        }

        @Override
        public void leaseCanceled(PoolProvider provider, Object userObject) {

        }

        @Override
        public void leaseYield(PoolProvider provider, Channel channel, Object userObject) {
            leaseYieldedLatch.countDown();
            listOfUserObjectReports.add(userObject.toString() + ".yield");
        }

        @Override
        public void leaseExpired(PoolProvider provider, Channel channel, Object userObject) {

        }

        @Override
        public void connectionClosed(PoolProvider provider, Channel ctx) {
            connectionClosedLatch.countDown();
        }

        @Override
        public void connectionCreated(PoolProvider provider, Channel ctx, boolean immortal) {
            connectionOpenedLatch.countDown();
        }

        @Override
        public void ephemeralReaped(PoolProvider poolProvider, Channel channel) {
            // Not tested here..
        }
    };

    //
    // The simple server side for testing.
    //

    SimpleServer simpleServer = new SimpleServer("127.0.0.1", 1887, 10, new SimpleServerListener() {

        @Override
        public void newConnection(ChannelHandlerContext ctx) {

        }

        @Override
        public void newValue(ChannelHandlerContext ctx, String val) {
            messageAtServer.set(val);
            ctx.writeAndFlush(val);
        }
    });

    simpleServer.start();

    //
    // Build the pool.
    //

    NettyConnectionPoolBuilder ncb = new NettyConnectionPoolBuilder(1, 1, 1);

    final EventLoopGroup elg = new NioEventLoopGroup();

    //
    // Create the boot strap.
    //
    ncb.withBootstrapProvider(new BootstrapProvider() {
        @Override
        public Bootstrap createBootstrap(PoolProvider poolProvider) {
            Bootstrap bs = new Bootstrap();
            bs.group(elg);
            bs.channel(NioSocketChannel.class);
            bs.option(ChannelOption.SO_KEEPALIVE, true);
            bs.option(ChannelOption.AUTO_READ, true);
            return bs;
        }
    });

    //
    // Sets up the connection info and the channel initializer.
    //
    ncb.withConnectionInfoProvider(new ConnectionInfoProvider() {
        @Override
        public ConnectionInfo connectionInfo(PoolProvider poolProvider) {

            return new ConnectionInfo(new InetSocketAddress("127.0.0.1", 1887), null, new ChannelInitializer() {
                @Override
                protected void initChannel(Channel ch) throws Exception {
                    ch.pipeline().addLast("decode", new SimpleInboundHandler(10));
                    ch.pipeline().addLast("encode", new SimpleOutboundHandler(10));
                }
            });

        }
    });

    //
    // Make the pool add listener and start.
    //
    NettyConnectionPool ncp = ncb.build();
    ncp.addListener(ppl);

    ncp.start(0, TimeUnit.SECONDS);

    TestCase.assertTrue("Opening connection..", connectionOpenedLatch.await(5, TimeUnit.SECONDS));
    TestCase.assertTrue("Not started..", startedLatch.await(5, TimeUnit.SECONDS));

    String userObject = "Foo!";

    LeasedChannel ctx = null;

    final CountDownLatch respLatch = new CountDownLatch(1);
    final AtomicReference<String> respValue = new AtomicReference<>();

    //
    // Call with callback / listener.
    //

    ncp.leaseAsync(10, TimeUnit.DAYS, userObject, new LeaseListener() {
        @Override
        public void leaseRequest(boolean success, LeasedChannel channel, Throwable th) {

            //
            // Remember that any mods you make the pipeline when you have leased the channel
            // Will impact the next lease holder.
            //

            channel.pipeline().addLast("_foo_", new ChannelInboundHandlerAdapter() {
                @Override
                public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

                    respValue.set(msg.toString());
                    respLatch.countDown();
                }
            });

            // Send the message.
            channel.writeAndFlush(originalMessage);

            //
            // Did we get a response back from the server.
            //
            try {
                TestCase.assertTrue("Echo from server.", respLatch.await(5, TimeUnit.SECONDS));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            //
            // Clean it up as a matter of habit.
            //
            channel.pipeline().remove("_foo_");

            //
            // Yield lease.
            //
            try {
                channel.yield();
            } catch (PoolProviderException e) {
                e.printStackTrace();
            }

        }
    });

    TestCase.assertTrue("Lease not requested", leaseRequestedLatch.await(5, TimeUnit.SECONDS));
    TestCase.assertTrue("Lease not granted", leaseGrantedLatch.await(5, TimeUnit.SECONDS));

    TestCase.assertTrue("Lease not yielded", leaseYieldedLatch.await(5, TimeUnit.SECONDS));

    ncp.stop(false);

    TestCase.assertTrue("Connection Not Closed.", connectionClosedLatch.await(5, TimeUnit.SECONDS));

    TestCase.assertTrue("Not stopped.", stopLatch.await(5, TimeUnit.SECONDS));

    //
    // Check we got back what we sent etc.
    //
    TestCase.assertEquals(originalMessage, messageAtServer.get());
    TestCase.assertEquals(originalMessage, respValue.get());

    //
    // - Request lease, Lease granted , Lease yielded check order.
    //
    TestCase.assertEquals(3, listOfUserObjectReports.size()); // Should only be 3 reports.

    TestCase.assertEquals(userObject + ".request", listOfUserObjectReports.get(0));
    TestCase.assertEquals(userObject + ".granted", listOfUserObjectReports.get(1));
    TestCase.assertEquals(userObject + ".yield", listOfUserObjectReports.get(2));

    simpleServer.stop();
}

From source file:org.r358.poolnetty.test.funcobs.AsyncLeaseTest.java

License:Open Source License

@Test
public void testWithFuture() throws Exception {
    final CountDownLatch startedLatch = new CountDownLatch(1);
    final CountDownLatch leaseRequestedLatch = new CountDownLatch(1);
    final CountDownLatch leaseGrantedLatch = new CountDownLatch(1);
    final CountDownLatch leaseYieldedLatch = new CountDownLatch(1);
    final CountDownLatch stopLatch = new CountDownLatch(1);
    final CountDownLatch connectionOpenedLatch = new CountDownLatch(1);
    final CountDownLatch connectionClosedLatch = new CountDownLatch(1);

    final AtomicReference<String> messageAtServer = new AtomicReference<>(); // I need to set the message into something!

    final List<Object> listOfUserObjectReports = new ArrayList<>();

    final String originalMessage = "The cat sat on the mat.";

    //// www  . j av a  2 s  .  c om
    // Pool listener.
    //
    PoolProviderListener ppl = new PoolProviderListener() {
        @Override
        public void started(PoolProvider provider) {
            startedLatch.countDown();
        }

        @Override
        public void stopped(PoolProvider provider) {
            stopLatch.countDown();
        }

        @Override
        public void leaseRequested(PoolProvider provider, int leaseTime, TimeUnit units, Object userObject) {
            leaseRequestedLatch.countDown();
            listOfUserObjectReports.add(userObject.toString() + ".request");
        }

        @Override
        public void leaseGranted(PoolProvider provider, Channel channel, Object userObject) {
            leaseGrantedLatch.countDown();
            listOfUserObjectReports.add(userObject.toString() + ".granted");
        }

        @Override
        public void leaseCanceled(PoolProvider provider, Object userObject) {

        }

        @Override
        public void leaseYield(PoolProvider provider, Channel channel, Object userObject) {
            leaseYieldedLatch.countDown();
            listOfUserObjectReports.add(userObject.toString() + ".yield");
        }

        @Override
        public void leaseExpired(PoolProvider provider, Channel channel, Object userObject) {

        }

        @Override
        public void connectionClosed(PoolProvider provider, Channel ctx) {
            connectionClosedLatch.countDown();
        }

        @Override
        public void connectionCreated(PoolProvider provider, Channel ctx, boolean immortal) {
            connectionOpenedLatch.countDown();
        }

        @Override
        public void ephemeralReaped(PoolProvider poolProvider, Channel channel) {
            // Not tested here..
        }
    };

    //
    // The simple server side for testing.
    //

    SimpleServer simpleServer = new SimpleServer("127.0.0.1", 1887, 10, new SimpleServerListener() {

        @Override
        public void newConnection(ChannelHandlerContext ctx) {

        }

        @Override
        public void newValue(ChannelHandlerContext ctx, String val) {
            messageAtServer.set(val);
            ctx.writeAndFlush(val);
        }
    });

    simpleServer.start();

    //
    // Build the pool.
    //

    NettyConnectionPoolBuilder ncb = new NettyConnectionPoolBuilder(1, 1, 1);

    final EventLoopGroup elg = new NioEventLoopGroup();

    //
    // Create the boot strap.
    //
    ncb.withBootstrapProvider(new BootstrapProvider() {
        @Override
        public Bootstrap createBootstrap(PoolProvider poolProvider) {
            Bootstrap bs = new Bootstrap();
            bs.group(elg);
            bs.channel(NioSocketChannel.class);
            bs.option(ChannelOption.SO_KEEPALIVE, true);
            bs.option(ChannelOption.AUTO_READ, true);
            return bs;
        }
    });

    //
    // Sets up the connection info and the channel initializer.
    //
    ncb.withConnectionInfoProvider(new ConnectionInfoProvider() {
        @Override
        public ConnectionInfo connectionInfo(PoolProvider poolProvider) {

            return new ConnectionInfo(new InetSocketAddress("127.0.0.1", 1887), null, new ChannelInitializer() {
                @Override
                protected void initChannel(Channel ch) throws Exception {
                    ch.pipeline().addLast("decode", new SimpleInboundHandler(10));
                    ch.pipeline().addLast("encode", new SimpleOutboundHandler(10));
                }
            });

        }
    });

    //
    // Make the pool add listener and start.
    //
    NettyConnectionPool ncp = ncb.build();
    ncp.addListener(ppl);

    ncp.start(0, TimeUnit.SECONDS);
    TestCase.assertTrue("Opening connection..", connectionOpenedLatch.await(5, TimeUnit.SECONDS));
    TestCase.assertTrue("Not started..", startedLatch.await(5, TimeUnit.SECONDS));

    String userObject = "Foo!";

    Future<LeasedChannel> ctxFuture = ncp.leaseAsync(10, TimeUnit.DAYS, userObject);

    LeasedChannel ctx = null;

    ctx = ctxFuture.get(5, TimeUnit.SECONDS);

    //
    // Lease a channel.
    //
    //   Channel ctx = ncp.lease(10, TimeUnit.DAYS, userObject);

    TestCase.assertTrue("Lease not requested", leaseRequestedLatch.await(5, TimeUnit.SECONDS));
    TestCase.assertTrue("Lease not granted", leaseGrantedLatch.await(5, TimeUnit.SECONDS));

    final CountDownLatch respLatch = new CountDownLatch(1);
    final AtomicReference<String> respValue = new AtomicReference<>();

    //
    // Remember that any mods you make the pipeline when you have leased the channel
    // Will impact the next lease holder.
    //

    ctx.pipeline().addLast("_foo_", new ChannelInboundHandlerAdapter() {
        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

            respValue.set(msg.toString());
            respLatch.countDown();
        }
    });

    // Send the message.
    ctx.writeAndFlush(originalMessage);

    //
    // Did we get a response back from the server.
    //
    TestCase.assertTrue("Echo from server.", respLatch.await(5, TimeUnit.SECONDS));

    //
    // Clean it up as a matter of habit.
    //
    ctx.pipeline().remove("_foo_");

    //
    // Yield lease.
    //
    ncp.yield(ctx);

    TestCase.assertTrue("Lease not yielded", leaseYieldedLatch.await(5, TimeUnit.SECONDS));

    ncp.stop(false);

    TestCase.assertTrue("Connection Not Closed.", connectionClosedLatch.await(5, TimeUnit.SECONDS));

    TestCase.assertTrue("Not stopped.", stopLatch.await(5, TimeUnit.SECONDS));

    //
    // Check we got back what we sent etc.
    //
    TestCase.assertEquals(originalMessage, messageAtServer.get());
    TestCase.assertEquals(originalMessage, respValue.get());

    //
    // - Request lease, Lease granted , Lease yielded check order.
    //
    TestCase.assertEquals(3, listOfUserObjectReports.size()); // Should only be 3 reports.

    TestCase.assertEquals(userObject + ".request", listOfUserObjectReports.get(0));
    TestCase.assertEquals(userObject + ".granted", listOfUserObjectReports.get(1));
    TestCase.assertEquals(userObject + ".yield", listOfUserObjectReports.get(2));

    simpleServer.stop();
}

From source file:org.r358.poolnetty.test.funcobs.EphemeralTest.java

License:Open Source License

/**
 * In this test an ephemeral connection is made as a result of a lease request.
 * Messages are exchanged and the channel is reaped and closed after yielding and has sat idle.
 *
 * @throws Exception//from   www . j a  v a2 s  . c o m
 */
@Test
public void testAgeOutOfEphemeral() throws Exception {

    final CountDownLatch startedLatch = new CountDownLatch(1);
    final CountDownLatch stopLatch = new CountDownLatch(1);
    final CountDownLatch connectionOpenedLatch = new CountDownLatch(1);
    final CountDownLatch connectionClosedLatch = new CountDownLatch(1);

    final CountDownLatch ephemeralAgedOut = new CountDownLatch(1);
    final CountDownLatch afterYeild = new CountDownLatch(1);

    final AtomicReference<String> messageAtServer = new AtomicReference<>(); // I need to set the message into something!

    final List<Object> listOfUserObjectReports = new ArrayList<>();

    final String originalMessage = "The cat sat on the mat.";

    //
    // Pool listener.
    //
    PoolProviderListener ppl = new PoolProviderListener() {
        @Override
        public void started(PoolProvider provider) {
            startedLatch.countDown();
        }

        @Override
        public void stopped(PoolProvider provider) {
            stopLatch.countDown();
        }

        @Override
        public void leaseRequested(PoolProvider provider, int leaseTime, TimeUnit units, Object userObject) {

            listOfUserObjectReports.add(userObject.toString() + ".request");
        }

        @Override
        public void leaseGranted(PoolProvider provider, Channel channel, Object userObject) {

            listOfUserObjectReports.add(userObject.toString() + ".granted");
        }

        @Override
        public void leaseCanceled(PoolProvider provider, Object userObject) {

        }

        @Override
        public void leaseYield(PoolProvider provider, Channel channel, Object userObject) {

            listOfUserObjectReports.add(userObject.toString() + ".yield");
            afterYeild.countDown();
        }

        @Override
        public void leaseExpired(PoolProvider provider, Channel channel, Object userObject) {
            // Not tested here..
        }

        @Override
        public void connectionClosed(PoolProvider provider, Channel ctx) {
            connectionClosedLatch.countDown();
        }

        @Override
        public void connectionCreated(PoolProvider provider, Channel ctx, boolean immortal) {
            connectionOpenedLatch.countDown();
        }

        @Override
        public void ephemeralReaped(PoolProvider poolProvider, Channel channel) {
            ephemeralAgedOut.countDown();
        }
    };

    //
    // The simple server side for testing.
    //

    simpleServer = new SimpleServer("127.0.0.1", 1887, 10, new SimpleServerListener() {

        @Override
        public void newConnection(ChannelHandlerContext ctx) {

        }

        @Override
        public void newValue(ChannelHandlerContext ctx, String val) {
            messageAtServer.set(val);
            ctx.writeAndFlush(val);
        }
    });

    simpleServer.start();

    //
    // Build the pool.
    //

    NettyConnectionPoolBuilder ncb = new NettyConnectionPoolBuilder(0, 1, 2000);

    final EventLoopGroup elg = new NioEventLoopGroup();

    //
    // Create the boot strap.
    //
    ncb.withBootstrapProvider(new BootstrapProvider() {
        @Override
        public Bootstrap createBootstrap(PoolProvider poolProvider) {
            Bootstrap bs = new Bootstrap();
            bs.group(elg);
            bs.channel(NioSocketChannel.class);
            bs.option(ChannelOption.SO_KEEPALIVE, true);
            bs.option(ChannelOption.AUTO_READ, true);
            return bs;
        }
    });

    //
    // Sets up the connection info and the channel initializer.
    //
    ncb.withConnectionInfoProvider(new ConnectionInfoProvider() {
        @Override
        public ConnectionInfo connectionInfo(PoolProvider poolProvider) {

            return new ConnectionInfo(new InetSocketAddress("127.0.0.1", 1887), null, new ChannelInitializer() {
                @Override
                protected void initChannel(Channel ch) throws Exception {
                    ch.pipeline().addLast("decode", new SimpleInboundHandler(10));
                    ch.pipeline().addLast("encode", new SimpleOutboundHandler(10));
                }
            });

        }
    });

    //
    // Make the pool add listener and start.
    //
    NettyConnectionPool ncp = ncb.build();
    ncp.addListener(ppl);

    ncp.start(0, TimeUnit.SECONDS);
    //
    // Should start as normal but with no immortal connections made.
    //
    TestCase.assertTrue("Not started..", startedLatch.await(5, TimeUnit.SECONDS));

    String userObject = "Foo!";

    //
    // Lease a channel, which should trigger channel opening..
    //
    Channel ctx = ncp.lease(10, TimeUnit.DAYS, userObject);

    TestCase.assertTrue("Opening connection..", connectionOpenedLatch.await(5, TimeUnit.SECONDS));

    final CountDownLatch respLatch = new CountDownLatch(1);
    final AtomicReference<String> respValue = new AtomicReference<>();

    //
    // Remember that any mods you make the pipeline when you have leased the channel
    // Will impact the next lease holder.
    //

    ctx.pipeline().addLast("_foo_", new ChannelInboundHandlerAdapter() {
        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

            respValue.set(msg.toString());
            respLatch.countDown();
        }
    });

    // Send the message.
    ctx.writeAndFlush(originalMessage);

    //
    // Did we get a response back from the server.
    //
    TestCase.assertTrue("Echo from server.", respLatch.await(5, TimeUnit.SECONDS));

    //
    // Hold off on yielding the lease, the connection should not be reaped when it is leased.
    //

    if (ephemeralAgedOut.await(4, TimeUnit.SECONDS)) {
        TestCase.fail("Ephemeral connection was harvested while leased.");
    }

    //
    // Yield lease.
    //
    ncp.yield(ctx);

    if (!afterYeild.await(5, TimeUnit.SECONDS)) {
        TestCase.fail("Yield did not occur.");
    }

    List l = (List) TestUtil.getField(ncp, "ephemeralContexts");

    //
    // Should be 1 ephemeral contexts.
    //
    TestCase.assertEquals(1, l.size());

    //
    // After yield the ephemeral connection should live on for one unit of its lifespan.
    //

    long tstart = System.currentTimeMillis();

    if (!ephemeralAgedOut.await(4, TimeUnit.SECONDS)) {
        TestCase.fail("Ephemeral connection was not harvested.");
    }

    long duration = System.currentTimeMillis() - tstart;
    if (duration < 2000) {
        TestCase.fail("Ephemeral expired early.");
    }

    l = (List) TestUtil.getField(ncp, "ephemeralContexts");

    //
    // Should be no ephemeral contexts.
    //
    TestCase.assertEquals(0, l.size());

    //
    // We should see a connection closed.
    //
    TestCase.assertTrue("Connection Not Closed.", connectionClosedLatch.await(5, TimeUnit.SECONDS));

    ncp.stop(false);

    TestCase.assertTrue("Not stopped.", stopLatch.await(5, TimeUnit.SECONDS));

    //
    // Check we got back what we sent etc.
    //

    TestCase.assertEquals(originalMessage, messageAtServer.get());
    TestCase.assertEquals(originalMessage, respValue.get());

    //
    // - Request lease, Lease granted , Lease yielded check order.
    //
    TestCase.assertEquals(3, listOfUserObjectReports.size()); // Should only be 3 reports.

    TestCase.assertEquals(userObject + ".request", listOfUserObjectReports.get(0));
    TestCase.assertEquals(userObject + ".granted", listOfUserObjectReports.get(1));
    TestCase.assertEquals(userObject + ".yield", listOfUserObjectReports.get(2));

    simpleServer.stop();
}

From source file:org.r358.poolnetty.test.simpleserver.SimpleServer.java

License:Open Source License

public SimpleServer(String host, int port, int backLog, final SimpleServerListener ssl) throws Exception {

    EventLoopGroup workers = new NioEventLoopGroup();
    EventLoopGroup bosses = new NioEventLoopGroup();

    bootstrap = new ServerBootstrap();

    bootstrap.group(bosses, workers);//from   w  w w  . j a  va 2s. co  m
    bootstrap.channel(NioServerSocketChannel.class);
    bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline cpl = ch.pipeline();
            cpl.addLast("encode", new SimpleOutboundHandler(-1));
            cpl.addLast("decode", new SimpleInboundHandler());
            cpl.addLast("adapt", new ChannelInboundHandlerAdapter() {

                @Override
                public void channelActive(ChannelHandlerContext ctx) throws Exception {
                    super.channelActive(ctx);
                    ssl.newConnection(ctx);
                }

                @Override
                public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                    ssl.newValue(ctx, msg.toString());
                }
            });

        }
    });

    bootstrap.localAddress(host, port);

    bootstrap.option(ChannelOption.ALLOW_HALF_CLOSURE, true);
    bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
    bootstrap.option(ChannelOption.SO_BACKLOG, backLog);

}

From source file:org.redisson.client.handler.RedisChannelInitializer.java

License:Apache License

private void initSsl(final RedisClientConfig config, Channel ch) throws KeyStoreException, IOException,
        NoSuchAlgorithmException, CertificateException, SSLException, UnrecoverableKeyException {
    if (!config.getAddress().isSsl()) {
        return;//ww  w .j a va 2 s . c o  m
    }

    io.netty.handler.ssl.SslProvider provided = io.netty.handler.ssl.SslProvider.JDK;
    if (config.getSslProvider() == SslProvider.OPENSSL) {
        provided = io.netty.handler.ssl.SslProvider.OPENSSL;
    }

    SslContextBuilder sslContextBuilder = SslContextBuilder.forClient().sslProvider(provided);
    if (config.getSslTruststore() != null) {
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());

        InputStream stream = config.getSslTruststore().openStream();
        try {
            char[] password = null;
            if (config.getSslTruststorePassword() != null) {
                password = config.getSslTruststorePassword().toCharArray();
            }
            keyStore.load(stream, password);
        } finally {
            stream.close();
        }

        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(keyStore);
        sslContextBuilder.trustManager(trustManagerFactory);
    }

    if (config.getSslKeystore() != null) {
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());

        InputStream stream = config.getSslKeystore().openStream();
        char[] password = null;
        if (config.getSslKeystorePassword() != null) {
            password = config.getSslKeystorePassword().toCharArray();
        }
        try {
            keyStore.load(stream, password);
        } finally {
            stream.close();
        }

        KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keyStore, password);
        sslContextBuilder.keyManager(keyManagerFactory);
    }

    SSLParameters sslParams = new SSLParameters();
    if (config.isSslEnableEndpointIdentification()) {
        // TODO remove for JDK 1.7+
        try {
            Method method = sslParams.getClass().getDeclaredMethod("setEndpointIdentificationAlgorithm",
                    String.class);
            method.invoke(sslParams, "HTTPS");
        } catch (Exception e) {
            throw new SSLException(e);
        }
    } else {
        if (config.getSslTruststore() == null) {
            sslContextBuilder.trustManager(InsecureTrustManagerFactory.INSTANCE);
        }
    }

    SslContext sslContext = sslContextBuilder.build();
    String hostname = config.getSslHostname();
    if (hostname == null || NetUtil.createByteArrayFromIpAddressString(hostname) != null) {
        hostname = config.getAddress().getHost();
    }

    SSLEngine sslEngine = sslContext.newEngine(ch.alloc(), hostname, config.getAddress().getPort());
    sslEngine.setSSLParameters(sslParams);

    SslHandler sslHandler = new SslHandler(sslEngine);
    ch.pipeline().addLast(sslHandler);
    ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {

        volatile boolean sslInitDone;

        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {
            if (sslInitDone) {
                super.channelActive(ctx);
            }
        }

        @Override
        public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
            if (!sslInitDone && (evt instanceof SslHandshakeCompletionEvent)) {
                SslHandshakeCompletionEvent e = (SslHandshakeCompletionEvent) evt;
                if (e.isSuccess()) {
                    sslInitDone = true;
                    ctx.fireChannelActive();
                } else {
                    RedisConnection connection = RedisConnection.getFrom(ctx.channel());
                    connection.getConnectionPromise().tryFailure(e.cause());
                }
            }

            super.userEventTriggered(ctx, evt);
        }

    });
}

From source file:org.rzo.netty.ahessian.application.jmx.remote.client.RPCClientSessionPipelineFactory.java

License:Apache License

public HandlerList getPipeline() throws Exception {
    HandlerList pipeline = new HandlerList();
    pipeline.addLast("logger", new OutLogger("1"));
    pipeline.addLast("reconnector", new ChannelInboundHandlerAdapter() {

        @Override/*w w  w.j a v a 2s  .  c o m*/
        public void channelInactive(ChannelHandlerContext ctx) {
            ctx.fireChannelInactive();
            System.out.println("channel closed wait to reconnect ...");
            timer.schedule(new TimerTask() {
                public void run() {
                    System.out.println("reconnecting...");
                    ChannelFuture f = _bootstrap.connect();
                    try {
                        System.out.println("future wait");
                        f.awaitUninterruptibly();
                        System.out.println("future wait terminated");
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    if (f.isSuccess())
                        System.out.println("connected");
                    else {
                        System.out.println("not connected");
                        // f.getChannel().close();
                    }

                }
            }, RECONNECT_DELAY);
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable e) {
            Throwable cause = e;
            if (cause instanceof ConnectException) {
                System.out.println("conection lost");
            }
            ctx.channel().close();
        }
    });
    pipeline.addLast("sessionFilter", _sessionFilter);

    return pipeline;
}

From source file:org.rzo.netty.mcast.bridge.MulticastAccessPoint.java

License:Apache License

public static void main(String[] args) {
    int port = Integer.parseInt(args[0]);

    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();

    ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class);

    bootstrap.childHandler(new ChannelPipelineFactory() {
        public HandlerList getPipeline() {
            return ChannelPipelineFactory.handlerList(new ChannelInboundHandlerAdapter() {

                @Override//from   ww w .j av  a2  s. c om
                public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                    if (mcast != null && mcast.isInit())
                        mcast.send((ByteBuf) msg);
                }

                @Override
                public void channelActive(ChannelHandlerContext ctx) throws Exception {
                    remoteChannels.add(ctx.channel());
                }

                @Override
                public void channelInactive(ChannelHandlerContext ctx) throws Exception {
                    remoteChannels.add(ctx.channel());
                }

                @Override
                public void exceptionCaught(ChannelHandlerContext paramChannelHandlerContext, Throwable e)
                        throws Exception {
                    Throwable cause = e.getCause();
                    System.out.println(e);
                }

            });
        }
    });
    try {
        bootstrap.bind(new InetSocketAddress(port)).sync();
    } catch (InterruptedException e1) {
        e1.printStackTrace();
    }

    try {
        mcast.init(new ChannelPipelineFactory() {
            public HandlerList getPipeline() {
                return ChannelPipelineFactory.handlerList(new ChannelInboundHandlerAdapter() {
                    @Override
                    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                        ByteBuf b = mcast.getMessage((ByteBuf) msg);
                        if (b == null)
                            return;
                        for (Channel c : remoteChannels) {
                            if (c.isActive())
                                c.write(b);
                        }
                    }

                });
            }
        });
    } catch (Exception e) {
        Constants.ahessianLogger.warn("", e);
    }

}

From source file:org.rzo.netty.mcast.bridge.MulticastAdapter.java

License:Apache License

public static void main(String[] args) throws Exception {
    String host = args[0];//ww  w .  j ava 2  s . c  o m
    int port = Integer.parseInt(args[1]);

    bootstrap = new Bootstrap();
    EventLoopGroup group = new OioEventLoopGroup();
    bootstrap.group(group);
    bootstrap.channel(OioDatagramChannel.class);

    bootstrap.remoteAddress(new InetSocketAddress(host, port));

    bootstrap.handler(new ChannelPipelineFactory() {
        public HandlerList getPipeline() {
            return ChannelPipelineFactory.handlerList(new ChannelInboundHandlerAdapter() {
                @Override
                public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                    if (mcast != null && mcast.isInit())
                        mcast.send((ByteBuf) msg);
                }

                @Override
                public void channelActive(ChannelHandlerContext ctx) {
                    timer.schedule(new TimerTask() {
                        public void run() {
                            bootstrap.connect();
                        }
                    }, RECONNECT_DELAY);
                }

                @Override
                public void exceptionCaught(ChannelHandlerContext ctx, Throwable e) {
                    Throwable cause = e.getCause();
                    if (cause instanceof ConnectException) {
                        System.out.println("conection lost: reconnecting...");
                    }
                    ctx.channel().close();
                }

            });
        }
    });

    ChannelFuture f = bootstrap.connect();
    channel = f.sync().channel();

    mcast.init(new ChannelPipelineFactory() {
        public HandlerList getPipeline() {
            return ChannelPipelineFactory.handlerList(new ChannelInboundHandlerAdapter() {
                @Override
                public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                    ByteBuf b = mcast.getMessage((ByteBuf) msg);
                    if (b == null)
                        return;
                    if (channel != null && channel.isActive())
                        channel.write(b);
                }

            });
        }
    });

}

From source file:org.rzo.netty.mcast.discovery.DiscoveryClient.java

License:Apache License

public void init() throws Exception {
    ChannelPipelineFactory factory = new ChannelPipelineFactory() {
        public HandlerList getPipeline() throws Exception {
            HandlerList pipeline = new HandlerList();
            pipeline.addLast("discoveryClient", new ChannelInboundHandlerAdapter() {

                @Override//from ww  w . j  av a2  s.c o m
                public void channelRead(ChannelHandlerContext ctx, Object e) throws Exception {
                    try {
                        String response = getStringMessage(((DatagramPacket) e).content());
                        InetSocketAddress remoteAddress = ((DatagramPacket) e).sender();
                        if (debug && logger != null)
                            logger.info("discoveryClient messageReceived " + response + "/" + remoteAddress);

                        if (response == null)
                            return;
                        String[] resp = response.split("&");
                        if (resp.length == 3) {
                            String remoteName = resp[0];
                            if (!name.equals(remoteName))
                                return;
                            if (!validate(((DatagramPacket) e).content(), remoteAddress))
                                return;
                            String host = resp[1];
                            // check the name. if not valid will
                            // cause an exception
                            InetAddress.getByName(host);
                            // get the port. if not a number will
                            // cause an exception
                            int port = Integer.parseInt(resp[2]);
                            if (!hosts.contains(response)) {
                                hosts.add(response);
                                for (DiscoveryListener listener : listeners) {
                                    listener.newHost(name, response);
                                }
                            }

                        }
                    } catch (Exception ex) {
                        Constants.ahessianLogger.warn("", ex);
                    }
                }
            });
            return pipeline;
        }

    };
    super.init(factory);

}

From source file:org.rzo.netty.mcast.discovery.DiscoveryServer.java

License:Apache License

public void init() throws Exception {
    if (host == null)
        host = whatIsMyIp();//ww w. ja v a2 s .  c o  m

    ChannelPipelineFactory factory = new ChannelPipelineFactory() {
        public HandlerList getPipeline() throws Exception {
            HandlerList pipeline = new HandlerList();
            pipeline.addLast("discoveryServer", new ChannelInboundHandlerAdapter() {

                @Override
                public void channelRead(ChannelHandlerContext ctx, Object e) throws Exception {
                    // System.out.println("discovery server received "+e);
                    String request = getStringMessage(((DatagramPacket) e).content());
                    InetSocketAddress remoteAddress = ((DatagramPacket) e).sender();
                    if (debug && logger != null)
                        logger.info("discoveryServer messageReceived " + request + "/" + remoteAddress);
                    if (request == null)
                        return;
                    if (name != null && name.equals(request) && host != null && port > 0) {
                        if (validate(((DatagramPacket) e).content(), remoteAddress))
                            send(Unpooled.wrappedBuffer((name + "&" + host + "&" + port).getBytes()));
                    } else if (debug && logger != null)
                        logger.info("discoveryServer request rejected");
                }

            });
            return pipeline;
        }

    };
    super.init(factory);
}