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:org.waarp.openr66.proxy.network.NetworkPacketCodec.java

License:Open Source License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf buf, List<Object> out) throws Exception {
    // Make sure if the length field was received.
    if (buf.readableBytes() < 4) {
        // The length field was not received yet - return null.
        // This method will be invoked again when more packets are
        // received and appended to the buffer.
        return;/* w ww.  j a  va  2  s .c  om*/
    }
    // Mark the current buffer position
    buf.markReaderIndex();
    // Read the length field
    final int length = buf.readInt();
    if (buf.readableBytes() < length) {
        buf.resetReaderIndex();
        return;
    }
    // Now we can read the two Ids
    // Slight change in Proxy = first is remote and second is local!
    final int remoteId = buf.readInt();
    final int localId = buf.readInt();
    final byte code = buf.readByte();
    int readerInder = buf.readerIndex();
    ByteBuf buffer = buf.slice(readerInder, length - 9);
    buffer.retain();
    buf.skipBytes(length - 9);
    NetworkPacket networkPacket = new NetworkPacket(localId, remoteId, code, buffer);
    if (code == LocalPacketFactory.KEEPALIVEPACKET) {
        KeepAlivePacket keepAlivePacket = (KeepAlivePacket) LocalPacketCodec
                .decodeNetworkPacket(networkPacket.getBuffer());
        if (keepAlivePacket.isToValidate()) {
            keepAlivePacket.validate();
            NetworkPacket response = new NetworkPacket(ChannelUtils.NOCHANNEL, ChannelUtils.NOCHANNEL,
                    keepAlivePacket, null);
            ctx.writeAndFlush(response.getNetworkPacket());
        }
        // Replaced by a NoOp packet
        networkPacket = new NetworkPacket(localId, remoteId, new NoOpPacket(), null);
        NetworkServerHandler nsh = (NetworkServerHandler) ctx.pipeline().last();
        nsh.setKeepAlivedSent();
    }
    out.add(networkPacket);
}

From source file:org.waarp.openr66.proxy.network.ssl.NetworkSslServerHandler.java

License:Open Source License

@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
    Channel channel = ctx.channel();
    logger.debug("Add channel to ssl");
    WaarpSslUtility.addSslOpenedChannel(channel);
    isSSL = true;//w  w w .j av  a  2s. co m
    // Get the SslHandler in the current pipeline.
    // We added it in NetworkSslServerInitializer.
    final ChannelHandler handler = ctx.pipeline().first();
    if (handler instanceof SslHandler) {
        final SslHandler sslHandler = (SslHandler) handler;
        sslHandler.handshakeFuture().addListener(new GenericFutureListener<Future<? super Channel>>() {
            public void operationComplete(Future<? super Channel> future) throws Exception {
                if (!future.isSuccess()) {
                    if (Configuration.configuration.getR66Mib() != null) {
                        Configuration.configuration.getR66Mib().notifyError("SSL Connection Error",
                                "During Handshake");
                    }
                }
            }
        });
    } else {
        logger.error("SSL Not found");
    }
    super.channelActive(ctx);
}

From source file:org.wso2.carbon.http2.transport.util.Http2ClientInitializer.java

License:Open Source License

private void configureSsl(SocketChannel ch) {
    ChannelPipeline pipeline = ch.pipeline();
    pipeline.addLast(sslCtx.newHandler(ch.alloc()));
    pipeline.addLast(new ApplicationProtocolNegotiationHandler("") {
        @Override/* w w  w  . jav  a 2s  .c  o  m*/
        protected void configurePipeline(ChannelHandlerContext ctx, String protocol) {
            if (ApplicationProtocolNames.HTTP_2.equals(protocol)) {
                ChannelPipeline p = ctx.pipeline();
                p.addLast(connectionHandler);
                configureEndOfPipeline(p);
                return;
            }
            ctx.close();
            throw new IllegalStateException("unknown protocol: " + protocol);
        }
    });
}

From source file:org.wso2.carbon.mss.internal.router.HttpDispatcher.java

License:Open Source License

