Example usage for io.netty.channel ChannelHandlerContext pipeline

List of usage examples for io.netty.channel ChannelHandlerContext pipeline

Introduction

In this page you can find the example usage for io.netty.channel ChannelHandlerContext pipeline.

Prototype

ChannelPipeline pipeline();

Source Link

Document

Return the assigned ChannelPipeline

Usage

From source file:io.urmia.api.handler.RestApiHandler.java

License:Open Source License

private void setupProxyToGET(final ChannelHandlerContext ctx, final FullObjectName fon) throws Exception {

    log.info("proxy GET storage node: download mode: {}", true);

    final Future<List<String>> futureStorageNodes = mds.storedNodes(ctx.executor(), fon.attributes.etag);

    futureStorageNodes.addListener(new GenericFutureListener<Future<List<String>>>() {
        @Override/*from   w  ww .j ava  2 s  .  c  om*/
        public void operationComplete(Future<List<String>> future) throws Exception {
            if (future.isSuccess()) {
                final List<String> st = future.getNow();

                Optional<ServiceInstance<NodeType>> si = findStorageInstanceUp(st);

                if (!si.isPresent()) {
                    log.error("failed to find running node, req: {}", objectRequest);
                    sendError(ctx, HttpResponseStatus.INTERNAL_SERVER_ERROR);
                    return;
                }

                List<ServiceInstance<NodeType>> l = Lists.newArrayList(si.get());
                log.info("proxy storage node: {}, download mode: {}, durability: {}", st, true,
                        objectRequest.getDurability());
                HttpProxyFrontendHandler proxy = new HttpProxyFrontendHandler(l, mds, httpRequest, ctx, true,
                        Optional.<FullObjectName>absent());

                ctx.pipeline().remove("encoder");

                ctx.pipeline().addLast("proxy", proxy);

                proxyMode = true;

                ctx.read(); // todo: can ve removed?

            } else {
                log.error("failed to fetch futureStorageNodes, req: {}", objectRequest, future.cause());
                sendError(ctx, HttpResponseStatus.INTERNAL_SERVER_ERROR);
            }
        }
    });

}

From source file:io.urmia.job.handler.JobHandler.java

License:Open Source License

private void setupProxyGet(final ChannelHandlerContext ctx, JobGetRequest getRequest) throws Exception {
    ServiceInstance<NodeType> ods = ns.get(NodeType.ODS, getRequest.getStorageNodeId());

    List<ServiceInstance<NodeType>> l = Lists.newArrayList(ods);
    log.info("proxy storage node: {}", ods);
    HttpRequest initHttpRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET,
            getRequest.objectName.toString());
    HttpProxyFrontendHandler proxy = new HttpProxyFrontendHandler(l, mds, initHttpRequest, ctx, true,
            Optional.<FullObjectName>absent());

    ctx.pipeline().remove("encoder");
    ctx.pipeline().remove("aggregator");
    ctx.pipeline().remove("job-decoder");
    ctx.pipeline().remove("job");

    ctx.pipeline().addLast("proxy", proxy);

}

From source file:io.vertx.core.http.Http2ClientTest.java

License:Open Source License

private ServerBootstrap createH2Server(
        BiFunction<Http2ConnectionDecoder, Http2ConnectionEncoder, Http2FrameListener> handler) {
    ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap.channel(NioServerSocketChannel.class);
    NioEventLoopGroup eventLoopGroup = new NioEventLoopGroup();
    eventLoopGroups.add(eventLoopGroup);
    bootstrap.group(eventLoopGroup);//w  ww  .  ja  v a  2s  .  c o  m
    bootstrap.childHandler(new ChannelInitializer<Channel>() {
        @Override
        protected void initChannel(Channel ch) throws Exception {
            SSLHelper sslHelper = new SSLHelper(serverOptions, Cert.SERVER_JKS.get(), null);
            SslHandler sslHandler = new SslHandler(
                    sslHelper.setApplicationProtocols(Arrays.asList(HttpVersion.HTTP_2, HttpVersion.HTTP_1_1))
                            .createEngine((VertxInternal) vertx, DEFAULT_HTTPS_HOST, DEFAULT_HTTPS_PORT));
            ch.pipeline().addLast(sslHandler);
            ch.pipeline().addLast(new ApplicationProtocolNegotiationHandler("whatever") {
                @Override
                protected void configurePipeline(ChannelHandlerContext ctx, String protocol) {
                    if (ApplicationProtocolNames.HTTP_2.equals(protocol)) {
                        ChannelPipeline p = ctx.pipeline();
                        Http2ConnectionHandler clientHandler = createHttpConnectionHandler(handler);
                        p.addLast("handler", clientHandler);
                        return;
                    }
                    ctx.close();
                    throw new IllegalStateException("unknown protocol: " + protocol);
                }
            });
        }
    });
    return bootstrap;
}

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

