use of org.apache.hc.core5.http.ssl.TLS in project httpcomponents-core by apache.
the class H2ViaHttp1ProxyExecutionExample method main.
public static void main(final String[] args) throws Exception {
// Create and start requester
final H2Config h2Config = H2Config.custom().setPushEnabled(false).build();
final HttpAsyncRequester requester = H2RequesterBootstrap.bootstrap().setH2Config(h2Config).setVersionPolicy(HttpVersionPolicy.NEGOTIATE).setStreamListener(new Http1StreamListener() {
@Override
public void onRequestHead(final HttpConnection connection, final HttpRequest request) {
System.out.println(connection.getRemoteAddress() + " " + new RequestLine(request));
}
@Override
public void onResponseHead(final HttpConnection connection, final HttpResponse response) {
System.out.println(connection.getRemoteAddress() + " " + new StatusLine(response));
}
@Override
public void onExchangeComplete(final HttpConnection connection, final boolean keepAlive) {
if (keepAlive) {
System.out.println(connection.getRemoteAddress() + " exchange completed (connection kept alive)");
} else {
System.out.println(connection.getRemoteAddress() + " exchange completed (connection closed)");
}
}
}).setStreamListener(new H2StreamListener() {
@Override
public void onHeaderInput(final HttpConnection connection, final int streamId, final List<? extends Header> headers) {
for (int i = 0; i < headers.size(); i++) {
System.out.println(connection.getRemoteAddress() + " (" + streamId + ") << " + headers.get(i));
}
}
@Override
public void onHeaderOutput(final HttpConnection connection, final int streamId, final List<? extends Header> headers) {
for (int i = 0; i < headers.size(); i++) {
System.out.println(connection.getRemoteAddress() + " (" + streamId + ") >> " + headers.get(i));
}
}
@Override
public void onFrameInput(final HttpConnection connection, final int streamId, final RawFrame frame) {
}
@Override
public void onFrameOutput(final HttpConnection connection, final int streamId, final RawFrame frame) {
}
@Override
public void onInputFlowControl(final HttpConnection connection, final int streamId, final int delta, final int actualSize) {
}
@Override
public void onOutputFlowControl(final HttpConnection connection, final int streamId, final int delta, final int actualSize) {
}
}).create();
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
System.out.println("HTTP requester shutting down");
requester.close(CloseMode.GRACEFUL);
}));
requester.start();
final HttpHost proxy = new HttpHost("localhost", 8888);
final HttpHost target = new HttpHost("https", "nghttp2.org");
final ComplexFuture<AsyncClientEndpoint> tunnelFuture = new ComplexFuture<>(null);
tunnelFuture.setDependency(requester.connect(proxy, Timeout.ofSeconds(30), null, new FutureContribution<AsyncClientEndpoint>(tunnelFuture) {
@Override
public void completed(final AsyncClientEndpoint endpoint) {
if (endpoint instanceof TlsUpgradeCapable) {
final HttpRequest connect = new BasicHttpRequest(Method.CONNECT, proxy, target.toHostString());
endpoint.execute(new BasicRequestProducer(connect, null), new BasicResponseConsumer<>(new DiscardingEntityConsumer<>()), new FutureContribution<Message<HttpResponse, Void>>(tunnelFuture) {
@Override
public void completed(final Message<HttpResponse, Void> message) {
final HttpResponse response = message.getHead();
if (response.getCode() == HttpStatus.SC_OK) {
((TlsUpgradeCapable) endpoint).tlsUpgrade(target, new FutureContribution<ProtocolIOSession>(tunnelFuture) {
@Override
public void completed(final ProtocolIOSession protocolSession) {
System.out.println("Tunnel to " + target + " via " + proxy + " established");
tunnelFuture.completed(endpoint);
}
});
} else {
tunnelFuture.failed(new HttpException("Tunnel refused: " + new StatusLine(response)));
}
}
});
} else {
tunnelFuture.failed(new IllegalStateException("TLS upgrade not supported"));
}
}
}));
final String[] requestUris = new String[] { "/httpbin/ip", "/httpbin/user-agent", "/httpbin/headers" };
final AsyncClientEndpoint endpoint = tunnelFuture.get(1, TimeUnit.MINUTES);
try {
final CountDownLatch latch = new CountDownLatch(requestUris.length);
for (final String requestUri : requestUris) {
endpoint.execute(new BasicRequestProducer(Method.GET, target, requestUri), new BasicResponseConsumer<>(new StringAsyncEntityConsumer()), new FutureCallback<Message<HttpResponse, String>>() {
@Override
public void completed(final Message<HttpResponse, String> message) {
final HttpResponse response = message.getHead();
final String body = message.getBody();
System.out.println(requestUri + "->" + response.getCode());
System.out.println(body);
latch.countDown();
}
@Override
public void failed(final Exception ex) {
System.out.println(requestUri + "->" + ex);
latch.countDown();
}
@Override
public void cancelled() {
System.out.println(requestUri + " cancelled");
latch.countDown();
}
});
}
latch.await();
} finally {
endpoint.releaseAndDiscard();
}
System.out.println("Shutting down I/O reactor");
requester.initiateShutdown();
}
use of org.apache.hc.core5.http.ssl.TLS in project httpcomponents-core by apache.
the class TlsVersionParser method parse.
ProtocolVersion parse(final CharSequence buffer, final Tokenizer.Cursor cursor, final BitSet delimiters) throws ParseException {
final int lowerBound = cursor.getLowerBound();
final int upperBound = cursor.getUpperBound();
int pos = cursor.getPos();
if (pos + 4 > cursor.getUpperBound()) {
throw new ParseException("Invalid TLS protocol version", buffer, lowerBound, upperBound, pos);
}
if (buffer.charAt(pos) != 'T' || buffer.charAt(pos + 1) != 'L' || buffer.charAt(pos + 2) != 'S' || buffer.charAt(pos + 3) != 'v') {
throw new ParseException("Invalid TLS protocol version", buffer, lowerBound, upperBound, pos);
}
pos = pos + 4;
cursor.updatePos(pos);
if (cursor.atEnd()) {
throw new ParseException("Invalid TLS version", buffer, lowerBound, upperBound, pos);
}
final String s = this.tokenizer.parseToken(buffer, cursor, delimiters);
final int idx = s.indexOf('.');
if (idx == -1) {
final int major;
try {
major = Integer.parseInt(s);
} catch (final NumberFormatException e) {
throw new ParseException("Invalid TLS major version", buffer, lowerBound, upperBound, pos);
}
return new ProtocolVersion("TLS", major, 0);
} else {
final String s1 = s.substring(0, idx);
final int major;
try {
major = Integer.parseInt(s1);
} catch (final NumberFormatException e) {
throw new ParseException("Invalid TLS major version", buffer, lowerBound, upperBound, pos);
}
final String s2 = s.substring(idx + 1);
final int minor;
try {
minor = Integer.parseInt(s2);
} catch (final NumberFormatException e) {
throw new ParseException("Invalid TLS minor version", buffer, lowerBound, upperBound, pos);
}
return new ProtocolVersion("TLS", major, minor);
}
}
use of org.apache.hc.core5.http.ssl.TLS in project commons-vfs by apache.
the class Http5FileProvider method createConnectionManager.
private HttpClientConnectionManager createConnectionManager(final Http5FileSystemConfigBuilder builder, final FileSystemOptions fileSystemOptions) throws FileSystemException {
final SocketConfig socketConfig = SocketConfig.custom().setSoTimeout(Timeout.ofMilliseconds(builder.getSoTimeoutDuration(fileSystemOptions).toMillis())).build();
final String[] tlsVersions = builder.getTlsVersions(fileSystemOptions).split("\\s*,\\s*");
final TLS[] tlsArray = Stream.of(tlsVersions).map(TLS::valueOf).toArray(TLS[]::new);
final SSLConnectionSocketFactory sslSocketFactory = SSLConnectionSocketFactoryBuilder.create().setSslContext(createSSLContext(builder, fileSystemOptions)).setHostnameVerifier(createHostnameVerifier(builder, fileSystemOptions)).setTlsVersions(tlsArray).build();
return PoolingHttpClientConnectionManagerBuilder.create().setSSLSocketFactory(sslSocketFactory).setMaxConnTotal(builder.getMaxTotalConnections(fileSystemOptions)).setMaxConnPerRoute(builder.getMaxConnectionsPerHost(fileSystemOptions)).setDefaultSocketConfig(socketConfig).build();
}
use of org.apache.hc.core5.http.ssl.TLS in project wiremock by wiremock.
the class HttpsAcceptanceTest method secureContentFor.
static String secureContentFor(String url, String clientTrustStore, String trustStorePassword) throws Exception {
KeyStore trustStore = readKeyStore(clientTrustStore, trustStorePassword);
SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).loadKeyMaterial(trustStore, trustStorePassword.toCharArray()).setKeyStoreType("pkcs12").setProtocol("TLS").build();
SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslcontext, // supported protocols
null, // supported cipher suites
null, NoopHostnameVerifier.INSTANCE);
PoolingHttpClientConnectionManager connectionManager = PoolingHttpClientConnectionManagerBuilder.create().setSSLSocketFactory(sslSocketFactory).build();
CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connectionManager).build();
HttpGet get = new HttpGet(url);
ClassicHttpResponse response = httpClient.execute(get);
String content = EntityUtils.toString(response.getEntity());
return content;
}
use of org.apache.hc.core5.http.ssl.TLS in project cxf by apache.
the class AsyncHTTPConduit method getSSLContext.
public synchronized SSLContext getSSLContext(TLSClientParameters tlsClientParameters) throws GeneralSecurityException {
int hash = tlsClientParameters.hashCode();
if (hash == lastTlsHash && sslContext != null) {
return sslContext;
}
final SSLContext ctx;
if (tlsClientParameters.getSslContext() != null) {
ctx = tlsClientParameters.getSslContext();
} else {
String provider = tlsClientParameters.getJsseProvider();
String protocol = tlsClientParameters.getSecureSocketProtocol() != null ? tlsClientParameters.getSecureSocketProtocol() : "TLS";
ctx = provider == null ? SSLContext.getInstance(protocol) : SSLContext.getInstance(protocol, provider);
KeyManager[] keyManagers = tlsClientParameters.getKeyManagers();
if (keyManagers == null) {
keyManagers = org.apache.cxf.configuration.jsse.SSLUtils.getDefaultKeyStoreManagers(LOG);
}
KeyManager[] configuredKeyManagers = org.apache.cxf.transport.https.SSLUtils.configureKeyManagersWithCertAlias(tlsClientParameters, keyManagers);
TrustManager[] trustManagers = tlsClientParameters.getTrustManagers();
if (trustManagers == null) {
trustManagers = org.apache.cxf.configuration.jsse.SSLUtils.getDefaultTrustStoreManagers(LOG);
}
ctx.init(configuredKeyManagers, trustManagers, tlsClientParameters.getSecureRandom());
if (ctx.getClientSessionContext() != null) {
ctx.getClientSessionContext().setSessionTimeout(tlsClientParameters.getSslCacheTimeout());
}
}
sslContext = ctx;
lastTlsHash = hash;
sslState = null;
sslURL = null;
session = null;
return ctx;
}
Aggregations