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

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

Introduction

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

Prototype

@Deprecated
public JdkSslContext(SSLContext sslContext, boolean isClient, ClientAuth clientAuth) 

Source Link

Document

Creates a new JdkSslContext from a pre-configured SSLContext .

Usage

From source file:io.druid.server.emitter.HttpEmitterModule.java

License:Apache License

static AsyncHttpClient createAsyncHttpClient(String nameFormat, String timerThreadNameFormat,
        @Nullable SSLContext sslContext) {
    final DefaultAsyncHttpClientConfig.Builder builder = new DefaultAsyncHttpClientConfig.Builder()
            .setThreadFactory(Execs.makeThreadFactory(nameFormat))
            .setNettyTimer(new HashedWheelTimer(Execs.makeThreadFactory(timerThreadNameFormat)));
    if (sslContext != null) {
        builder.setSslContext(new JdkSslContext(sslContext, true, ClientAuth.NONE));
    }/*ww  w.  j a v  a2 s .  co m*/
    return new DefaultAsyncHttpClient(builder.build());
}

From source file:io.druid.server.emitter.ParametrizedUriEmitterModule.java

License:Apache License

@Provides
@ManageLifecycle/*from  w ww.j a va  2  s  .co m*/
@Named("parametrized")
public Emitter getEmitter(Supplier<ParametrizedUriEmitterConfig> config, @Nullable SSLContext sslContext,
        Lifecycle lifecycle, ObjectMapper jsonMapper) {
    final DefaultAsyncHttpClientConfig.Builder builder = new DefaultAsyncHttpClientConfig.Builder();
    if (sslContext != null) {
        builder.setSslContext(new JdkSslContext(sslContext, true, ClientAuth.NONE));
    }
    final AsyncHttpClient client = new DefaultAsyncHttpClient(builder.build());
    lifecycle.addCloseableInstance(client);

    return new ParametrizedUriEmitter(config.get(), client, jsonMapper);
}

From source file:org.glassfish.jersey.netty.connector.NettyConnector.java

License:Open Source License

