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

The following examples show how to use io.netty.channel.ChannelPipeline#replace() . 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: OptionalSslHandler.java    From drift with Apache License 2.0 6 votes vote down vote up
@Override
protected void decode(ChannelHandlerContext context, ByteBuf in, List<Object> out)
{
    // minimum bytes required to detect ssl
    if (in.readableBytes() < SSL_RECORD_HEADER_LENGTH) {
        return;
    }

    ChannelPipeline pipeline = context.pipeline();
    if (isTls(in, in.readerIndex())) {
        pipeline.replace(this, "ssl", sslContext.newHandler(context.alloc()));
    }
    else {
        pipeline.remove(this);
    }
}
 
Example 2
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 3
Source File: SpigotServerConnectionChannel.java    From ProtocolSupport with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
protected void initChannel(Channel channel) {
	ChannelPipeline pipeline = channel.pipeline();
	NetworkManagerWrapper networkmanager = new SpigotNetworkManagerWrapper(channel, (NetworkManager) pipeline.get(SpigotChannelHandlers.NETWORK_MANAGER));
	networkmanager.setPacketListener(new SpigotFakePacketListener(networkmanager));
	ConnectionImpl connection = new ConnectionImpl(networkmanager);
	ProtocolStorage.addConnection(channel.remoteAddress(), connection);
	pipeline.addAfter(SpigotChannelHandlers.READ_TIMEOUT, ChannelHandlers.INITIAL_DECODER, new InitialPacketDecoder());
	pipeline.addBefore(SpigotChannelHandlers.NETWORK_MANAGER, ChannelHandlers.LOGIC, new LogicHandler(connection, Packet.class));
	pipeline.remove("legacy_query");
	pipeline.replace(SpigotChannelHandlers.READ_TIMEOUT, SpigotChannelHandlers.READ_TIMEOUT, new SimpleReadTimeoutHandler(30));
	pipeline.replace(SpigotChannelHandlers.SPLITTER, SpigotChannelHandlers.SPLITTER, new SpigotWrappedSplitter());
	pipeline.replace(SpigotChannelHandlers.PREPENDER, SpigotChannelHandlers.PREPENDER, new SpigotWrappedPrepender());
	pipeline.addAfter(SpigotChannelHandlers.PREPENDER, ChannelHandlers.RAW_CAPTURE_SEND, new RawPacketDataCaptureSend(connection));
	pipeline.addAfter(SpigotChannelHandlers.SPLITTER, ChannelHandlers.RAW_CAPTURE_RECEIVE, new RawPacketDataCaptureReceive(connection));
	if (replaceDecoderEncoder) {
		if (pipeline.get(SpigotChannelHandlers.DECODER).getClass().equals(net.minecraft.server.v1_16_R1.PacketDecoder.class)) {
			pipeline.replace(SpigotChannelHandlers.DECODER, SpigotChannelHandlers.DECODER, new SpigotPacketDecoder());
		}
		if (pipeline.get(SpigotChannelHandlers.ENCODER).getClass().equals(net.minecraft.server.v1_16_R1.PacketEncoder.class)) {
			pipeline.replace(SpigotChannelHandlers.ENCODER, SpigotChannelHandlers.ENCODER, new SpigotPacketEncoder());
		}
	}
}
 
Example 4
Source File: PipeLineBuilder.java    From ProtocolSupportBungee with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public void buildBungeeClientCodec(Channel channel, Connection connection) {
	ChannelPipeline pipeline = channel.pipeline();
	NetworkDataCache cache = new NetworkDataCache();
	cache.storeIn(connection);
	pipeline.replace(PipelineUtils.PACKET_DECODER, PipelineUtils.PACKET_DECODER, new FromClientPacketDecoder(connection, cache));
	pipeline.replace(PipelineUtils.PACKET_ENCODER, PipelineUtils.PACKET_ENCODER, new ToClientPacketEncoder(connection, cache));
	pipeline.get(CustomHandlerBoss.class).setHandlerChangeListener((handler) -> {
		try {
			return (handler instanceof UpstreamBridge) ? new EntityRewriteUpstreamBridge(
				ReflectionUtils.getFieldValue(handler, "con"), connection.getVersion()
			) : handler;
		} catch (IllegalArgumentException | IllegalAccessException e) {
			throw new RuntimeException(e);
		}
	});
}
 
Example 5
Source File: HardwareLoginHandler.java    From blynk-server with GNU General Public License v3.0 6 votes vote down vote up
private void createSessionAndReregister(ChannelHandlerContext ctx,
                                        User user, DashBoard dash, Device device, int msgId) {
    HardwareStateHolder hardwareStateHolder = new HardwareStateHolder(user, dash, device);

    ChannelPipeline pipeline = ctx.pipeline();
    pipeline.replace(this, "HHArdwareHandler", new HardwareHandler(holder, hardwareStateHolder));

    Session session = holder.sessionDao.getOrCreateSessionByUser(
            hardwareStateHolder.userKey, ctx.channel().eventLoop());

    if (session.isSameEventLoop(ctx)) {
        completeLogin(ctx.channel(), session, user, dash, device, msgId);
    } else {
        log.debug("Re registering hard channel. {}", ctx.channel());
        ReregisterChannelUtil.reRegisterChannel(ctx, session, channelFuture ->
                completeLogin(channelFuture.channel(), session, user, dash, device, msgId));
    }
}
 
