List of usage examples for io.netty.channel ChannelPipeline addFirst
ChannelPipeline addFirst(ChannelHandler... handlers);
From source file:io.atomix.catalyst.transport.netty.NettyServer.java
License:Apache License
/** * Starts listening for the given member. *//*from w ww.j a va 2 s . c o m*/ private void listen(Address address, Consumer<Connection> listener, ThreadContext context) { channelGroup = new DefaultChannelGroup("catalyst-acceptor-channels", GlobalEventExecutor.INSTANCE); handler = new ServerHandler(connections, listener, context, transport.properties()); final ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(transport.eventLoopGroup()).channel(NioServerSocketChannel.class) .handler(new LoggingHandler(LogLevel.DEBUG)).childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel channel) throws Exception { ChannelPipeline pipeline = channel.pipeline(); if (transport.properties().sslEnabled()) { pipeline.addFirst( new SslHandler(new NettyTls(transport.properties()).initSslEngine(false))); } pipeline.addLast(FIELD_PREPENDER); pipeline.addLast(new LengthFieldBasedFrameDecoder(transport.properties().maxFrameSize(), 0, 4, 0, 4)); pipeline.addLast(handler); } }).option(ChannelOption.SO_BACKLOG, transport.properties().acceptBacklog()) .option(ChannelOption.TCP_NODELAY, transport.properties().tcpNoDelay()) .option(ChannelOption.SO_REUSEADDR, transport.properties().reuseAddress()) .childOption(ChannelOption.ALLOCATOR, ALLOCATOR) .childOption(ChannelOption.SO_KEEPALIVE, transport.properties().tcpKeepAlive()); if (transport.properties().sendBufferSize() != -1) { bootstrap.childOption(ChannelOption.SO_SNDBUF, transport.properties().sendBufferSize()); } if (transport.properties().receiveBufferSize() != -1) { bootstrap.childOption(ChannelOption.SO_RCVBUF, transport.properties().receiveBufferSize()); } LOGGER.info("Binding to {}", address); ChannelFuture bindFuture = bootstrap.bind(address.socketAddress()); bindFuture.addListener((ChannelFutureListener) channelFuture -> { if (channelFuture.isSuccess()) { listening = true; context.executor().execute(() -> { LOGGER.info("Listening at {}", bindFuture.channel().localAddress()); listenFuture.complete(null); }); } else { context.execute(() -> listenFuture.completeExceptionally(channelFuture.cause())); } }); channelGroup.add(bindFuture.channel()); }
From source file:io.crate.plugin.PipelineRegistry.java
License:Apache License
public void registerItems(ChannelPipeline pipeline) { for (PipelineRegistry.ChannelPipelineItem item : addBeforeList) { pipeline.addBefore(item.base, item.name, item.handlerFactory.get()); }/* www .j a va 2s. c o m*/ if (sslContextProvider != null) { SslContext sslContext = sslContextProvider.get(); if (sslContext != null) { SslHandler sslHandler = sslContext.newHandler(pipeline.channel().alloc()); pipeline.addFirst(sslHandler); } } }
From source file:io.crate.protocols.postgres.SslReqHandler.java
License:Apache License
/** * Process receives incoming data from the Netty pipeline. It * may request more data by returning the WAITING_FOR_INPUT * state. The process method should return DONE when it has * finished processing. It may add additional elements to the * pipeline. The handler is responsible for to position the * buffer read marker correctly such that successive readers * see the correct data. The handler is expected to position the * marker after the SSLRequest payload.//from w w w . j av a 2 s.c o m * @param buffer The buffer with incoming data * @param pipeline The Netty pipeline which may be modified * @return The state of the handler */ public State process(ByteBuf buffer, ChannelPipeline pipeline) { if (buffer.readableBytes() < SSL_REQUEST_BYTE_LENGTH) { return State.WAITING_FOR_INPUT; } // mark the buffer so we can jump back if we don't handle this startup buffer.markReaderIndex(); // reads the total message length (int) and the SSL request code (int) if (buffer.readInt() == SSL_REQUEST_BYTE_LENGTH && buffer.readInt() == SSL_REQUEST_CODE) { // received optional SSL negotiation pkg if (sslContext != null) { writeByteAndFlushMessage(pipeline.channel(), 'S'); SslHandler sslHandler = sslContext.newHandler(pipeline.channel().alloc()); pipeline.addFirst(sslHandler); } else { writeByteAndFlushMessage(pipeline.channel(), 'N'); } buffer.markReaderIndex(); } else { buffer.resetReaderIndex(); } return State.DONE; }
From source file:io.reactivex.netty.client.ConnectionPoolTest.java
License:Apache License
@Before public void setUp() throws Exception { testId = name.getMethodName();/*w w w . j av a 2s. com*/ long currentTime = System.currentTimeMillis(); System.out.println("Time: " + currentTime + ". Setting up test id: " + testId); serverConnHandler = new ConnectionHandlerImpl(testId); server = RxNetty.createTcpServer(0, PipelineConfigurators.textOnlyConfigurator(), serverConnHandler) .start(); serverInfo = new RxClient.ServerInfo("localhost", server.getServerPort()); metricEventsListener = new TrackableMetricEventsListener(); strategy = new MaxConnectionsBasedStrategy(1); clientBootstrap = new Bootstrap().group(new NioEventLoopGroup(4)).channel(NioSocketChannel.class); pipelineConfigurator = new PipelineConfiguratorComposite<String, String>( PipelineConfigurators.textOnlyConfigurator(), new PipelineConfigurator() { @Override public void configureNewPipeline(ChannelPipeline pipeline) { channelCloseListener.reset(); pipeline.addFirst(channelCloseListener); } }); pipelineConfigurator = PipelineConfigurators.createClientConfigurator(pipelineConfigurator, newDefaultConfig()); clientBootstrap.handler(new ChannelInitializer<Channel>() { @Override public void initChannel(Channel ch) throws Exception { pipelineConfigurator.configureNewPipeline(ch.pipeline()); } }); poolConfig = new PoolConfig(MAX_IDLE_TIME_MILLIS); MetricEventsSubject<ClientMetricsEvent<?>> eventsSubject = new MetricEventsSubject<ClientMetricsEvent<?>>(); factory = new ClientChannelFactoryImpl<String, String>(clientBootstrap, eventsSubject); pool = new ConnectionPoolImpl<String, String>(serverInfo, poolConfig, strategy, null, factory, eventsSubject); pool.subscribe(metricEventsListener); stats = new PoolStats(); pool.subscribe(stats); }
From source file:io.reactivex.netty.pipeline.PipelineConfigurators.java
License:Apache License
/** * Enables wire level logs (all events received by netty) to be logged at the passed {@code wireLogginLevel}. <br/> * * Since, in most of the production systems, the logging level is set to {@link LogLevel#WARN} or * {@link LogLevel#ERROR}, if this wire level logging is required for all requests (not at all recommended as this * logging is very verbose), the passed level must be {@link LogLevel#WARN} or {@link LogLevel#ERROR} respectively. <br/> * * It is recommended to set this level to {@link LogLevel#DEBUG} and then dynamically enabled disable this log level * whenever required. <br/>/*w ww. j a v a 2s . c o m*/ * * @param wireLogginLevel Log level at which the wire level logs will be logged. * * @return This builder. * * @see LoggingHandler */ public static <I, O> PipelineConfigurator<I, O> wireLoggingConfigurator(final LogLevel wireLogginLevel) { return new PipelineConfigurator<I, O>() { @Override public void configureNewPipeline(ChannelPipeline pipeline) { pipeline.addFirst(new LoggingHandler(wireLogginLevel)); } }; }
From source file:io.reactivex.netty.pipeline.ssl.SslPipelineConfigurator.java
License:Apache License
@Override public void configureNewPipeline(ChannelPipeline pipeline) { pipeline.addFirst(new SslHandler(sslEngineFactory.createSSLEngine(pipeline.channel().alloc()))); }
From source file:io.reactivex.netty.protocol.http.client.HttpClientPoolTest.java
License:Apache License
private HttpClientImpl<ByteBuf, ByteBuf> newHttpClient(int maxConnections, long idleTimeout, HttpClient.HttpClientConfig clientConfig) { if (null == clientConfig) { clientConfig = HttpClient.HttpClientConfig.Builder.newDefaultConfig(); }/*ww w .jav a2s . c o m*/ PipelineConfigurator<HttpClientResponse<ByteBuf>, HttpClientRequest<ByteBuf>> configurator = new PipelineConfiguratorComposite<HttpClientResponse<ByteBuf>, HttpClientRequest<ByteBuf>>( PipelineConfigurators.httpClientConfigurator(), new PipelineConfigurator() { @Override public void configureNewPipeline(ChannelPipeline pipeline) { channelCloseListener.reset(); pipeline.addFirst(channelCloseListener); } }); HttpClientImpl<ByteBuf, ByteBuf> client = (HttpClientImpl<ByteBuf, ByteBuf>) new HttpClientBuilder<ByteBuf, ByteBuf>( "localhost", port).withMaxConnections(maxConnections).withIdleConnectionsTimeoutMillis(idleTimeout) .config(clientConfig).enableWireLogging(LogLevel.DEBUG).pipelineConfigurator(configurator) .build(); stateChangeListener = new TrackableMetricEventsListener(); client.subscribe(stateChangeListener); stats = new PoolStats(); client.subscribe(stats); return client; }
From source file:org.apache.hadoop.hbase.ipc.NettyRpcConnection.java
License:Apache License
private void saslNegotiate(final Channel ch) { UserGroupInformation ticket = getUGI(); if (ticket == null) { failInit(ch, new FatalConnectionException("ticket/user is null")); return;/*from w w w .j a v a2 s. com*/ } Promise<Boolean> saslPromise = ch.eventLoop().newPromise(); final NettyHBaseSaslRpcClientHandler saslHandler; try { saslHandler = new NettyHBaseSaslRpcClientHandler(saslPromise, ticket, authMethod, token, serverPrincipal, rpcClient.fallbackAllowed, this.rpcClient.conf); } catch (IOException e) { failInit(ch, e); return; } ch.pipeline().addFirst(new SaslChallengeDecoder(), saslHandler); saslPromise.addListener(new FutureListener<Boolean>() { @Override public void operationComplete(Future<Boolean> future) throws Exception { if (future.isSuccess()) { ChannelPipeline p = ch.pipeline(); p.remove(SaslChallengeDecoder.class); p.remove(NettyHBaseSaslRpcClientHandler.class); // check if negotiate with server for connection header is necessary if (saslHandler.isNeedProcessConnectionHeader()) { Promise<Boolean> connectionHeaderPromise = ch.eventLoop().newPromise(); // create the handler to handle the connection header ChannelHandler chHandler = new NettyHBaseRpcConnectionHeaderHandler(connectionHeaderPromise, conf, connectionHeaderWithLength); // add ReadTimeoutHandler to deal with server doesn't response connection header // because of the different configuration in client side and server side p.addFirst(new ReadTimeoutHandler(RpcClient.DEFAULT_SOCKET_TIMEOUT_READ, TimeUnit.MILLISECONDS)); p.addLast(chHandler); connectionHeaderPromise.addListener(new FutureListener<Boolean>() { @Override public void operationComplete(Future<Boolean> future) throws Exception { if (future.isSuccess()) { ChannelPipeline p = ch.pipeline(); p.remove(ReadTimeoutHandler.class); p.remove(NettyHBaseRpcConnectionHeaderHandler.class); // don't send connection header, NettyHbaseRpcConnectionHeaderHandler // sent it already established(ch); } else { final Throwable error = future.cause(); scheduleRelogin(error); failInit(ch, toIOE(error)); } } }); } else { // send the connection header to server ch.write(connectionHeaderWithLength.retainedDuplicate()); established(ch); } } else { final Throwable error = future.cause(); scheduleRelogin(error); failInit(ch, toIOE(error)); } } }); }
From source file:org.springframework.cloud.stream.app.netty.tcp.source.NettyTcpReceivingChannelAdapter.java
License:Apache License
@Override protected void onInit() { super.onInit(); serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() { @Override//w w w . java 2s . c o m protected void initChannel(final SocketChannel socketChannel) throws Exception { final ChannelPipeline channelPipeline = socketChannel.pipeline(); boolean first = true; ChannelInboundHandler[] channelInboundHandlers = channelInboundHandlerFactory .createChannelInboundHandlers(); for (ChannelInboundHandler channelInboundHandler : channelInboundHandlers) { if (first) { channelPipeline.addFirst(channelInboundHandler); first = false; } else { channelPipeline.addLast(channelInboundHandler); } } channelPipeline.addLast("sourceOutputHandler", new SimpleChannelInboundHandler<ByteBuf>() { @Override protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception { byte[] data; if (msg.hasArray()) { data = msg.array(); } else { data = new byte[msg.readableBytes()]; msg.readBytes(data); } AbstractIntegrationMessageBuilder<byte[]> builder = getMessageBuilderFactory() .withPayload(data); sendMessage(builder.build()); } }); socketChannel.closeFuture().addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { socketChannel.close(); } }); } }); serverBootstrap.validate(); }
From source file:org.wso2.carbon.stream.processor.core.ha.transport.EventSyncConnection.java
License:Open Source License
public EventSyncConnection(int numberOfThreads, boolean keepAlive, boolean noDelay) { group = new NioEventLoopGroup(numberOfThreads); bootstrap = new Bootstrap(); bootstrap.group(group).channel(NioSocketChannel.class).option(ChannelOption.SO_KEEPALIVE, keepAlive) .option(ChannelOption.TCP_NODELAY, noDelay).handler(new ChannelInitializer<SocketChannel>() { @Override//from w ww .j av a2s . com protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addFirst(new MessageEncoder()); } }); }