Java Code Examples for reactor.netty.http.client.httpclient#secure()

The following examples show how to use reactor.netty.http.client.httpclient#secure() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TitusWebClientAddOns.java    From titus-control-plane with Apache License 2.0 6 votes vote down vote up
public static WebClient.Builder addTitusDefaults(WebClient.Builder clientBuilder,
                                                 boolean secure,
                                                 WebClientMetric webClientMetric) {
    HttpClient httpClient = HttpClient.create();
    // SSL
    if (secure) {
        try {
            SslContext sslContext = SslContextBuilder.forClient().build();
            httpClient = httpClient.secure(spec -> spec.sslContext(sslContext));
        } catch (SSLException e) {
            logger.error("Unable configure Docker registry client SSL context: {}", e.getMessage());
            throw new RuntimeException("Error configuring SSL context", e);
        }
    }

    return addTitusDefaults(clientBuilder, httpClient, webClientMetric);
}
 
Example 2
Source File: ClientHttpConnectorFactory.java    From spring-vault with Apache License 2.0 6 votes vote down vote up
static ClientHttpConnector usingReactorNetty(ClientOptions options, SslConfiguration sslConfiguration) {
	HttpClient client = HttpClient.create();

	if (hasSslConfiguration(sslConfiguration)) {

		SslContextBuilder sslContextBuilder = SslContextBuilder.forClient();
		configureSsl(sslConfiguration, sslContextBuilder);

		client = client.secure(builder -> {
			builder.sslContext(sslContextBuilder);
		});
	}

	client = client.tcpConfiguration(it -> it.option(ChannelOption.CONNECT_TIMEOUT_MILLIS,
			Math.toIntExact(options.getConnectionTimeout().toMillis())));

	return new ReactorClientHttpConnector(client);
}
 
Example 3
Source File: HelloWorldClient.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
	HttpClient client =
			HttpClient.create()
			          .port(PORT)
			          .wiretap(WIRETAP)
			          .compress(COMPRESS);

	if (SECURE) {
		client = client.secure(
				spec -> spec.sslContext(SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE)));
	}

	String response =
			client.get()
			      .uri("/hello")
			      .responseContent()
			      .aggregate()
			      .asString()
			      .block();

	System.out.println("Response: " + response);
}
 
Example 4
Source File: EchoClient.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
	HttpClient client =
			HttpClient.create()
			          .port(PORT)
			          .wiretap(WIRETAP)
			          .compress(COMPRESS);

	if (SECURE) {
		client = client.secure(
				spec -> spec.sslContext(SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE)));
	}

	String response =
			client.post()
			      .uri("/echo")
			      .send(ByteBufFlux.fromString(Mono.just("echo")))
			      .responseContent()
			      .aggregate()
			      .asString()
			      .block();

	System.out.println("Response: " + response);
}
 
Example 5
Source File: ClientHttpConnectorFactory.java    From spring-credhub with Apache License 2.0 5 votes vote down vote up
/**
 * Create a {@link ClientHttpConnector} for the given {@link ClientOptions}.
 * @param options must not be {@literal null}
 * @return a new {@link ClientHttpConnector}.
 */
public static ClientHttpConnector create(ClientOptions options) {
	HttpClient httpClient = HttpClient.create();

	if (usingCustomCerts(options)) {
		TrustManagerFactory trustManagerFactory = sslCertificateUtils
				.createTrustManagerFactory(options.getCaCertFiles());

		httpClient = httpClient.secure((sslContextSpec) -> sslContextSpec.sslContext(
				SslContextBuilder.forClient().sslProvider(SslProvider.JDK).trustManager(trustManagerFactory)));
	}
	else {
		httpClient = httpClient.secure((sslContextSpec) -> {
			try {
				sslContextSpec.sslContext(new JdkSslContext(SSLContext.getDefault(), true, null,
						IdentityCipherSuiteFilter.INSTANCE, null, ClientAuth.REQUIRE, null, false));
			}
			catch (NoSuchAlgorithmException ex) {
				logger.error("Error configuring HTTP connections", ex);
				throw new RuntimeException("Error configuring HTTP connections", ex);
			}
		});
	}

	if (options.getConnectionTimeout() != null) {
		httpClient = httpClient
				.tcpConfiguration((tcpClient) -> tcpClient.option(ChannelOption.CONNECT_TIMEOUT_MILLIS,
						Math.toIntExact(options.getConnectionTimeout().toMillis())));
	}

	return new ReactorClientHttpConnector(httpClient);
}
 
Example 6
Source File: ReactorHttpRpcClient.java    From etherjar with Apache License 2.0 5 votes vote down vote up
public ReactorHttpRpcClient build() {
    if (transportType == null) {
        transportType = TransportType.BATCH;
    }
    if (target == null) {
        target = Mono.just("http://127.0.0.1:8545");
    }
    if (rpcConverter == null) {
        rpcConverter = new JacksonRpcConverter();
    }
    HttpClient clientBuilder = HttpClient.create();
    if (headers != null) {
        clientBuilder = clientBuilder.headers(headers);
    }
    clientBuilder = clientBuilder.headers((h) -> {
        h.add(HttpHeaderNames.CONTENT_TYPE, "application/json");
    });
    if (sslProviderBuilder != null) {
        clientBuilder = clientBuilder.secure(sslProviderBuilder);
    }
    ReactorRpcTransport transport;
    if (transportType == TransportType.BATCH) {
        BatchToString batchToString = new BatchToString(rpcConverter);
        transport = new BatchTransport(clientBuilder, target, rpcConverter, batchToString);
    } else if (transportType == TransportType.SEPARATED) {
        transport = new SeparatedTransport(clientBuilder, target, rpcConverter);
    } else {
        throw new IllegalStateException("Transport type cannot be null");
    }
    return new ReactorHttpRpcClient(transport);
}
 
