Example usage for io.netty.handler.ssl SslHandler SslHandler

List of usage examples for io.netty.handler.ssl SslHandler SslHandler

Introduction

In this page you can find the example usage for io.netty.handler.ssl SslHandler SslHandler.

Prototype

public SslHandler(SSLEngine engine) 

Source Link

Document

Creates a new instance which runs all delegated tasks directly on the EventExecutor .

Usage

From source file:org.wso2.carbon.transport.http.netty.sender.HTTPClientInitializer.java

License:Open Source License

@Override
protected void initChannel(SocketChannel ch) throws Exception {
    // Add the generic handlers to the pipeline
    // e.g. SSL handler
    if (proxyServerConfiguration != null) {
        if (proxyServerConfiguration.getProxyUsername() != null
                && proxyServerConfiguration.getProxyPassword() != null) {
            ch.pipeline().addLast("proxyServer",
                    new HttpProxyHandler(proxyServerConfiguration.getInetSocketAddress(),
                            proxyServerConfiguration.getProxyUsername(),
                            proxyServerConfiguration.getProxyPassword()));
        } else {//  w ww  .ja  v a  2s  . co  m
            ch.pipeline().addLast("proxyServer",
                    new HttpProxyHandler(proxyServerConfiguration.getInetSocketAddress()));
        }
    }
    if (sslEngine != null) {
        log.debug("adding ssl handler");
        ch.pipeline().addLast("ssl", new SslHandler(this.sslEngine));
    }
    ch.pipeline().addLast("compressor", new CustomHttpContentCompressor(chunkDisabled));
    ch.pipeline().addLast("decoder", new HttpResponseDecoder());
    ch.pipeline().addLast("encoder", new HttpRequestEncoder());
    ch.pipeline().addLast("chunkWriter", new ChunkedWriteHandler());
    if (httpTraceLogEnabled) {
        ch.pipeline().addLast(Constants.HTTP_TRACE_LOG_HANDLER,
                new HTTPTraceLoggingHandler("tracelog.http.upstream", LogLevel.DEBUG));
    }
    if (followRedirect) {
        if (log.isDebugEnabled()) {
            log.debug("Follow Redirect is enabled, so adding the redirect handler to the pipeline.");
        }
        RedirectHandler redirectHandler = new RedirectHandler(sslEngine, httpTraceLogEnabled, maxRedirectCount,
                chunkDisabled);
        ch.pipeline().addLast(Constants.REDIRECT_HANDLER, redirectHandler);
    }
    handler = new TargetHandler();
    ch.pipeline().addLast(Constants.TARGET_HANDLER, handler);
}

From source file:org.wso2.carbon.transport.http.netty.sender.RedirectChannelInitializer.java

License:Open Source License

@Override
protected void initChannel(SocketChannel ch) throws Exception {
    // Add the generic handlers to the pipeline
    // e.g. SSL handler
    if (sslEngine != null) {
        if (log.isDebugEnabled()) {
            log.debug("adding ssl handler");
        }/*w w  w. j  a v a2s  .  co  m*/
        ch.pipeline().addLast("ssl", new SslHandler(this.sslEngine));
    }
    ch.pipeline().addLast("compressor", new HttpContentCompressor());
    ch.pipeline().addLast("decoder", new HttpResponseDecoder());
    ch.pipeline().addLast("encoder", new HttpRequestEncoder());
    if (httpTraceLogEnabled) {
        ch.pipeline().addLast(Constants.HTTP_TRACE_LOG_HANDLER,
                new HTTPTraceLoggingHandler("tracelog.http.upstream", LogLevel.DEBUG));
    }
    RedirectHandler redirectHandler = new RedirectHandler(sslEngine, httpTraceLogEnabled, maxRedirectCount,
            chunkDisabled, originalChannelContext, isIdleHandlerOfTargetChannelRemoved);
    ch.pipeline().addLast(Constants.REDIRECT_HANDLER, redirectHandler);
}

From source file:org.wso2.carbon.transport.http.netty.util.server.HTTPServerInitializer.java

License:Open Source License