@Override
protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws HandlerException {
    Object httpMethodInfoBuilderObj = ctx.pipeline().context(RequestRouter.class)
            .attr(AttributeKey.valueOf(RequestRouter.METHOD_INFO_BUILDER)).get();
    if (httpMethodInfoBuilderObj instanceof HttpMethodInfoBuilder) {
        httpMethodInfoBuilder = (HttpMethodInfoBuilder) httpMethodInfoBuilderObj;
        if (msg instanceof FullHttpRequest) {
            FullHttpRequest fullHttpRequest = (FullHttpRequest) msg;
            httpMethodInfoBuilder.httpRequest(fullHttpRequest).build().invoke();
        } else if (msg instanceof HttpContent) {
            httpMethodInfoBuilder.build().chunk((HttpContent) msg);
        }//from   w  ww.jav  a 2 s .  c o  m
    }
}

From source file:org.wso2.carbon.transport.http.netty.listener.CustomHttpObjectAggregator.java

License:Open Source License

@Override
protected void decode(ChannelHandlerContext ctx, HttpObject msg, List<Object> out) throws Exception {
    try {//from   ww  w  .  j a  v a2 s .c  o  m
        super.decode(ctx, msg, out);
    } catch (Exception e) {
        log.warn("Message length validation failed");

        Iterator<Map.Entry<String, ChannelHandler>> iterator = ctx.pipeline().iterator();

        boolean canRemove = false;
        while (iterator.hasNext()) {
            Map.Entry<String, ChannelHandler> channelHandlerEntry = iterator.next();
            if (channelHandlerEntry.getKey().equalsIgnoreCase(ctx.name())) {
                canRemove = true;
            }
            if (canRemove && !channelHandlerEntry.getKey().equalsIgnoreCase(ctx.name())) {
                ctx.pipeline().remove(channelHandlerEntry.getKey());
            }
        }

        String rejectMessage = requestSizeValidationConfig.getRequestRejectMessage();
        byte[] errorMessageBytes = rejectMessage.getBytes(Charset.defaultCharset());
        ByteBuf content = Unpooled.wrappedBuffer(errorMessageBytes);
        DefaultFullHttpResponse rejectResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
                HttpResponseStatus.valueOf(requestSizeValidationConfig.getRequestRejectStatusCode()), content);
        rejectResponse.headers().set(Constants.HTTP_CONTENT_LENGTH, errorMessageBytes.length);
        rejectResponse.headers().set(Constants.HTTP_CONTENT_TYPE,
                requestSizeValidationConfig.getRequestRejectMsgContentType());

        ctx.writeAndFlush(rejectResponse);
    }
}

From source file:org.wso2.carbon.transport.http.netty.listener.CustomHttpRequestDecoder.java

License:Open Source License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf buffer, List<Object> out) throws Exception {
    super.decode(ctx, buffer, out);

    for (Object o : out) {
        if (o instanceof DefaultHttpRequest) {
            DefaultHttpRequest httpRequest = (DefaultHttpRequest) o;
            if (httpRequest.getDecoderResult().isFailure()
                    && httpRequest.getDecoderResult().cause() instanceof TooLongFrameException) {

                log.warn("Header size is larger than the valid limit");

                Iterator<Map.Entry<String, ChannelHandler>> iterator = ctx.pipeline().iterator();

                boolean canRemove = false;
                while (iterator.hasNext()) {
                    Map.Entry<String, ChannelHandler> channelHandlerEntry = iterator.next();
                    if (channelHandlerEntry.getKey().equalsIgnoreCase(ctx.name())) {
                        canRemove = true;
                    }//from www  .  j  a v  a 2s .  c  om
                    if (canRemove && !channelHandlerEntry.getKey().equalsIgnoreCase(ctx.name())) {
                        ctx.pipeline().remove(channelHandlerEntry.getKey());
                    }
                }

                String rejectMessage = requestSizeValidationConfig.getHeaderRejectMessage();
                byte[] errorMessageBytes = rejectMessage.getBytes(Charset.defaultCharset());
                ByteBuf content = Unpooled.wrappedBuffer(errorMessageBytes);
                DefaultFullHttpResponse rejectResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
                        HttpResponseStatus.valueOf(requestSizeValidationConfig.getHeaderRejectStatusCode()),
                        content);
                rejectResponse.headers().set(Constants.HTTP_CONTENT_LENGTH, errorMessageBytes.length);
                rejectResponse.headers().set(Constants.HTTP_CONTENT_TYPE,
                        requestSizeValidationConfig.getHeaderRejectMsgContentType());

                ctx.writeAndFlush(rejectResponse);
                break;
            }
        }
    }
}

