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.hekate.network.netty.NettyClientTimeoutHandler.java

License:Apache License

private void mayBeRegisterHeartbeatHandler(NettyClientHandshakeEvent evt, ChannelHandlerContext ctx) {
    int interval = evt.hbInterval();
    int threshold = evt.hbLossThreshold();
    boolean disableHeartbeats = evt.isHbDisabled();

    ChannelPipeline pipe = ctx.pipeline();

    if (idleTimeout > 0) {
        if (trace) {
            log.trace("Registering idle connection handler [to={}, idle-timeout={}]", id, idleTimeout);
        }//from   w ww.j ava  2  s  .  c  om

        pipe.addBefore(ctx.name(), "idle-channel-handler", new HeartbeatOnlyIdleStateHandler(idleTimeout));
    }

    if (interval > 0 && threshold > 0) {
        int readerIdle = interval * threshold;
        int writerIdle = disableHeartbeats ? 0 : interval;

        if (trace) {
            log.trace("Registering heartbeat handler [to={}, reader-idle={}, writer-idle={}]", id, readerIdle,
                    writerIdle);
        }

        pipe.addBefore(ctx.name(), "heartbeat-handler",
                new IdleStateHandler(readerIdle, writerIdle, 0, TimeUnit.MILLISECONDS));
    }
}

From source file:io.jsync.http.impl.ClientConnection.java

License:Open Source License

void toWebSocket(String uri, final WebSocketVersion wsVersion, final MultiMap headers,
        int maxWebSocketFrameSize, final Set<String> subProtocols, final Handler<WebSocket> wsConnect) {
    if (ws != null) {
        throw new IllegalStateException("Already websocket");
    }//from  w  w w.ja  v  a  2 s  .c  o m

    try {
        URI wsuri = new URI(uri);
        if (!wsuri.isAbsolute()) {
            // Netty requires an absolute url
            wsuri = new URI((ssl ? "https:" : "http:") + "//" + host + ":" + port + uri);
        }
        io.netty.handler.codec.http.websocketx.WebSocketVersion version;
        if (wsVersion == WebSocketVersion.HYBI_00) {
            version = io.netty.handler.codec.http.websocketx.WebSocketVersion.V00;
        } else if (wsVersion == WebSocketVersion.HYBI_08) {
            version = io.netty.handler.codec.http.websocketx.WebSocketVersion.V08;
        } else if (wsVersion == WebSocketVersion.RFC6455) {
            version = io.netty.handler.codec.http.websocketx.WebSocketVersion.V13;
        } else {
            throw new IllegalArgumentException("Invalid version");
        }
        HttpHeaders nettyHeaders;
        if (headers != null) {
            nettyHeaders = new DefaultHttpHeaders();
            for (Map.Entry<String, String> entry : headers) {
                nettyHeaders.add(entry.getKey(), entry.getValue());
            }
        } else {
            nettyHeaders = null;
        }
        String wsSubProtocols = null;
        if (subProtocols != null && !subProtocols.isEmpty()) {
            StringBuilder sb = new StringBuilder();

            Iterator<String> protocols = subProtocols.iterator();
            while (protocols.hasNext()) {
                sb.append(protocols.next());
                if (protocols.hasNext()) {
                    sb.append(",");
                }
            }
            wsSubProtocols = sb.toString();
        }
        handshaker = WebSocketClientHandshakerFactory.newHandshaker(wsuri, version, wsSubProtocols, false,
                nettyHeaders, maxWebSocketFrameSize);
        final ChannelPipeline p = channel.pipeline();
        p.addBefore("handler", "handshakeCompleter", new HandshakeInboundHandler(wsConnect));
        handshaker.handshake(channel).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (!future.isSuccess()) {
                    client.handleException((Exception) future.cause());
                }
            }
        });
        upgradedConnection = true;

    } catch (Exception e) {
        handleException(e);
    }
}

From source file:io.liveoak.container.protocols.PipelineConfigurator.java

License:Open Source License

public void switchToWebSocketsHandshake(ChannelPipeline pipeline) {
    pipeline.addBefore("ws-handshake", "aggregator", new HttpObjectAggregator(1024 * 1024));
}

From source file:io.reactiverse.pgclient.impl.SocketConnection.java

License:Apache License

