use of org.apache.http.config.Registry in project questdb by bluestreak01.
the class HttpServerTest method createHttpClient_AcceptsUntrustedCerts.
private static HttpClientBuilder createHttpClient_AcceptsUntrustedCerts() throws Exception {
HttpClientBuilder b = HttpClientBuilder.create();
// setup a Trust Strategy that allows all certificates.
//
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, (arg0, arg1) -> true).build();
b.setSSLContext(sslContext);
// here's the special part:
// -- need to create an SSL Socket Factory, to use our weakened "trust strategy";
// -- and create a Registry, to register it.
//
SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, (s, sslSession) -> true);
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.getSocketFactory()).register("https", sslSocketFactory).build();
// now, we create connection-manager using our Registry.
// -- allows multi-threaded use
b.setConnectionManager(new PoolingHttpClientConnectionManager(socketFactoryRegistry));
return b;
}
use of org.apache.http.config.Registry in project yorc-a4c-plugin by ystia.
the class RestClient method setProviderConfiguration.
public void setProviderConfiguration(ProviderConfig providerConfiguration) throws PluginConfigurationException {
this.providerConfiguration = providerConfiguration;
log.debug("setProviderConfiguration YorcURL=" + providerConfiguration.getUrlYorc());
RequestConfig clientConfig = RequestConfig.custom().setConnectTimeout(((Long) CONNECTION_TIMEOUT).intValue()).setSocketTimeout(((Long) SOCKET_TIMEOUT).intValue()).setConnectionRequestTimeout(((Long) SOCKET_TIMEOUT).intValue()).build();
CloseableHttpClient httpClient;
if (Boolean.TRUE.equals(providerConfiguration.getInsecureTLS())) {
SSLContext sslContext;
try {
sslContext = SSLContexts.custom().loadTrustMaterial(null, (chain, authType) -> true).build();
} catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) {
e.printStackTrace();
throw new PluginConfigurationException("Failed to create SSL socket factory", e);
}
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new AllowAllHostnameVerifier());
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create().register("https", sslsf).build();
PoolingHttpClientConnectionManager poolHttpConnManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
configurePoolingHttpClientConnectionManager(poolHttpConnManager);
httpClient = HttpClientBuilder.create().useSystemProperties().setConnectionManager(poolHttpConnManager).setDefaultRequestConfig(clientConfig).setSslcontext(sslContext).build();
} else if (providerConfiguration.getUrlYorc().startsWith("https")) {
SSLContext sslContext;
// on system default keystore and truststore
if (providerConfiguration.getCaCertificate().isEmpty() || providerConfiguration.getClientCertificate().isEmpty() || providerConfiguration.getClientKey().isEmpty()) {
log.warn("Missing CA|Client certificate|Client key in plugin configuration, will use system defaults");
if (System.getProperty("javax.net.ssl.keyStore") == null || System.getProperty("javax.net.ssl.keyStorePassword") == null) {
log.warn("Using SSL but you didn't provide client keystore and password. This means that if required by Yorc client authentication will fail.\n" + "Please use -Djavax.net.ssl.keyStore <keyStorePath> -Djavax.net.ssl.keyStorePassword <password> while starting java VM");
}
if (System.getProperty("javax.net.ssl.trustStore") == null || System.getProperty("javax.net.ssl.trustStorePassword") == null) {
log.warn("You didn't provide client trustore and password. Using defalut one \n" + "Please use -Djavax.net.ssl.trustStore <trustStorePath> -Djavax.net.ssl.trustStorePassword <password> while starting java VM");
}
sslContext = SSLContexts.createSystemDefault();
} else {
// Create a key store containing CA and client key/certificate provided
// in the plugin configuration
KeyStore keystore;
try {
// Create the CA certificate from its configuration string value
CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
ByteArrayInputStream inputStream = new ByteArrayInputStream(providerConfiguration.getCaCertificate().getBytes());
X509Certificate trustedCert = (X509Certificate) certFactory.generateCertificate(inputStream);
inputStream.close();
// Create the client private key from its configuration string value
String keyContent = providerConfiguration.getClientKey().replaceFirst("-----BEGIN PRIVATE KEY-----\n", "").replaceFirst("\n-----END PRIVATE KEY-----", "").trim();
PKCS8EncodedKeySpec clientKeySpec = new PKCS8EncodedKeySpec(Base64.getMimeDecoder().decode(keyContent));
// Getting the key algorithm
ASN1InputStream bIn = new ASN1InputStream(new ByteArrayInputStream(clientKeySpec.getEncoded()));
PrivateKeyInfo pki = PrivateKeyInfo.getInstance(bIn.readObject());
bIn.close();
String algorithm = pki.getPrivateKeyAlgorithm().getAlgorithm().getId();
// Workaround for a missing algorithm OID in the list of default providers
if ("1.2.840.113549.1.1.1".equals(algorithm)) {
algorithm = "RSA";
}
KeyFactory keyFactory = KeyFactory.getInstance(algorithm);
PrivateKey clientKey = keyFactory.generatePrivate(clientKeySpec);
// Create the client certificate from its configuration string value
inputStream = new ByteArrayInputStream(providerConfiguration.getClientCertificate().getBytes());
Certificate clientCert = certFactory.generateCertificate(inputStream);
inputStream.close();
// Create an empty keystore
keystore = KeyStore.getInstance(KeyStore.getDefaultType());
keystore.load(null);
// Add the certificate authority
keystore.setCertificateEntry(trustedCert.getSubjectX500Principal().getName(), trustedCert);
// Add client key/certificate and chain to the Key store
Certificate[] chain = { clientCert, trustedCert };
keystore.setKeyEntry("Yorc Client", clientKey, "yorc".toCharArray(), chain);
} catch (CertificateException | IOException | NoSuchAlgorithmException | InvalidKeySpecException | KeyStoreException e) {
e.printStackTrace();
throw new PluginConfigurationException("Failed to create keystore", e);
}
// Create a SSL context using this Key Store
try {
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(keystore);
sslContext = SSLContext.getInstance("TLS");
KeyManagerFactory kmf = KeyManagerFactory.getInstance("NewSunX509");
kmf.init(keystore, "yorc".toCharArray());
sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
} catch (NoSuchAlgorithmException | KeyStoreException | UnrecoverableKeyException | KeyManagementException e) {
e.printStackTrace();
throw new PluginConfigurationException("Failed to create SSL context", e);
}
}
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create().register("https", sslsf).build();
PoolingHttpClientConnectionManager poolHttpConnManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
configurePoolingHttpClientConnectionManager(poolHttpConnManager);
httpClient = HttpClientBuilder.create().useSystemProperties().setConnectionManager(poolHttpConnManager).setDefaultRequestConfig(clientConfig).setSslcontext(sslContext).build();
} else {
PoolingHttpClientConnectionManager poolHttpConnManager = new PoolingHttpClientConnectionManager();
configurePoolingHttpClientConnectionManager(poolHttpConnManager);
httpClient = HttpClientBuilder.create().useSystemProperties().setConnectionManager(poolHttpConnManager).setDefaultRequestConfig(clientConfig).build();
}
// Instantiate restTemplate
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
restTemplate = new RestTemplate(requestFactory);
// Display deployments
try {
logDeployments();
} catch (Exception e) {
log.warn("Unable to retrieve deployments due to: {}", e.getMessage());
e.printStackTrace();
throw new PluginConfigurationException("Failed to connect to yorc", e);
}
}
use of org.apache.http.config.Registry in project ats-framework by Axway.
the class RestClient method constructApacheConnectorInvocationBuilder.
private void constructApacheConnectorInvocationBuilder(String descriptionToken, boolean suppressHttpComplianceValidation) {
// create the client config object
ClientConfig clientConfig = createClientConfig(suppressHttpComplianceValidation);
// check if user had specified custom connection manager and custom connection factory
boolean hasConnectionManager = this.clientConfigurator.getConnectionManager() != null;
boolean hasConnectionFactory = this.clientConfigurator.getConnectionFactory() != null;
// handle HTTPS requests
Registry registry = null;
if (isHttps()) {
// configure Trust-all SSL context
if (!hasConnectionManager) {
}
registry = constructRegistry();
}
HttpClientConnectionManager connectionManager = null;
HttpConnectionFactory connectionFactory = null;
if (hasConnectionManager) {
connectionManager = this.clientConfigurator.getConnectionManager();
if (hasConnectionFactory) {
connectionFactory = this.clientConfigurator.getConnectionFactory();
} else {
throw new RuntimeException("Connection manager was specified, but connection factory was not. " + "Provide both if you want to use custom connection manager");
}
} else {
if (hasConnectionFactory) {
connectionFactory = this.clientConfigurator.getConnectionFactory();
} else {
connectionFactory = new ManagedHttpClientConnectionFactory();
}
if (registry != null) {
if (usePooling) {
connectionManager = new PoolingHttpClientConnectionManager(registry, connectionFactory);
} else {
connectionManager = new BasicHttpClientConnectionManager(registry, connectionFactory);
}
} else {
if (usePooling) {
connectionManager = new PoolingHttpClientConnectionManager(connectionFactory);
} else {
connectionManager = new BasicHttpClientConnectionManager(RegistryBuilder.<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.getSocketFactory()).register("https", SSLConnectionSocketFactory.getSocketFactory()).build(), connectionFactory);
}
}
}
if (connectionManager != null && connectionManager instanceof PoolingHttpClientConnectionManager) {
// 10 sec
((PoolingHttpClientConnectionManager) connectionManager).setValidateAfterInactivity(10 * 1000);
}
try {
Class<?> apacheClientProperties = Class.forName(RestClient.APACHE_CLIENT_PROPERTIES_CLASSNAME);
clientConfig.property((String) apacheClientProperties.getDeclaredField("CONNECTION_MANAGER").get(null), connectionManager);
} catch (Exception e) {
throw new RuntimeException("Could not set validity timeinterval for '" + connectionManager.getClass().getName() + "'", e);
}
// create the client builder
ClientBuilder clientBuilder = ClientBuilder.newBuilder().withConfig(clientConfig);
// now create the client
createClient(clientBuilder);
createInvocationBuilder(descriptionToken);
}
use of org.apache.http.config.Registry in project thingsboard by thingsboard.
the class AbstractContainerTest method getRequestFactoryForSelfSignedCert.
private static HttpComponentsClientHttpRequestFactory getRequestFactoryForSelfSignedCert() throws Exception {
SSLContextBuilder builder = SSLContexts.custom();
builder.loadTrustMaterial(null, (TrustStrategy) (chain, authType) -> true);
SSLContext sslContext = builder.build();
SSLConnectionSocketFactory sslSelfSigned = new SSLConnectionSocketFactory(sslContext, (s, sslSession) -> true);
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create().register("https", sslSelfSigned).build();
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(cm).build();
return new HttpComponentsClientHttpRequestFactory(httpClient);
}
Aggregations