List of usage examples for io.netty.channel ChannelOption AUTO_READ
ChannelOption AUTO_READ
To view the source code for io.netty.channel ChannelOption AUTO_READ.
Click Source Link
From source file:org.columbia.parikshan.proxy.NettyProxyFrontendHandler.java
License:Apache License
@Override public void channelActive(ChannelHandlerContext ctx) { final Channel inboundChannel = ctx.channel(); // Start the connection attempt to SERVER 2 Bootstrap server2Bootstrap = new Bootstrap(); server2Bootstrap.group(inboundChannel.eventLoop()).channel(ctx.channel().getClass()) .handler(new NettyProxyBackendHandler(inboundChannel)).option(ChannelOption.AUTO_READ, false); ChannelFuture server2Future = server2Bootstrap.connect(remoteHost, remotePort); server2OutboundChannel = server2Future.channel(); server2Future.addListener(new ChannelFutureListener() { @Override//from w ww . j a v a 2s .c o m public void operationComplete(ChannelFuture future) { if (future.isSuccess()) { // connection complete start to read first data inboundChannel.read(); } else { // Close the connection if the connection attempt has failed. inboundChannel.close(); } } }); }
From source file:org.eclipse.californium.elements.tcp.TcpClientConnector.java
License:Open Source License
@Override public synchronized void start() throws IOException { if (rawDataChannel == null) { throw new IllegalStateException("Cannot start without message handler."); }//from w w w . j a va 2s.c o m if (workerGroup != null) { throw new IllegalStateException("Connector already started"); } workerGroup = new NioEventLoopGroup(numberOfThreads); poolMap = new AbstractChannelPoolMap<SocketAddress, ChannelPool>() { @Override protected ChannelPool newPool(SocketAddress key) { Bootstrap bootstrap = new Bootstrap().group(workerGroup).channel(NioSocketChannel.class) .option(ChannelOption.SO_KEEPALIVE, true).option(ChannelOption.AUTO_READ, true) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeoutMillis).remoteAddress(key); // We multiplex over the same TCP connection, so don't acquire // more than one connection per endpoint. // TODO: But perhaps we could make it a configurable property. if (USE_FIXED_CONNECTION_POOL) { return new FixedChannelPool(bootstrap, new MyChannelPoolHandler(key), 1); } else { return new SimpleChannelPool(bootstrap, new MyChannelPoolHandler(key)); } } }; }
From source file:org.eclipse.californium.elements.tcp.TcpServerConnector.java
License:Open Source License
@Override public synchronized void start() throws IOException { if (rawDataChannel == null) { throw new IllegalStateException("Cannot start without message handler."); }// w ww . ja v a 2 s.com if (bossGroup != null) { throw new IllegalStateException("Connector already started"); } if (workerGroup != null) { throw new IllegalStateException("Connector already started"); } bossGroup = new NioEventLoopGroup(1); workerGroup = new NioEventLoopGroup(numberOfThreads); ServerBootstrap bootstrap = new ServerBootstrap(); // server socket bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .childHandler(new ChannelRegistry()).option(ChannelOption.SO_BACKLOG, 100) .option(ChannelOption.AUTO_READ, true).childOption(ChannelOption.SO_KEEPALIVE, true); // Start the server. ChannelFuture channelFuture = bootstrap.bind(localAddress).syncUninterruptibly(); if (channelFuture.isSuccess() && 0 == localAddress.getPort()) { // replace port with the assigned one InetSocketAddress listenAddress = (InetSocketAddress) channelFuture.channel().localAddress(); effectiveLocalAddress = new InetSocketAddress(localAddress.getAddress(), listenAddress.getPort()); } }
From source file:org.kobeyoung81.dummyhttpproxy.HexDumpProxy.java
License:Apache License
public static void main(String[] args) throws Exception { if (args.length < 4) { System.err.println("Too less arguments! " + args.length + " (Role LocalPort RemoteHost RemotePort)"); return;//from w w w.j a v a 2 s .co m } ROLE = args[0]; LOCAL_PORT = Integer.parseInt(args[1]); REMOTE_HOST = args[2]; REMOTE_PORT = Integer.parseInt(args[3]); System.err.println("Proxying *:" + LOCAL_PORT + " to " + REMOTE_HOST + ':' + REMOTE_PORT + " ..."); // Configure the bootstrap. EventLoopGroup bossGroup = new NioEventLoopGroup(1); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .childHandler(new HexDumpProxyInitializer(ROLE, REMOTE_HOST, REMOTE_PORT)) .childOption(ChannelOption.AUTO_READ, false).bind(LOCAL_PORT).sync().channel().closeFuture() .sync(); } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } }
From source file:org.kobeyoung81.dummyhttpproxy.HexDumpProxyFrontendHandler.java
License:Apache License
@Override public void channelActive(ChannelHandlerContext ctx) { final Channel inboundChannel = ctx.channel(); // Start the connection attempt. Bootstrap b = new Bootstrap(); b.group(inboundChannel.eventLoop()).channel(ctx.channel().getClass()) .handler(new HexDumpProxyBackendHandler(inboundChannel)).option(ChannelOption.AUTO_READ, false); ChannelFuture f = b.connect(remoteHost, remotePort); outboundChannel = f.channel();//from w w w.j a v a 2s. c o m if ("local".equals(role)) { outboundChannel.pipeline().addLast(new SnappyFramedEncoder()); outboundChannel.pipeline().addLast(new DummyHttpRequestEncoder()); outboundChannel.pipeline().addFirst(new SnappyFramedDecoder()); outboundChannel.pipeline().addFirst(new DummyHttpResponseDecoder()); } f.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) { if (future.isSuccess()) { // connection complete start to read first data inboundChannel.read(); } else { // Close the connection if the connection attempt has // failed. inboundChannel.close(); } } }); }
From source file:org.kobeyoung81.hexdumpproxy.HexDumpProxyFrontendHandler.java
License:Apache License
@Override public void channelActive(ChannelHandlerContext ctx) { final Channel inboundChannel = ctx.channel(); // Start the connection attempt. Bootstrap b = new Bootstrap(); b.group(inboundChannel.eventLoop()).channel(ctx.channel().getClass()) .handler(new HexDumpProxyBackendHandler(inboundChannel)).option(ChannelOption.AUTO_READ, false); ChannelFuture f = b.connect(remoteHost, remotePort); outboundChannel = f.channel();/*from w w w . ja v a2 s . c o m*/ if ("local".equals(role)) { outboundChannel.pipeline().addLast(new SnappyFramedEncoder()); outboundChannel.pipeline().addFirst(new SnappyFramedDecoder()); } f.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) { if (future.isSuccess()) { // connection complete start to read first data inboundChannel.read(); } else { // Close the connection if the connection attempt has // failed. inboundChannel.close(); } } }); }
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 ww. ja v 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 . j a va2s . 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 ww.j av a 2 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.funcobs.LifecycleTest.java
License:Open Source License
/** * Test that during unforced shutdown it: * <ul>/*from w w w . j a v a2 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(); }