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

The following examples show how to use io.netty.channel.ChannelPipeline#get() . 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: HttpClientConfig.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
static void configureHttp2Pipeline(ChannelPipeline p, HttpResponseDecoderSpec decoder, Http2Settings http2Settings,
		ConnectionObserver observer) {
	Http2FrameCodecBuilder http2FrameCodecBuilder =
			Http2FrameCodecBuilder.forClient()
			                      .validateHeaders(decoder.validateHeaders())
			                      .initialSettings(http2Settings);

	if (p.get(NettyPipeline.LoggingHandler) != null) {
		http2FrameCodecBuilder.frameLogger(new Http2FrameLogger(LogLevel.DEBUG,
				"reactor.netty.http.client.h2"));
	}

	p.addBefore(NettyPipeline.ReactiveBridge, NettyPipeline.HttpCodec, http2FrameCodecBuilder.build())
	 .addBefore(NettyPipeline.ReactiveBridge, NettyPipeline.H2MultiplexHandler, new Http2MultiplexHandler(new H2Codec()))
	 .addBefore(NettyPipeline.ReactiveBridge, NettyPipeline.HttpTrafficHandler, new HttpTrafficHandler(observer));
}
 
Example 2
Source File: AbstractServerChannelManager.java    From openAGV with Apache License 2.0 6 votes vote down vote up
/**
 * 设置日志是否开启
 *
 * @param key     客户端关键字,须保证唯一
 * @param enabled 是否开启,true为开启
 */
public void setLoggingEnabled(String key, boolean enabled, Class<?> channelManagerClass, String loggingName) {
    if (!initialized) {
        throw new IllegalArgumentException("服务没有初始化成功");
    }

    ClientEntry entry = clientEntries.get(key);
    if (null == entry) {
        throw new NullPointerException("根据[" + key + "]查找不到对应的ClientEntry对象,可能没有注册成功,请检查!");
    }

    Channel channel = entry.getChannel();
    if (null == channel) {
        LOG.debug("根据[{}]没有找到对应的channel/pipeline,退出处理!", key);
        return;
    }

    ChannelPipeline pipeline = channel.pipeline();
    if (enabled && pipeline.get(loggingName) == null) {
        pipeline.addFirst(loggingName,
                new LoggingHandler(channelManagerClass));
    } else if (!enabled && pipeline.get(loggingName) != null) {
        pipeline.remove(loggingName);
    }
}
 
Example 3
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 4
Source File: NettyPipelineSslUtils.java    From servicetalk with Apache License 2.0 6 votes vote down vote up
/**
 * Extract the {@link SSLSession} from the {@link ChannelPipeline} if the {@link SslHandshakeCompletionEvent}
 * is successful.
 *
 * @param pipeline the {@link ChannelPipeline} which contains handler containing the {@link SSLSession}.
 * @param sslEvent the event indicating a SSL/TLS handshake completed.
 * @param failureConsumer invoked if a failure is encountered.
 * @return The {@link SSLSession} or {@code null} if none can be found.
 */
@Nullable
public static SSLSession extractSslSession(ChannelPipeline pipeline,
                                           SslHandshakeCompletionEvent sslEvent,
                                           Consumer<Throwable> failureConsumer) {
    if (sslEvent.isSuccess()) {
        final SslHandler sslHandler = pipeline.get(SslHandler.class);
        if (sslHandler != null) {
            return sslHandler.engine().getSession();
        } else {
            failureConsumer.accept(new IllegalStateException("Unable to find " + SslHandler.class.getName() +
                    " in the pipeline."));
        }
    } else {
        failureConsumer.accept(sslEvent.cause());
    }
    return null;
}
 
Example 5
Source File: WebSocketServerProtocolHandler.java    From netty4.0.27Learn with Apache License 2.0 5 votes vote down vote up
@Override
public void handlerAdded(ChannelHandlerContext ctx) {
    ChannelPipeline cp = ctx.pipeline();
    if (cp.get(WebSocketServerProtocolHandshakeHandler.class) == null) {
        // Add the WebSocketHandshakeHandler before this one.
        ctx.pipeline().addBefore(ctx.name(), WebSocketServerProtocolHandshakeHandler.class.getName(),
                new WebSocketServerProtocolHandshakeHandler(websocketPath, subprotocols,
                        allowExtensions, maxFramePayloadLength));
    }
}
 
