Java Code Examples for io.netty.channel.ChannelPipeline#addBefore()

The following examples show how to use io.netty.channel.ChannelPipeline#addBefore() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Http2OrHttpHandler.java    From zuul with Apache License 2.0 6 votes vote down vote up
private void configureHttp2(ChannelPipeline pipeline) {

        // setup the initial stream settings for the server to use.
        Http2Settings settings = new Http2Settings()
                .maxConcurrentStreams(maxConcurrentStreams)
                .initialWindowSize(initialWindowSize)
                .headerTableSize(maxHeaderTableSize)
                .maxHeaderListSize(maxHeaderListSize);

        Http2FrameCodec frameCodec = Http2FrameCodecBuilder.forServer()
                .frameLogger(FRAME_LOGGER)
                .initialSettings(settings)
                .validateHeaders(true)
                .build();

        Http2MultiplexHandler multiplexHandler = new Http2MultiplexHandler(http2StreamHandler);

        // The frame codec MUST be in the pipeline.
        pipeline.addBefore("codec_placeholder", /* name= */ null, frameCodec);
        pipeline.replace("codec_placeholder", HTTP_CODEC_HANDLER_NAME, multiplexHandler);
    }
 
Example 2
Source File: MixinClientConnection.java    From ViaFabric with MIT License 6 votes vote down vote up
@Redirect(method = "setCompressionThreshold", at = @At(
        value = "INVOKE",
        remap = false,
        target = "Lio/netty/channel/ChannelPipeline;addBefore(Ljava/lang/String;Ljava/lang/String;Lio/netty/channel/ChannelHandler;)Lio/netty/channel/ChannelPipeline;"
))
private ChannelPipeline decodeEncodePlacement(ChannelPipeline instance, String base, String newHandler, ChannelHandler handler) {
    // Fixes the handler order
    switch (base) {
        case "decoder": {
            if (instance.get(CommonTransformer.HANDLER_DECODER_NAME) != null)
                base = CommonTransformer.HANDLER_DECODER_NAME;
            break;
        }
        case "encoder": {
            if (instance.get(CommonTransformer.HANDLER_ENCODER_NAME) != null)
                base = CommonTransformer.HANDLER_ENCODER_NAME;
            break;
        }
    }
    return instance.addBefore(base, newHandler, handler);
}
 
Example 3
Source File: PgSocketConnection.java    From vertx-sql-client with Apache License 2.0 6 votes vote down vote up
void upgradeToSSLConnection(Handler<AsyncResult<Void>> completionHandler) {
  ChannelPipeline pipeline = socket.channelHandlerContext().pipeline();
  Promise<Void> upgradePromise = Promise.promise();
  upgradePromise.future().onComplete(ar->{
    if (ar.succeeded()) {
      completionHandler.handle(Future.succeededFuture());
    } else {
      Throwable cause = ar.cause();
      if (cause instanceof DecoderException) {
        DecoderException err = (DecoderException) cause;
        cause = err.getCause();
      }
      completionHandler.handle(Future.failedFuture(cause));
    }
  });
  pipeline.addBefore("handler", "initiate-ssl-handler", new InitiateSslHandler(this, upgradePromise));
}
 
Example 4
Source File: ProxyProvider.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
public void addProxyHandler(Channel channel) {
	ChannelPipeline pipeline = channel.pipeline();
	pipeline.addFirst(NettyPipeline.ProxyHandler, newProxyHandler());

	if (pipeline.get(NettyPipeline.LoggingHandler) != null) {
		pipeline.addBefore(NettyPipeline.ProxyHandler,
				NettyPipeline.ProxyLoggingHandler,
				new LoggingHandler("reactor.netty.proxy"));
	}
}
 
