Example usage for io.netty.handler.ssl SslContextBuilder forClient

List of usage examples for io.netty.handler.ssl SslContextBuilder forClient

Introduction

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

Prototype

public static SslContextBuilder forClient() 

Source Link

Document

Creates a builder for new client-side SslContext .

Usage

From source file:ozy.client.Client.java

License:Open Source License

private void perform(EventLoopGroup group) throws Exception {
    final boolean ssl = scheme().equalsIgnoreCase("https");
    final SslContext sslCtx;
    if (ssl) {/*ww w .j  a v  a  2s .c  om*/
        sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();
    } else {
        sslCtx = null;
    }

    System.out.println("[Client] creating bootstrap");

    Bootstrap b = new Bootstrap();
    b.group(group).channel(NioSocketChannel.class).handler(new ClientInitializer(sslCtx));

    System.out.println("[Client] connecting to host");

    Channel ch = b.connect(host(), port()).sync().channel();

    ClientHandler clientHandler = (ClientHandler) ch.pipeline().get("clientHandler");
    clientHandler.setPromise(_promise);

    ByteBuf requestBytes;
    if (!body().isEmpty()) {
        requestBytes = Unpooled.copiedBuffer(body(), CharsetUtil.UTF_8);
    } else {
        requestBytes = Unpooled.buffer(0);
    }

    String pathWithParams = path();
    if (params() != null) {
        pathWithParams += "?";
        for (Map.Entry<String, List<String>> e : params().entrySet()) {
            for (String v : e.getValue()) {
                if (!pathWithParams.endsWith("?")) {
                    pathWithParams += "&";
                }
                pathWithParams += e.getKey() + "=" + v;
            }
        }
    }

    DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, method(), pathWithParams,
            requestBytes);

    HttpHeaders.setHost(request, host());
    HttpHeaders.setKeepAlive(request, false);
    HttpHeaders.setContentLength(request, request.content().readableBytes());

    setCookies(request.headers());

    System.out.println("[Client] writeAndFlush");

    ch.writeAndFlush(request);
}

From source file:push2.apns.demo2.Http2Client.java

License:Apache License

public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;

    SslProvider provider = OpenSsl.isAlpnSupported() ? SslProvider.OPENSSL : SslProvider.JDK;
    sslCtx = SslContextBuilder.forClient().sslProvider(provider)
            /* NOTE: the cipher filter may not include all ciphers required by the HTTP/2 specification.
             * Please refer to the HTTP/2 specification for cipher requirements. */
            .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE)
            .trustManager(InsecureTrustManagerFactory.INSTANCE)
            .applicationProtocolConfig(new ApplicationProtocolConfig(Protocol.ALPN,
                    // NO_ADVERTISE is currently the only mode supported by both OpenSsl and JDK providers.
                    SelectorFailureBehavior.NO_ADVERTISE,
                    // ACCEPT is currently the only mode supported by both OpenSsl and JDK providers.
                    SelectedListenerFailureBehavior.ACCEPT, ApplicationProtocolNames.HTTP_2,
                    ApplicationProtocolNames.HTTP_1_1))
            .build();//from  w  w  w  .  j  a v a 2s .  co  m

    EventLoopGroup workerGroup = new NioEventLoopGroup();
    Http2ClientInitializer initializer = new Http2ClientInitializer(sslCtx, Integer.MAX_VALUE);

    try {
        // Configure the client.
        Bootstrap b = new Bootstrap();
        b.group(workerGroup);
        b.channel(NioSocketChannel.class);
        b.option(ChannelOption.SO_KEEPALIVE, true);
        b.remoteAddress(HOST, PORT);
        b.handler(initializer);

        // Start the client.
        Channel channel = b.connect().channel();
        System.out.println("Connected to [" + HOST + ':' + PORT + ']');

        // Wait for the HTTP/2 upgrade to occur.
        Http2SettingsHandler http2SettingsHandler = initializer.settingsHandler();
        //http2SettingsHandler.awaitSettings(5, TimeUnit.SECONDS);

        HttpResponseHandler responseHandler = initializer.responseHandler();
        int streamId = 3;

        AsciiString hostName = new AsciiString(HOST + ':' + PORT);
        System.err.println("Sending request(s)...");

        // Create a simple POST request with a body.
        FullHttpRequest request = new DefaultFullHttpRequest(HTTP_1_1, POST,
                "https://" + HOST + "/3/device/" + DEVICE_TOKEN,
                wrappedBuffer(payload.getBytes(CharsetUtil.UTF_8)));
        request.headers().add(HttpHeaderNames.HOST, hostName);
        request.headers().add(HttpConversionUtil.ExtensionHeaderNames.SCHEME.text(), HttpScheme.HTTPS.name());
        request.headers().add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP);
        request.headers().add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.DEFLATE);
        request.headers().add("authorization", "bearer " + JWT.getToken(TEAM_ID, KEY_ID, ACCESS_SECRET));
        request.headers().add("apns-topic", "com.hujiang.hjm.normandy");

        channel.write(request);
        // responseHandler.put(streamId, channel.write(request), channel.newPromise());

        channel.flush();
        //responseHandler.awaitResponses(5, TimeUnit.SECONDS);
        System.out.println("Finished HTTP/2 request(s)");

        // Wait until the connection is closed.
        channel.close().syncUninterruptibly();
    } finally {
        workerGroup.shutdownGracefully();
    }

    while (Thread.activeCount() > 1) {
        Thread.yield();
    }
}