Example 6
Source File: HttpServerHandler.java    From armeria with Apache License 2.0 5 votes vote down vote up
private void handleHttp2Settings(ChannelHandlerContext ctx, Http2Settings h2settings) {
    if (h2settings.isEmpty()) {
        logger.trace("{} HTTP/2 settings: <empty>", ctx.channel());
    } else {
        logger.debug("{} HTTP/2 settings: {}", ctx.channel(), h2settings);
    }

    if (protocol == H1) {
        protocol = H2;
    } else if (protocol == H1C) {
        protocol = H2C;
    }

    final ChannelPipeline pipeline = ctx.pipeline();
    final Http2ServerConnectionHandler handler = pipeline.get(Http2ServerConnectionHandler.class);
    if (responseEncoder == null) {
        responseEncoder = newServerHttp2ObjectEncoder(ctx, handler);
    } else if (responseEncoder instanceof Http1ObjectEncoder) {
        responseEncoder.close();
        responseEncoder = newServerHttp2ObjectEncoder(ctx, handler);
    }

    // Update the connection-level flow-control window size.
    final int initialWindow = config.http2InitialConnectionWindowSize();
    if (initialWindow > DEFAULT_WINDOW_SIZE) {
        incrementLocalWindowSize(pipeline, initialWindow - DEFAULT_WINDOW_SIZE);
    }
}
 
Example 7
Source File: ReactorNetty.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
static boolean mustChunkFileTransfer(Connection c, Path file) {
	// if channel multiplexing a parent channel as an http2 stream
	if (c.channel().parent() != null && c.channel().parent().pipeline().get(Http2ConnectionHandler.class) != null) {
		return true;
	}
	ChannelPipeline p = c.channel().pipeline();
	return p.get(SslHandler.class) != null  ||
			p.get(NettyPipeline.CompressionHandler) != null ||
			(!(c.channel().eventLoop() instanceof NioEventLoop) &&
					!"file".equals(file.toUri().getScheme()));
}
 
Example 8
Source File: WebSocketIndexPageHandler.java    From tools-journey with Apache License 2.0 5 votes vote down vote up
private static String getWebSocketLocation(ChannelPipeline cp, HttpRequest req, String path) {
    String protocol = "ws";
    if (cp.get(SslHandler.class) != null) {
        // SSL in use so use Secure WebSockets
        protocol = "wss";
    }
    return protocol + "://" + req.headers().get(HttpHeaderNames.HOST) + path;
}
 
Example 9
Source File: HttpFilterAdapterImpl.java    From yfs with Apache License 2.0 5 votes vote down vote up
@Override
public void proxyToServerConnectionSucceeded(final ChannelHandlerContext serverCtx) {
    ChannelPipeline pipeline = serverCtx.pipeline();
    //当没有修改getMaximumResponseBufferSizeInBytes中buffer默认的大小时,下面两个handler是不存在的
    if (pipeline.get("inflater") != null) {
        pipeline.remove("inflater");
    }
    if (pipeline.get("aggregator") != null) {
        pipeline.remove("aggregator");
    }
    super.proxyToServerConnectionSucceeded(serverCtx);
}
 
Example 10
Source File: HttpServerConfig.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
@Override
public void handlerAdded(ChannelHandlerContext ctx) {
	ChannelPipeline pipeline = ctx.pipeline();
	pipeline.addAfter(ctx.name(), NettyPipeline.HttpCodec, upgrader.http2FrameCodec)
	        .addAfter(NettyPipeline.HttpCodec, NettyPipeline.H2MultiplexHandler, new Http2MultiplexHandler(upgrader))
	        .remove(this);
	if (pipeline.get(NettyPipeline.AccessLogHandler) != null){
		pipeline.remove(NettyPipeline.AccessLogHandler);
	}
	if (pipeline.get(NettyPipeline.CompressionHandler) != null) {
		pipeline.remove(NettyPipeline.CompressionHandler);
	}
	pipeline.remove(NettyPipeline.HttpTrafficHandler);
	pipeline.remove(NettyPipeline.ReactiveBridge);
}
 