Example 5
Source File: HttpClientConfig.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
static void configureHttp11Pipeline(ChannelPipeline p,
		boolean acceptGzip,
		HttpResponseDecoderSpec decoder,
		@Nullable Supplier<? extends ChannelMetricsRecorder> metricsRecorder,
		@Nullable Function<String, String> uriTagValue) {
	p.addBefore(NettyPipeline.ReactiveBridge,
			NettyPipeline.HttpCodec,
			new HttpClientCodec(
					decoder.maxInitialLineLength(),
					decoder.maxHeaderSize(),
					decoder.maxChunkSize(),
					decoder.failOnMissingResponse,
					decoder.validateHeaders(),
					decoder.initialBufferSize(),
					decoder.parseHttpAfterConnectRequest));

	if (acceptGzip) {
		p.addAfter(NettyPipeline.HttpCodec, NettyPipeline.HttpDecompressor, new HttpContentDecompressor());
	}

	if (metricsRecorder != null) {
		ChannelMetricsRecorder channelMetricsRecorder = metricsRecorder.get();
		if (channelMetricsRecorder instanceof HttpClientMetricsRecorder) {
			p.addBefore(NettyPipeline.ReactiveBridge,
					NettyPipeline.HttpMetricsHandler,
					new HttpClientMetricsHandler((HttpClientMetricsRecorder) channelMetricsRecorder, uriTagValue));
		}
	}
}
 
Example 6
Source File: RfbSecurityHandshaker.java    From jfxvnc with Apache License 2.0 5 votes vote down vote up
public final ChannelFuture handshake(Channel channel, boolean sendResponse, ChannelPromise promise) {
  ChannelPipeline p = channel.pipeline();
  ChannelHandlerContext ctx = p.context(RfbClientDecoder.class);
  p.addBefore(ctx.name(), "rfb-security-decoder", newSecurityDecoder());

  ChannelHandlerContext ctx2 = p.context(RfbClientEncoder.class);
  p.addBefore(ctx2.name(), "rfb-security-encoder", newSecurityEncoder());
  if (!sendResponse) {
    return promise.setSuccess();
  }
  channel.writeAndFlush(Unpooled.buffer(1).writeByte(securityType.getType()), promise);
  return promise;
}
 
Example 7
Source File: ProxyEndpoint.java    From zuul with Apache License 2.0 5 votes vote down vote up
private void writeClientRequestToOrigin(final PooledConnection conn, int readTimeout) {
    final Channel ch = conn.getChannel();
    passport.setOnChannel(ch);

    // set read timeout on origin channel
    ch.attr(ClientTimeoutHandler.ORIGIN_RESPONSE_READ_TIMEOUT).set(readTimeout);

    context.set(ORIGIN_CHANNEL, ch);
    context.set(POOLED_ORIGIN_CONNECTION_KEY, conn);

    preWriteToOrigin(chosenServer.get(), zuulRequest);

    final ChannelPipeline pipeline = ch.pipeline();
    originResponseReceiver = getOriginResponseReceiver();
    pipeline.addBefore("connectionPoolHandler", OriginResponseReceiver.CHANNEL_HANDLER_NAME, originResponseReceiver);

    // check if body needs to be repopulated for retry
    repopulateRetryBody();

    ch.write(zuulRequest);
    writeBufferedBodyContent(zuulRequest, ch);
    ch.flush();

    //Get ready to read origin's response
    ch.read();

    originConn = conn;
    channelCtx.read();
}
 
Example 8
Source File: MqttServerImpl.java    From vertx-mqtt with Apache License 2.0 5 votes vote down vote up
private void initChannel(ChannelPipeline pipeline) {

    pipeline.addBefore("handler", "mqttEncoder", MqttEncoder.INSTANCE);
    if (this.options.getMaxMessageSize() > 0) {
      pipeline.addBefore("handler", "mqttDecoder", new MqttDecoder(this.options.getMaxMessageSize()));
    } else {
      // max message size not set, so the default from Netty MQTT codec is used
      pipeline.addBefore("handler", "mqttDecoder", new MqttDecoder());
    }

    // adding the idle state handler for timeout on CONNECT packet
    pipeline.addBefore("handler", "idle", new IdleStateHandler(this.options.timeoutOnConnect(), 0, 0));
    pipeline.addBefore("handler", "timeoutOnConnect", new ChannelDuplexHandler() {

      @Override
      public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {

        if (evt instanceof IdleStateEvent) {
          IdleStateEvent e = (IdleStateEvent) evt;
          if (e.state() == IdleState.READER_IDLE) {
            // as MQTT 3.1.1 describes, if no packet is sent after a "reasonable" time (here CONNECT timeout)
            // the connection is closed
            ctx.channel().close();
          }
        }
      }
    });
  }
 
