Example usage for io.netty.channel ChannelPipeline addBefore

List of usage examples for io.netty.channel ChannelPipeline addBefore

Introduction

In this page you can find the example usage for io.netty.channel ChannelPipeline addBefore.

Prototype

ChannelPipeline addBefore(String baseName, String name, ChannelHandler handler);

Source Link

Document

Inserts a ChannelHandler before an existing handler of this pipeline.

Usage

From source file:io.vertx.core.net.NetTest.java

License:Open Source License

private void testNetClientInternal_(HttpServerOptions options, boolean expectSSL) throws Exception {
    waitFor(2);/*w  w w .ja v  a  2 s . c  om*/
    HttpServer server = vertx.createHttpServer(options);
    server.requestHandler(req -> {
        req.response().end("Hello World");
    });
    CountDownLatch latch = new CountDownLatch(1);
    server.listen(onSuccess(v -> {
        latch.countDown();
    }));
    awaitLatch(latch);
    client.connect(1234, "localhost", onSuccess(so -> {
        NetSocketInternal soInt = (NetSocketInternal) so;
        assertEquals(expectSSL, soInt.isSsl());
        ChannelHandlerContext chctx = soInt.channelHandlerContext();
        ChannelPipeline pipeline = chctx.pipeline();
        pipeline.addBefore("handler", "http", new HttpClientCodec());
        AtomicInteger status = new AtomicInteger();
        soInt.handler(buff -> fail());
        soInt.messageHandler(obj -> {
            switch (status.getAndIncrement()) {
            case 0:
                assertTrue(obj instanceof HttpResponse);
                HttpResponse resp = (HttpResponse) obj;
                assertEquals(200, resp.status().code());
                break;
            case 1:
                assertTrue(obj instanceof LastHttpContent);
                ByteBuf content = ((LastHttpContent) obj).content();
                assertEquals(!expectSSL, content.isDirect());
                assertEquals(1, content.refCnt());
                String val = content.toString(StandardCharsets.UTF_8);
                assertTrue(content.release());
                assertEquals("Hello World", val);
                complete();
                break;
            default:
                fail();
            }
        });
        soInt.writeMessage(new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/somepath"),
                onSuccess(v -> complete()));
    }));
    await();
}

From source file:io.vertx.mqtt.impl.MqttClientImpl.java

License:Apache License

private void initChannel(ChannelPipeline pipeline) {

    // add into pipeline netty's (en/de)coder
    pipeline.addBefore("handler", "mqttEncoder", MqttEncoder.INSTANCE);

    if (this.options.getMaxMessageSize() > 0) {
        pipeline.addBefore("handler", "mqttDecoder", new MqttDecoder(this.options.getMaxMessageSize()));
    } else {//  ww w.jav a  2 s.c  om
        // max message size not set, so the default from Netty MQTT codec is used
        pipeline.addBefore("handler", "mqttDecoder", new MqttDecoder());
    }

    if (this.options.isAutoKeepAlive() && this.options.getKeepAliveTimeSeconds() != 0) {

        pipeline.addBefore("handler", "idle",
                new IdleStateHandler(0, this.options.getKeepAliveTimeSeconds(), 0));
        pipeline.addBefore("handler", "keepAliveHandler", new ChannelDuplexHandler() {

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

                if (evt instanceof IdleStateEvent) {
                    IdleStateEvent e = (IdleStateEvent) evt;
                    if (e.state() == IdleState.WRITER_IDLE) {
                        ping();
                    }
                }
            }
        });
    }
}

From source file:io.vertx.mqtt.impl.MqttServerImpl.java

License:Apache License

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 {//from  ww  w.j av  a  2s  .  c o m
        // 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();
                }
            }
        }
    });
}

From source file:jp.llv.locapi.PacketHandler.java

License:Open Source License

protected static void handle(ProxiedPlayer player) {
    ChannelPipeline chp = getPipeline(player);
    chp.addBefore(PipelineUtils.BOSS_HANDLER, PACKET_LISTENER, new PacketHandler(player));
}

From source file:net.dongliu.prettypb.rpc.server.RequestHandler.java

License:Apache License

private void completePipeline(RpcServerChannel rpcServerChannel) {
    ChannelPipeline p = rpcServerChannel.getChannel().pipeline();

    if (rpcServerChannel.isCompress()) {
        p.addBefore(Handlers.FRAME_DECODER, Handlers.COMPRESSOR,
                ZlibCodecFactory.newZlibEncoder(ZlibWrapper.GZIP));
        p.addAfter(Handlers.COMPRESSOR, Handlers.DECOMPRESSOR,
                ZlibCodecFactory.newZlibDecoder(ZlibWrapper.GZIP));
    }//from w w  w .ja va 2 s.c o m

    RpcServerHandler rpcServerHandler = new RpcServerHandler(rpcServerChannel, rpcServiceRegistry,
            rpcServiceExecutor, rpcServerChannelRegistry, extensionRegistry);
    p.addLast(Handlers.RPC_SERVER, rpcServerHandler);
}