From source file:org.wso2.carbon.transport.http.netty.listener.http2.HTTPProtocolNegotiationHandler.java

License:Open Source License

@Override
/**//from w  w  w .  j  a v a2  s.co m
 *  Configure pipeline after SSL handshake
 */
protected void configurePipeline(ChannelHandlerContext ctx, String protocol) throws Exception {
    ChannelPipeline p = ctx.pipeline();
    // handles pipeline for HTTP/2 requests after SSL handshake
    if (ApplicationProtocolNames.HTTP_2.equals(protocol)) {
        ctx.pipeline().addLast("http2-handler",
                new HTTP2SourceHandlerBuilder(connectionManager, listenerConfiguration).build());
        return;
    }
    // handles pipeline for HTTP/1 requests after SSL handshake
    if (ApplicationProtocolNames.HTTP_1_1.equals(protocol)) {
        p.addLast("encoder", new HttpResponseEncoder());
        if (requestSizeValidationConfig.isHeaderSizeValidation()) {
            p.addLast("decoder", new CustomHttpRequestDecoder(requestSizeValidationConfig));
        } else {
            p.addLast("decoder", new HttpRequestDecoder());
        }
        if (requestSizeValidationConfig.isRequestSizeValidation()) {
            p.addLast("custom-aggregator", new CustomHttpObjectAggregator(requestSizeValidationConfig));
        }
        p.addLast("compressor", new HttpContentCompressor());
        p.addLast("chunkWriter", new ChunkedWriteHandler());
        try {
            // TODO: Properly fix this part once we start HTTP2 integration
            p.addLast("handler", new SourceHandler(new HttpWsServerConnectorFuture(null), null));
        } catch (Exception e) {
            log.error("Cannot Create SourceHandler ", e);
        }
        return;
    }

    throw new IllegalStateException("unknown protocol: " + protocol);
}

From source file:org.wso2.custom.inbound.InboundHttp2ServerInitializer.java

License:Apache License

/**
 * Configure the pipeline for a clear text upgrade from HTTP to HTTP/2.0
 *//*w  w  w.  j a v  a  2 s  .  com*/
private void configureClearText(SocketChannel ch) {
    final ChannelPipeline p = ch.pipeline();
    final HttpServerCodec sourceCodec = new HttpServerCodec();

    p.addLast(sourceCodec);
    p.addLast(new HttpServerUpgradeHandler(sourceCodec, upgradeCodecFactory));
    p.addLast(new SimpleChannelInboundHandler<HttpMessage>() {
        @Override
        protected void channelRead0(ChannelHandlerContext ctx, HttpMessage msg) throws Exception {
            // If this handler is hit then no upgrade has been attempted and the client is just talking HTTP.
            log.info("No upgrade done: continue with " + msg.protocolVersion());
            ChannelPipeline pipeline = ctx.pipeline();
            ChannelHandlerContext thisCtx = pipeline.context(this);
            pipeline.addAfter(thisCtx.name(), null, new InboundHttpSourceHandler(config));
            pipeline.replace(this, null, new HttpObjectAggregator(maxHttpContentLength));
            ctx.fireChannelRead(msg);
        }
    });
    p.addLast(new UserEventLogger());
}

From source file:org.wso2.esb.integration.common.utils.servers.http2.Http2OrHttpHandler.java

License:Open Source License

@Override
protected void configurePipeline(ChannelHandlerContext ctx, String protocol) throws Exception {
    if (ApplicationProtocolNames.HTTP_2.equals(protocol)) {
        ctx.pipeline().addLast(new Http2Codec(true, new Http2Handler()));
        return;//from  www  .ja v a 2 s . c o m
    }

    if (ApplicationProtocolNames.HTTP_1_1.equals(protocol)) {
        ctx.pipeline().addLast(new HttpServerCodec(), new HttpObjectAggregator(MAX_CONTENT_LENGTH),
                new Http1Handler("ALPN Negotiation"));
        return;
    }

    throw new IllegalStateException("unknown protocol: " + protocol);
}