Example 9
Source File: AccessoryHandler.java    From HAP-Java with MIT License 5 votes vote down vote up
@Override
public void channelRead0(ChannelHandlerContext ctx, FullHttpRequest req) throws Exception {
  try {
    HttpResponse response = connection.handleRequest(new FullRequestHttpRequestImpl(req));
    if (response.doUpgrade()) {
      ChannelPipeline pipeline = ctx.channel().pipeline();
      pipeline.addBefore(
          ServerInitializer.HTTP_HANDLER_NAME, "binary", new BinaryHandler(connection));
    }
    sendResponse(response, ctx);
  } catch (Exception e) {
    LOGGER.warn("Error handling homekit http request", e);
    sendResponse(HttpResponseStatus.INTERNAL_SERVER_ERROR, "Error: " + e.getMessage(), ctx);
  }
}
 
Example 10
Source File: ProxyTunnelInitHandler.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Override
public void handlerAdded(ChannelHandlerContext ctx) {
    ChannelPipeline pipeline = ctx.pipeline();
    pipeline.addBefore(ctx.name(), null, httpCodecSupplier.get());
    HttpRequest connectRequest = connectRequest();
    ctx.channel().writeAndFlush(connectRequest).addListener(f -> {
        if (!f.isSuccess()) {
            ctx.close();
            sourcePool.release(ctx.channel());
            initPromise.setFailure(new IOException("Unable to send CONNECT request to proxy", f.cause()));
        }
    });
}
 
Example 11
Source File: MySQLSocketConnection.java    From vertx-sql-client with Apache License 2.0 5 votes vote down vote up
@Override
public void init() {
  codec = new MySQLCodec(this);
  ChannelPipeline pipeline = socket.channelHandlerContext().pipeline();
  pipeline.addBefore("handler", "codec", codec);
  super.init();
}
 
Example 12
Source File: MSSQLCodec.java    From vertx-sql-client with Apache License 2.0 5 votes vote down vote up
public static void initPipeLine(ChannelPipeline pipeline) {
  final ArrayDeque<MSSQLCommandCodec<?, ?>> inflight = new ArrayDeque<>();

  TdsMessageEncoder encoder = new TdsMessageEncoder(inflight);
  TdsMessageDecoder messageDecoder = new TdsMessageDecoder(inflight, encoder);
  TdsPacketDecoder packetDecoder = new TdsPacketDecoder();
  pipeline.addBefore("handler", "encoder", encoder);
  pipeline.addBefore("encoder", "messageDecoder", messageDecoder);
  pipeline.addBefore("messageDecoder", "packetDecoder", packetDecoder);
}
 
Example 13
Source File: DB2SocketConnection.java    From vertx-sql-client with Apache License 2.0 5 votes vote down vote up
@Override
public void init() {
  codec = new DB2Codec(this);
  ChannelPipeline pipeline = socket.channelHandlerContext().pipeline();
  pipeline.addBefore("handler", "codec", codec);
  super.init();
}
 
Example 14
Source File: PgSocketConnection.java    From vertx-sql-client with Apache License 2.0 5 votes vote down vote up
@Override
public void init() {
  codec = new PgCodec();
  ChannelPipeline pipeline = socket.channelHandlerContext().pipeline();
  pipeline.addBefore("handler", "codec", codec);
  super.init();
}
 
Example 15
Source File: PacketHandler.java    From ehacks-pro with GNU General Public License v3.0 5 votes vote down vote up
public PacketHandler(Events eventHandler) {
    this.protector = new MainProtector();
    this.protector.init();
    this.eventHandler = eventHandler;
    try {
        ChannelPipeline pipeline = Wrapper.INSTANCE.mc().getNetHandler().getNetworkManager().channel().pipeline();
        pipeline.addBefore("packet_handler", "PacketHandler", this);
        InteropUtils.log("Attached", "PacketHandler");
    } catch (Exception exception) {
        InteropUtils.log("Error on attaching", "PacketHandler");
    }
}
 
Example 16
Source File: Socks5ProxyHandler.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Override
protected void addCodec(ChannelHandlerContext ctx) throws Exception {
    ChannelPipeline p = ctx.pipeline();
    String name = ctx.name();

    Socks5InitialResponseDecoder decoder = new Socks5InitialResponseDecoder();
    p.addBefore(name, null, decoder);

    decoderName = p.context(decoder).name();
    encoderName = decoderName + ".encoder";

    p.addBefore(name, encoderName, Socks5ClientEncoder.DEFAULT);
}
 
