List of usage examples for io.netty.channel ChannelHandlerContext pipeline
ChannelPipeline pipeline();
From source file:com.uber.tchannel.handlers.InitRequestInitiator.java
License:Open Source License
@Override protected void messageReceived(ChannelHandlerContext ctx, ByteBuf buf) throws TChannelError { Frame frame = MessageCodec.decode(MessageCodec.decode(buf)); switch (frame.getType()) { case InitResponse: InitResponseFrame initResponseFrameMessage = (InitResponseFrame) frame; if (initResponseFrameMessage.getVersion() == InitFrame.DEFAULT_VERSION) { ctx.pipeline().remove(this); peerManager.setIdentified(ctx.channel(), initResponseFrameMessage.getHeaders()); } else {//from w ww. j ava 2s. c o m // This will lead to a connection reset throw new TChannelProtocol(String.format("Expected Protocol version: %d, got version: %d", InitFrame.DEFAULT_VERSION, initResponseFrameMessage.getVersion())); } break; default: // This will lead to a connection reset throw new TChannelProtocol("Frame recieved before Init Response"); } }
From source file:com.whizzosoftware.wzwave.channel.ZWaveDataFrameTransactionInboundHandler.java
License:Open Source License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) { if (msg instanceof Frame) { Frame frame = (Frame) msg; if (hasCurrentRequestTransaction()) { logger.trace("Received frame within transaction context: {}", frame); if (currentDataFrameTransaction.addFrame(frame)) { if (currentDataFrameTransaction.isComplete()) { // cancel the timeout callback if (timeoutFuture != null) { timeoutFuture.cancel(true); timeoutFuture = null; }//from w ww . j a v a 2s .co m // flag that we're in the process of completing a frame transaction so that any code that checks // will know that the transaction isn't quite done yet processingTransactionCompletion = true; if (!currentDataFrameTransaction.hasError()) { DataFrame finalFrame = currentDataFrameTransaction.getFinalFrame(); logger.trace("*** Data frame transaction completed with final frame: {}", finalFrame); logger.trace(""); // if there's an ApplicationUpdate with no node ID (e.g. when there's a app update failure), attempt // to set the node ID based on the request frame that triggered it if (finalFrame instanceof ApplicationUpdate) { ApplicationUpdate update = (ApplicationUpdate) finalFrame; if ((update.getNodeId() == null || update.getNodeId() == 0) && currentDataFrameTransaction.getStartFrame() instanceof RequestNodeInfo) { update.setNodeId(((RequestNodeInfo) currentDataFrameTransaction.getStartFrame()) .getNodeId()); } } // pass the final frame down the pipeline if (finalFrame != null) { ctx.fireChannelRead(finalFrame); } } else { attemptResend(ctx); } // clear the current transaction currentDataFrameTransaction = null; // now the frame transaction is truly done processingTransactionCompletion = false; // alert the outbound pipeline that a frame transaction has been completed ChannelPipeline pipeline = ctx.pipeline(); if (pipeline != null) { ZWaveQueuedOutboundHandler writeHandler = (ZWaveQueuedOutboundHandler) ctx.pipeline() .get("writeQueue"); if (writeHandler != null) { writeHandler.onDataFrameTransactionComplete(); } } } } else { logger.trace("Transaction didn't consume frame so passing it along"); ctx.fireChannelRead(msg); } } else { logger.trace("Received frame outside of transaction context: {}", frame); ctx.fireChannelRead(msg); } } else if (msg instanceof TransactionTimeout) { // if a timeout is received for the current transaction, attempt to resend; otherwise ignore it TransactionTimeout tt = (TransactionTimeout) msg; if (tt.getId().equals(currentDataFrameTransaction.getId())) { logger.trace("Transaction timed out"); attemptResend(ctx); } } }
From source file:com.whizzosoftware.wzwave.channel.ZWaveQueuedOutboundHandler.java
License:Open Source License
@Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { logger.trace("write: " + msg); if (msg instanceof DataFrame) { ZWaveDataFrameTransactionInboundHandler transactionHandler = (ZWaveDataFrameTransactionInboundHandler) ctx .pipeline().get("transaction"); if (transactionHandler != null) { DataFrame frame = (DataFrame) msg; if (transactionHandler.hasCurrentRequestTransaction()) { logger.trace("Queueing data frame: " + frame + "; current queue size: " + pendingQueue.size()); pendingQueue.add(frame); } else { logger.trace("No transaction detected, sending data frame: {}", frame); ctx.writeAndFlush(msg, promise); frame.incremenentSendCount(); transactionHandler.onDataFrameWrite(frame); }/*from ww w . j av a 2s .co m*/ } else { logger.error("No transaction handler found; dropping data frame"); } } else { ctx.writeAndFlush(msg, promise); } }
From source file:com.witjit.game.server.communication.netty.handler.NodeChannelInitializer.java
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (!bindNode(ctx.channel(), (ByteBuf) msg)) { return;//from w w w . j a va 2s. c o m } initChannel(ctx.channel()); ctx.pipeline().remove(this); ctx.fireChannelRead(msg); }
From source file:com.wuma.securechat.SecureChatServerHandler.java
License:Apache License
@Override public void channelActive(final ChannelHandlerContext ctx) { // Once session is secured, send a greeting and register the channel to the global channel // list so the channel received the messages from others. ctx.pipeline().get(SslHandler.class).handshakeFuture() .addListener(new GenericFutureListener<Future<Channel>>() { public void operationComplete(Future<Channel> future) throws Exception { ctx.writeAndFlush("Welcome to " + InetAddress.getLocalHost().getHostName() + " secure chat service!\n"); ctx.writeAndFlush("Your session is protected by " + ctx.pipeline().get(SslHandler.class).engine().getSession().getCipherSuite() + " cipher suite.\n"); channels.add(ctx.channel()); }// ww w .jav a 2 s.c o m }); }
From source file:com.xxx.netty.handle.SecureChatServerHandler.java
License:Apache License
@Override public void channelActive(final ChannelHandlerContext ctx) {// ? // System.out.println("channelactive!"); // Once session is secured, send a greeting and register the channel to // the global channel // list so the channel received the messages from others. // ??/* ww w . ja v a 2s .co m*/ ctx.pipeline().get(SslHandler.class).handshakeFuture() .addListener(new GenericFutureListener<Future<Channel>>() { @Override public void operationComplete(Future<Channel> future) throws Exception { ctx.writeAndFlush("@Welcome to " + InetAddress.getLocalHost().getHostName() + " secure chat service!\n"); LOGGER.info("connected :{}" + ctx.channel().remoteAddress()); } }); }
From source file:com.xx_dev.apn.proxy.ApnProxySchemaHandler.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext uaChannelCtx, final Object msg) throws Exception { if (msg instanceof HttpRequest) { HttpRequest httpRequest = (HttpRequest) msg; String originalHost = HostNamePortUtil.getHostName(httpRequest); int originalPort = HostNamePortUtil.getPort(httpRequest); ApnProxyRemote apnProxyRemote = ApnProxyRemoteChooser.chooseRemoteAddr(originalHost, originalPort); Channel uaChannel = uaChannelCtx.channel(); ApnProxyConnectionAttribute apnProxyConnectionAttribute = ApnProxyConnectionAttribute.build( uaChannel.remoteAddress().toString(), httpRequest.getMethod().name(), httpRequest.getUri(), httpRequest.getProtocolVersion().text(), httpRequest.headers().get(HttpHeaders.Names.USER_AGENT), apnProxyRemote); uaChannelCtx.attr(ApnProxyConnectionAttribute.ATTRIBUTE_KEY).set(apnProxyConnectionAttribute); uaChannel.attr(ApnProxyConnectionAttribute.ATTRIBUTE_KEY).set(apnProxyConnectionAttribute); if (httpRequest.getMethod().equals(HttpMethod.CONNECT)) { if (uaChannelCtx.pipeline().get(ApnProxyUserAgentForwardHandler.HANDLER_NAME) != null) { uaChannelCtx.pipeline().remove(ApnProxyUserAgentForwardHandler.HANDLER_NAME); }/*from ww w .j a va2s . co m*/ if (uaChannelCtx.pipeline().get(ApnProxyUserAgentTunnelHandler.HANDLER_NAME) == null) { uaChannelCtx.pipeline().addLast(ApnProxyUserAgentTunnelHandler.HANDLER_NAME, new ApnProxyUserAgentTunnelHandler()); } } else { if (uaChannelCtx.pipeline().get(ApnProxyUserAgentForwardHandler.HANDLER_NAME) == null) { uaChannelCtx.pipeline().addLast(ApnProxyUserAgentForwardHandler.HANDLER_NAME, new ApnProxyUserAgentForwardHandler()); } } } LoggerUtil.debug(logger, uaChannelCtx.attr(ApnProxyConnectionAttribute.ATTRIBUTE_KEY), "UA msg", msg); uaChannelCtx.fireChannelRead(msg); }
From source file:com.xx_dev.apn.proxy.ApnProxyUserAgentTunnelHandler.java
License:Apache License
@Override public void channelRead(final ChannelHandlerContext uaChannelCtx, Object msg) throws Exception { if (msg instanceof HttpRequest) { final HttpRequest httpRequest = (HttpRequest) msg; //Channel uaChannel = uaChannelCtx.channel(); // connect remote Bootstrap bootstrap = new Bootstrap(); bootstrap.group(uaChannelCtx.channel().eventLoop()).channel(NioSocketChannel.class) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000) .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT) .option(ChannelOption.AUTO_READ, false) .handler(new ApnProxyTunnelChannelInitializer(uaChannelCtx.channel())); final ApnProxyRemote apnProxyRemote = uaChannelCtx.channel() .attr(ApnProxyConnectionAttribute.ATTRIBUTE_KEY).get().getRemote(); // set local address if (StringUtils.isNotBlank(ApnProxyLocalAddressChooser.choose(apnProxyRemote.getRemoteHost()))) { bootstrap.localAddress(new InetSocketAddress( (ApnProxyLocalAddressChooser.choose(apnProxyRemote.getRemoteHost())), 0)); }/*from w w w . j a v a2s .c o m*/ bootstrap.connect(apnProxyRemote.getRemoteHost(), apnProxyRemote.getRemotePort()) .addListener(new ChannelFutureListener() { @Override public void operationComplete(final ChannelFuture future1) throws Exception { if (future1.isSuccess()) { if (apnProxyRemote.isAppleyRemoteRule()) { uaChannelCtx.pipeline().remove("codec"); uaChannelCtx.pipeline().remove(ApnProxyPreHandler.HANDLER_NAME); uaChannelCtx.pipeline().remove(ApnProxyUserAgentTunnelHandler.HANDLER_NAME); // add relay handler uaChannelCtx.pipeline() .addLast(new ApnProxyRelayHandler("UA --> Remote", future1.channel())); future1.channel() .writeAndFlush(Unpooled.copiedBuffer( constructConnectRequestForProxy(httpRequest, apnProxyRemote), CharsetUtil.UTF_8)) .addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future2) throws Exception { if (!future2.channel().config() .getOption(ChannelOption.AUTO_READ)) { future2.channel().read(); } } }); } else { HttpResponse proxyConnectSuccessResponse = new DefaultFullHttpResponse( HttpVersion.HTTP_1_1, new HttpResponseStatus(200, "Connection established")); uaChannelCtx.writeAndFlush(proxyConnectSuccessResponse) .addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future2) throws Exception { // remove handlers uaChannelCtx.pipeline().remove("codec"); uaChannelCtx.pipeline().remove(ApnProxyPreHandler.HANDLER_NAME); uaChannelCtx.pipeline() .remove(ApnProxyUserAgentTunnelHandler.HANDLER_NAME); // add relay handler uaChannelCtx.pipeline() .addLast(new ApnProxyRelayHandler( "UA --> " + apnProxyRemote.getRemoteAddr(), future1.channel())); } }); } } else { if (uaChannelCtx.channel().isActive()) { uaChannelCtx.channel().writeAndFlush(Unpooled.EMPTY_BUFFER) .addListener(ChannelFutureListener.CLOSE); } } } }); } ReferenceCountUtil.release(msg); }
From source file:com.xx_dev.apn.socks.remote.SocksServerConnectHandler.java
License:Apache License
@Override public void channelRead0(final ChannelHandlerContext ctx, final SocksCmdRequest request) throws Exception { Promise<Channel> promise = ctx.executor().newPromise(); promise.addListener(new GenericFutureListener<Future<Channel>>() { @Override/*from www . j a v a 2 s. c om*/ public void operationComplete(final Future<Channel> future) throws Exception { final Channel outboundChannel = future.getNow(); if (future.isSuccess()) { restLogger.info(request.host() + ":" + request.port() + "," + "T"); ctx.channel().writeAndFlush(new SocksCmdResponse(SocksCmdStatus.SUCCESS, request.addressType())) .addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture channelFuture) { ctx.pipeline().remove(SocksServerConnectHandler.this); outboundChannel.pipeline().addLast(new RelayHandler(ctx.channel())); ctx.pipeline().addLast(new RelayHandler(outboundChannel)); } }); } else { restLogger.info(request.host() + ":" + request.port() + "," + "F"); ctx.channel() .writeAndFlush(new SocksCmdResponse(SocksCmdStatus.FAILURE, request.addressType())); SocksServerUtils.closeOnFlush(ctx.channel()); } } }); final Channel inboundChannel = ctx.channel(); b.group(inboundChannel.eventLoop()).channel(NioSocketChannel.class) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000).option(ChannelOption.SO_KEEPALIVE, true) .handler(new DirectClientHandler(promise)); b.connect(request.host(), request.port()).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { // Connection established use handler provided results } else { // Close the connection if the connection attempt has failed. restLogger.info(request.host() + ":" + request.port() + "," + "F"); ctx.channel() .writeAndFlush(new SocksCmdResponse(SocksCmdStatus.FAILURE, request.addressType())); SocksServerUtils.closeOnFlush(ctx.channel()); } } }); }
From source file:com.xx_dev.apn.socks.remote.SocksServerHandler.java
License:Apache License
@Override public void channelRead0(ChannelHandlerContext ctx, SocksRequest socksRequest) throws Exception { switch (socksRequest.requestType()) { case INIT: {//from w w w . j a v a2 s . c o m // auth support example //ctx.pipeline().addFirst(new SocksAuthRequestDecoder()); //ctx.write(new SocksInitResponse(SocksAuthScheme.AUTH_PASSWORD)); ctx.pipeline().addAfter("log", "cmdRequstDecoder", new SocksCmdRequestDecoder()); ctx.write(new SocksInitResponse(SocksAuthScheme.NO_AUTH)); break; } case AUTH: ctx.pipeline().addAfter("log", "cmdRequstDecoder", new SocksCmdRequestDecoder()); ctx.write(new SocksAuthResponse(SocksAuthStatus.SUCCESS)); break; case CMD: SocksCmdRequest req = (SocksCmdRequest) socksRequest; if (req.cmdType() == SocksCmdType.CONNECT) { ctx.pipeline().addLast(new SocksServerConnectHandler()); ctx.pipeline().remove(this); ctx.fireChannelRead(socksRequest); } else { ctx.close(); } break; case UNKNOWN: ctx.close(); break; } }