@Override
public Future<?> apply(final ClientRequest jerseyRequest, final AsyncConnectorCallback jerseyCallback) {

    final CompletableFuture<Object> settableFuture = new CompletableFuture<>();

    final URI requestUri = jerseyRequest.getUri();
    String host = requestUri.getHost();
    int port = requestUri.getPort() != -1 ? requestUri.getPort()
            : "https".equals(requestUri.getScheme()) ? 443 : 80;

    try {//from  w  w w .  ja va 2  s . co  m
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ChannelPipeline p = ch.pipeline();

                // Enable HTTPS if necessary.
                if ("https".equals(requestUri.getScheme())) {
                    // making client authentication optional for now; it could be extracted to configurable property
                    JdkSslContext jdkSslContext = new JdkSslContext(client.getSslContext(), true,
                            ClientAuth.NONE);
                    p.addLast(jdkSslContext.newHandler(ch.alloc()));
                }

                // http proxy
                Configuration config = jerseyRequest.getConfiguration();
                final Object proxyUri = config.getProperties().get(ClientProperties.PROXY_URI);
                if (proxyUri != null) {
                    final URI u = getProxyUri(proxyUri);

                    final String userName = ClientProperties.getValue(config.getProperties(),
                            ClientProperties.PROXY_USERNAME, String.class);
                    final String password = ClientProperties.getValue(config.getProperties(),
                            ClientProperties.PROXY_PASSWORD, String.class);

                    p.addLast(new HttpProxyHandler(
                            new InetSocketAddress(u.getHost(), u.getPort() == -1 ? 8080 : u.getPort()),
                            userName, password));
                }

                p.addLast(new HttpClientCodec());
                p.addLast(new ChunkedWriteHandler());
                p.addLast(new HttpContentDecompressor());
                p.addLast(new JerseyClientHandler(NettyConnector.this, jerseyRequest, jerseyCallback,
                        settableFuture));
            }
        });

        // connect timeout
        Integer connectTimeout = ClientProperties.getValue(jerseyRequest.getConfiguration().getProperties(),
                ClientProperties.CONNECT_TIMEOUT, 0);
        if (connectTimeout > 0) {
            b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeout);
        }

        // Make the connection attempt.
        final Channel ch = b.connect(host, port).sync().channel();

        // guard against prematurely closed channel
        final GenericFutureListener<io.netty.util.concurrent.Future<? super Void>> closeListener = new GenericFutureListener<io.netty.util.concurrent.Future<? super Void>>() {
            @Override
            public void operationComplete(io.netty.util.concurrent.Future<? super Void> future)
                    throws Exception {
                if (!settableFuture.isDone()) {
                    settableFuture.completeExceptionally(new IOException("Channel closed."));
                }
            }
        };

        ch.closeFuture().addListener(closeListener);

        HttpRequest nettyRequest;

        if (jerseyRequest.hasEntity()) {
            nettyRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1,
                    HttpMethod.valueOf(jerseyRequest.getMethod()), requestUri.getRawPath());
        } else {
            nettyRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1,
                    HttpMethod.valueOf(jerseyRequest.getMethod()), requestUri.getRawPath());
        }

        // headers
        for (final Map.Entry<String, List<String>> e : jerseyRequest.getStringHeaders().entrySet()) {
            nettyRequest.headers().add(e.getKey(), e.getValue());
        }

        // host header - http 1.1
        nettyRequest.headers().add(HttpHeaderNames.HOST, jerseyRequest.getUri().getHost());

        if (jerseyRequest.hasEntity()) {
            if (jerseyRequest.getLengthLong() == -1) {
                HttpUtil.setTransferEncodingChunked(nettyRequest, true);
            } else {
                nettyRequest.headers().add(HttpHeaderNames.CONTENT_LENGTH, jerseyRequest.getLengthLong());
            }
        }

        if (jerseyRequest.hasEntity()) {
            // Send the HTTP request.
            ch.writeAndFlush(nettyRequest);

            final JerseyChunkedInput jerseyChunkedInput = new JerseyChunkedInput(ch);
            jerseyRequest.setStreamProvider(new OutboundMessageContext.StreamProvider() {
                @Override
                public OutputStream getOutputStream(int contentLength) throws IOException {
                    return jerseyChunkedInput;
                }
            });

            if (HttpUtil.isTransferEncodingChunked(nettyRequest)) {
                ch.write(new HttpChunkedInput(jerseyChunkedInput));
            } else {
                ch.write(jerseyChunkedInput);
            }

            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    // close listener is not needed any more.
                    ch.closeFuture().removeListener(closeListener);

                    try {
                        jerseyRequest.writeEntity();
                    } catch (IOException e) {
                        jerseyCallback.failure(e);
                        settableFuture.completeExceptionally(e);
                    }
                }
            });

            ch.flush();
        } else {
            // close listener is not needed any more.
            ch.closeFuture().removeListener(closeListener);

            // Send the HTTP request.
            ch.writeAndFlush(nettyRequest);
        }

    } catch (InterruptedException e) {
        settableFuture.completeExceptionally(e);
        return settableFuture;
    }

    return settableFuture;
}

From source file:ratpack.config.internal.module.ServerConfigDataDeserializer.java

License:Apache License

