Example usage for io.netty.channel ChannelOption SO_KEEPALIVE

List of usage examples for io.netty.channel ChannelOption SO_KEEPALIVE

Introduction

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

Prototype

ChannelOption SO_KEEPALIVE

To view the source code for io.netty.channel ChannelOption SO_KEEPALIVE.

Click Source Link

Usage

From source file:org.proton.plug.test.minimalserver.MinimalServer.java

License:Apache License

public synchronized void start(String host, int port, final boolean sasl) throws Exception {
    this.host = host;
    this.port = port;
    this.sasl = sasl;

    if (channelClazz != null) {
        // Already started
        return;//from  ww w . j a  v a2 s. c  o m
    }

    int threadsToUse = Runtime.getRuntime().availableProcessors() * 3;
    channelClazz = NioServerSocketChannel.class;
    eventLoopGroup = new NioEventLoopGroup(threadsToUse, new SimpleServerThreadFactory("simple-server", true,
            Thread.currentThread().getContextClassLoader()));

    bootstrap = new ServerBootstrap();
    bootstrap.group(eventLoopGroup);
    bootstrap.channel(channelClazz);

    ChannelInitializer<Channel> factory = new ChannelInitializer<Channel>() {
        @Override
        public void initChannel(Channel channel) throws Exception {
            ChannelPipeline pipeline = channel.pipeline();
            pipeline.addLast("amqp-handler", new ProtocolDecoder());
        }
    };
    bootstrap.childHandler(factory);

    bootstrap.option(ChannelOption.SO_REUSEADDR, true).childOption(ChannelOption.SO_REUSEADDR, true)
            .childOption(ChannelOption.SO_KEEPALIVE, true).
            //       childOption(ChannelOption.AUTO_READ, false).
            childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);

    channelGroup = new DefaultChannelGroup("activemq-accepted-channels", GlobalEventExecutor.INSTANCE);

    serverChannelGroup = new DefaultChannelGroup("activemq-acceptor-channels", GlobalEventExecutor.INSTANCE);

    SocketAddress address;
    address = new InetSocketAddress(host, port);
    Channel serverChannel = bootstrap.bind(address).syncUninterruptibly().channel();
    serverChannelGroup.add(serverChannel);

}

From source file:org.pumpkindb.Client.java

License:Mozilla Public License

public void connect() {
    workerGroup = new NioEventLoopGroup();
    Bootstrap b = new Bootstrap();
    b.group(workerGroup);//  www.  j  a v  a2s  . c  o m
    b.channel(NioSocketChannel.class);
    b.option(ChannelOption.SO_KEEPALIVE, true);

    b.handler(new ChannelInitializer<SocketChannel>() {

        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline().addFirst(new LoggingHandler(LogLevel.DEBUG));

            ch.pipeline().addLast(new LengthFieldPrepender(4));
            ch.pipeline().addLast(new FrameEncoder());

            ch.pipeline().addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));

            ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
                @Override
                public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                    ByteBuf buf = (ByteBuf) msg;
                    messageHandler.accept(buf);
                }
            });
        }

    });

    ChannelFuture channelFuture = b.connect(host, port).syncUninterruptibly();

    channel = channelFuture.channel();

}

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.";

    ///*from   w  w  w .  jav  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!";

    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.";

    ////w w  w. java 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// w w  w . ja v  a 2  s.  com
 */
@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.funcobs.LifecycleTest.java

License:Open Source License

/**
 * Test that during unforced shutdown it:
 * <ul>//from   w w  w .j a  v  a  2 s  .  c o m
 * <l1>Await the return of all leased connections.</l1>
 * <li>Blocks the leasing of connections.</li>
 * <p/>
 * <p>Also test that leases are not granted during this time.</p>
 * </ul>
 *
 * @throws Exception
 */