License:Open Source License

private synchronized NetSocket upgrade(StreamImpl stream) {
    if (options.isPipelining()) {
        throw new IllegalStateException("Cannot upgrade a pipe-lined request");
    }/*from   ww  w  .j  a  v  a2 s  .com*/
    if (upgraded) {
        throw new IllegalStateException("Request already upgraded to NetSocket");
    }
    upgraded = true;

    // connection was upgraded to raw TCP socket
    AtomicBoolean paused = new AtomicBoolean(false);
    NetSocketImpl socket = new NetSocketImpl(vertx, chctx, context, client.getSslHelper(), metrics) {
        {
            super.pause();
        }

        @Override
        public synchronized NetSocket handler(Handler<Buffer> dataHandler) {
            return super.handler(dataHandler);
        }

        @Override
        public synchronized NetSocket pause() {
            paused.set(true);
            return super.pause();
        }

        @Override
        public synchronized NetSocket resume() {
            paused.set(false);
            return super.resume();
        }
    };
    socket.metric(metric());

    // Flush out all pending data
    endReadAndFlush();

    // remove old http handlers and replace the old handler with one that handle plain sockets
    ChannelPipeline pipeline = chctx.pipeline();
    ChannelHandler inflater = pipeline.get(HttpContentDecompressor.class);
    if (inflater != null) {
        pipeline.remove(inflater);
    }
    pipeline.replace("handler", "handler", new VertxNetHandler(socket) {
        @Override
        public void channelRead(ChannelHandlerContext chctx, Object msg) throws Exception {
            if (msg instanceof HttpContent) {
                if (msg instanceof LastHttpContent) {
                    stream.endResponse((LastHttpContent) msg);
                }
                ReferenceCountUtil.release(msg);
                return;
            }
            super.channelRead(chctx, msg);
        }
    }.removeHandler(sock -> listener.onDiscard()));

    // Removing this codec might fire pending buffers in the HTTP decoder
    // this happens when the channel reads the HTTP response and the following data in a single buffer
    pipeline.remove("codec");

    // Async check to deliver the pending messages
    // because the netSocket access in HttpClientResponse is synchronous
    // we need to pause the NetSocket to avoid losing or reordering buffers
    // and then asynchronously un-pause it unless it was actually paused by the application
    context.runOnContext(v -> {
        if (!paused.get()) {
            socket.resume();
        }
    });

    return socket;
}

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

License:Open Source License

private void end(ChannelHandlerContext ctx, ByteBuf buf, boolean h2c) {
    if (current > 0) {
        ByteBuf msg = Unpooled.buffer(current + buf.readableBytes());
        msg.writeBytes(HTTP_2_PREFACE_ARRAY, 0, current);
        msg.writeBytes(buf);/*from w  w  w.  ja  v a  2 s  . c o m*/
        buf.release();
        buf = msg;
    }
    configure(ctx, h2c);
    ctx.pipeline().remove(this);
    ctx.fireChannelRead(buf);
}

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

License:Open Source License