@Override
public ServerConfigData deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
    ObjectCodec codec = jp.getCodec();//from   w w  w.jav a  2  s.c  om
    ObjectNode serverNode = jp.readValueAsTree();
    ServerConfigData data = new ServerConfigData(baseDirSupplier.get(), address, port, development,
            publicAddress);
    if (serverNode.hasNonNull("port")) {
        data.setPort(parsePort(serverNode.get("port")));
    }
    if (serverNode.hasNonNull("address")) {
        data.setAddress(toValue(codec, serverNode.get("address"), InetAddress.class));
    }
    if (serverNode.hasNonNull("idleTimeout")) {
        data.setIdleTimeout(toValue(codec, serverNode.get("idleTimeout"), Duration.class));
    }
    if (serverNode.hasNonNull("development")) {
        data.setDevelopment(serverNode.get("development").asBoolean(false));
    }
    if (serverNode.hasNonNull("threads")) {
        data.setThreads(serverNode.get("threads").asInt(ServerConfig.DEFAULT_THREADS));
    }
    if (serverNode.hasNonNull("registerShutdownHook")) {
        data.setRegisterShutdownHook(serverNode.get("registerShutdownHook").asBoolean(true));
    }
    if (serverNode.hasNonNull("publicAddress")) {
        data.setPublicAddress(toValue(codec, serverNode.get("publicAddress"), URI.class));
    }
    if (serverNode.hasNonNull("maxContentLength")) {
        data.setMaxContentLength(
                serverNode.get("maxContentLength").asInt(ServerConfig.DEFAULT_MAX_CONTENT_LENGTH));
    }
    if (serverNode.hasNonNull("maxChunkSize")) {
        data.setMaxChunkSize(serverNode.get("maxChunkSize").asInt(ServerConfig.DEFAULT_MAX_CHUNK_SIZE));
    }
    if (serverNode.hasNonNull("maxInitialLineLength")) {
        data.setMaxInitialLineLength(
                serverNode.get("maxInitialLineLength").asInt(ServerConfig.DEFAULT_MAX_INITIAL_LINE_LENGTH));
    }
    if (serverNode.hasNonNull("maxHeaderSize")) {
        data.setMaxHeaderSize(serverNode.get("maxHeaderSize").asInt(ServerConfig.DEFAULT_MAX_HEADER_SIZE));
    }
    if (serverNode.hasNonNull("requireClientSslAuth")) {
        data.setRequireClientSslAuth(serverNode.get("requireClientSslAuth").asBoolean(false));
    }
    if (serverNode.hasNonNull("ssl")) {
        data.setSslContext(toValue(codec, serverNode.get("ssl"), SslContext.class));
    } else if (serverNode.hasNonNull("jdkSsl")) {
        SSLContext jdkSslContext = toValue(codec, serverNode.get("jdkSsl"), SSLContext.class);
        data.setSslContext(new JdkSslContext(jdkSslContext, false,
                data.isRequireClientSslAuth() ? ClientAuth.REQUIRE : ClientAuth.NONE));
    }
    if (serverNode.hasNonNull("baseDir")) {
        throw new IllegalStateException(
                "baseDir value cannot be set via config, it must be set directly via ServerConfigBuilder.baseDir()");
    }
    if (serverNode.hasNonNull("connectTimeoutMillis")) {
        parseOptionalIntValue("connectTimeoutMillis", serverNode.get("connectTimeoutMillis"))
                .ifPresent(data::setConnectTimeoutMillis);
    }
    if (serverNode.hasNonNull("maxMessagesPerRead")) {
        parseOptionalIntValue("maxMessagesPerRead", serverNode.get("maxMessagesPerRead"))
                .ifPresent(data::setMaxMessagesPerRead);
    }
    if (serverNode.hasNonNull("receiveBufferSize")) {
        parseOptionalIntValue("receiveBufferSize", serverNode.get("receiveBufferSize"))
                .ifPresent(data::setReceiveBufferSize);
    }
    if (serverNode.hasNonNull("writeSpinCount")) {
        parseOptionalIntValue("writeSpinCount", serverNode.get("writeSpinCount"))
                .ifPresent(data::setWriteSpinCount);
    }
    if (serverNode.hasNonNull("connectQueueSize")) {
        parseOptionalIntValue("connectQueueSize", serverNode.get("connectQueueSize"))
                .ifPresent(data::setConnectQueueSize);
    }

    return data;
}