Example 11
Source File: DFWSRequestHandler.java    From dfactor with MIT License 5 votes vote down vote up
private static String _getWebSocketLocation(ChannelPipeline cp, HttpRequest req, String path) {
	String protocol = "ws";
	if (cp.get(SslHandler.class) != null) {
		// SSL in use so use Secure WebSockets
		protocol = "wss";
	}
	return protocol + "://" + req.headers().get(HttpHeaderNames.HOST) + path;
}
 
Example 12
Source File: WebSocketServerProtocolHandshakeHandler.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
private static String getWebSocketLocation(ChannelPipeline cp, HttpRequest req, String path) {
    String protocol = "ws";
    if (cp.get(SslHandler.class) != null) {
        // SSL in use so use Secure WebSockets
        protocol = "wss";
    }
    String host = req.headers().get(HttpHeaderNames.HOST);
    return protocol + "://" + host + path;
}
 
Example 13
Source File: MobileStateHolderUtil.java    From blynk-server with GNU General Public License v3.0 5 votes vote down vote up
private static MobileStateHolder getAppState(ChannelPipeline pipeline) {
    MobileHandler handler = pipeline.get(MobileHandler.class);
    if (handler == null) {
        return getShareState(pipeline);
    }
    return handler.state;
}
 
Example 14
Source File: WebSocketServerProtocolHandler.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Override
public void handlerAdded(ChannelHandlerContext ctx) {
    ChannelPipeline cp = ctx.pipeline();
    if (cp.get(WebSocketServerProtocolHandshakeHandler.class) == null) {
        // Add the WebSocketHandshakeHandler before this one.
        ctx.pipeline().addBefore(ctx.name(), WebSocketServerProtocolHandshakeHandler.class.getName(),
                new WebSocketServerProtocolHandshakeHandler(websocketPath, subprotocols,
                        allowExtensions, maxFramePayloadLength, allowMaskMismatch, checkStartsWith));
    }
    if (cp.get(Utf8FrameValidator.class) == null) {
        // Add the UFT8 checking before this one.
        ctx.pipeline().addBefore(ctx.name(), Utf8FrameValidator.class.getName(),
                new Utf8FrameValidator());
    }
}
 
Example 15
Source File: WebSocketIndexPageHandler.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
private static String getWebSocketLocation(ChannelPipeline cp, HttpRequest req, String path) {
    String protocol = "ws";
    if (cp.get(SslHandler.class) != null) {
        // SSL in use so use Secure WebSockets
        protocol = "wss";
    }
    return protocol + "://" + req.headers().get(HttpHeaderNames.HOST) + path;
}
 
Example 16
Source File: WebSocketClient.java    From ext-opensource-netty with Mozilla Public License 2.0 5 votes vote down vote up
private String getWebSocketUrl(ChannelPipeline cp, String path) {
	String protocol = "ws";
	if (cp.get(SslHandler.class) != null) {
		// SSL in use so use Secure WebSockets
		protocol = "wss";
	}
	return protocol + "://" + this.getHost() + path;
}
 
Example 17
Source File: DefaultClientChannelManager.java    From zuul with Apache License 2.0 4 votes vote down vote up
public static void removeHandlerFromPipeline(final String handlerName, final ChannelPipeline pipeline) {
    if (pipeline.get(handlerName) != null) {
        pipeline.remove(handlerName);
    }
}
 