From source file:reactor.ipc.netty.http.client.HttpClientTest.java

License:Open Source License

@Test
public void sshExchangeRelativeGet() throws CertificateException, SSLException {
    SelfSignedCertificate ssc = new SelfSignedCertificate();
    SslContext sslServer = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
    SslContext sslClient = SslContextBuilder.forClient()
            //make the client to trust the self signed certificate
            .trustManager(ssc.cert()).build();

    NettyContext context = HttpServer.create(opt -> opt.sslContext(sslServer))
            .newHandler((req, resp) -> resp.sendString(Flux.just("hello ", req.uri()))).block();

    HttpClientResponse response = HttpClient
            .create(opt -> opt.port(context.address().getPort()).sslContext(sslClient)).get("/foo")
            .block(Duration.ofMillis(200));
    context.dispose();//from   ww w .ja  v a  2  s  .c  om
    context.onClose().block();

    String responseString = response.receive().aggregate().asString(CharsetUtil.UTF_8).block();
    assertThat(responseString).isEqualTo("hello /foo");
}

From source file:reactor.ipc.netty.http.client.HttpClientTest.java

License:Open Source License

@Test
public void sshExchangeAbsoluteGet() throws CertificateException, SSLException {
    SelfSignedCertificate ssc = new SelfSignedCertificate();
    SslContext sslServer = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
    SslContext sslClient = SslContextBuilder.forClient().trustManager(ssc.cert()).build();

    NettyContext context = HttpServer.create(opt -> opt.sslContext(sslServer))
            .newHandler((req, resp) -> resp.sendString(Flux.just("hello ", req.uri()))).block();

    HttpClientResponse response = HttpClient
            .create(opt -> opt.port(context.address().getPort()).sslContext(sslClient))
            .get("https://localhost:" + context.address().getPort() + "/foo").block(Duration.ofMillis(200));
    context.dispose();//from   w  ww .  j av a 2s. co m
    context.onClose().block();

    String responseString = response.receive().aggregate().asString(CharsetUtil.UTF_8).block();
    assertThat(responseString).isEqualTo("hello /foo");
}

From source file:reactor.ipc.netty.http.client.HttpClientTest.java

License:Open Source License

@Test
public void secureSendFile() throws CertificateException, SSLException, InterruptedException {
    Path largeFile = Paths.get(getClass().getResource("/largeFile.txt").getFile());
    SelfSignedCertificate ssc = new SelfSignedCertificate();
    SslContext sslServer = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
    SslContext sslClient = SslContextBuilder.forClient().trustManager(ssc.cert()).build();
    AtomicReference<String> uploaded = new AtomicReference<>();

    NettyContext context = HttpServer.create(opt -> opt.sslContext(sslServer))
            .newRouter(//from  w w  w.  ja v  a 2s  .  c  om
                    r -> r.post("/upload",
                            (req, resp) -> req.receive().aggregate().asString().doOnNext(uploaded::set)
                                    .then(resp.status(201).sendString(Mono.just("Received File")).then())))
            .block();

    HttpClientResponse response = HttpClient
            .create(opt -> opt.port(context.address().getPort()).sslContext(sslClient))
            .post("/upload", r -> r.sendFile(largeFile)).block(Duration.ofSeconds(120));

    context.dispose();
    context.onClose().block();

    String responseBody = response.receive().aggregate().asString().block();
    assertThat(response.status().code()).isEqualTo(201);
    assertThat(responseBody).isEqualTo("Received File");

    assertThat(uploaded.get())
            .startsWith(
                    "This is an UTF-8 file that is larger than 1024 bytes.\n" + "It contains accents like .")
            .contains("1024 mark here -><- 1024 mark here").endsWith("End of File");
}

From source file:reactor.ipc.netty.http.server.HttpServerTests.java

License:Open Source License

@Test
public void secureSendFile() throws CertificateException, SSLException, InterruptedException {
    Path largeFile = Paths.get(getClass().getResource("/largeFile.txt").getFile());
    SelfSignedCertificate ssc = new SelfSignedCertificate();
    SslContext sslServer = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
    SslContext sslClient = SslContextBuilder.forClient().trustManager(ssc.cert()).build();

    NettyContext context = HttpServer.create(opt -> opt.sslContext(sslServer))
            .newHandler((req, resp) -> resp.sendFile(largeFile)).block();

    HttpClientResponse response = HttpClient
            .create(opt -> opt.port(context.address().getPort()).sslContext(sslClient)).get("/foo")
            .block(Duration.ofSeconds(120));

    context.dispose();// w  ww . j  av  a 2 s  . co  m
    context.onClose().block();

    String body = response.receive().aggregate().asString().block();

    assertThat(body)
            .startsWith(
                    "This is an UTF-8 file that is larger than 1024 bytes.\n" + "It contains accents like .")
            .contains("1024 mark here -><- 1024 mark here").endsWith("End of File");
}