@Test
public void testUnforcedShutdownDuringLease() throws Exception {
    TestPoolProviderListener ppl = new TestPoolProviderListener();
    final ArrayList<Object> serverReceivedMessages = new ArrayList<>();
    String testMessage = "The cat sat on the mat.";

    //
    // 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) {
            serverReceivedMessages.add(val);
            ctx.writeAndFlush(val);
        }
    });

    simpleServer.start();

    final CountDownLatch leaseExpiredHandlerCalled = new CountDownLatch(1);

    //
    // Build the pool.
    //

    NettyConnectionPoolBuilder ncb = new NettyConnectionPoolBuilder();
    ncb.withImmortalCount(2);
    ncb.withReaperIntervalMillis(1000); // Set short for testing..
    ncb.withLeaseExpiryHarvester(new FullPassSimpleLeaseReaper());
    ncb.withLeaseExpiredHandler(new LeaseExpiredHandler() {
        @Override
        public boolean closeExpiredLease(LeasedContext context, PoolProvider provider) {
            leaseExpiredHandlerCalled.countDown();
            return true; // Cause lease to be expired.
        }
    });

    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);

    LeasedChannel firstLease = ncp.lease(5, TimeUnit.SECONDS, "aardvarks");

    ncp.stop(false);

    //
    // Should not stop because channel is being leased.
    //
    TestCase.assertFalse(ppl.getStoppedLatch().await(1, TimeUnit.SECONDS));

    //
    // Should not grant lease as shutdown is pending.
    //
    try {
        ncp.lease(3, TimeUnit.SECONDS, "ground pigs");
        TestCase.fail();

    } catch (Exception ex) {

    }

    Future<LeasedChannel> future = ncp.leaseAsync(1, TimeUnit.SECONDS, "Erdferkel");
    try {
        future.get(1, TimeUnit.SECONDS);
        TestCase.fail(); // Should fail.
    } catch (Exception ex) {

    }

    ncp.leaseAsync(1, TimeUnit.SECONDS, "Erdferkel", new LeaseListener() {
        @Override
        public void leaseRequest(boolean success, LeasedChannel channel, Throwable th) {
            TestCase.assertFalse(success);
            TestCase.assertTrue(th instanceof IllegalArgumentException);
        }
    });

    firstLease.yield();

    TestCase.assertTrue(ppl.getStoppedLatch().await(5, TimeUnit.SECONDS));

    simpleServer.stop();

}

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

License:Open Source License

@Test
public void testLeaseCancellationViaFuture() throws Exception {
    TestPoolProviderListener ppl = new TestPoolProviderListener();
    final ArrayList<Object> serverReceivedMessages = new ArrayList<>();
    String testMessage = "The cat sat on the mat.";

    ////from w ww  .ja v a2 s .  c  o m
    // 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) {
            serverReceivedMessages.add(val);
            ctx.writeAndFlush(val);
        }
    });

    simpleServer.start();

    final CountDownLatch leaseExpiredHandlerCalled = new CountDownLatch(1);

    //
    // Build the pool.
    //

    NettyConnectionPoolBuilder ncb = new NettyConnectionPoolBuilder();
    ncb.withImmortalCount(1);
    ncb.withMaxEphemeralCount(0);
    ncb.withReaperIntervalMillis(1000); // Set short for testing..
    ncb.withLeaseExpiryHarvester(new FullPassSimpleLeaseReaper());
    ncb.withLeaseExpiredHandler(new LeaseExpiredHandler() {
        @Override
        public boolean closeExpiredLease(LeasedContext context, PoolProvider provider) {
            leaseExpiredHandlerCalled.countDown();
            return true; // Cause lease to be expired.
        }
    });

    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);

    //
    // Get the first lease.
    //
    LeasedChannel firstLease = ncp.lease(5, TimeUnit.SECONDS, "aardvarks");

    final AtomicBoolean failedInListener = new AtomicBoolean(false);

    Future<LeasedChannel> secondLease = ncp.leaseAsync(10, TimeUnit.SECONDS, "Erdferkel", new LeaseListener() {
        @Override
        public void leaseRequest(boolean success, LeasedChannel channel, Throwable th) {
            failedInListener.set(true);
        }
    });

    try {
        secondLease.get(1, TimeUnit.SECONDS);
        TestCase.fail();
    } catch (Exception ex) {
        TestCase.assertEquals(TimeoutException.class, ex.getClass());
    }

    secondLease.cancel(false); // The flag has no effect.

    firstLease.yield();

    //
    // Lease cancellation is asynchronous to the pool, but the detection of a canceled lease is done
    // 1. Before the lease logic executes on the lease request.
    // 2. After the lease logic executes, which will then cause an immediate yield to execute.
    //
    // However if the lease is pending it will be sitting in a holding queue and will be removed from there.
    //
    // The future listener event is driven from the future so calling cancel() on that will fire
    // the future listener on the thread that called cancel but the pool may fire leaseCanceled
    // potentially at some point in between because it is driven from the pools thread.
    //
    // Between those two sources 0f information the order of notification is indeterminate.

    //
    // The call to cancel() may also through an illegal state exception if the granting of the lease is in
    // progress at that moment.
    //
    // For testing sake we give it a moment to settle.

    Thread.sleep(500); // Excessive.

    TestCase.assertTrue(secondLease.isCancelled());
    TestCase.assertTrue(failedInListener.get());
    TestCase.assertTrue(ppl.getLeaseCanceled().await(5, TimeUnit.SECONDS));

    secondLease = ncp.leaseAsync(10, TimeUnit.SECONDS, "Foo");

    try {
        LeasedChannel lc = secondLease.get(1, TimeUnit.SECONDS);
        TestCase.assertEquals("Foo", lc.getUserObject());
    } catch (Exception ex) {
        TestCase.fail();
    }

    ncp.stop(true);
    TestCase.assertTrue(ppl.getStoppedLatch().await(5, TimeUnit.SECONDS));

    simpleServer.stop();
}