Example 6
Source File: PipeLineBuilder.java    From ProtocolSupportBungee with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public void buildBungeeServer(Channel channel, Connection connection) {
	ChannelPipeline pipeline = channel.pipeline();
	pipeline.addFirst(new EncapsulatedHandshakeSender(null, false));
	NetworkDataCache cache = NetworkDataCache.getFrom(connection);
	pipeline.replace(PipelineUtils.PACKET_DECODER, PipelineUtils.PACKET_DECODER, new FromServerPacketDecoder(connection, cache));
	pipeline.replace(PipelineUtils.PACKET_ENCODER, PipelineUtils.PACKET_ENCODER, new ToServerPacketEncoder(connection, cache));
	pipeline.get(CustomHandlerBoss.class).setHandlerChangeListener(handler -> {
		try {
			return (handler instanceof DownstreamBridge) ? new EntityRewriteDownstreamBridge(
				ReflectionUtils.getFieldValue(handler, "con"), connection.getVersion()
			) : handler;
		} catch (IllegalArgumentException | IllegalAccessException e) {
			throw new RuntimeException(e);
		}
	});
}
 
Example 7
Source File: PipeLineBuilder.java    From ProtocolSupportBungee with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public void buildBungeeClientCodec(Channel channel, Connection connection) {
	ChannelPipeline pipeline = channel.pipeline();
	NetworkDataCache cache = new NetworkDataCache();
	cache.storeIn(connection);
	pipeline.replace(PipelineUtils.PACKET_DECODER, PipelineUtils.PACKET_DECODER, new FromClientPacketDecoder(connection, cache));
	pipeline.replace(PipelineUtils.PACKET_ENCODER, PipelineUtils.PACKET_ENCODER, new ToClientPacketEncoder(connection, cache));
	pipeline.get(CustomHandlerBoss.class).setHandlerChangeListener((handler) -> {
		try {
			return (handler instanceof UpstreamBridge) ? new EntityRewriteUpstreamBridge(
				ReflectionUtils.getFieldValue(handler, "con"), connection.getVersion()
			) : handler;
		} catch (IllegalArgumentException | IllegalAccessException e) {
			throw new RuntimeException(e);
		}
	});
}
 
Example 8
Source File: InitialPacketDecoder.java    From ProtocolSupportBungee with GNU Affero General Public License v3.0 6 votes vote down vote up
protected void setProtocol(Channel channel, ProtocolVersion version) {
	ConnectionImpl connection = prepare(channel, version);
	IPipeLineBuilder builder = InitialPacketDecoder.BUILDERS.get(connection.getVersion());
	builder.buildBungeeClientCodec(channel, connection);
	if (encapsulatedinfo == null) {
		builder.buildBungeeClientPipeLine(channel, connection);
	} else {
		ChannelPipeline pipeline = channel.pipeline();
		pipeline.replace(PipelineUtils.FRAME_DECODER, PipelineUtils.FRAME_DECODER, new VarIntFrameDecoder());
		if (encapsulatedinfo.hasCompression()) {
			pipeline.addAfter(PipelineUtils.FRAME_DECODER, "decompress", new PacketDecompressor());
			pipeline.addAfter(PipelineUtils.FRAME_PREPENDER, "compress", new PacketCompressor(256));
		}
		if ((encapsulatedinfo.getAddress() != null) && connection.getRawAddress().getAddress().isLoopbackAddress()) {
			connection.changeAddress(encapsulatedinfo.getAddress());
		}
	}
	buffer.readerIndex(0);
	channel.pipeline().firstContext().fireChannelRead(buffer.unwrap());
}
 
Example 9
Source File: PipeLineBuilder.java    From ProtocolSupportBungee with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public void buildBungeeServer(Channel channel, Connection connection) {
	ChannelPipeline pipeline = channel.pipeline();
	pipeline.addFirst(new EncapsulatedHandshakeSender(null, false));
	NetworkDataCache cache = NetworkDataCache.getFrom(connection);
	pipeline.replace(PipelineUtils.PACKET_DECODER, PipelineUtils.PACKET_DECODER, new FromServerPacketDecoder(connection, cache));
	pipeline.replace(PipelineUtils.PACKET_ENCODER, PipelineUtils.PACKET_ENCODER, new ToServerPacketEncoder(connection, cache));
	pipeline.get(CustomHandlerBoss.class).setHandlerChangeListener(handler -> {
		try {
			return (handler instanceof DownstreamBridge) ? new EntityRewriteDownstreamBridge(
				ReflectionUtils.getFieldValue(handler, "con"), connection.getVersion()
			) : handler;
		} catch (IllegalArgumentException | IllegalAccessException e) {
			throw new RuntimeException(e);
		}
	});
}
 