Example 17
Source File: ProtocolHandler.java    From jfxvnc with Apache License 2.0 4 votes vote down vote up
@Override
protected void decode(final ChannelHandlerContext ctx, Object msg, List<Object> out) throws Exception {

  if (msg instanceof ImageRect) {
    final ImageRect rect = (ImageRect) msg;
    render.render(rect);
    return;
  }
  if (msg instanceof ServerDecoderEvent) {
    final ServerDecoderEvent event = (ServerDecoderEvent) msg;
    render.eventReceived(event);
    return;
  }

  if (!(msg instanceof ServerInitEvent)) {
    logger.error("unknown message: {}", msg);
    ctx.fireChannelRead(msg);
    return;
  }

  serverInit = (ServerInitEvent) msg;
  logger.debug("handshake completed with {}", serverInit);

  FrameDecoderHandler frameHandler = new FrameDecoderHandler(serverInit.getPixelFormat());
  if (!frameHandler.isPixelFormatSupported()) {
    ProtocolException e = new ProtocolException(String.format("pixelformat: (%s bpp) not supported yet", serverInit.getPixelFormat().getBitPerPixel()));
    exceptionCaught(ctx, e);
    return;
  }

  ChannelPipeline cp = ctx.pipeline();

  cp.addBefore(ctx.name(), "rfb-encoding-encoder", new PreferedEncodingEncoder());
  PreferedEncoding prefEncodings = getPreferedEncodings(frameHandler.getSupportedEncodings());
  ctx.write(prefEncodings);

  cp.addBefore(ctx.name(), "rfb-pixelformat-encoder", new PixelFormatEncoder());
  ctx.write(serverInit.getPixelFormat());
  ctx.flush();

  cp.addBefore(ctx.name(), "rfb-frame-handler", frameHandler);
  cp.addBefore(ctx.name(), "rfb-keyevent-encoder", new KeyButtonEventEncoder());
  cp.addBefore(ctx.name(), "rfb-pointerevent-encoder", new PointerEventEncoder());
  cp.addBefore(ctx.name(), "rfb-cuttext-encoder", new ClientCutTextEncoder());

  render.eventReceived(getConnectInfoEvent(ctx, prefEncodings));

  render.registerInputEventListener(event -> ctx.writeAndFlush(event, ctx.voidPromise()));

  logger.debug("request full framebuffer update");
  sendFramebufferUpdateRequest(ctx, false, 0, 0, serverInit.getFrameBufferWidth(), serverInit.getFrameBufferHeight());

  logger.trace("channel pipeline: {}", cp.toMap().keySet());
}
 
Example 18
Source File: HttpProxyHandler.java    From netty-4.1.22 with Apache License 2.0 4 votes vote down vote up
@Override
protected void addCodec(ChannelHandlerContext ctx) throws Exception {
    ChannelPipeline p = ctx.pipeline();
    String name = ctx.name();
    p.addBefore(name, null, codec);
}
 