@Override
protected void initChannel(Channel channel) throws Exception {

    ChannelPipeline p = channel.pipeline();
    if (sslContext != null) {
        SSLEngine engine = sslContext.createSSLEngine();
        engine.setUseClientMode(false);//  w w  w.j av a2s .com
        p.addLast("ssl", new SslHandler(engine));
    }

    p.addLast("decoder", new HttpRequestDecoder());
    p.addLast("encoder", new HttpResponseEncoder());
    HTTPServerHandler httpServerHandler = new HTTPServerHandler();
    httpServerHandler.setMessage(message, contentType);
    httpServerHandler.setResponseStatusCode(responseCode);
    p.addLast("handler", httpServerHandler);
}

From source file:org.wso2.carbon.transport.http.netty.util.server.initializers.HTTPServerInitializer.java

License:Open Source License

@Override
protected void initChannel(Channel channel) throws Exception {

    logger.debug("Server connection established");
    ChannelPipeline p = channel.pipeline();
    if (sslContext != null) {
        SSLEngine engine = sslContext.createSSLEngine();
        engine.setUseClientMode(false);//  w w  w. java  2 s  .  co  m
        p.addLast("ssl", new SslHandler(engine));
    }

    p.addLast("decoder", new HttpRequestDecoder());
    p.addLast("encoder", new HttpResponseEncoder());
    addBusinessLogicHandler(channel);
}

From source file:org.wso2.netty.SecureChatClientInitializer.java

License:Apache License

@Override
public void initChannel(SocketChannel ch) throws Exception {
    ChannelPipeline pipeline = ch.pipeline();

    // Add SSL handler first to encrypt and decrypt everything.
    // In this example, we use a bogus certificate in the server side
    // and accept any invalid certificates in the client side.
    // You will need something more complicated to identify both
    // and server in the real world.

    SSLEngine engine = KeyStoreLoader.getClientContext().createSSLEngine();
    engine.setUseClientMode(true);/*ww w. j av a2  s  . com*/

    pipeline.addLast("ssl", new SslHandler(engine));

    pipeline.addLast(new HexDumpProxyBackendHandler(inbound));
}

From source file:org.wso2.netty.SecureProxyInitializer.java

License:Apache License

@Override
public void initChannel(SocketChannel ch) throws Exception {
    ChannelPipeline pipeline = ch.pipeline();

    // Add SSL handler first to encrypt and decrypt everything.
    // In this example, we use a bogus certificate in the server side
    // and accept any invalid certificates in the client side.
    // You will need something more complicated to identify both
    // and server in the real world.

    pipeline.addLast(new LoggingHandler(LogLevel.DEBUG));

    if (isSecureBackend) {
        LOGGER.info("Adding the SSL Handler to the pipeline");

        SSLEngine engine = SSLUtil.createClientSSLContext(trustStoreLocation, trustStorePassword)
                .createSSLEngine();/* w  w w . j  av a2s  .c o  m*/
        engine.setUseClientMode(true);

        pipeline.addLast("ssl", new SslHandler(engine));
    }

    pipeline.addLast(new HexDumpProxyBackendHandler(inbound));
}

From source file:ratpack.http.client.internal.RequestActionSupport.java

License:Apache License