Example 18
Source File: SslProvider.java    From reactor-netty with Apache License 2.0 4 votes vote down vote up
public void addSslHandler(Channel channel, @Nullable SocketAddress remoteAddress, boolean sslDebug) {
	SslHandler sslHandler;

	if (remoteAddress instanceof InetSocketAddress) {
		InetSocketAddress sniInfo = (InetSocketAddress) remoteAddress;
		sslHandler = getSslContext()
				.newHandler(channel.alloc(), sniInfo.getHostString(), sniInfo.getPort());

		if (log.isDebugEnabled()) {
			log.debug(format(channel, "SSL enabled using engine {} and SNI {}"),
					sslHandler.engine().getClass().getSimpleName(), sniInfo);
		}
	}
	else {
		sslHandler = getSslContext().newHandler(channel.alloc());

		if (log.isDebugEnabled()) {
			log.debug(format(channel, "SSL enabled using engine {}"),
					sslHandler.engine().getClass().getSimpleName());
		}
	}

	configure(sslHandler);

	ChannelPipeline pipeline = channel.pipeline();
	if (pipeline.get(NettyPipeline.ProxyHandler) != null) {
		pipeline.addAfter(NettyPipeline.ProxyHandler, NettyPipeline.SslHandler, sslHandler);
	}
	else {
		pipeline.addFirst(NettyPipeline.SslHandler, sslHandler);
	}

	if (pipeline.get(NettyPipeline.LoggingHandler) != null) {
		pipeline.addAfter(NettyPipeline.LoggingHandler, NettyPipeline.SslReader, new SslReadHandler());
		if (sslDebug) {
			pipeline.addBefore(NettyPipeline.SslHandler,
					NettyPipeline.SslLoggingHandler,
					new LoggingHandler("reactor.netty.tcp.ssl"));
		}

	}
	else {
		pipeline.addAfter(NettyPipeline.SslHandler, NettyPipeline.SslReader, new SslReadHandler());
	}
}
 
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: WebSocketClientHandshaker.java    From netty4.0.27Learn with Apache License 2.0 4 votes vote down vote up
/**
 * Validates and finishes the opening handshake initiated by {@link #handshake}}.
 *
 * @param channel
 *            Channel
 * @param response
 *            HTTP response containing the closing handshake details
 */
public final void finishHandshake(Channel channel, FullHttpResponse response) {
    verify(response);

    // Verify the subprotocol that we received from the server.
    // This must be one of our expected subprotocols - or null/empty if we didn't want to speak a subprotocol
    String receivedProtocol = response.headers().get(HttpHeaders.Names.SEC_WEBSOCKET_PROTOCOL);
    receivedProtocol = receivedProtocol != null ? receivedProtocol.trim() : null;
    String expectedProtocol = expectedSubprotocol != null ? expectedSubprotocol : "";
    boolean protocolValid = false;

    if (expectedProtocol.isEmpty() && receivedProtocol == null) {
        // No subprotocol required and none received
        protocolValid = true;
        setActualSubprotocol(expectedSubprotocol); // null or "" - we echo what the user requested
    } else if (!expectedProtocol.isEmpty() && receivedProtocol != null && !receivedProtocol.isEmpty()) {
        // We require a subprotocol and received one -> verify it
        for (String protocol : StringUtil.split(expectedSubprotocol, ',')) {
            if (protocol.trim().equals(receivedProtocol)) {
                protocolValid = true;
                setActualSubprotocol(receivedProtocol);
                break;
            }
        }
    } // else mixed cases - which are all errors

    if (!protocolValid) {
        throw new WebSocketHandshakeException(String.format(
                "Invalid subprotocol. Actual: %s. Expected one of: %s",
                receivedProtocol, expectedSubprotocol));
    }

    setHandshakeComplete();

    ChannelPipeline p = channel.pipeline();
    // Remove decompressor from pipeline if its in use
    HttpContentDecompressor decompressor = p.get(HttpContentDecompressor.class);
    if (decompressor != null) {
        p.remove(decompressor);
    }

    // Remove aggregator if present before
    HttpObjectAggregator aggregator = p.get(HttpObjectAggregator.class);
    if (aggregator != null) {
        p.remove(aggregator);
    }

    ChannelHandlerContext ctx = p.context(HttpResponseDecoder.class);
    if (ctx == null) {
        ctx = p.context(HttpClientCodec.class);
        if (ctx == null) {
            throw new IllegalStateException("ChannelPipeline does not contain " +
                    "a HttpRequestEncoder or HttpClientCodec");
        }
        p.replace(ctx.name(), "ws-decoder", newWebsocketDecoder());
    } else {
        if (p.get(HttpRequestEncoder.class) != null) {
            p.remove(HttpRequestEncoder.class);
        }
        p.replace(ctx.name(),
                "ws-decoder", newWebsocketDecoder());
    }
}