Example 19
Source File: HttpServerConfig.java    From reactor-netty with Apache License 2.0 4 votes vote down vote up
static void configureHttp11OrH2CleartextPipeline(ChannelPipeline p,
		@Nullable BiPredicate<HttpServerRequest, HttpServerResponse> compressPredicate,
		ServerCookieDecoder cookieDecoder,
		ServerCookieEncoder cookieEncoder,
		HttpRequestDecoderSpec decoder,
		boolean forwarded,
		Http2Settings http2Settings,
		ConnectionObserver listener,
		@Nullable Supplier<? extends ChannelMetricsRecorder> metricsRecorder,
		int minCompressionSize,
		ChannelOperations.OnSetup opsFactory,
		@Nullable Function<String, String> uriTagValue) {
	HttpServerCodec httpServerCodec =
			new HttpServerCodec(decoder.maxInitialLineLength(), decoder.maxHeaderSize(),
					decoder.maxChunkSize(), decoder.validateHeaders(), decoder.initialBufferSize());

	Http11OrH2CleartextCodec
			upgrader = new Http11OrH2CleartextCodec(cookieDecoder, cookieEncoder, p.get(NettyPipeline.LoggingHandler) != null,
					forwarded, http2Settings, listener, opsFactory, decoder.validateHeaders());

	ChannelHandler http2ServerHandler = new H2CleartextCodec(upgrader);
	CleartextHttp2ServerUpgradeHandler h2cUpgradeHandler = new CleartextHttp2ServerUpgradeHandler(
			httpServerCodec,
			new HttpServerUpgradeHandler(httpServerCodec, upgrader, decoder.h2cMaxContentLength()),
			http2ServerHandler);

	p.addBefore(NettyPipeline.ReactiveBridge,
	            NettyPipeline.H2CUpgradeHandler, h2cUpgradeHandler)
	 .addBefore(NettyPipeline.ReactiveBridge,
	            NettyPipeline.HttpTrafficHandler,
	            new HttpTrafficHandler(listener, forwarded, compressPredicate, cookieEncoder, cookieDecoder));

	if (ACCESS_LOG) {
		p.addAfter(NettyPipeline.H2CUpgradeHandler, NettyPipeline.AccessLogHandler, new AccessLogHandler());
	}

	boolean alwaysCompress = compressPredicate == null && minCompressionSize == 0;

	if (alwaysCompress) {
		p.addBefore(NettyPipeline.HttpTrafficHandler, NettyPipeline.CompressionHandler, new SimpleCompressionHandler());
	}

	if (metricsRecorder != null) {
		ChannelMetricsRecorder channelMetricsRecorder = metricsRecorder.get();
		if (channelMetricsRecorder instanceof HttpServerMetricsRecorder) {
			p.addAfter(NettyPipeline.HttpTrafficHandler, NettyPipeline.HttpMetricsHandler,
			           new HttpServerMetricsHandler((HttpServerMetricsRecorder) channelMetricsRecorder, uriTagValue));
			if (channelMetricsRecorder instanceof MicrometerHttpServerMetricsRecorder) {
				// MicrometerHttpServerMetricsRecorder does not implement metrics on protocol level
				// ChannelMetricsHandler will be removed from the pipeline
				p.remove(NettyPipeline.ChannelMetricsHandler);
			}
		}
	}
}
 
Example 20
Source File: HttpServerConfig.java    From reactor-netty with Apache License 2.0 4 votes vote down vote up
static void configureHttp11Pipeline(ChannelPipeline p,
		@Nullable BiPredicate<HttpServerRequest, HttpServerResponse> compressPredicate,
		ServerCookieDecoder cookieDecoder,
		ServerCookieEncoder cookieEncoder,
		HttpRequestDecoderSpec decoder,
		boolean forwarded,
		ConnectionObserver listener,
		@Nullable Supplier<? extends ChannelMetricsRecorder> metricsRecorder,
		int minCompressionSize,
		@Nullable Function<String, String> uriTagValue) {
	p.addBefore(NettyPipeline.ReactiveBridge,
	            NettyPipeline.HttpCodec,
	            new HttpServerCodec(decoder.maxInitialLineLength(), decoder.maxHeaderSize(),
	                    decoder.maxChunkSize(), decoder.validateHeaders(), decoder.initialBufferSize()))
	 .addBefore(NettyPipeline.ReactiveBridge,
	            NettyPipeline.HttpTrafficHandler,
	            new HttpTrafficHandler(listener, forwarded, compressPredicate, cookieEncoder, cookieDecoder));

	if (ACCESS_LOG) {
		p.addAfter(NettyPipeline.HttpCodec, NettyPipeline.AccessLogHandler, new AccessLogHandler());
	}

	boolean alwaysCompress = compressPredicate == null && minCompressionSize == 0;

	if (alwaysCompress) {
		p.addBefore(NettyPipeline.HttpTrafficHandler, NettyPipeline.CompressionHandler, new SimpleCompressionHandler());
	}

	if (metricsRecorder != null) {
		ChannelMetricsRecorder channelMetricsRecorder = metricsRecorder.get();
		if (channelMetricsRecorder instanceof HttpServerMetricsRecorder) {
			p.addAfter(NettyPipeline.HttpTrafficHandler, NettyPipeline.HttpMetricsHandler,
			           new HttpServerMetricsHandler((HttpServerMetricsRecorder) channelMetricsRecorder, uriTagValue));
			if (channelMetricsRecorder instanceof MicrometerHttpServerMetricsRecorder) {
				// MicrometerHttpServerMetricsRecorder does not implement metrics on protocol level
				// ChannelMetricsHandler will be removed from the pipeline
				p.remove(NettyPipeline.ChannelMetricsHandler);
			}
		}
	}
}