Example 10
Source File: PipeLineBuilder.java    From ProtocolSupportBungee with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public void buildBungeeClientCodec(Channel channel, Connection connection) {
	ChannelPipeline pipeline = channel.pipeline();
	NetworkDataCache cache = new NetworkDataCache();
	cache.storeIn(connection);
	pipeline.replace(PipelineUtils.PACKET_DECODER, PipelineUtils.PACKET_DECODER, new FromClientPacketDecoder(connection, cache));
	pipeline.replace(PipelineUtils.PACKET_ENCODER, PipelineUtils.PACKET_ENCODER, new ToClientPacketEncoder(connection, cache));
	pipeline.get(CustomHandlerBoss.class).setHandlerChangeListener((handler) -> {
		try {
			return (handler instanceof UpstreamBridge) ? new EntityRewriteUpstreamBridge(
				ReflectionUtils.getFieldValue(handler, "con"), connection.getVersion()
			) : handler;
		} catch (IllegalArgumentException | IllegalAccessException e) {
			throw new RuntimeException(e);
		}
	});
}
 
Example 11
Source File: PipeLineBuilder.java    From ProtocolSupportBungee with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public void buildBungeeServer(Channel channel, Connection connection) {
	ChannelPipeline pipeline = channel.pipeline();
	pipeline.addFirst(new EncapsulatedHandshakeSender(null, false));
	NetworkDataCache cache = NetworkDataCache.getFrom(connection);
	pipeline.replace(PipelineUtils.PACKET_DECODER, PipelineUtils.PACKET_DECODER, new FromServerPacketDecoder(connection, cache));
	pipeline.replace(PipelineUtils.PACKET_ENCODER, PipelineUtils.PACKET_ENCODER, new ToServerPacketEncoder(connection, cache));
	pipeline.get(CustomHandlerBoss.class).setHandlerChangeListener(handler -> {
		try {
			return (handler instanceof DownstreamBridge) ? new EntityRewriteDownstreamBridge(
				ReflectionUtils.getFieldValue(handler, "con"), connection.getVersion()
			) : handler;
		} catch (IllegalArgumentException | IllegalAccessException e) {
			throw new RuntimeException(e);
		}
	});
}
 
Example 12
Source File: StreamingAsyncHttpClient.java    From riposte with Apache License 2.0 5 votes vote down vote up
protected void addOrReplacePipelineHandler(ChannelHandler handler, String handlerName, ChannelPipeline p,
                                           List<String> registeredHandlerNames) {
    if (registeredHandlerNames.contains(handlerName))
        p.replace(handlerName, handlerName, handler);
    else
        p.addLast(handlerName, handler);
}
 
Example 13
Source File: VerifyResponseSenderExceptionBehaviorComponentTest.java    From riposte with Apache License 2.0 5 votes vote down vote up
@Override
public void executePipelineCreateHook(@NotNull ChannelPipeline pipeline) {
    pipeline.replace(
        RESPONSE_SENDER_HANDLER_NAME,
        RESPONSE_SENDER_HANDLER_NAME,
        new ResponseSenderHandler(explodingResponseSender)
    );
}
 
Example 14
Source File: PipeLineBuilder.java    From ProtocolSupportBungee with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public void buildBungeeClientPipeLine(Channel channel, Connection connection) {
	ChannelPipeline pipeline = channel.pipeline();
	pipeline.replace(PipelineUtils.FRAME_DECODER, PipelineUtils.FRAME_DECODER, new NoOpFrameDecoder());
	pipeline.replace(PipelineUtils.FRAME_PREPENDER, PipelineUtils.FRAME_PREPENDER, new NoOpFrameEncoder());
}
 
Example 15
Source File: PipeLineBuilder.java    From ProtocolSupportBungee with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public void buildBungeeClientPipeLine(Channel channel, Connection connection) {
	ChannelPipeline pipeline = channel.pipeline();
	pipeline.replace(PipelineUtils.FRAME_DECODER, PipelineUtils.FRAME_DECODER, new NoOpFrameDecoder());
	pipeline.replace(PipelineUtils.FRAME_PREPENDER, PipelineUtils.FRAME_PREPENDER, new NoOpFrameEncoder());
}
 
Example 16
Source File: PipeLineBuilder.java    From ProtocolSupportBungee with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public void buildBungeeClientPipeLine(Channel channel, Connection connection) {
	ChannelPipeline pipeline = channel.pipeline();
	pipeline.replace(PipelineUtils.FRAME_DECODER, PipelineUtils.FRAME_DECODER, new NoOpFrameDecoder());
	pipeline.replace(PipelineUtils.FRAME_PREPENDER, PipelineUtils.FRAME_PREPENDER, new NoOpFrameEncoder());
}
 
Example 17
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());
    }
}
 
Example 18
Source File: Http2SslChannelInitializer.java    From zuul with Apache License 2.0 4 votes vote down vote up
protected void http1Codec(ChannelPipeline pipeline) {
    pipeline.replace("codec_placeholder", HTTP_CODEC_HANDLER_NAME, createHttpServerCodec());
}