List of usage examples for io.netty.channel ChannelHandlerContext pipeline
ChannelPipeline pipeline();
From source file:org.aotorrent.client.InboundHandshakeHandler.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { final ByteBuf buf = (ByteBuf) msg; if (handshakeDone.get()) { super.channelRead(ctx, msg); return;//from ww w . jav a 2 s. c om } try { HandshakeRequest handshakeRequest = new HandshakeRequest(buf); final String hexInfoHash = Hex.encodeHexString(handshakeRequest.getInfoHash()); final TorrentEngine torrentEngine = client.getEngine(hexInfoHash); if (torrentEngine != null) { final PeerRequest peerHandshake = new HandshakeRequest(torrentEngine.getInfoHash(), torrentEngine.getPeerId()); ctx.write(peerHandshake.toTransmit()); ctx.flush(); PeerConnection peerConnection = new PeerConnection(torrentEngine, ctx); ctx.pipeline().addFirst("trafficCounter", torrentEngine.getCounter()); ctx.pipeline().addLast("peerConnection", peerConnection); ctx.pipeline().remove(this); handshakeDone.set(true); LOGGER.info("Handshake done"); ByteBuf out = ((ByteBuf) msg).copy(); ctx.fireChannelRead(out); peerConnection.sendBitField(); } else { LOGGER.info("Peer want to exchange torrent that we haven't"); ctx.close(); } } finally { buf.release(); } }
From source file:org.aotorrent.client.OutboundHandshakeHandler.java
License:Apache License
@Override protected synchronized void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception { final ByteBuf buf = (ByteBuf) msg; if (handshakeDone) { super.channelRead(ctx, msg); return;/*from w w w .j av a 2s. c o m*/ } try { HandshakeRequest handshakeRequest = new HandshakeRequest(buf); if (ArrayUtils.isEquals(handshakeRequest.getInfoHash(), torrentEngine.getInfoHash())) { handshakeDone = true; PeerConnection peerConnection = new PeerConnection(torrentEngine, ctx); torrentEngine.registerConnection(ctx.channel().remoteAddress(), peerConnection); final ChannelPipeline pipeline = ctx.pipeline(); pipeline.addLast("peerConnection", peerConnection); pipeline.remove(this); ByteBuf out = ((ByteBuf) msg).copy(); ctx.fireChannelRead(out); peerConnection.sendBitField(); } } finally { buf.release(); } }
From source file:org.apache.activemq.artemis.tests.integration.transports.netty.NettyConnectorWithHTTPUpgradeTest.java
License:Apache License
private void startWebServer(int port) throws InterruptedException { bossGroup = new NioEventLoopGroup(); workerGroup = new NioEventLoopGroup(); ServerBootstrap b = new ServerBootstrap(); b.childOption(ChannelOption.ALLOCATOR, PartialPooledByteBufAllocator.INSTANCE); b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override//from w w w.j a va 2s . c om protected void initChannel(SocketChannel ch) throws Exception { // create a HTTP server ChannelPipeline p = ch.pipeline(); p.addLast("decoder", new HttpRequestDecoder()); p.addLast("encoder", new HttpResponseEncoder()); p.addLast("http-upgrade-handler", new SimpleChannelInboundHandler<Object>() { // handle HTTP GET + Upgrade with a handshake specific to ActiveMQ Artemis remoting. @Override protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof HttpRequest) { HttpRequest request = (HttpRequest) msg; for (Map.Entry<String, String> entry : request.headers()) { System.out.println(entry); } String upgrade = request.headers().get(UPGRADE); String secretKey = request.headers().get(SEC_ACTIVEMQ_REMOTING_KEY); FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, SWITCHING_PROTOCOLS); response.headers().set(UPGRADE, upgrade); response.headers().set(SEC_ACTIVEMQ_REMOTING_ACCEPT, createExpectedResponse(MAGIC_NUMBER, secretKey)); ctx.writeAndFlush(response); // when the handshake is successful, the HTTP handlers are removed ctx.pipeline().remove("decoder"); ctx.pipeline().remove("encoder"); ctx.pipeline().remove(this); System.out.println("HTTP handshake sent, transferring channel"); // transfer the control of the channel to the Netty Acceptor NettyAcceptor acceptor = (NettyAcceptor) server.getRemotingService() .getAcceptor(acceptorName); acceptor.transfer(ctx.channel()); // at this point, the HTTP upgrade process is over and the netty acceptor behaves like regular ones. } } }); } @Override public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { ctx.flush(); } }); b.bind(port).sync(); }
From source file:org.apache.activemq.tests.integration.transports.netty.NettyConnectorWithHTTPUpgradeTest.java
License:Apache License
private void startWebServer(int port) throws InterruptedException { bossGroup = new NioEventLoopGroup(); workerGroup = new NioEventLoopGroup(); ServerBootstrap b = new ServerBootstrap(); b.childOption(ChannelOption.ALLOCATOR, PartialPooledByteBufAllocator.INSTANCE); b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override//www .j a v a2 s . c om protected void initChannel(SocketChannel ch) throws Exception { // create a HTTP server ChannelPipeline p = ch.pipeline(); p.addLast("decoder", new HttpRequestDecoder()); p.addLast("encoder", new HttpResponseEncoder()); p.addLast("http-upgrade-handler", new SimpleChannelInboundHandler<Object>() { // handle HTTP GET + Upgrade with a handshake specific to ActiveMQ remoting. @Override protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof HttpRequest) { HttpRequest request = (HttpRequest) msg; for (Map.Entry<String, String> entry : request.headers()) { System.out.println(entry); } String upgrade = request.headers().get(UPGRADE); String secretKey = request.headers().get(SEC_ACTIVEMQ_REMOTING_KEY); FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, SWITCHING_PROTOCOLS); response.headers().set(UPGRADE, upgrade); response.headers().set(SEC_ACTIVEMQ_REMOTING_ACCEPT, createExpectedResponse(MAGIC_NUMBER, secretKey)); ctx.writeAndFlush(response); // when the handshake is successful, the HTTP handlers are removed ctx.pipeline().remove("decoder"); ctx.pipeline().remove("encoder"); ctx.pipeline().remove(this); System.out.println("HTTP handshake sent, transferring channel"); // transfer the control of the channel to the Netty Acceptor NettyAcceptor acceptor = (NettyAcceptor) server.getRemotingService() .getAcceptor(acceptorName); acceptor.transfer(ctx.channel()); // at this point, the HTTP upgrade process is over and the netty acceptor behaves like regular ones. } } }); } @Override public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { ctx.flush(); } }); b.bind(port).sync(); }
From source file:org.apache.camel.component.netty4.handlers.ClientChannelHandler.java
License:Apache License
@Override protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception { // TODO Auto-generated method stub messageReceived = true;//from w w w. j a v a 2s . com if (LOG.isTraceEnabled()) { LOG.trace("Message received: {}", msg); } if (producer.getConfiguration().getRequestTimeout() > 0) { ChannelHandler handler = ctx.pipeline().get("timeout"); if (handler != null) { LOG.trace("Removing timeout channel as we received message"); ctx.pipeline().remove(handler); } } Exchange exchange = getExchange(ctx); if (exchange == null) { // we just ignore the received message as the channel is closed return; } AsyncCallback callback = getAsyncCallback(ctx); Message message; try { message = getResponseMessage(exchange, ctx, msg); } catch (Exception e) { exchange.setException(e); callback.done(false); return; } // set the result on either IN or OUT on the original exchange depending on its pattern if (ExchangeHelper.isOutCapable(exchange)) { exchange.setOut(message); } else { exchange.setIn(message); } try { // should channel be closed after complete? Boolean close; if (ExchangeHelper.isOutCapable(exchange)) { close = exchange.getOut().getHeader(NettyConstants.NETTY_CLOSE_CHANNEL_WHEN_COMPLETE, Boolean.class); } else { close = exchange.getIn().getHeader(NettyConstants.NETTY_CLOSE_CHANNEL_WHEN_COMPLETE, Boolean.class); } // check the setting on the exchange property if (close == null) { close = exchange.getProperty(NettyConstants.NETTY_CLOSE_CHANNEL_WHEN_COMPLETE, Boolean.class); } // should we disconnect, the header can override the configuration boolean disconnect = producer.getConfiguration().isDisconnect(); if (close != null) { disconnect = close; } if (disconnect) { if (LOG.isTraceEnabled()) { LOG.trace("Closing channel when complete at address: {}", producer.getConfiguration().getAddress()); } NettyHelper.close(ctx.channel()); } } finally { // signal callback callback.done(false); } }
From source file:org.apache.camel.component.netty4.NettyEndpoint.java
License:Apache License
protected SSLSession getSSLSession(ChannelHandlerContext ctx) { final SslHandler sslHandler = ctx.pipeline().get(SslHandler.class); SSLSession sslSession = null; if (sslHandler != null) { sslSession = sslHandler.engine().getSession(); }//from w ww . j a va 2 s.c om return sslSession; }
From source file:org.apache.dubbo.qos.server.handler.QosProcessHandlerTest.java
License:Apache License
@Test public void testDecodeHttp() throws Exception { ByteBuf buf = Unpooled.wrappedBuffer(new byte[] { 'G' }); ChannelHandlerContext context = Mockito.mock(ChannelHandlerContext.class); ChannelPipeline pipeline = Mockito.mock(ChannelPipeline.class); Mockito.when(context.pipeline()).thenReturn(pipeline); QosProcessHandler handler = new QosProcessHandler("welcome", false); handler.decode(context, buf, Collections.emptyList()); verify(pipeline).addLast(any(HttpServerCodec.class)); verify(pipeline).addLast(any(HttpObjectAggregator.class)); verify(pipeline).addLast(any(HttpProcessHandler.class)); verify(pipeline).remove(handler);/*from w w w. ja v a2 s . c o m*/ }
From source file:org.apache.dubbo.qos.server.handler.QosProcessHandlerTest.java
License:Apache License
@Test public void testDecodeTelnet() throws Exception { ByteBuf buf = Unpooled.wrappedBuffer(new byte[] { 'A' }); ChannelHandlerContext context = Mockito.mock(ChannelHandlerContext.class); ChannelPipeline pipeline = Mockito.mock(ChannelPipeline.class); Mockito.when(context.pipeline()).thenReturn(pipeline); QosProcessHandler handler = new QosProcessHandler("welcome", false); handler.decode(context, buf, Collections.emptyList()); verify(pipeline).addLast(any(LineBasedFrameDecoder.class)); verify(pipeline).addLast(any(StringDecoder.class)); verify(pipeline).addLast(any(StringEncoder.class)); verify(pipeline).addLast(any(TelnetProcessHandler.class)); verify(pipeline).remove(handler);/*w w w .ja va2s .c o m*/ }
From source file:org.apache.giraph.comm.netty.handler.ResponseEncoder.java
License:Apache License
@Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { if (LOG.isDebugEnabled()) { LOG.debug("write(" + ctx + "," + msg); }/*from w w w . j av a2 s . com*/ if (!(msg instanceof WritableRequest)) { throw new IllegalArgumentException("encode: cannot encode message of type " + msg.getClass() + " since it is not an instance of an implementation of " + " WritableRequest."); } @SuppressWarnings("unchecked") WritableRequest writableRequest = (WritableRequest) msg; ByteBuf buf = ctx.alloc().buffer(10); ByteBufOutputStream output = new ByteBufOutputStream(buf); if (LOG.isDebugEnabled()) { LOG.debug("encode: Encoding a message of type " + msg.getClass()); } // Space is reserved now to be filled later by the serialize request size output.writeInt(0); // write type of object. output.writeByte(writableRequest.getType().ordinal()); // write the object itself. writableRequest.write(output); output.flush(); output.close(); // Set the correct size at the end. buf.setInt(0, buf.writerIndex() - SIZE_OF_INT); if (LOG.isDebugEnabled()) { LOG.debug("encode: Encoding a message of type " + msg.getClass()); } ctx.write(buf, promise); /*if[HADOOP_NON_SECURE] else[HADOOP_NON_SECURE]*/ if (writableRequest.getType() == RequestType.SASL_COMPLETE_REQUEST) { // We are sending to the client a SASL_COMPLETE response (created by // the SaslServer handler). The SaslServer handler has removed itself // from the pipeline after creating this response, and now it's time for // the ResponseEncoder to remove itself also. if (LOG.isDebugEnabled()) { LOG.debug("encode: Removing RequestEncoder handler: no longer needed," + " since client: " + ctx.channel().remoteAddress() + " has " + "completed authenticating."); } ctx.pipeline().remove(this); } /*end[HADOOP_NON_SECURE]*/ ctx.write(buf, promise); }
From source file:org.apache.giraph.comm.netty.handler.SaslClientHandler.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { WritableRequest decodedMessage = decode(ctx, msg); // Generate SASL response to server using Channel-local SASL client. SaslNettyClient saslNettyClient = ctx.attr(NettyClient.SASL).get(); if (saslNettyClient == null) { throw new Exception( "handleUpstream: saslNettyClient was unexpectedly " + "null for channel: " + ctx.channel()); }/* ww w .j ava 2 s. c om*/ if (decodedMessage.getClass() == SaslCompleteRequest.class) { if (LOG.isDebugEnabled()) { LOG.debug("handleUpstream: Server has sent us the SaslComplete " + "message. Allowing normal work to proceed."); } synchronized (saslNettyClient.getAuthenticated()) { saslNettyClient.getAuthenticated().notify(); } if (!saslNettyClient.isComplete()) { LOG.error("handleUpstream: Server returned a Sasl-complete message, " + "but as far as we can tell, we are not authenticated yet."); throw new Exception("handleUpstream: Server returned a " + "Sasl-complete message, but as far as " + "we can tell, we are not authenticated yet."); } // Remove SaslClientHandler and replace LengthFieldBasedFrameDecoder // from client pipeline. ctx.pipeline().remove(this); ctx.pipeline().replace("length-field-based-frame-decoder", "fixed-length-frame-decoder", new FixedLengthFrameDecoder(RequestServerHandler.RESPONSE_BYTES)); return; } SaslTokenMessageRequest serverToken = (SaslTokenMessageRequest) decodedMessage; if (LOG.isDebugEnabled()) { LOG.debug( "handleUpstream: Responding to server's token of length: " + serverToken.getSaslToken().length); } // Generate SASL response (but we only actually send the response if it's // non-null. byte[] responseToServer = saslNettyClient.saslResponse(serverToken); if (responseToServer == null) { // If we generate a null response, then authentication has completed (if // not, warn), and return without sending a response back to the server. if (LOG.isDebugEnabled()) { LOG.debug( "handleUpstream: Response to server is null: " + "authentication should now be complete."); } if (!saslNettyClient.isComplete()) { LOG.warn("handleUpstream: Generated a null response, " + "but authentication is not complete."); } return; } else { if (LOG.isDebugEnabled()) { LOG.debug("handleUpstream: Response to server token has length:" + responseToServer.length); } } // Construct a message containing the SASL response and send it to the // server. SaslTokenMessageRequest saslResponse = new SaslTokenMessageRequest(responseToServer); ctx.channel().writeAndFlush(saslResponse); }