void upgradeToSSLConnection(Handler<AsyncResult<Void>> completionHandler) {
    ChannelPipeline pipeline = socket.channelHandlerContext().pipeline();
    Future<Void> upgradeFuture = Future.future();
    upgradeFuture.setHandler(ar -> {/*  w w w . ja v  a  2 s  . c  om*/
        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, upgradeFuture));
}

From source file:io.reactiverse.pgclient.impl.SocketConnection.java

License:Apache License

void initializeCodec() {
    decoder = new MessageDecoder(inflight, socket.channelHandlerContext().alloc());
    encoder = new MessageEncoder(socket.channelHandlerContext());

    ChannelPipeline pipeline = socket.channelHandlerContext().pipeline();
    pipeline.addBefore("handler", "decoder", decoder);

    socket.closeHandler(this::handleClosed);
    socket.exceptionHandler(this::handleException);
    socket.messageHandler(msg -> {//from  ww w .j  a va 2s.c  o  m
        try {
            handleMessage(msg);
        } catch (Exception e) {
            handleException(e);
        }
    });
}

From source file:io.reactivex.netty.protocol.http.sse.SseClientPipelineConfigurator.java

License:Apache License

@Override
public void configureNewPipeline(ChannelPipeline pipeline) {
    httpClientPipelineConfigurator.configureNewPipeline(pipeline);
    if (null != pipeline.get(HttpClientPipelineConfigurator.REQUEST_RESPONSE_CONVERTER_HANDLER_NAME)) {
        pipeline.addBefore(HttpClientPipelineConfigurator.REQUEST_RESPONSE_CONVERTER_HANDLER_NAME,
                SseChannelHandler.NAME, SSE_CHANNEL_HANDLER);
    } else {/*from   w w  w .j  a va  2s  .c  o m*/
        // Assuming that the underlying HTTP configurator knows what its doing. It will mostly fail though.
        pipeline.addLast(SseChannelHandler.NAME, SSE_CHANNEL_HANDLER);
    }
}

From source file:io.reactivex.netty.protocol.http.sse.SseOverHttpClientPipelineConfigurator.java

License:Apache License

@Override
public void configureNewPipeline(ChannelPipeline pipeline) {
    httpClientPipelineConfigurator.configureNewPipeline(pipeline);
    if (null != pipeline.get(HttpClientPipelineConfigurator.REQUEST_RESPONSE_CONVERTER_HANDLER_NAME)) {
        pipeline.addBefore(HttpClientPipelineConfigurator.REQUEST_RESPONSE_CONVERTER_HANDLER_NAME,
                SSEInboundHandler.NAME, SSEClientPipelineConfigurator.SSE_INBOUND_HANDLER);
    } else {//from w w w.  j  a  v a 2  s . c om
        // Assuming that the underlying HTTP configurator knows what its doing. It will mostly fail though.
        pipeline.addLast(SSEInboundHandler.NAME, SSEClientPipelineConfigurator.SSE_INBOUND_HANDLER);
    }
}

From source file:io.vertx.core.http.impl.ClientConnection.java

License:Open Source License

synchronized void toWebSocket(String requestURI, MultiMap headers, WebsocketVersion vers, String subProtocols,
        int maxWebSocketFrameSize, Handler<WebSocket> wsConnect) {
    if (ws != null) {
        throw new IllegalStateException("Already websocket");
    }//  ww  w  . j a  va 2  s  .  co m

    try {
        URI wsuri = new URI(requestURI);
        if (!wsuri.isAbsolute()) {
            // Netty requires an absolute url
            wsuri = new URI((ssl ? "https:" : "http:") + "//" + host + ":" + port + requestURI);
        }
        WebSocketVersion version = WebSocketVersion
                .valueOf((vers == null ? WebSocketVersion.V13 : vers).toString());
        HttpHeaders nettyHeaders;
        if (headers != null) {
            nettyHeaders = new DefaultHttpHeaders();
            for (Map.Entry<String, String> entry : headers) {
                nettyHeaders.add(entry.getKey(), entry.getValue());
            }
        } else {
            nettyHeaders = null;
        }
        handshaker = WebSocketClientHandshakerFactory.newHandshaker(wsuri, version, subProtocols, false,
                nettyHeaders, maxWebSocketFrameSize, !client.getOptions().isSendUnmaskedFrames(), false);
        ChannelPipeline p = channel.pipeline();
        p.addBefore("handler", "handshakeCompleter",
                new HandshakeInboundHandler(wsConnect, version != WebSocketVersion.V00));
        handshaker.handshake(channel).addListener(future -> {
            Handler<Throwable> handler = exceptionHandler();
            if (!future.isSuccess() && handler != null) {
                handler.handle(future.cause());
            }
        });
    } catch (Exception e) {
        handleException(e);
    }
}