Example 7
Source File: HttpsSendFileTests.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
@Override
protected HttpClient customizeClientOptions(HttpClient httpClient) {
	try {
		SslContext ctx = SslContextBuilder.forClient()
		                                  .trustManager(InsecureTrustManagerFactory.INSTANCE).build();
		return httpClient.secure(ssl -> ssl.sslContext(ctx));
	}
	catch (SSLException e) {
		throw new RuntimeException(e);
	}
}
 
Example 8
Source File: HttpsMetricsHandlerTests.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
@Override
protected HttpClient customizeClientOptions(HttpClient httpClient) {
	try {
		SslContext ctx = SslContextBuilder.forClient()
		                                  .trustManager(InsecureTrustManagerFactory.INSTANCE)
		                                  .sslProvider(SslProvider.JDK)
		                                  .build();
		return httpClient.secure(ssl -> ssl.sslContext(ctx));
	}
	catch (SSLException e) {
		throw new RuntimeException(e);
	}
}
 
Example 9
Source File: ByteBufFluxTest.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
private void doTestByteBufFluxFromPath(boolean withSecurity) throws Exception {
	final int serverPort = SocketUtils.findAvailableTcpPort();
	HttpServer server = HttpServer.create()
	                              .port(serverPort)
	                              .wiretap(true);
	HttpClient client = HttpClient.create()
	                              .port(serverPort)
	                              .wiretap(true);
	if (withSecurity) {
		SelfSignedCertificate ssc = new SelfSignedCertificate();
		SslContext sslServer = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
		SslContext sslClient = SslContextBuilder.forClient()
		                                        .trustManager(InsecureTrustManagerFactory.INSTANCE).build();
		server = server.secure(ssl -> ssl.sslContext(sslServer));
		client = client.secure(ssl -> ssl.sslContext(sslClient));
	}

	Path path = Paths.get(getClass().getResource("/largeFile.txt").toURI());
	DisposableServer c = server.handle((req, res) ->
	                                      res.send(ByteBufFlux.fromPath(path))
	                                         .then())
	                           .bindNow();

	AtomicLong counter = new AtomicLong(0);
	client.get()
	      .uri("/download")
	      .responseContent()
	      .doOnNext(b -> counter.addAndGet(b.readableBytes()))
	      .blockLast(Duration.ofSeconds(30));

	assertEquals(1245, counter.get());

	c.disposeNow();
}
 
Example 10
Source File: HttpProtocolsTests.java    From reactor-netty with Apache License 2.0 4 votes vote down vote up
@Parameters(name = "{index}: {0}, {1}")
public static Object[][] data() throws Exception {
	SelfSignedCertificate cert = new SelfSignedCertificate();
	SslContextBuilder serverCtx = SslContextBuilder.forServer(cert.certificate(), cert.privateKey());
	SslContextBuilder clientCtx = SslContextBuilder.forClient()
	                                               .trustManager(InsecureTrustManagerFactory.INSTANCE);

	HttpServer _server = HttpServer.create()
	                               .wiretap(true)
	                               .httpRequestDecoder(spec -> spec.h2cMaxContentLength(256));
	HttpServer securedServer = _server.secure(spec -> spec.sslContext(serverCtx));

	HttpServer[] servers = new HttpServer[]{
			_server, // by default protocol is HTTP/1.1
			_server.protocol(HttpProtocol.H2C),
			_server.protocol(HttpProtocol.HTTP11, HttpProtocol.H2C),
			securedServer, // by default protocol is HTTP/1.1
			securedServer.protocol(HttpProtocol.H2),
			securedServer.protocol(HttpProtocol.HTTP11, HttpProtocol.H2)
	};

	HttpClient _client = HttpClient.create()
	                               .wiretap(true);
	HttpClient securedClient = _client.secure(spec -> spec.sslContext(clientCtx));

	HttpClient[] clients = new HttpClient[]{
			_client, // by default protocol is HTTP/1.1
			_client.protocol(HttpProtocol.H2C),
			_client.protocol(HttpProtocol.HTTP11, HttpProtocol.H2C),
			securedClient, // by default protocol is HTTP/1.1
			securedClient.protocol(HttpProtocol.H2),
			securedClient.protocol(HttpProtocol.HTTP11, HttpProtocol.H2)
	};

	Flux<HttpServer> f1 = Flux.fromArray(servers).concatMap(o -> Flux.just(o).repeat(clients.length - 1));
	Flux<HttpClient> f2 = Flux.fromArray(clients).repeat(servers.length - 1);

	return Flux.zip(f1, f2)
	           .map(Tuple2::toArray)
	           .collectList()
	           .block(Duration.ofSeconds(30))
	           .toArray(new Object[servers.length * clients.length][2]);
}