List of usage examples for io.netty.channel ChannelHandlerContext pipeline
ChannelPipeline pipeline();
From source file:org.ethereum.net.eth.handler.Eth62.java
License:Open Source License
/************************* * Message Processing */* w ww. ja v a 2s. com*/ *************************/ protected synchronized void processStatus(StatusMessage msg, ChannelHandlerContext ctx) throws InterruptedException { try { if (!Arrays.equals(msg.getGenesisHash(), config.getGenesis().getHash())) { if (!peerDiscoveryMode) { loggerNet.debug("Removing EthHandler for {} due to protocol incompatibility", ctx.channel().remoteAddress()); } ethState = EthState.STATUS_FAILED; disconnect(ReasonCode.INCOMPATIBLE_PROTOCOL); ctx.pipeline().remove(this); // Peer is not compatible for the 'eth' sub-protocol return; } if (msg.getNetworkId() != config.networkId()) { ethState = EthState.STATUS_FAILED; disconnect(ReasonCode.NULL_IDENTITY); return; } // basic checks passed, update statistics channel.getNodeStatistics().ethHandshake(msg); ethereumListener.onEthStatusUpdated(channel, msg); if (peerDiscoveryMode) { loggerNet.trace("Peer discovery mode: STATUS received, disconnecting..."); disconnect(ReasonCode.REQUESTED); ctx.close().sync(); ctx.disconnect().sync(); return; } // update bestKnownBlock info sendGetBlockHeaders(msg.getBestHash(), 1, 0, false); } catch (NoSuchElementException e) { loggerNet.debug("EthHandler already removed"); } }
From source file:org.ethereum.net.NettyTest.java
License:Open Source License
@Test public void pipelineTest() { final int[] int2 = new int[1]; final boolean[] exception = new boolean[1]; final ByteToMessageDecoder decoder2 = new ByteToMessageDecoder() { @Override// w ww.j a v a 2s . c om protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { int i = in.readInt(); System.out.println("decoder2 read int (4 bytes): " + Integer.toHexString(i)); int2[0] = i; if (i == 0) out.add("aaa"); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { System.out.println("Decoder2 exception: " + cause); } }; final MessageToMessageCodec decoder3 = new MessageToMessageCodec<Object, Object>() { @Override protected void decode(ChannelHandlerContext ctx, Object msg, List<Object> out) throws Exception { System.out.println("NettyTest.decode: msg = [" + msg + "]"); if (msg == "aaa") { throw new RuntimeException("Test exception 3"); } } @Override protected void encode(ChannelHandlerContext ctx, Object msg, List<Object> out) throws Exception { throw new RuntimeException("Test exception 4"); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { System.out.println("Decoder3 exception: " + cause); exception[0] = true; } }; final ByteToMessageDecoder decoder1 = new ByteToMessageDecoder() { @Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { int i = in.readInt(); System.out.println("decoder1 read int (4 bytes). Needs no more: " + Integer.toHexString(i)); ctx.pipeline().addAfter("decoder1", "decoder2", decoder2); ctx.pipeline().addAfter("decoder2", "decoder3", decoder3); ctx.pipeline().remove(this); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { System.out.println("Decoder1 exception: " + cause); } }; ChannelInboundHandlerAdapter initiator = new ChannelInboundHandlerAdapter() { @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { ctx.pipeline().addFirst("decoder1", decoder1); System.out.println("NettyTest.channelActive"); } }; EmbeddedChannel channel0 = new EmbeddedChannel(new ChannelOutboundHandlerAdapter() { @Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { throw new RuntimeException("Test"); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { System.out.println("Exception caught: " + cause); } }); EmbeddedChannel channel = new EmbeddedChannel(initiator); ByteBuf buffer = Unpooled.buffer(); buffer.writeInt(0x12345678); buffer.writeInt(0xabcdefff); channel.writeInbound(buffer); Assert.assertEquals(0xabcdefff, int2[0]); channel.writeInbound(Unpooled.buffer().writeInt(0)); Assert.assertTrue(exception[0]); // Need the following for the exception in outbound handler to be fired // ctx.writeAndFlush(msg).addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE); // exception[0] = false; // channel.writeOutbound("outMsg"); // Assert.assertTrue(exception[0]); }
From source file:org.ethereum.net.rlpx.HandshakeHandler.java
License:Open Source License
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { loggerWire.debug("Decoding handshake... (" + in.readableBytes() + " bytes available)"); decodeHandshake(ctx, in);/*w ww .jav a2 s . co m*/ if (isHandshakeDone) { loggerWire.debug("Handshake done, removing HandshakeHandler from pipeline."); ctx.pipeline().remove(this); } }
From source file:org.glassfish.jersey.netty.httpserver.HttpVersionChooser.java
License:Open Source License
@Override protected void configurePipeline(ChannelHandlerContext ctx, String protocol) throws Exception { if (ApplicationProtocolNames.HTTP_2.equals(protocol)) { ctx.pipeline().addLast(new Http2Codec(true, new JerseyHttp2ServerHandler(baseUri, container))); return;// w w w.j a va 2 s . c o m } if (ApplicationProtocolNames.HTTP_1_1.equals(protocol)) { ctx.pipeline().addLast(new HttpServerCodec(), new ChunkedWriteHandler(), new JerseyServerHandler(baseUri, container)); return; } throw new IllegalStateException("Unknown protocol: " + protocol); }
From source file:org.glassfish.jersey.netty.httpserver.JerseyServerInitializer.java
License:Open Source License
/** * Configure the pipeline for a cleartext upgrade from HTTP to HTTP/2. *//* w w w. j av a2 s . com*/ private void configureClearText(SocketChannel ch) { final ChannelPipeline p = ch.pipeline(); final HttpServerCodec sourceCodec = new HttpServerCodec(); p.addLast(sourceCodec); p.addLast(new HttpServerUpgradeHandler(sourceCodec, new HttpServerUpgradeHandler.UpgradeCodecFactory() { @Override public HttpServerUpgradeHandler.UpgradeCodec newUpgradeCodec(CharSequence protocol) { if (AsciiString.contentEquals(Http2CodecUtil.HTTP_UPGRADE_PROTOCOL_NAME, protocol)) { return new Http2ServerUpgradeCodec( new Http2Codec(true, new JerseyHttp2ServerHandler(baseUri, container))); } else { return null; } } })); p.addLast(new SimpleChannelInboundHandler<HttpMessage>() { @Override protected void channelRead0(ChannelHandlerContext ctx, HttpMessage msg) throws Exception { // If this handler is hit then no upgrade has been attempted and the client is just talking HTTP. // "Directly talking: " + msg.protocolVersion() + " (no upgrade was attempted)"); ChannelPipeline pipeline = ctx.pipeline(); ChannelHandlerContext thisCtx = pipeline.context(this); pipeline.addAfter(thisCtx.name(), null, new JerseyServerHandler(baseUri, container)); pipeline.replace(this, null, new ChunkedWriteHandler()); ctx.fireChannelRead(msg); } }); }
From source file:org.glowroot.agent.plugin.netty.CleartextHttp2ServerUpgradeHandler.java
License:Apache License
@Override public void handlerAdded(ChannelHandlerContext ctx) throws Exception { ctx.pipeline().addBefore(ctx.name(), null, new PriorKnowledgeHandler()) .addBefore(ctx.name(), null, httpServerCodec).replace(this, null, httpServerUpgradeHandler); }
From source file:org.hawkular.metrics.clients.ptrans.DemuxHandler.java
License:Apache License
@Override protected void decode(ChannelHandlerContext ctx, ByteBuf msg, @SuppressWarnings("rawtypes") List out) throws Exception { if (msg.readableBytes() < 5) { msg.clear();/* w ww.ja va 2 s .c o m*/ ctx.close(); return; } ChannelPipeline pipeline = ctx.pipeline(); String data = msg.toString(CharsetUtil.UTF_8); if (logger.isDebugEnabled()) { logger.debug("Incoming: [" + data + "]"); } boolean done = false; if (data.contains("type=metric")) { pipeline.addLast(new SyslogEventDecoder()); pipeline.addLast("forwarder", new RestForwardingHandler(configuration)); pipeline.remove(this); done = true; } else if (!data.contains("=")) { String[] items = data.split(" |\\n"); if (items.length % 3 == 0) { pipeline.addLast("encoder", new GraphiteEventDecoder()); pipeline.addLast("forwarder", forwardingHandler); pipeline.remove(this); done = true; } } if (!done) { logger.warn("Unknown input [" + data + "], ignoring"); msg.clear(); ctx.close(); } }
From source file:org.helios.octo.client.ResponseHandler.java
License:Open Source License
/** * {@inheritDoc}//from ww w . j a va2s .c o m * @see io.netty.handler.codec.ByteToMessageDecoder#decode(io.netty.channel.ChannelHandlerContext, io.netty.buffer.ByteBuf, io.netty.channel.MessageList) */ @Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, MessageList<Object> out) { long bytesAvailable = super.actualReadableBytes(); log.info("Replay Bytes Available:" + bytesAvailable); if (bytesAvailable < 1) return; switch (state()) { case REQUEST_ID: log.info("--------------------------------->Processing [" + state() + "]"); long reqId = in.readLong(); ctx.channel().attr(OctoShared.REQ_ID).set(reqId); checkpoint(RESPONSE_TYPE); log.info("REQUEST_ID:" + reqId); case RESPONSE_TYPE: log.info("--------------------------------->Processing [" + state() + "]"); byte responseType = in.readByte(); log.info("RESPONSE_TYPE:" + responseType); if (responseType == 0) { checkpoint(STREAM_TYPE); } else { // if(!ctx.pipeline().get(name)) ctx.pipeline().addAfter(OctoShared.RESPONSE_HANDLER, OctoShared.OBJECT_DECODER, new ObjectDecoder(ClassResolvers.cacheDisabled(null))); out.add(in.copy(0, super.actualReadableBytes())); checkpoint(FORWARD); return; } case STREAM_TYPE: log.info("--------------------------------->Processing [" + state() + "]"); byte streamType = in.readByte(); ctx.channel().attr(OctoShared.STREAM).set(streamType); log.info("STREAM_TYPE:" + streamType); checkpoint(FORWARD); return; // out.add(in.readBytes(super.actualReadableBytes())); // return; case FORWARD: log.info("--------------------------------->Processing [" + state() + "]"); log.info("Forwarding [" + super.actualReadableBytes() + "]...."); out.add(in.readBytes(super.actualReadableBytes())); log.info("Forward Complete. Remaining: [" + super.actualReadableBytes() + "]"); return; default: log.warn("Unexpected state [" + state() + "]"); break; } }
From source file:org.helios.octo.server.streams.StreamOutputAdapter.java
License:Open Source License
@Override public void write(ChannelHandlerContext ctx, MessageList<Object> msgs, ChannelPromise promise) { MessageList<ByteBuf> buffers = msgs.cast(); ByteBuf acc = ctx.attr(ACC).get();//from w w w .jav a 2 s . c o m if (acc == null) { acc = Unpooled.buffer(); ctx.attr(ACC).set(acc); } for (ByteBuf b : buffers) { acc.writeBytes(b); } msgs.releaseAllAndRecycle(); while (true) { int loc = acc.bytesBefore(ByteBufIndexFinder.LF); if (loc == -1) break; ByteBuf buf = Unpooled.buffer(10); buf.writeLong(System.nanoTime()).writeByte(0).writeByte(streamType); //.writeBytes(acc.readBytes(loc+1)); ChannelHandler se = ctx.pipeline().remove("stringEncoder"); ctx.write(buf); ctx.pipeline().addAfter("out", "stringEncoder", se); byte[] bytes = new byte[loc]; acc.readBytes(bytes); String s = new String(bytes); log.info("Writing out [" + s + "]"); ctx.write(s + "\n"); } }
From source file:org.hornetq.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//w w w.java 2 s. c o m 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 HornetQ 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_HORNETQ_REMOTING_KEY); FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, SWITCHING_PROTOCOLS); response.headers().set(UPGRADE, upgrade); response.headers().set(SEC_HORNETQ_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(); }