From source file:io.vertx.core.http.impl.Http1xClientConnection.java

License:Open Source License

synchronized void toWebSocket(String requestURI, MultiMap headers, WebsocketVersion vers, String subProtocols,
        int maxWebSocketFrameSize, Handler<WebSocket> wsConnect) {
    if (ws != null) {
        throw new IllegalStateException("Already websocket");
    }//from   w  w w . j  a v a  2 s  .c  o m

    try {
        URI wsuri = new URI(requestURI);
        if (!wsuri.isAbsolute()) {
            // Netty requires an absolute url
            wsuri = new URI((ssl ? "https:" : "http:") + "//" + host + ":" + port + requestURI);
        }
        WebSocketVersion version = WebSocketVersion
                .valueOf((vers == null ? WebSocketVersion.V13 : vers).toString());
        HttpHeaders nettyHeaders;
        if (headers != null) {
            nettyHeaders = new DefaultHttpHeaders();
            for (Map.Entry<String, String> entry : headers) {
                nettyHeaders.add(entry.getKey(), entry.getValue());
            }
        } else {
            nettyHeaders = null;
        }

        ChannelPipeline p = chctx.channel().pipeline();
        ArrayList<WebSocketClientExtensionHandshaker> extensionHandshakers = initializeWebsocketExtensionHandshakers(
                client.getOptions());
        if (!extensionHandshakers.isEmpty()) {
            p.addBefore("handler", "websocketsExtensionsHandler",
                    new WebSocketClientExtensionHandler(extensionHandshakers
                            .toArray(new WebSocketClientExtensionHandshaker[extensionHandshakers.size()])));
        }

        handshaker = WebSocketClientHandshakerFactory.newHandshaker(wsuri, version, subProtocols,
                !extensionHandshakers.isEmpty(), nettyHeaders, maxWebSocketFrameSize,
                !options.isSendUnmaskedFrames(), false);

        p.addBefore("handler", "handshakeCompleter",
                new HandshakeInboundHandler(wsConnect, version != WebSocketVersion.V00));
        handshaker.handshake(chctx.channel()).addListener(future -> {
            Handler<Throwable> handler = exceptionHandler();
            if (!future.isSuccess() && handler != null) {
                handler.handle(future.cause());
            }
        });
    } catch (Exception e) {
        handleException(e);
    }
}

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

License:Open Source License

private void testNetServerInternal_(HttpClientOptions clientOptions, boolean expectSSL) throws Exception {
    waitFor(2);//w  w w . ja  v  a  2s .  c  om
    server.connectHandler(so -> {
        NetSocketInternal internal = (NetSocketInternal) so;
        assertEquals(expectSSL, internal.isSsl());
        ChannelHandlerContext chctx = internal.channelHandlerContext();
        ChannelPipeline pipeline = chctx.pipeline();
        pipeline.addBefore("handler", "http", new HttpServerCodec());
        internal.handler(buff -> fail());
        internal.messageHandler(obj -> {
            if (obj instanceof LastHttpContent) {
                DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
                        HttpResponseStatus.OK, Unpooled.copiedBuffer("Hello World", StandardCharsets.UTF_8));
                response.headers().set(HttpHeaderNames.CONTENT_LENGTH, "11");
                internal.writeMessage(response, onSuccess(v -> complete()));
            }
        });
    });
    startServer(SocketAddress.inetSocketAddress(1234, "localhost"));
    HttpClient client = vertx.createHttpClient(clientOptions);
    client.getNow(1234, "localhost", "/somepath", onSuccess(resp -> {
        assertEquals(200, resp.statusCode());
        resp.bodyHandler(buff -> {
            assertEquals("Hello World", buff.toString());
            complete();
        });
    }));
    await();
}