List of usage examples for io.netty.channel ChannelPipeline addLast
ChannelPipeline addLast(EventExecutorGroup group, ChannelHandler... handlers);
From source file:com.gemstone.gemfire.redis.GemFireRedisServer.java
License:Apache License
/** * Helper method to start the server listening for connections. The * server is bound to the port specified by {@link GemFireRedisServer#serverPort} * // ww w. j a v a 2 s .c o m * @throws IOException * @throws InterruptedException */ private void startRedisServer() throws IOException, InterruptedException { ThreadFactory selectorThreadFactory = new ThreadFactory() { private final AtomicInteger counter = new AtomicInteger(); @Override public Thread newThread(Runnable r) { Thread t = new Thread(r); t.setName("GemFireRedisServer-SelectorThread-" + counter.incrementAndGet()); t.setDaemon(true); return t; } }; ThreadFactory workerThreadFactory = new ThreadFactory() { private final AtomicInteger counter = new AtomicInteger(); @Override public Thread newThread(Runnable r) { Thread t = new Thread(r); t.setName("GemFireRedisServer-WorkerThread-" + counter.incrementAndGet()); return t; } }; bossGroup = null; workerGroup = null; Class<? extends ServerChannel> socketClass = null; if (singleThreadPerConnection) { bossGroup = new OioEventLoopGroup(Integer.MAX_VALUE, selectorThreadFactory); workerGroup = new OioEventLoopGroup(Integer.MAX_VALUE, workerThreadFactory); socketClass = OioServerSocketChannel.class; } else { bossGroup = new NioEventLoopGroup(this.numSelectorThreads, selectorThreadFactory); workerGroup = new NioEventLoopGroup(this.numWorkerThreads, workerThreadFactory); socketClass = NioServerSocketChannel.class; } InternalDistributedSystem system = (InternalDistributedSystem) cache.getDistributedSystem(); String pwd = system.getConfig().getRedisPassword(); final byte[] pwdB = Coder.stringToBytes(pwd); ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup).channel(socketClass).childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { if (logger.fineEnabled()) logger.fine("GemFireRedisServer-Connection established with " + ch.remoteAddress()); ChannelPipeline p = ch.pipeline(); p.addLast(ByteToCommandDecoder.class.getSimpleName(), new ByteToCommandDecoder()); p.addLast(ExecutionHandlerContext.class.getSimpleName(), new ExecutionHandlerContext(ch, cache, regionCache, GemFireRedisServer.this, pwdB)); } }).option(ChannelOption.SO_REUSEADDR, true).option(ChannelOption.SO_RCVBUF, getBufferSize()) .childOption(ChannelOption.SO_KEEPALIVE, true) .childOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, GemFireRedisServer.connectTimeoutMillis) .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT); // Bind and start to accept incoming connections. ChannelFuture f = b.bind(new InetSocketAddress(getBindAddress(), serverPort)).sync(); if (this.logger.infoEnabled()) { String logMessage = "GemFireRedisServer started {" + getBindAddress() + ":" + serverPort + "}, Selector threads: " + this.numSelectorThreads; if (this.singleThreadPerConnection) logMessage += ", One worker thread per connection"; else logMessage += ", Worker threads: " + this.numWorkerThreads; this.logger.info(logMessage); } this.serverChannel = f.channel(); }
From source file:com.github.ambry.rest.NettyServerChannelInitializer.java
License:Open Source License
@Override protected void initChannel(SocketChannel ch) throws Exception { // If channel handler implementations are not annotated with @Sharable, Netty creates a new instance of every class // in the pipeline for every connection. // i.e. if there are a 1000 active connections there will be a 1000 NettyMessageProcessor instances. ChannelPipeline pipeline = ch.pipeline(); // connection stats handler to track connection related metrics pipeline.addLast("connectionStatsHandler", connectionStatsHandler); // if SSL is enabled, add an SslHandler before the HTTP codec if (sslFactory != null) { InetSocketAddress peerAddress = ch.remoteAddress(); String peerHost = peerAddress.getHostName(); int peerPort = peerAddress.getPort(); SslHandler sslHandler = new SslHandler( sslFactory.createSSLEngine(peerHost, peerPort, SSLFactory.Mode.SERVER)); pipeline.addLast("sslHandler", sslHandler); }//from w w w . j ava2 s . co m pipeline // for http encoding/decoding. .addLast("codec", new HttpServerCodec(nettyConfig.nettyServerMaxInitialLineLength, nettyConfig.nettyServerMaxHeaderSize, nettyConfig.nettyServerMaxChunkSize)) // for health check request handling .addLast("healthCheckHandler", new HealthCheckHandler(restServerState, nettyMetrics)) // for public access logging .addLast("publicAccessLogHandler", new PublicAccessLogHandler(publicAccessLogger, nettyMetrics)) // for detecting connections that have been idle too long - probably because of an error. .addLast("idleStateHandler", new IdleStateHandler(0, 0, nettyConfig.nettyServerIdleTimeSeconds)) // for safe writing of chunks for responses .addLast("chunker", new ChunkedWriteHandler()) // custom processing class that interfaces with a BlobStorageService. .addLast("processor", new NettyMessageProcessor(nettyMetrics, nettyConfig, requestHandler)); }
From source file:com.github.kpavlov.jreactive8583.netty.pipeline.Iso8583ChannelInitializer.java
License:Apache License
@Override public void initChannel(C ch) throws Exception { final ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast("lengthFieldFameDecoder", new LengthFieldBasedFrameDecoder( configuration.getMaxFrameLength(), 0, headerLength, 0, headerLength)); pipeline.addLast("iso8583Decoder", createIso8583Decoder(isoMessageFactory)); pipeline.addLast("iso8583Encoder", isoMessageEncoder); if (configuration.addLoggingHandler()) { pipeline.addLast(workerGroup, "logging", loggingHandler); }//from w ww. j a va2 s . c o m if (configuration.replyOnError()) { pipeline.addLast(workerGroup, "replyOnError", loggingHandler); } pipeline.addLast("idleState", new IdleStateHandler(0, 0, configuration.getIdleTimeout())); pipeline.addLast("idleEventHandler", new IdleEventHandler(isoMessageFactory)); if (customChannelHandlers != null) { pipeline.addLast(workerGroup, customChannelHandlers); } if (configurer != null) { configurer.configurePipeline(pipeline, configuration); } }
From source file:com.github.rmannibucau.featuredmock.http.FeaturedChannelInitializer.java
License:Apache License
@Override protected void initChannel(final SocketChannel ch) throws Exception { final ChannelPipeline pipeline = ch.pipeline(); if (sslHandler != null) { pipeline.addLast("ssl", sslHandler); }//from ww w. j a v a 2 s . c om pipeline.addLast("decoder", new HttpRequestDecoder()) .addLast("aggregator", new HttpObjectAggregator(Integer.MAX_VALUE)) .addLast("encoder", new HttpResponseEncoder()).addLast("chunked-writer", new ChunkedWriteHandler()) .addLast("featured-mock-server", handler); }
From source file:com.github.sinsinpub.pero.manual.proxyhandler.Socks5ProxyServer.java
License:Apache License
@Override protected void configure(SocketChannel ch) throws Exception { ChannelPipeline p = ch.pipeline(); switch (testMode) { case INTERMEDIARY: p.addLast(DECODER, new Socks5InitialRequestDecoder()); p.addLast(ENCODER, Socks5ServerEncoder.DEFAULT); p.addLast(new Socks5IntermediaryHandler()); break;/*from w w w. j a v a 2 s . co m*/ case TERMINAL: p.addLast(DECODER, new Socks5InitialRequestDecoder()); p.addLast(ENCODER, Socks5ServerEncoder.DEFAULT); p.addLast(new Socks5TerminalHandler()); break; case UNRESPONSIVE: p.addLast(UnresponsiveHandler.INSTANCE); break; } }
From source file:com.github.spapageo.jannel.client.JannelClient.java
License:Open Source License
protected ClientSession createSession(Channel channel, ClientSessionConfiguration config, @Nullable SessionHandler sessionHandler) { ClientSession session = new ClientSession(config, channel, timer, sessionHandler); ChannelPipeline pipeline = channel.pipeline(); if (config.getWriteTimeout() > 0) { pipeline.addLast(HandlerType.WRITE_TIMEOUT_HANDLER.name(), channelHandlerProvider .getChangeHandler(HandlerType.WRITE_TIMEOUT_HANDLER, config, session, transcoder)); }/*from w w w .jav a 2 s .co m*/ pipeline.addLast(HandlerType.LENGTH_FRAME_DECODER.name(), channelHandlerProvider.getChangeHandler(HandlerType.LENGTH_FRAME_DECODER, config, session, transcoder)) .addLast(HandlerType.LENGTH_FRAME_ENCODER.name(), channelHandlerProvider.getChangeHandler(HandlerType.LENGTH_FRAME_ENCODER, config, session, transcoder)) .addLast(HandlerType.MESSAGE_DECODER.name(), channelHandlerProvider.getChangeHandler(HandlerType.MESSAGE_DECODER, config, session, transcoder)) .addLast(HandlerType.MESSAGE_ENCODER.name(), channelHandlerProvider.getChangeHandler(HandlerType.MESSAGE_ENCODER, config, session, transcoder)) .addLast(HandlerType.MESSAGE_LOGGER.name(), channelHandlerProvider.getChangeHandler(HandlerType.MESSAGE_LOGGER, config, session, transcoder)) .addLast(sessionExecutor, HandlerType.SESSION_WRAPPER.name(), channelHandlerProvider.getChangeHandler(HandlerType.SESSION_WRAPPER, config, session, transcoder)) //removes the placeholder handler that we added earlier .remove(DummyChannelHandler.class); return session; }
From source file:com.github.spapageo.jannel.client.JannelClientTest.java
License:Open Source License
@Test public void testIdentifyAddsTheCorrectlyHandlersToThePipelineWithEnabledWriteTimeout() throws Exception { Channel channel = mock(Channel.class, Answers.RETURNS_SMART_NULLS.get()); mockWriteHandler = mock(ChannelHandler.class); DefaultChannelPromise completedFuture = new DefaultChannelPromise(channel); completedFuture.setSuccess();// www . java 2s.c o m ChannelPipeline channelPipeline = mock(ChannelPipeline.class); when(channelPipeline.addLast(anyString(), any(ChannelHandler.class))).thenReturn(channelPipeline); when(channelPipeline.addLast(any(EventExecutorGroup.class), anyString(), any(ChannelHandler.class))) .thenReturn(channelPipeline); when(channel.pipeline()).thenReturn(channelPipeline); when(channel.isActive()).thenReturn(true); when(channel.writeAndFlush(any())).thenReturn(completedFuture); when(channelHandlerProvider.getChangeHandler(eq(HandlerType.WRITE_TIMEOUT_HANDLER), any(ClientSessionConfiguration.class), any(ClientSession.class), any(Transcoder.class))) .thenReturn(mockWriteHandler); when(channelHandlerProvider.getChangeHandler(eq(HandlerType.LENGTH_FRAME_ENCODER), any(ClientSessionConfiguration.class), any(ClientSession.class), any(Transcoder.class))) .thenReturn(mockLengthWriteHandler); when(channelHandlerProvider.getChangeHandler(eq(HandlerType.LENGTH_FRAME_DECODER), any(ClientSessionConfiguration.class), any(ClientSession.class), any(Transcoder.class))) .thenReturn(mockLengthReadHandler); when(channelHandlerProvider.getChangeHandler(eq(HandlerType.MESSAGE_ENCODER), any(ClientSessionConfiguration.class), any(ClientSession.class), any(Transcoder.class))) .thenReturn(mockEncoderHandler); when(channelHandlerProvider.getChangeHandler(eq(HandlerType.MESSAGE_DECODER), any(ClientSessionConfiguration.class), any(ClientSession.class), any(Transcoder.class))) .thenReturn(mockDecoderHandler); when(channelHandlerProvider.getChangeHandler(eq(HandlerType.MESSAGE_LOGGER), any(ClientSessionConfiguration.class), any(ClientSession.class), any(Transcoder.class))) .thenReturn(mockLoggerHandler); when(channelHandlerProvider.getChangeHandler(eq(HandlerType.SESSION_WRAPPER), any(ClientSessionConfiguration.class), any(ClientSession.class), any(Transcoder.class))) .thenReturn(mockSessionHandler); when(bootstrap.connect(anyString(), anyInt())).thenReturn(completedFuture); InOrder pipelineOrder = inOrder(channelPipeline); ClientSessionConfiguration configuration = new ClientSessionConfiguration(); configuration.setWriteTimeout(1000); jannelClient.identify(configuration, null); pipelineOrder.verify(channelPipeline).addLast(HandlerType.WRITE_TIMEOUT_HANDLER.name(), mockWriteHandler); pipelineOrder.verify(channelPipeline).addLast(HandlerType.LENGTH_FRAME_DECODER.name(), mockLengthReadHandler); pipelineOrder.verify(channelPipeline).addLast(HandlerType.LENGTH_FRAME_ENCODER.name(), mockLengthWriteHandler); pipelineOrder.verify(channelPipeline).addLast(HandlerType.MESSAGE_DECODER.name(), mockDecoderHandler); pipelineOrder.verify(channelPipeline).addLast(HandlerType.MESSAGE_ENCODER.name(), mockEncoderHandler); pipelineOrder.verify(channelPipeline).addLast(HandlerType.MESSAGE_LOGGER.name(), mockLoggerHandler); pipelineOrder.verify(channelPipeline).addLast(eventExecutors, HandlerType.SESSION_WRAPPER.name(), mockSessionHandler); pipelineOrder.verify(channelPipeline).remove(JannelClient.DummyChannelHandler.class); verify(channelHandlerProvider).getChangeHandler(eq(HandlerType.WRITE_TIMEOUT_HANDLER), eq(configuration), any(ClientSession.class), eq(transcoder)); verify(channelHandlerProvider).getChangeHandler(eq(HandlerType.LENGTH_FRAME_DECODER), eq(configuration), any(ClientSession.class), eq(transcoder)); verify(channelHandlerProvider).getChangeHandler(eq(HandlerType.LENGTH_FRAME_ENCODER), eq(configuration), any(ClientSession.class), eq(transcoder)); verify(channelHandlerProvider).getChangeHandler(eq(HandlerType.MESSAGE_DECODER), eq(configuration), any(ClientSession.class), eq(transcoder)); verify(channelHandlerProvider).getChangeHandler(eq(HandlerType.MESSAGE_ENCODER), eq(configuration), any(ClientSession.class), eq(transcoder)); verify(channelHandlerProvider).getChangeHandler(eq(HandlerType.MESSAGE_LOGGER), eq(configuration), any(ClientSession.class), eq(transcoder)); verify(channelHandlerProvider).getChangeHandler(eq(HandlerType.SESSION_WRAPPER), eq(configuration), any(ClientSession.class), eq(transcoder)); }
From source file:com.github.spapageo.jannel.client.JannelClientTest.java
License:Open Source License
@Test public void testIdentifyAddsTheCorrectlyHandlersToThePipelineWithDisabledWriteTimeout() throws Exception { Channel channel = mock(Channel.class, Answers.RETURNS_SMART_NULLS.get()); DefaultChannelPromise completedFuture = new DefaultChannelPromise(channel); completedFuture.setSuccess();//from ww w. ja va 2 s . c om ChannelPipeline channelPipeline = mock(ChannelPipeline.class); when(channelPipeline.addLast(anyString(), any(ChannelHandler.class))).thenReturn(channelPipeline); when(channelPipeline.addLast(any(EventExecutorGroup.class), anyString(), any(ChannelHandler.class))) .thenReturn(channelPipeline); when(channel.pipeline()).thenReturn(channelPipeline); when(channel.isActive()).thenReturn(true); when(channel.writeAndFlush(any())).thenReturn(completedFuture); when(channelHandlerProvider.getChangeHandler(eq(HandlerType.WRITE_TIMEOUT_HANDLER), any(ClientSessionConfiguration.class), any(ClientSession.class), any(Transcoder.class))) .thenReturn(mockWriteHandler); when(channelHandlerProvider.getChangeHandler(eq(HandlerType.LENGTH_FRAME_ENCODER), any(ClientSessionConfiguration.class), any(ClientSession.class), any(Transcoder.class))) .thenReturn(mockLengthWriteHandler); when(channelHandlerProvider.getChangeHandler(eq(HandlerType.LENGTH_FRAME_DECODER), any(ClientSessionConfiguration.class), any(ClientSession.class), any(Transcoder.class))) .thenReturn(mockLengthReadHandler); when(channelHandlerProvider.getChangeHandler(eq(HandlerType.MESSAGE_ENCODER), any(ClientSessionConfiguration.class), any(ClientSession.class), any(Transcoder.class))) .thenReturn(mockEncoderHandler); when(channelHandlerProvider.getChangeHandler(eq(HandlerType.MESSAGE_DECODER), any(ClientSessionConfiguration.class), any(ClientSession.class), any(Transcoder.class))) .thenReturn(mockDecoderHandler); when(channelHandlerProvider.getChangeHandler(eq(HandlerType.MESSAGE_LOGGER), any(ClientSessionConfiguration.class), any(ClientSession.class), any(Transcoder.class))) .thenReturn(mockLoggerHandler); when(channelHandlerProvider.getChangeHandler(eq(HandlerType.SESSION_WRAPPER), any(ClientSessionConfiguration.class), any(ClientSession.class), any(Transcoder.class))) .thenReturn(mockSessionHandler); when(bootstrap.connect(anyString(), anyInt())).thenReturn(completedFuture); InOrder pipelineOrder = inOrder(channelPipeline); ClientSessionConfiguration configuration = new ClientSessionConfiguration(); jannelClient.identify(configuration, null); pipelineOrder.verify(channelPipeline).addLast(HandlerType.LENGTH_FRAME_DECODER.name(), mockLengthReadHandler); pipelineOrder.verify(channelPipeline).addLast(HandlerType.LENGTH_FRAME_ENCODER.name(), mockLengthWriteHandler); pipelineOrder.verify(channelPipeline).addLast(HandlerType.MESSAGE_DECODER.name(), mockDecoderHandler); pipelineOrder.verify(channelPipeline).addLast(HandlerType.MESSAGE_ENCODER.name(), mockEncoderHandler); pipelineOrder.verify(channelPipeline).addLast(HandlerType.MESSAGE_LOGGER.name(), mockLoggerHandler); pipelineOrder.verify(channelPipeline).addLast(eventExecutors, HandlerType.SESSION_WRAPPER.name(), mockSessionHandler); pipelineOrder.verify(channelPipeline).remove(JannelClient.DummyChannelHandler.class); verify(channelHandlerProvider, times(0)).getChangeHandler(eq(HandlerType.WRITE_TIMEOUT_HANDLER), eq(configuration), any(ClientSession.class), eq(transcoder)); verify(channelHandlerProvider).getChangeHandler(eq(HandlerType.LENGTH_FRAME_DECODER), eq(configuration), any(ClientSession.class), eq(transcoder)); verify(channelHandlerProvider).getChangeHandler(eq(HandlerType.LENGTH_FRAME_ENCODER), eq(configuration), any(ClientSession.class), eq(transcoder)); verify(channelHandlerProvider).getChangeHandler(eq(HandlerType.MESSAGE_DECODER), eq(configuration), any(ClientSession.class), eq(transcoder)); verify(channelHandlerProvider).getChangeHandler(eq(HandlerType.MESSAGE_ENCODER), eq(configuration), any(ClientSession.class), eq(transcoder)); verify(channelHandlerProvider).getChangeHandler(eq(HandlerType.MESSAGE_LOGGER), eq(configuration), any(ClientSession.class), eq(transcoder)); verify(channelHandlerProvider).getChangeHandler(eq(HandlerType.SESSION_WRAPPER), eq(configuration), any(ClientSession.class), eq(transcoder)); }
From source file:com.github.spapageo.jannel.client.JannelClientTest.java
License:Open Source License
@Test public void testIdentifyConnectsToCorrectRemoteServerWithConnectionTimeout() throws Exception { Channel channel = mock(Channel.class, Answers.RETURNS_SMART_NULLS.get()); mockWriteHandler = mock(ChannelHandler.class); DefaultChannelPromise completedFuture = new DefaultChannelPromise(channel); completedFuture.setSuccess();// w w w .j av a 2 s . c o m ChannelPipeline channelPipeline = mock(ChannelPipeline.class); when(channelPipeline.addLast(anyString(), any(ChannelHandler.class))).thenReturn(channelPipeline); when(channelPipeline.addLast(any(EventExecutorGroup.class), anyString(), any(ChannelHandler.class))) .thenReturn(channelPipeline); when(channel.pipeline()).thenReturn(channelPipeline); when(channel.isActive()).thenReturn(true); when(channel.writeAndFlush(any())).thenReturn(completedFuture); when(bootstrap.connect(anyString(), anyInt())).thenReturn(completedFuture); ClientSessionConfiguration configuration = new ClientSessionConfiguration(); configuration.setHost("testHost"); configuration.setPort(1111); configuration.setConnectTimeout(10000); jannelClient.identify(configuration, null); verify(bootstrap).connect(configuration.getHost(), configuration.getPort()); verify(bootstrap).option(ChannelOption.valueOf("connectTimeoutMillis"), configuration.getConnectTimeout()); }
From source file:com.github.spapageo.jannel.client.JannelClientTest.java
License:Open Source License
@Test public void testIdentifySendsCorrectIdentifyCommand() throws Exception { Channel channel = mock(Channel.class, Answers.RETURNS_SMART_NULLS.get()); mockWriteHandler = mock(ChannelHandler.class); DefaultChannelPromise completedFuture = new DefaultChannelPromise(channel); completedFuture.setSuccess();//w w w.j a va 2 s .c o m ChannelPipeline channelPipeline = mock(ChannelPipeline.class); when(channelPipeline.addLast(anyString(), any(ChannelHandler.class))).thenReturn(channelPipeline); when(channelPipeline.addLast(any(EventExecutorGroup.class), anyString(), any(ChannelHandler.class))) .thenReturn(channelPipeline); when(channel.pipeline()).thenReturn(channelPipeline); when(channel.isActive()).thenReturn(true); when(channel.writeAndFlush(any())).thenReturn(completedFuture); when(bootstrap.connect(anyString(), anyInt())).thenReturn(completedFuture); ClientSessionConfiguration configuration = new ClientSessionConfiguration(); configuration.setClientId("testId"); jannelClient.identify(configuration, null); ArgumentCaptor<Admin> captor = ArgumentCaptor.forClass(Admin.class); verify(channel).writeAndFlush(captor.capture()); Admin command = captor.getValue(); assertEquals("Wrong command type", AdminCommand.IDENTIFY, command.getAdminCommand()); assertEquals("Wrong client id", configuration.getClientId(), command.getBoxId()); }