From source file:org.r358.poolnetty.test.MultiConnectionTest.java

License:Open Source License

/**
 * Test the creation and leasing of connections and harvesting of expired leases.
 *
 * @throws Exception/*from w  ww . j av  a 2s. c  o m*/
 */
@Test
public void testHarvestingWithMultiples() throws Exception {

    final int maxImmortal = 5;
    final int maxEphemeral = 10;
    final int maxAll = maxEphemeral + maxImmortal;

    TestPoolProviderListener ppl = new TestPoolProviderListener();
    final ArrayList<Object> serverReceivedMessages = new ArrayList<>();
    String testMessage = "The cat sat on the mat.";

    //
    // 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) {
            serverReceivedMessages.add(val);
            ctx.writeAndFlush(val);
        }
    });

    simpleServer.start();

    final CountDownLatch leaseExpiredHandlerCalled = new CountDownLatch(1);

    //
    // Build the pool.
    //

    NettyConnectionPoolBuilder ncb = new NettyConnectionPoolBuilder();
    ncb.withImmortalCount(maxImmortal);
    ncb.withMaxEphemeralCount(maxEphemeral);
    ncb.withEphemeralLifespanMillis(5000);
    ncb.withReaperIntervalMillis(1000); // Set short for testing..
    ncb.withLeaseExpiryHarvester(new FullPassSimpleLeaseReaper());
    ncb.withLeaseExpiredHandler(new LeaseExpiredHandler() {
        @Override
        public boolean closeExpiredLease(LeasedContext context, PoolProvider provider) {
            leaseExpiredHandlerCalled.countDown();
            return true; // Cause lease to be expired.
        }
    });

    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);

    final CountDownLatch leaseAll = new CountDownLatch(maxAll);

    final CountDownLatch harvestedLeases = new CountDownLatch(maxAll);

    final CountDownLatch closedConnections = new CountDownLatch(maxEphemeral);

    final CountDownLatch openedConnections = new CountDownLatch(maxAll + maxImmortal);

    ncp.addListener(new PoolProviderListenerAdapter() {

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

        @Override
        public void leaseGranted(PoolProvider provider, Channel channel, Object userObject) {
            leaseAll.countDown();
        }

        @Override
        public void leaseExpired(PoolProvider provider, Channel channel, Object userObject) {
            harvestedLeases.countDown();
        }

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

    TestCase.assertTrue(ncp.start(10, TimeUnit.SECONDS));

    TestCase.assertEquals(5, ((List) TestUtil.getField(ncp, "immortalContexts")).size());
    TestCase.assertEquals(0, ((List) TestUtil.getField(ncp, "ephemeralContexts")).size());

    //
    // Lease all 15 connections which is 5 immortal and 10 ephemeral.
    //

    List<LeasedChannel> leasedChannels = new ArrayList<>();

    for (int t = 0; t < 15; t++) {
        leasedChannels.add(ncp.lease(2, TimeUnit.SECONDS, t));
    }

    TestCase.assertTrue(leaseAll.await(5, TimeUnit.SECONDS));

    TestCase.assertEquals(0, ((List) TestUtil.getField(ncp, "immortalContexts")).size());
    TestCase.assertEquals(0, ((List) TestUtil.getField(ncp, "ephemeralContexts")).size());

    TestCase.assertEquals(maxAll, ((List) TestUtil.getField(ncp, "leasedContexts")).size());
    TestCase.assertEquals(maxAll, ((Set) TestUtil.getField(ncp, "leasedContextSet")).size());

    //
    // Over this period the leases should all expire and drop back to the pool.
    //

    TestCase.assertTrue(harvestedLeases.await(10, TimeUnit.SECONDS));

    //
    // Wait for ephemeral connections to be closed.
    //

    TestCase.assertTrue(closedConnections.await(10, TimeUnit.SECONDS));

    //
    // At this point we wait until the replace immortal connections are created.
    //

    // Total opened connections should be maxAll+maxImmortal.
    TestCase.assertTrue(openedConnections.await(10, TimeUnit.SECONDS));

    TestCase.assertEquals(5, ((List) TestUtil.getField(ncp, "immortalContexts")).size());

    TestCase.assertEquals(0, ((List) TestUtil.getField(ncp, "ephemeralContexts")).size());

    TestCase.assertEquals(0, ((List) TestUtil.getField(ncp, "leasedContexts")).size());
    TestCase.assertEquals(0, ((Set) TestUtil.getField(ncp, "leasedContextSet")).size());

    simpleServer.stop();

}

From source file:org.r358.poolnetty.test.MultiConnectionTest.java

License:Open Source License

@Test
public void leaseAndYield() throws Exception {
    final int maxImmortal = 5;
    final int maxEphemeral = 10;
    final int maxAll = maxEphemeral + maxImmortal;

    TestPoolProviderListener ppl = new TestPoolProviderListener();
    final ArrayList<Object> serverReceivedMessages = new ArrayList<>();
    String testMessage = "The cat sat on the mat.";

    ///*from  w w  w .  j av a 2  s . c  o m*/
    // 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) {
            serverReceivedMessages.add(val);
            ctx.writeAndFlush(val);
        }
    });

    simpleServer.start();

    final CountDownLatch leaseExpiredHandlerCalled = new CountDownLatch(1);

    //
    // Build the pool.
    //

    NettyConnectionPoolBuilder ncb = new NettyConnectionPoolBuilder();
    ncb.withImmortalCount(maxImmortal);
    ncb.withMaxEphemeralCount(maxEphemeral);
    ncb.withEphemeralLifespanMillis(5000);
    ncb.withReaperIntervalMillis(1000); // Set short for testing..
    ncb.withLeaseExpiryHarvester(new FullPassSimpleLeaseReaper());
    ncb.withLeaseExpiredHandler(new LeaseExpiredHandler() {
        @Override
        public boolean closeExpiredLease(LeasedContext context, PoolProvider provider) {
            leaseExpiredHandlerCalled.countDown();
            return true; // Cause lease to be expired.
        }
    });

    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);

    final CountDownLatch leaseAll = new CountDownLatch(maxAll);

    final CountDownLatch closedConnections = new CountDownLatch(maxEphemeral);

    final CountDownLatch openedConnections = new CountDownLatch(maxAll);

    final CountDownLatch yieldedConnections = new CountDownLatch(maxAll);

    ncp.addListener(new PoolProviderListenerAdapter() {

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

        @Override
        public void leaseGranted(PoolProvider provider, Channel channel, Object userObject) {
            leaseAll.countDown();
        }

        @Override
        public void leaseYield(PoolProvider provider, Channel channel, Object userObject) {
            yieldedConnections.countDown();
        }

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

    TestCase.assertTrue(ncp.start(10, TimeUnit.SECONDS));

    TestCase.assertEquals(5, ((List) TestUtil.getField(ncp, "immortalContexts")).size());
    TestCase.assertEquals(0, ((List) TestUtil.getField(ncp, "ephemeralContexts")).size());

    //
    // Lease all 15 connections which is 5 immortal and 10 ephemeral.
    //

    List<LeasedChannel> leasedChannels = new ArrayList<>();

    for (int t = 0; t < maxAll; t++) {
        leasedChannels.add(ncp.lease(2, TimeUnit.SECONDS, t));
    }

    TestCase.assertTrue(leaseAll.await(5, TimeUnit.SECONDS));

    TestCase.assertEquals(0, ((List) TestUtil.getField(ncp, "immortalContexts")).size());
    TestCase.assertEquals(0, ((List) TestUtil.getField(ncp, "ephemeralContexts")).size());

    TestCase.assertEquals(maxAll, ((List) TestUtil.getField(ncp, "leasedContexts")).size());
    TestCase.assertEquals(maxAll, ((Set) TestUtil.getField(ncp, "leasedContextSet")).size());

    while (!leasedChannels.isEmpty()) {
        leasedChannels.remove(0).yield();
    }

    TestCase.assertTrue(yieldedConnections.await(10, TimeUnit.SECONDS));

    //
    // At this point we have yielded the leases so we need to wait for
    // the ephemeral connections to be closed.
    //

    //
    // Wait for ephemeral connections to be closed.
    //

    TestCase.assertTrue(closedConnections.await(20, TimeUnit.SECONDS));

    //
    // At this point we wait until the replace immortal connections are created.
    //

    // Total opened connections should be maxAll.
    TestCase.assertTrue(openedConnections.await(10, TimeUnit.SECONDS));

    TestCase.assertEquals(5, ((List) TestUtil.getField(ncp, "immortalContexts")).size());

    TestCase.assertEquals(0, ((List) TestUtil.getField(ncp, "ephemeralContexts")).size());

    TestCase.assertEquals(0, ((List) TestUtil.getField(ncp, "leasedContexts")).size());
    TestCase.assertEquals(0, ((Set) TestUtil.getField(ncp, "leasedContextSet")).size());

    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);/* w ww  .  j a va2 s .  c  om*/
    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);

}