public void execute(final Fulfiller<? super T> fulfiller) throws Exception {
    final AtomicBoolean redirecting = new AtomicBoolean();

    final Bootstrap b = new Bootstrap();
    b.group(this.execution.getEventLoop()).channel(ChannelImplDetector.getSocketChannelImpl())
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override//from  w  w  w .j  av a2 s  . c o m
                protected void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline p = ch.pipeline();

                    if (finalUseSsl) {
                        SSLEngine engine = SSLContext.getDefault().createSSLEngine();
                        engine.setUseClientMode(true);
                        p.addLast("ssl", new SslHandler(engine));
                    }

                    p.addLast("codec", new HttpClientCodec());
                    p.addLast("readTimeout",
                            new ReadTimeoutHandler(requestParams.readTimeoutNanos, TimeUnit.NANOSECONDS));

                    p.addLast("redirectHandler", new SimpleChannelInboundHandler<HttpObject>(false) {
                        @Override
                        protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg)
                                throws Exception {
                            if (msg instanceof HttpResponse) {
                                final HttpResponse response = (HttpResponse) msg;
                                final Headers headers = new NettyHeadersBackedHeaders(response.headers());
                                final Status status = new DefaultStatus(response.status());
                                int maxRedirects = requestSpecBacking.getMaxRedirects();
                                String locationValue = headers.get("Location");

                                //Check for redirect and location header if it is follow redirect if we have request forwarding left
                                if (shouldRedirect(status) && maxRedirects > 0 && locationValue != null) {
                                    redirecting.compareAndSet(false, true);

                                    Action<? super RequestSpec> redirectRequestConfig = Action
                                            .join(requestConfigurer, s -> {
                                                if (status.getCode() == 301 || status.getCode() == 302) {
                                                    s.method("GET");
                                                }

                                                s.redirects(maxRedirects - 1);
                                            });

                                    URI locationUrl;
                                    if (ABSOLUTE_PATTERN.matcher(locationValue).matches()) {
                                        locationUrl = new URI(locationValue);
                                    } else {
                                        locationUrl = new URI(uri.getScheme(), null, uri.getHost(),
                                                uri.getPort(), locationValue, null, null);
                                    }

                                    buildRedirectRequestAction(redirectRequestConfig, locationUrl)
                                            .execute(fulfiller);
                                } else {
                                    p.remove(this);
                                }
                            }

                            if (!redirecting.get()) {
                                ctx.fireChannelRead(msg);
                            }
                        }
                    });

                    addResponseHandlers(p, fulfiller);
                }

                @Override
                public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
                    ctx.close();
                    error(fulfiller, cause);
                }
            });

    ChannelFuture connectFuture = b.connect(host, port);
    connectFuture.addListener(f1 -> {
        if (connectFuture.isSuccess()) {
            String fullPath = getFullPath(uri);
            FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1,
                    HttpMethod.valueOf(requestSpecBacking.getMethod()), fullPath, requestSpecBacking.getBody());
            if (headers.get(HttpHeaderConstants.HOST) == null) {
                headers.set(HttpHeaderConstants.HOST, host);
            }
            headers.set(HttpHeaderConstants.CONNECTION, HttpHeaderValues.CLOSE);
            int contentLength = request.content().readableBytes();
            if (contentLength > 0) {
                headers.set(HttpHeaderConstants.CONTENT_LENGTH, Integer.toString(contentLength, 10));
            }

            HttpHeaders requestHeaders = request.headers();

            for (String name : headers.getNames()) {
                requestHeaders.set(name, headers.getAll(name));
            }

            ChannelFuture writeFuture = connectFuture.channel().writeAndFlush(request);
            writeFuture.addListener(f2 -> {
                if (!writeFuture.isSuccess()) {
                    writeFuture.channel().close();
                    error(fulfiller, writeFuture.cause());
                }
            });
        } else {
            connectFuture.channel().close();
            error(fulfiller, connectFuture.cause());
        }
    });
}

From source file:ratpack.server.internal.DefaultRatpackServer.java

License:Apache License