NetSocket createNetSocket() {
    NetSocketImpl socket = new NetSocketImpl(vertx, chctx, context, sslHelper, metrics);
    socket.metric(metric());/*  w w  w.j  a va 2  s.  com*/
    Map<Channel, NetSocketImpl> connectionMap = new HashMap<>(1);
    connectionMap.put(chctx.channel(), socket);

    // Flush out all pending data
    endReadAndFlush();

    // remove old http handlers and replace the old handler with one that handle plain sockets
    ChannelPipeline pipeline = chctx.pipeline();
    ChannelHandler compressor = pipeline.get(HttpChunkContentCompressor.class);
    if (compressor != null) {
        pipeline.remove(compressor);
    }

    pipeline.remove("httpDecoder");
    if (pipeline.get("chunkedWriter") != null) {
        pipeline.remove("chunkedWriter");
    }

    chctx.pipeline().replace("handler", "handler", new VertxNetHandler(socket) {
        @Override
        public void channelRead(ChannelHandlerContext chctx, Object msg) throws Exception {
            if (msg instanceof HttpContent) {
                ReferenceCountUtil.release(msg);
                return;
            }
            super.channelRead(chctx, msg);
        }
    }.removeHandler(sock -> {
        if (metrics != null) {
            metrics.responseEnd(responseInProgress.metric(), responseInProgress.response());
        }
        connectionMap.remove(chctx.channel());
    }));

    // check if the encoder can be removed yet or not.
    chctx.pipeline().remove("httpEncoder");
    return socket;
}

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

License:Open Source License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    if (msg instanceof HttpResponse) {
        HttpResponse resp = (HttpResponse) msg;
        response = new DefaultFullHttpResponse(resp.protocolVersion(), resp.status());
        response.headers().add(resp.headers());
    }//from  w w  w . j a v a  2s . com
    if (msg instanceof HttpContent) {
        if (response != null) {
            response.content().writeBytes(((HttpContent) msg).content());
            if (msg instanceof LastHttpContent) {
                response.trailingHeaders().add(((LastHttpContent) msg).trailingHeaders());
                ChannelPipeline pipeline = chctx.pipeline();
                pipeline.remove(WebSocketHandshakeInboundHandler.this);
                ChannelHandler handler = pipeline.get(HttpContentDecompressor.class);
                if (handler != null) {
                    // remove decompressor as its not needed anymore once connection was upgraded to websockets
                    ctx.pipeline().remove(handler);
                }
                Future<Void> fut = handshakeComplete(response);
                wsHandler.handle(fut);
            }
        }
    }
}

From source file:io.vertx.core.net.impl.SslHandshakeCompletionHandler.java

License:Open Source License

@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) {
    if (evt instanceof SniCompletionEvent) {
        // Shall we care ?
        SniCompletionEvent completion = (SniCompletionEvent) evt;
        Attribute<String> val = ctx.channel().attr(SERVER_NAME_ATTR);
        val.set(completion.hostname());
    } else if (evt instanceof SslHandshakeCompletionEvent) {
        SslHandshakeCompletionEvent completion = (SslHandshakeCompletionEvent) evt;
        if (completion.isSuccess()) {
            ctx.pipeline().remove(this);
            handler.handle(Future.succeededFuture(ctx.channel()));
        } else {//from   w w  w  . java2s  . c  o  m
            handler.handle(Future.failedFuture(completion.cause()));
        }
    } else {
        ctx.fireUserEventTriggered(evt);
    }
}

From source file:io.vertx.core.net.impl.VertxSniHandler.java

License:Open Source License

@Override
protected void replaceHandler(ChannelHandlerContext ctx, String hostname, SslContext sslContext)
        throws Exception {
    SslHandler sslHandler = null;/*from   w ww  .j  a v a2  s. com*/
    try {
        SSLEngine engine = helper.createEngine(sslContext);
        sslHandler = new SslHandler(engine);
        ctx.pipeline().replace(this, "ssl", sslHandler);
        Future<Channel> fut = sslHandler.handshakeFuture();
        fut.addListener(future -> {
            if (future.isSuccess()) {
                Attribute<String> val = ctx.channel().attr(SERVER_NAME_ATTR);
                val.set(hostname);
                handshakeFuture.setSuccess(ctx.channel());
            } else {
                handshakeFuture.setFailure(future.cause());
            }
        });
        sslHandler = null;
    } finally {
        // Since the SslHandler was not inserted into the pipeline the ownership of the SSLEngine was not
        // transferred to the SslHandler.
        // See https://github.com/netty/netty/issues/5678
        if (sslHandler != null) {
            ReferenceCountUtil.safeRelease(sslHandler.engine());
        }
    }
}

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 . j  a  v  a2 s.  c o m
    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();
}