From source file:net.tomp2p.connection.Sender.java

License:Apache License

private boolean addOrReplace(ChannelPipeline pipeline, String before, String name,
        ChannelHandler channelHandler) {
    List<String> names = pipeline.names();
    if (names.contains(name)) {
        pipeline.replace(name, name, channelHandler);
        return false;
    } else {/*from   ww w . j  a  v a2  s .  co m*/
        if (before == null) {
            pipeline.addFirst(name, channelHandler);
        } else {
            pipeline.addBefore(before, name, channelHandler);
        }
        return true;
    }
}

From source file:org.apache.hadoop.hbase.ipc.NettyRpcConnection.java

License:Apache License

private void established(Channel ch) throws IOException {
    ChannelPipeline p = ch.pipeline();
    String addBeforeHandler = p.context(BufferCallBeforeInitHandler.class).name();
    p.addBefore(addBeforeHandler, null,
            new IdleStateHandler(0, rpcClient.minIdleTimeBeforeClose, 0, TimeUnit.MILLISECONDS));
    p.addBefore(addBeforeHandler, null, new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4));
    p.addBefore(addBeforeHandler, null,/*from   w w w .j a  va  2s .  co  m*/
            new NettyRpcDuplexHandler(this, rpcClient.cellBlockBuilder, codec, compressor));
    p.fireUserEventTriggered(BufferCallEvent.success());
}

From source file:org.asynchttpclient.netty.channel.ChannelManager.java

License:Open Source License

public void upgradePipelineForWebSockets(ChannelPipeline pipeline) {
    pipeline.addAfter(HTTP_CLIENT_CODEC, WS_ENCODER_HANDLER, new WebSocket08FrameEncoder(true));
    pipeline.addBefore(AHC_WS_HANDLER, WS_DECODER_HANDLER,
            new WebSocket08FrameDecoder(false, false, config.getWebSocketMaxFrameSize()));
    pipeline.addAfter(WS_DECODER_HANDLER, WS_FRAME_AGGREGATOR,
            new WebSocketFrameAggregator(config.getWebSocketMaxBufferSize()));
    pipeline.remove(HTTP_CLIENT_CODEC);//from  w w  w  .  j ava2s  . c o  m
}

From source file:org.asynchttpclient.netty.NettyAsyncProviderPipelineTest.java

License:Open Source License

@Test(groups = { "standalone", "netty_provider" })
public void asyncPipelineTest() throws Exception {

    NettyAsyncHttpProviderConfig nettyConfig = new NettyAsyncHttpProviderConfig();
    nettyConfig.setHttpAdditionalPipelineInitializer(new AdditionalPipelineInitializer() {
        public void initPipeline(ChannelPipeline pipeline) throws Exception {
            pipeline.addBefore("inflater", "copyEncodingHeader", new CopyEncodingHandler());
        }/*from w ww  . j a  va 2s .  c  om*/
    });

    try (AsyncHttpClient p = getAsyncHttpClient(
            new AsyncHttpClientConfig.Builder().setAsyncHttpClientProviderConfig(nettyConfig).build())) {
        final CountDownLatch l = new CountDownLatch(1);
        Request request = new RequestBuilder("GET").setUrl(getTargetUrl()).build();
        p.executeRequest(request, new AsyncCompletionHandlerAdapter() {
            @Override
            public Response onCompleted(Response response) throws Exception {
                try {
                    assertEquals(response.getStatusCode(), 200);
                    assertEquals(response.getHeader("X-Original-Content-Encoding"), "<original encoding>");
                } finally {
                    l.countDown();
                }
                return response;
            }
        }).get();
        if (!l.await(TIMEOUT, TimeUnit.SECONDS)) {
            fail("Timeout out");
        }
    }
}

From source file:org.asynchttpclient.providers.netty.channel.ChannelManager.java

License:Open Source License

public void upgradePipelineForWebSockets(ChannelPipeline pipeline) {
    pipeline.addAfter(HTTP_HANDLER, WS_ENCODER_HANDLER, new WebSocket08FrameEncoder(true));
    pipeline.remove(HTTP_HANDLER);/*  w  ww  .j  a v  a 2s  .com*/
    pipeline.addBefore(WS_PROCESSOR, WS_DECODER_HANDLER,
            new WebSocket08FrameDecoder(false, false, nettyConfig.getWebSocketMaxFrameSize()));
    pipeline.addAfter(WS_DECODER_HANDLER, WS_FRAME_AGGREGATOR,
            new WebSocketFrameAggregator(nettyConfig.getWebSocketMaxBufferSize()));
}