protected Channel buildChannel(final ServerConfig serverConfig, final ChannelHandler handlerAdapter)
        throws InterruptedException {

    SslContext sslContext = serverConfig.getNettySslContext();
    this.useSsl = sslContext != null;

    ServerBootstrap serverBootstrap = new ServerBootstrap();

    serverConfig.getConnectTimeoutMillis().ifPresent(i -> {
        serverBootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, i);
        serverBootstrap.childOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, i);
    });/*from  w w  w. j  av a 2  s.  c o m*/
    serverConfig.getMaxMessagesPerRead().ifPresent(i -> {
        FixedRecvByteBufAllocator allocator = new FixedRecvByteBufAllocator(i);
        serverBootstrap.option(ChannelOption.RCVBUF_ALLOCATOR, allocator);
        serverBootstrap.childOption(ChannelOption.RCVBUF_ALLOCATOR, allocator);
    });
    serverConfig.getReceiveBufferSize().ifPresent(i -> {
        serverBootstrap.option(ChannelOption.SO_RCVBUF, i);
        serverBootstrap.childOption(ChannelOption.SO_RCVBUF, i);
    });
    serverConfig.getWriteSpinCount().ifPresent(i -> {
        serverBootstrap.option(ChannelOption.WRITE_SPIN_COUNT, i);
        serverBootstrap.childOption(ChannelOption.WRITE_SPIN_COUNT, i);
    });
    serverConfig.getConnectQueueSize().ifPresent(i -> serverBootstrap.option(ChannelOption.SO_BACKLOG, i));

    return serverBootstrap.group(execController.getEventLoopGroup())
            .channel(ChannelImplDetector.getServerSocketChannelImpl())
            .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline pipeline = ch.pipeline();

                    new ConnectionIdleTimeout(pipeline, serverConfig.getIdleTimeout());

                    if (sslContext != null) {
                        SSLEngine sslEngine = sslContext.newEngine(PooledByteBufAllocator.DEFAULT);
                        pipeline.addLast("ssl", new SslHandler(sslEngine));
                    }

                    pipeline.addLast("decoder", new HttpRequestDecoder(serverConfig.getMaxInitialLineLength(),
                            serverConfig.getMaxHeaderSize(), serverConfig.getMaxChunkSize(), false));
                    pipeline.addLast("encoder", new HttpResponseEncoder());
                    pipeline.addLast("deflater", new IgnorableHttpContentCompressor());
                    pipeline.addLast("chunkedWriter", new ChunkedWriteHandler());
                    pipeline.addLast("adapter", handlerAdapter);

                    ch.config().setAutoRead(false);
                }
            }).bind(buildSocketAddress(serverConfig)).sync().channel();
}

From source file:ratpack.server.internal.NettyRatpackServer.java

License:Apache License

protected Channel buildChannel(final ServerConfig serverConfig, final ChannelHandler handlerAdapter)
        throws InterruptedException {

    SSLContext sslContext = serverConfig.getSSLContext();
    if (sslContext != null) {
        this.sslEngine = sslContext.createSSLEngine();
        sslEngine.setUseClientMode(false);
    }/*from w  ww  .jav  a2 s . co m*/

    return new ServerBootstrap().group(execController.getEventLoopGroup())
            .channel(ChannelImplDetector.getServerSocketChannelImpl())
            .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline pipeline = ch.pipeline();
                    if (sslContext != null) {
                        pipeline.addLast("ssl", new SslHandler(sslEngine));
                    }

                    pipeline.addLast("decoder", new HttpRequestDecoder(4096, 8192, 8192, false));
                    pipeline.addLast("aggregator",
                            new HttpObjectAggregator(serverConfig.getMaxContentLength()));
                    pipeline.addLast("encoder", new HttpResponseEncoder());
                    pipeline.addLast("deflater", new SmartHttpContentCompressor());
                    pipeline.addLast("chunkedWriter", new ChunkedWriteHandler());
                    pipeline.addLast("adapter", handlerAdapter);
                }
            }).bind(buildSocketAddress(serverConfig)).sync().channel();
}

From source file:ratpack.server.internal.RatpackChannelInitializer.java

License:Apache License

public void initChannel(SocketChannel ch) {
    ChannelPipeline pipeline = ch.pipeline();

    if (sslContext != null) {
        SSLEngine engine = sslContext.createSSLEngine();
        engine.setUseClientMode(false);/*from   w ww  . j a  v  a  2  s . c o  m*/
        pipeline.addLast("ssl", new SslHandler(engine));
    }

    pipeline.addLast("decoder", new HttpRequestDecoder(4096, 8192, 8192, false));
    pipeline.addLast("aggregator", new HttpObjectAggregator(maxContentLength));
    pipeline.addLast("encoder", new HttpResponseEncoder());
    if (compressResponses) {
        pipeline.addLast("deflater", new SmartHttpContentCompressor());
    }
    pipeline.addLast("chunkedWriter", new ChunkedWriteHandler());
    pipeline.addLast("handler", nettyHandlerAdapter);
}