From source file:reactor.ipc.netty.options.ClientOptions.java

License:Open Source License

/**
 * Enable default sslContext support and enable further customization via the passed
 * configurator. The builder will then produce the {@link SslContext} to be passed to
 * {@link #sslContext(SslContext)}.// ww w.j  a va2  s  . c o  m
 *
 * @param configurator builder callback for further customization.
 *
 * @return this {@link ClientOptions}
 */
public ClientOptions sslSupport(Consumer<? super SslContextBuilder> configurator) {
    Objects.requireNonNull(configurator, "configurator");
    try {
        SslContextBuilder builder = SslContextBuilder.forClient();
        configurator.accept(builder);
        return sslContext(builder.build());
    } catch (Exception sslException) {
        throw Exceptions.bubble(sslException);
    }
}

From source file:reactor.ipc.netty.options.HttpClientOptions.java

License:Open Source License

/**
 *
 * @return this {@link HttpClientOptions}
 *///from  ww  w .  j  av  a2  s. c  o m
@Override
public HttpClientOptions sslSupport() {
    super.ssl(SslContextBuilder.forClient());
    return this;
}

From source file:reactor.ipc.netty.tcp.TcpServerTests.java

License:Open Source License

@Test
public void tcpServerHandlesJsonPojosOverSsl() throws Exception {
    final CountDownLatch latch = new CountDownLatch(2);

    SslContext clientOptions = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE)
            .build();// w  w  w.ja va2s .c o m
    final TcpServer server = TcpServer.create(opts -> opts.listen("localhost").sslSelfSigned());

    ObjectMapper m = new ObjectMapper();

    NettyContext connectedServer = server.newHandler((in, out) -> {
        in.receive().asByteArray().map(bb -> {
            try {
                return m.readValue(bb, Pojo.class);
            } catch (IOException io) {
                throw Exceptions.propagate(io);
            }
        }).log("conn").subscribe(data -> {
            if ("John Doe".equals(data.getName())) {
                latch.countDown();
            }
        });

        return out.sendString(Mono.just("Hi")).neverComplete();
    }).block();

    final TcpClient client = TcpClient.create(
            opts -> opts.connect("localhost", connectedServer.address().getPort()).sslContext(clientOptions));

    NettyContext connectedClient = client.newHandler((in, out) -> {
        //in
        in.receive().asString().log("receive").subscribe(data -> {
            if (data.equals("Hi")) {
                latch.countDown();
            }
        });

        //out
        return out.send(Flux.just(new Pojo("John" + " Doe")).map(s -> {
            try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
                m.writeValue(os, s);
                return out.alloc().buffer().writeBytes(os.toByteArray());
            } catch (IOException ioe) {
                throw Exceptions.propagate(ioe);
            }
        })).neverComplete();
        //         return Mono.empty();
    }).block();

    assertTrue("Latch was counted down", latch.await(5, TimeUnit.SECONDS));

    connectedClient.dispose();
    connectedServer.dispose();
}

From source file:sample.WebfluxX509ApplicationTest.java

License:Apache License

private WebTestClient createWebTestClientWithClientCertificate() throws KeyStoreException, IOException,
        NoSuchAlgorithmException, CertificateException, UnrecoverableEntryException {
    ClassPathResource serverKeystore = new ClassPathResource("/certs/server.p12");

    KeyStore keyStore = KeyStore.getInstance("PKCS12");
    keyStore.load(serverKeystore.getInputStream(), "password".toCharArray());

    X509Certificate devCA = (X509Certificate) keyStore.getCertificate("DevCA");

    X509Certificate clientCrt = (X509Certificate) keyStore.getCertificate("client");
    KeyStore.Entry keyStoreEntry = keyStore.getEntry("client",
            new KeyStore.PasswordProtection("password".toCharArray()));
    PrivateKey clientKey = ((KeyStore.PrivateKeyEntry) keyStoreEntry).getPrivateKey();

    SslContextBuilder sslContextBuilder = SslContextBuilder.forClient().clientAuth(ClientAuth.REQUIRE)
            .trustManager(devCA).keyManager(clientKey, clientCrt);

    HttpClient httpClient = HttpClient.create()
            .secure(sslContextSpec -> sslContextSpec.sslContext(sslContextBuilder));
    ClientHttpConnector httpConnector = new ReactorClientHttpConnector(httpClient);

    return WebTestClient.bindToServer(httpConnector).baseUrl("https://localhost:" + port).build();
}