Java Examples for org.apache.http.conn.ssl.TrustSelfSignedStrategy
The following java examples will help you to understand the usage of org.apache.http.conn.ssl.TrustSelfSignedStrategy. These source code samples are taken from different open source projects.
Example 1
| Project: mobilecloud-14-master File: UnsafeHttpsClient.java View source code |
public static HttpClient createUnsafeClient() {
try {
SSLContextBuilder builder = new SSLContextBuilder();
builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build());
CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
return httpclient;
} catch (Exception e) {
throw new RuntimeException(e);
}
}Example 2
| Project: mobilecloud-15-master File: UnsafeHttpsClient.java View source code |
public static HttpClient createUnsafeClient() {
try {
SSLContextBuilder builder = new SSLContextBuilder();
builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build());
CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
return httpclient;
} catch (Exception e) {
throw new RuntimeException(e);
}
}Example 3
| Project: programming-cloud-services-for-android-master File: UnsafeHttpsClient.java View source code |
public static HttpClient createUnsafeClient() {
try {
SSLContextBuilder builder = new SSLContextBuilder();
builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build());
CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
return httpclient;
} catch (Exception e) {
throw new RuntimeException(e);
}
}Example 4
| Project: brooklyn-service-broker-master File: HttpClientConfig.java View source code |
@Bean
public HttpClient httpClient() {
LOG.info("Using development (trust-self-signed) http client");
try {
ConnectionSocketFactory plainsf = PlainConnectionSocketFactory.getSocketFactory();
SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build();
LayeredConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
Registry<ConnectionSocketFactory> r = RegistryBuilder.<ConnectionSocketFactory>create().register("http", plainsf).register("https", sslsf).build();
HttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(r);
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(30000).setConnectTimeout(30000).setTargetPreferredAuthSchemes(ImmutableList.of(AuthSchemes.BASIC)).setProxyPreferredAuthSchemes(ImmutableList.of(AuthSchemes.BASIC)).build();
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY, getUsernamePasswordCredentials());
return HttpClients.custom().setConnectionManager(cm).setDefaultCredentialsProvider(credentialsProvider).setDefaultRequestConfig(requestConfig).build();
} catch (Exception e) {
throw new RuntimeException("Cannot build HttpClient using self signed certificate", e);
}
}Example 5
| Project: building-microservices-master File: X509ApplicationTests.java View source code |
private SSLConnectionSocketFactory socketFactory() throws Exception {
char[] password = "password".toCharArray();
KeyStore truststore = KeyStore.getInstance("PKCS12");
truststore.load(new ClassPathResource("rod.p12").getInputStream(), password);
SSLContextBuilder builder = new SSLContextBuilder();
builder.loadKeyMaterial(truststore, password);
builder.loadTrustMaterial(truststore, new TrustSelfSignedStrategy());
return new SSLConnectionSocketFactory(builder.build(), new NoopHostnameVerifier());
}Example 6
| Project: cloudbreak-master File: MockSetup.java View source code |
private void disableSSLCheck() {
try {
SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext);
CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
Unirest.setHttpClient(httpclient);
} catch (NoSuchAlgorithmExceptionKeyManagementException | KeyStoreException | e) {
throw new RuntimeException("can't create ssl settings");
}
}Example 7
| Project: comsat-master File: SampleUndertowSslApplicationTests.java View source code |
@Test
public void testHome() throws Exception {
SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build());
HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory).build();
TestRestTemplate testRestTemplate = new TestRestTemplate();
((HttpComponentsClientHttpRequestFactory) testRestTemplate.getRequestFactory()).setHttpClient(httpClient);
ResponseEntity<String> entity = testRestTemplate.getForEntity("https://localhost:" + this.port, String.class);
assertEquals(HttpStatus.OK, entity.getStatusCode());
assertEquals("Hello World", entity.getBody());
}Example 8
| Project: core-ng-project-master File: HTTPClientBuilder.java View source code |
public HTTPClient build() {
StopWatch watch = new StopWatch();
try {
HttpClientBuilder builder = HttpClients.custom();
builder.setUserAgent(userAgent);
builder.setKeepAliveStrategy(( response, context) -> keepAliveTimeout.toMillis());
builder.setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE).setSSLContext(new SSLContextBuilder().loadTrustMaterial(TrustSelfSignedStrategy.INSTANCE).build());
// builder use PoolingHttpClientConnectionManager by default, and connTimeToLive will be set by keepAlive value
builder.setDefaultSocketConfig(SocketConfig.custom().setSoKeepAlive(true).build());
builder.setDefaultRequestConfig(RequestConfig.custom().setSocketTimeout((int) timeout.toMillis()).setConnectionRequestTimeout((int) timeout.toMillis()).setConnectTimeout((int) timeout.toMillis()).build());
builder.setMaxConnPerRoute(maxConnections).setMaxConnTotal(maxConnections);
builder.disableAuthCaching();
builder.disableConnectionState();
// retry should be handled in framework level with better trace log
builder.disableAutomaticRetries();
if (!enableRedirect)
builder.disableRedirectHandling();
if (!enableCookie)
builder.disableCookieManagement();
CloseableHttpClient httpClient = builder.build();
return new HTTPClient(httpClient, userAgent, slowOperationThreshold);
} catch (NoSuchAlgorithmExceptionKeyManagementException | KeyStoreException | e) {
throw new Error(e);
} finally {
logger.info("create http client, elapsedTime={}", watch.elapsedTime());
}
}Example 9
| Project: pdt-master File: AsyncDownloader.java View source code |
protected void init() {
super.init();
try {
SSLContextBuilder builder = new SSLContextBuilder();
builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
SSLConnectionSocketFactory ssf = new SSLConnectionSocketFactory(builder.build());
Registry<ConnectionSocketFactory> r = RegistryBuilder.<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.getSocketFactory()).register("https", //$NON-NLS-1$ //$NON-NLS-2$
ssf).build();
connectionManager = new PoolingHttpClientConnectionManager(r);
} catch (NoSuchAlgorithmException e) {
log.error("Exception during init", e);
} catch (KeyManagementException e) {
log.error("Exception during init", e);
} catch (KeyStoreException e) {
log.error("Exception during init", e);
}
}Example 10
| Project: spring-boot-https-kit-master File: TomcatConfigTest.java View source code |
@Before
public void init() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
SSLContextBuilder builder = new SSLContextBuilder();
// trust self signed certificate
builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(builder.build());
final HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sslConnectionSocketFactory).build();
restTemplate = new TestRestTemplate();
restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory(httpClient) {
@Override
protected HttpContext createHttpContext(HttpMethod httpMethod, URI uri) {
HttpClientContext context = HttpClientContext.create();
RequestConfig.Builder builder = RequestConfig.custom().setCookieSpec(CookieSpecs.IGNORE_COOKIES).setAuthenticationEnabled(false).setRedirectsEnabled(false).setConnectTimeout(1000).setConnectionRequestTimeout(1000).setSocketTimeout(1000);
context.setRequestConfig(builder.build());
return context;
}
});
}Example 11
| Project: spring-xd-master File: SecuredShellAccessWithSslTests.java View source code |
@Test
public void testSpringXDTemplate() throws Exception {
BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("admin", "whosThere"));
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(HttpClientBuilder.create().setDefaultCredentialsProvider(credentialsProvider).setSSLSocketFactory(new SSLConnectionSocketFactory(new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build())).build());
SpringXDTemplate template = new SpringXDTemplate(requestFactory, new URI("https://localhost:" + adminPort));
PagedResources<ModuleDefinitionResource> moduleDefinitions = template.moduleOperations().list(RESTModuleType.sink);
assertThat(moduleDefinitions.getLinks().size(), greaterThan(0));
}Example 12
| Project: uw-android-master File: ClientCustomSSL.java View source code |
public static final void main(String[] args) throws Exception {
// Trust own CA and all self-signed certs
SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(new File("my.keystore"), "nopassword".toCharArray(), new TrustSelfSignedStrategy()).build();
// Allow TLSv1 protocol only
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" }, null, SSLConnectionSocketFactory.getDefaultHostnameVerifier());
CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
try {
HttpGet httpget = new HttpGet("https://localhost/");
System.out.println("executing request " + httpget.getRequestLine());
CloseableHttpResponse response = httpclient.execute(httpget);
try {
HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
EntityUtils.consume(entity);
} finally {
response.close();
}
} finally {
httpclient.close();
}
}Example 13
| Project: chaos-lemur-master File: StandardDirectorUtils.java View source code |
private static RestTemplate createRestTemplate(String host, String username, String password, Set<ClientHttpRequestInterceptor> interceptors) throws GeneralSecurityException {
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(new AuthScope(host, 25555), new UsernamePasswordCredentials(username, password));
SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).useTLS().build();
SSLConnectionSocketFactory connectionFactory = new SSLConnectionSocketFactory(sslContext, new AllowAllHostnameVerifier());
HttpClient httpClient = HttpClientBuilder.create().disableRedirectHandling().setDefaultCredentialsProvider(credentialsProvider).setSSLSocketFactory(connectionFactory).build();
RestTemplate restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory(httpClient));
restTemplate.getInterceptors().addAll(interceptors);
return restTemplate;
}Example 14
| Project: cloudstack-master File: HttpClientHelper.java View source code |
private static Registry<ConnectionSocketFactory> createSocketFactoryConfigration() throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException {
Registry<ConnectionSocketFactory> socketFactoryRegistry;
final SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(new TrustSelfSignedStrategy()).build();
final SSLConnectionSocketFactory cnnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create().register(HTTPS, cnnectionSocketFactory).build();
return socketFactoryRegistry;
}Example 15
| Project: com.swookiee.tools-master File: SwookieClientBuilder.java View source code |
private CloseableHttpClient getHttpClient() throws SwookieeClientException {
final CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(new AuthScope(this.hostname, this.port), new UsernamePasswordCredentials(this.username, this.password));
final HttpClientBuilder httpClientBuilder = HttpClients.custom().setDefaultCredentialsProvider(credsProvider);
if (this.enableSelfSigned) {
try {
final SSLContextBuilder builder = new SSLContextBuilder();
builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build());
final CloseableHttpClient httpclient = httpClientBuilder.setSSLSocketFactory(sslsf).build();
} catch (NoSuchAlgorithmExceptionKeyStoreException | KeyManagementException | ex) {
throw new SwookieeClientException("Could not initiate self signed certification", ex);
}
}
return httpClientBuilder.build();
}Example 16
| Project: dropwizard-master File: DropwizardSSLConnectionSocketFactory.java View source code |
private void loadTrustMaterial(SSLContextBuilder sslContextBuilder) throws Exception {
KeyStore trustStore = null;
if (configuration.getTrustStorePath() != null) {
trustStore = loadKeyStore(configuration.getTrustStoreType(), configuration.getTrustStorePath(), configuration.getTrustStorePassword());
}
TrustStrategy trustStrategy = null;
if (configuration.isTrustSelfSignedCertificates()) {
trustStrategy = new TrustSelfSignedStrategy();
}
sslContextBuilder.loadTrustMaterial(trustStore, trustStrategy);
}Example 17
| Project: geni-openflow-vertical-handover-master File: ClientCustomSSL.java View source code |
public static final void main(String[] args) throws Exception {
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
FileInputStream instream = new FileInputStream(new File("my.keystore"));
try {
trustStore.load(instream, "nopassword".toCharArray());
} finally {
instream.close();
}
// Trust own CA and all self-signed certs
SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build();
// Allow TLSv1 protocol only
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" }, null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
try {
HttpGet httpget = new HttpGet("https://localhost/");
System.out.println("executing request" + httpget.getRequestLine());
CloseableHttpResponse response = httpclient.execute(httpget);
try {
HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
if (entity != null) {
System.out.println("Response content length: " + entity.getContentLength());
}
EntityUtils.consume(entity);
} finally {
response.close();
}
} finally {
httpclient.close();
}
}Example 18
| Project: moskito-central-master File: RESTHttpsConnector.java View source code |
/**
* Builds {@link javax.net.ssl.SSLContext} instance according to connector's config.
*
* @return Configured {@link javax.net.ssl.SSLContext} instance or null.
*/
private SSLContext getSslContext() {
SSLContext sslContext = null;
SSLContextBuilder builder = new SSLContextBuilder();
File storeFile = null;
FileInputStream storeStream = null;
try {
if (StringUtils.isNotEmpty(getConnectorConfig().getTrustStoreFilePath())) {
storeFile = new File(getConnectorConfig().getTrustStoreFilePath());
}
if (storeFile != null && storeFile.exists()) {
storeStream = new FileInputStream(storeFile);
KeyStore trustStore = KeyStore.getInstance("JKS");
trustStore.load(storeStream, getConnectorConfig().getTrustStorePassword().toCharArray());
if (getConnectorConfig().isTrustSelfSigned()) {
builder.loadTrustMaterial(trustStore, new TrustSelfSignedStrategy());
} else {
builder.loadTrustMaterial(trustStore);
}
} else {
/* default TrustStore will be used */
if (getConnectorConfig().isTrustSelfSigned()) {
builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
} else {
builder.loadTrustMaterial(null);
}
}
sslContext = builder.useTLS().build();
} catch (Exception e) {
log.error("Error while initializing SSL context: " + e.getMessage(), e);
} finally {
if (storeStream != null) {
try {
storeStream.close();
} catch (IOException ignored) {
}
}
}
return sslContext;
}Example 19
| Project: rest-driver-master File: SecureClientDriverTest.java View source code |
@Test
public void testConnectionSucceedsWithGivenTrustMaterial() throws Exception {
// Arrange
KeyStore keyStore = getKeystore();
SecureClientDriver driver = new SecureClientDriver(new DefaultClientDriverJettyHandler(new DefaultRequestMatcher()), 1111, keyStore, "password", "certificate");
driver.addExpectation(onRequestTo("/test"), giveEmptyResponse());
// set the test certificate as trusted
SSLContext context = SSLContexts.custom().loadTrustMaterial(keyStore, TrustSelfSignedStrategy.INSTANCE).build();
HttpClient client = HttpClients.custom().setSSLHostnameVerifier(new NoopHostnameVerifier()).setSSLContext(context).build();
HttpGet getter = new HttpGet(driver.getBaseUrl() + "/test");
// Act
HttpResponse response = client.execute(getter);
// Assert
assertEquals(204, response.getStatusLine().getStatusCode());
driver.verify();
}Example 20
| Project: RestIt-master File: UsingHttpsTest.java View source code |
/**
* Helper which returns HTTP client configured for https session
*/
private HttpClient sslReadyHttpClient() throws GeneralSecurityException {
final SSLContext context = new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build();
final SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(context);
Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create().register("https", socketFactory).build();
return HttpClientBuilder.create().setDefaultRequestConfig(custom().setConnectionRequestTimeout(10000).build()).setConnectionManager(new PoolingHttpClientConnectionManager(registry)).setSSLSocketFactory(socketFactory).build();
}Example 21
| Project: RipplePower-master File: TestNames.java View source code |
public static void main(String[] args) throws Exception {
// History h=new History("rKiCet8SdvWxPXnAgYarFUXMh1zCPz432Y");
// System.out.println(h.getUrl());
System.out.println(NameFind.getAddress("ripplefox"));
// System.out.println(NameFind.getAddress("baidutest"));
// HttpRequest
// req=HttpRequest.get("https://id.staging.ripple.com/v1/user/testUser");
// System.out.println(req.cookies());
// System.out.println(req.ok());
/*
* KeyStore trustStore =
* KeyStore.getInstance(KeyStore.getDefaultType()); FileInputStream
* instream = new FileInputStream(new File("my.keystore")); try {
* trustStore.load(instream, "nopassword".toCharArray()); } finally {
* instream.close(); } // Trust own CA and all self-signed certs
* SSLContext sslcontext = SSLContexts.custom()
* .loadTrustMaterial(trustStore, new TrustSelfSignedStrategy())
* .build(); // Allow TLSv1 protocol only SSLConnectionSocketFactory
* sslsf = new SSLConnectionSocketFactory( sslcontext, new String[] {
* "TLSv1" }, null,
* SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
*/
}Example 22
| Project: saki-monkey-master File: MandrillClient.java View source code |
protected SSLConnectionSocketFactory createSSLConnectionSocketFactory() {
try {
SSLContextBuilder sslContextBuilder = new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy());
return new SSLConnectionSocketFactory(sslContextBuilder.build(), createHostnameVerifier());
} catch (Exception e) {
log.error(e.getMessage(), e);
}
return null;
}Example 23
| Project: uaa-master File: UaaContextFactory.java View source code |
public static ClientHttpRequestFactory getNoValidatingClientHttpRequestFactory(boolean followRedirects) {
ClientHttpRequestFactory requestFactory;
SSLContext sslContext;
try {
sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build();
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
} catch (KeyManagementException e) {
throw new RuntimeException(e);
} catch (KeyStoreException e) {
throw new RuntimeException(e);
}
//
CloseableHttpClient httpClient = HttpClients.custom().setSslcontext(sslContext).setRedirectStrategy(followRedirects ? new DefaultRedirectStrategy() : new RedirectStrategy() {
@Override
public boolean isRedirected(HttpRequest request, HttpResponse response, HttpContext context) throws ProtocolException {
return false;
}
@Override
public HttpUriRequest getRedirect(HttpRequest request, HttpResponse response, HttpContext context) throws ProtocolException {
return null;
}
}).build();
requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
return requestFactory;
}Example 24
| Project: web-framework-master File: DropwizardSSLConnectionSocketFactory.java View source code |
private void loadTrustMaterial(SSLContextBuilder sslContextBuilder) throws Exception {
KeyStore trustStore = null;
if (configuration.getTrustStorePath() != null) {
trustStore = loadKeyStore(configuration.getTrustStoreType(), configuration.getTrustStorePath(), configuration.getTrustStorePassword());
}
TrustStrategy trustStrategy = null;
if (configuration.isTrustSelfSignedCertificates()) {
trustStrategy = new TrustSelfSignedStrategy();
}
sslContextBuilder.loadTrustMaterial(trustStore, trustStrategy);
}Example 25
| Project: antiope-master File: MyTest.java View source code |
private static HttpClient buildHttpClient() throws Exception {
SSLContextBuilder builder = new SSLContextBuilder();
builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build());
HttpClient oHC = HttpClients.custom().setSSLSocketFactory(sslsf).build();
return oHC;
}Example 26
| Project: camel-master File: JettySolrFactory.java View source code |
private static void installAllTrustingClientSsl() throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException {
SSLContextBuilder builder = new SSLContextBuilder();
builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
// // Create a trust manager that does not validate certificate chains
final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
@Override
public void checkClientTrusted(final X509Certificate[] chain, final String authType) {
}
@Override
public void checkServerTrusted(final X509Certificate[] chain, final String authType) {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
} };
final SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
SSLContext.setDefault(sslContext);
// // Install the all-trusting trust manager
// final SSLContext sslContext = SSLContext.getInstance( "SSL" );
// sslContext.init( null, trustAllCerts, new
// java.security.SecureRandom() );
// // Create an ssl socket factory with our all-trusting manager
// final SSLSocketFactory sslSocketFactory =
// sslContext.getSocketFactory();
// HttpsURLConnection.setDefaultSSLSocketFactory(sslSocketFactory);
}Example 27
| Project: categolj2-backend-master File: EntryRestControllerIntegrationTest.java View source code |
@Before
public void setUp() throws Exception {
SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).useTLS().build();
sockectFactory = new SSLSocketFactory(sslContext, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
// clean data
entryRepository.deleteAll();
userRepository.deleteAll();
roleRepository.deleteAll();
tagRepository.deleteAll();
entryRepository.flush();
// initialize user
Role adminRole = new Role(100, "ADMIN", null);
Role editorRole = new Role(200, "EDITOR", null);
roleRepository.save(Arrays.asList(adminRole, editorRole));
roleRepository.flush();
admin = new User("admin", passwordEncoder.encode("demo"), "admin@a.b", true, false, "Tarou", "Yamada", Sets.newHashSet(roleRepository.findOneByRoleName("ADMIN")));
editor = new User("editor", passwordEncoder.encode("demo"), "editor@a.b", true, false, "Ichiro", "Suzuki", Sets.newHashSet(roleRepository.findOneByRoleName("EDITOR")));
userRepository.save(Arrays.asList(admin, editor));
userRepository.flush();
// initialize entry
entry1 = new Entry(null, "This is entry1!", "**Hello World1!**", "md", Arrays.asList(), true, Arrays.asList(), Collections.<Tag>emptySet());
entry1.setCreatedBy("admin");
entry1.setCreatedDate(now);
entry1.setLastModifiedBy("admin");
entry1.setLastModifiedDate(now);
entry1 = entryRepository.saveAndFlush(entry1);
entry1.setCategory(Categories.fromCategory("aa::bb::cc").getCategories());
entry1.getCategory().stream().forEach( c -> c.getCategoryPK().setEntryId(entry1.getEntryId()));
entry1.setTags(Sets.newHashSet(new Tag("Java"), new Tag("Spring")));
entry2 = new Entry(null, "This is entry2!", "**Hello World2!**", "md", Arrays.asList(), false, Arrays.asList(), Collections.<Tag>emptySet());
entry2.setCreatedBy("admin");
entry2.setCreatedDate(now.plus(2));
entry2.setLastModifiedBy("admin");
entry2.setLastModifiedDate(now.plus(2));
entry2 = entryRepository.saveAndFlush(entry2);
entry2.setCategory(Categories.fromCategory("aa::bb::cc").getCategories());
entry2.getCategory().stream().forEach( c -> c.getCategoryPK().setEntryId(entry2.getEntryId()));
entry2.setTags(Sets.newHashSet(new Tag("Java"), new Tag("Java EE")));
entry3 = new Entry(null, "This is entry3!", "**Hello World3!**", "md", Arrays.asList(), true, Arrays.asList(), Collections.<Tag>emptySet());
entry3.setCreatedBy("editor");
entry3.setCreatedDate(now.plus(3));
entry3.setLastModifiedBy("editor");
entry3.setLastModifiedDate(now.plus(3));
entry3 = entryRepository.saveAndFlush(entry3);
entry3.setCategory(Categories.fromCategory("aa::bb::cc").getCategories());
entry3.getCategory().stream().forEach( c -> c.getCategoryPK().setEntryId(entry3.getEntryId()));
entry3.setTags(Sets.newHashSet(new Tag("Java"), new Tag("Java SE")));
entry4 = new Entry(null, "This is entry4!", "<h1>Hello World4!</h1>", "html", Arrays.asList(), true, Arrays.asList(), Collections.<Tag>emptySet());
entry4.setCreatedBy("editor");
entry4.setCreatedDate(now.plus(4));
entry4.setLastModifiedBy("editor");
entry4.setLastModifiedDate(now.plus(4));
entry4 = entryRepository.saveAndFlush(entry4);
entry4.setCategory(Categories.fromCategory("aa::bb::cc").getCategories());
entry4.getCategory().stream().forEach( c -> c.getCategoryPK().setEntryId(entry4.getEntryId()));
entry5 = new Entry(null, "This is entry5!", "**Foo World5!**", "md", Arrays.asList(), true, Arrays.asList(), Collections.<Tag>emptySet());
entry5.setCreatedBy("editor");
entry5.setCreatedDate(now.plus(5));
entry5.setLastModifiedBy("editor");
entry5.setLastModifiedDate(now.plus(5));
entry5 = entryRepository.saveAndFlush(entry5);
entry5.setCategory(Categories.fromCategory("aa::bb::dd::ee").getCategories());
entry5.getCategory().stream().forEach( c -> c.getCategoryPK().setEntryId(entry5.getEntryId()));
entryRepository.save(Arrays.asList(entry1, entry2, entry3, entry4, entry5));
RestAssured.port = port;
RestAssured.baseURI = "https://localhost";
RestAssured.config = RestAssuredConfig.newConfig().sslConfig(new SSLConfig().sslSocketFactory(sockectFactory));
}Example 28
| Project: dig-elasticsearch-master File: BulkLoadSequenceFile.java View source code |
public static void main(String[] args) throws IllegalArgumentException, IOException, InterruptedException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException, InstantiationException, IllegalAccessException, ClassNotFoundException {
Options options = createCommandLineOptions();
CommandLine cl = parse(args, options, BulkLoadSequenceFile.class.getSimpleName());
if (cl == null) {
return;
}
String filePath = (String) cl.getOptionValue("filepath");
String index = (String) cl.getOptionValue("index");
String type = (String) cl.getOptionValue("type");
String hostname = (String) cl.getOptionValue("hostname");
String sleep = (String) cl.getOptionValue("sleep");
String bulksize = (String) cl.getOptionValue("bulksize");
String port = (String) cl.getOptionValue("port");
String protocol = (String) cl.getOptionValue("protocol");
String username = null;
if (cl.hasOption("username")) {
username = (String) cl.getOptionValue("username");
} else {
username = "";
}
String password = null;
if (cl.hasOption("password")) {
password = (String) cl.getOptionValue("password");
} else {
password = "";
}
SSLContextBuilder builder = new SSLContextBuilder();
builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build());
CloseableHttpClient httpClient = null;
if (protocol.equalsIgnoreCase("https"))
httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
else if (protocol.equalsIgnoreCase("http"))
httpClient = HttpClients.createDefault();
HttpPost httpPost = null;
if (!username.equals("") && !password.equals("")) {
httpPost = new HttpPost(protocol + "://" + username + ":" + password + "@" + hostname + ":" + port + "/" + index + "/_bulk");
} else {
httpPost = new HttpPost(protocol + "://" + hostname + ":" + port + "/" + index + "/_bulk");
}
String bulkFormat = null;
Configuration conf = new Configuration();
FileSystem fs = FileSystem.get(new Configuration());
Path path = new Path(filePath);
for (FileStatus s : fs.listStatus(path)) {
SequenceFile.Reader reader = new SequenceFile.Reader(new Configuration(), SequenceFile.Reader.file(s.getPath()));
Writable key = (Writable) Class.forName(reader.getKeyClass().getCanonicalName()).newInstance();
Text val = new Text();
StringBuilder sb = new StringBuilder();
long counter = 0;
while (reader.next(key, val)) {
JSONObject jObj = new JSONObject(val.toString());
String id = null;
if (jObj.has("uri")) {
id = jObj.getString("uri");
}
if (id != null) {
bulkFormat = "{\"index\":{\"_index\":\"" + index + "\",\"_type\":\"" + type + "\",\"_id\":\"" + id + "\"}}";
} else {
bulkFormat = "{\"index\":{\"_index\":\"" + index + "\",\"_type\":\"" + type + "\"}}";
}
sb.append(bulkFormat);
sb.append(System.getProperty("line.separator"));
sb.append(val.toString());
//System.out.println("got val:" + val.toString());
sb.append(System.getProperty("line.separator"));
counter++;
if (counter % Integer.parseInt(bulksize) == 0) {
int i = 0;
Exception ex = null;
while (i < retry) {
try {
StringEntity entity = new StringEntity(sb.toString(), "UTF-8");
entity.setContentType("application/json");
httpPost.setEntity(entity);
httpClient.execute(httpPost);
httpClient.close();
Thread.sleep(Integer.parseInt(sleep));
//System.out.println(counter + " processed");
break;
} catch (Exception e) {
ex = e;
i++;
}
}
if (i > 0) {
System.out.println("Exception occurred!");
ex.printStackTrace();
break;
}
httpClient = null;
if (protocol.equalsIgnoreCase("https"))
httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
else if (protocol.equalsIgnoreCase("http"))
httpClient = HttpClients.createDefault();
httpPost = new HttpPost(protocol + "://" + hostname + ":" + port + "/" + index + "/_bulk");
sb = new StringBuilder();
}
}
StringEntity entity = new StringEntity(sb.toString(), "UTF-8");
entity.setContentType("application/json");
httpPost.setEntity(entity);
httpClient.execute(httpPost);
httpClient.close();
reader.close();
}
}Example 29
| Project: ipp-master File: HttpServerPublisher.java View source code |
private SSLContext sslContext() {
try {
KeyStore cks = KeyStore.getInstance(KeyStore.getDefaultType());
cks.load(new FileInputStream(options.getKeystore().get().toFile()), options.getKeystorePass().toCharArray());
SSLContextBuilder builder = SSLContexts.custom();
if (options.getTruststore().isPresent()) {
KeyStore tks = KeyStore.getInstance(KeyStore.getDefaultType());
tks.load(new FileInputStream(options.getTruststore().get().toFile()), options.getTruststorePass().toCharArray());
builder.loadTrustMaterial(tks, new TrustSelfSignedStrategy());
}
return builder.loadKeyMaterial(cks, options.getKeystorePass().toCharArray()).build();
} catch (Exception e) {
LOG.error("Exception", e);
}
return null;
}Example 30
| Project: jetty-bootstrap-master File: AbstractJettyBootstrapTest.java View source code |
protected SimpleResponse get(String url) throws IllegalStateException, IOException, JettyBootstrapException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
SimpleResponse simpleResponse = new SimpleResponse();
CloseableHttpClient httpClient = null;
HttpGet httpGet = null;
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(SOCKET_TIMEOUT).build();
if (ssl) {
SSLContextBuilder sSLContextBuilder = new SSLContextBuilder();
sSLContextBuilder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
SSLConnectionSocketFactory sSLConnectionSocketFactory = new SSLConnectionSocketFactory(sSLContextBuilder.build(), SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
httpClient = HttpClients.custom().setSSLSocketFactory(sSLConnectionSocketFactory).build();
httpGet = new HttpGet("https://" + HOST + ":" + getPort() + url);
} else {
httpClient = HttpClients.createDefault();
httpGet = new HttpGet("http://" + HOST + ":" + getPort() + url);
}
httpGet.setConfig(requestConfig);
CloseableHttpResponse response = null;
try {
response = httpClient.execute(httpGet);
simpleResponse.setStatusCode(response.getStatusLine().getStatusCode());
simpleResponse.setContent(IOUtils.toString(response.getEntity().getContent()));
} finally {
if (response != null) {
response.close();
}
httpClient.close();
}
return simpleResponse;
}Example 31
| Project: jw-community-master File: HttpUtil.java View source code |
/**
* Make a HTTP POST request to a URL, passing in a JSESSIONID cookie,
* with support for SSL (including prompting a warning for self-signed certs).
* If the JSESSIONID is invalid, then a password dialog appears.
* @param cookieStore
* @param url
* @param port
* @param sessionId
* @param cookieDomain
* @param cookiePath
* @param username
* @param password
* @param trustAllSsl
* @param failOnError
* @param filename
* @param file
* @return
* @throws IOException
* @throws NoSuchAlgorithmException
* @throws KeyManagementException
* @throws KeyStoreException
* @throws UnrecoverableKeyException
* @throws AuthenticationException
*/
public static String httpPost(CookieStore cookieStore, String url, int port, String sessionId, String cookieDomain, String cookiePath, String username, String password, boolean trustAllSsl, boolean failOnError, String filename, File file) throws IOException, NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException, AuthenticationException {
String contents = null;
HttpClientBuilder httpClientBuilder = HttpClients.custom();
// Set no redirect
httpClientBuilder.setRedirectStrategy(new RedirectStrategy() {
@Override
public boolean isRedirected(HttpRequest httpRequest, HttpResponse httpResponse, HttpContext httpContext) {
return false;
}
@Override
public HttpUriRequest getRedirect(HttpRequest httpRequest, HttpResponse httpResponse, HttpContext httpContext) {
return null;
}
});
// set csrf token in URL
if (url.contains("?" + Designer.TOKEN_NAME)) {
url = url.substring(0, url.indexOf("?" + Designer.TOKEN_NAME));
}
url += "?" + Designer.TOKEN_NAME + "=" + URLEncoder.encode(Designer.TOKEN_VALUE, "UTF-8");
// Prepare a request object
HttpPost httpRequest = new HttpPost(url);
if (file != null) {
HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("packageXpdl", new FileBody(file)).build();
httpRequest.setEntity(reqEntity);
} else {
if (username != null && password != null) {
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
formparams.add(new BasicNameValuePair("j_username", username));
formparams.add(new BasicNameValuePair("j_password", password));
formparams.add(new BasicNameValuePair("username", username));
formparams.add(new BasicNameValuePair("password", password));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8");
httpRequest.setEntity(entity);
}
}
// set referer header
String referer = "http://" + Designer.DOMAIN;
httpRequest.addHeader("Referer", referer);
// Set session cookie
if (cookieStore == null) {
cookieStore = new BasicCookieStore();
}
if (sessionId != null) {
BasicClientCookie cookie = new BasicClientCookie("JSESSIONID", sessionId);
cookie.setDomain(cookieDomain);
cookie.setPath(cookiePath);
cookieStore.addCookie(cookie);
}
httpClientBuilder.setDefaultCookieStore(cookieStore);
// Prepare SSL trust
SSLContextBuilder builder = new SSLContextBuilder();
builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build(), NoopHostnameVerifier.INSTANCE);
if (SSL_TRUSTED || trustAllSsl) {
httpClientBuilder.setSSLSocketFactory(sslsf);
}
// Execute the request
CloseableHttpClient httpClient = httpClientBuilder.build();
try {
HttpResponse response = null;
try {
response = httpClient.execute(httpRequest);
} catch (SSLException se) {
int result = JOptionPane.showConfirmDialog(null, ResourceManager.getLanguageDependentString("InvalidSSLPrompt"), ResourceManager.getLanguageDependentString("InvalidSSLTitle"), JOptionPane.YES_NO_OPTION);
if (result == JOptionPane.YES_OPTION) {
httpClientBuilder.setSSLSocketFactory(sslsf);
httpClient = httpClientBuilder.build();
response = httpClient.execute(httpRequest);
SSL_TRUSTED = true;
}
}
// Examine the response status
if (response == null) {
throw new HttpResponseException(403, ResourceManager.getLanguageDependentString("InvalidSSLMessage"));
}
StatusLine status = response.getStatusLine();
if (status == null || status.getStatusCode() == 302 || status.getStatusCode() == 401 || status.getStatusCode() == 500) {
if (failOnError) {
throw new AuthenticationException(ResourceManager.getLanguageDependentString("AuthenticationFailed"));
}
// Request is unauthenticated, attempt to authenticate
String credentials = password;
if (credentials == null) {
// prompt for username and password
JTextField uField = new JTextField(15);
uField.setText(username);
JPasswordField pField = new JPasswordField(15);
pField.addHierarchyListener(new HierarchyListener() {
public void hierarchyChanged(HierarchyEvent e) {
final Component c = e.getComponent();
if (c.isShowing() && (e.getChangeFlags() & HierarchyEvent.SHOWING_CHANGED) != 0) {
Window toplevel = SwingUtilities.getWindowAncestor(c);
toplevel.addWindowFocusListener(new WindowAdapter() {
@Override
public void windowGainedFocus(WindowEvent e) {
c.requestFocus();
}
});
}
}
});
JPanel pPanel = new JPanel(new GridLayout(2, 2));
pPanel.add(new JLabel(ResourceManager.getLanguageDependentString("UsernameKey")));
pPanel.add(uField);
pPanel.add(new JLabel(ResourceManager.getLanguageDependentString("PasswordKey")));
pPanel.add(pField);
int okCxl = JOptionPane.showConfirmDialog(null, pPanel, ResourceManager.getLanguageDependentString("SessionTimedOut"), JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
if (okCxl == JOptionPane.OK_OPTION) {
username = uField.getText();
credentials = new String(pField.getPassword());
Designer.USERNAME = username;
} else if (okCxl == JOptionPane.CANCEL_OPTION) {
return null;
}
}
try {
// login and store session cookie
String loginUrl = Designer.URLPATH + "/web/json/directory/user/sso";
String ssoResponse = HttpUtil.httpPost(cookieStore, loginUrl, port, null, cookieDomain, cookiePath, username, credentials, true, true, null, null);
String isAdminStr = "isAdmin";
if (!ssoResponse.contains(isAdminStr)) {
throw new AuthenticationException();
}
List<Cookie> cookies = cookieStore.getCookies();
for (Cookie ck : cookies) {
if ("JSESSIONID".equalsIgnoreCase(ck.getName())) {
sessionId = ck.getValue();
Designer.SESSION = sessionId;
}
}
// set new csrf token
String tokenAttr = "\"token\":\"";
if (ssoResponse.contains(tokenAttr)) {
String csrfToken = ssoResponse.substring(ssoResponse.indexOf(tokenAttr) + tokenAttr.length(), ssoResponse.length() - 2);
StringTokenizer st = new StringTokenizer(csrfToken, "=");
if (st.countTokens() == 2) {
Designer.TOKEN_NAME = st.nextToken();
Designer.TOKEN_VALUE = st.nextToken();
}
}
// repeat request with session cookie
contents = HttpUtil.httpPost(cookieStore, url, port, sessionId, cookieDomain, cookiePath, null, null, true, true, filename, file);
// return contents
return contents;
} catch (AuthenticationException ate) {
JOptionPane.showMessageDialog(null, ResourceManager.getLanguageDependentString("InvalidLogin"));
return HttpUtil.httpPost(null, url, port, sessionId, cookieDomain, cookiePath, username, null, false, false, filename, file);
} catch (HttpResponseException hre) {
throw new AuthenticationException(ResourceManager.getLanguageDependentString("InvalidLogin"));
}
}
// Get hold of the response entity
HttpEntity entity = response.getEntity();
// to worry about connection release
if (entity != null) {
InputStream instream = null;
try {
instream = entity.getContent();
contents = "";
BufferedReader reader = new BufferedReader(new InputStreamReader(instream, "UTF-8"));
String line = reader.readLine();
while (line != null) {
contents += line;
line = reader.readLine();
}
} catch (IOException ex) {
throw ex;
} catch (RuntimeException ex) {
httpRequest.abort();
throw ex;
} finally {
// Closing the input stream will trigger connection release
if (instream != null) {
instream.close();
}
}
}
} finally {
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpClient.close();
}
return contents;
}Example 32
| Project: liferay-portal-master File: SSLSocketFactoryBuilderImpl.java View source code |
@Override
public SSLConnectionSocketFactory build() throws Exception {
KeyStore keyStore = _keyStoreLoader.load(_keyStoreType, _keyStorePath, _keyStorePassword);
if (keyStore == null) {
if (_log.isDebugEnabled()) {
_log.debug("Use system defaults because there is no custom key store");
}
return SSLConnectionSocketFactory.getSystemSocketFactory();
}
KeyStore trustKeyStore = null;
TrustStrategy trustStrategy = null;
if (_verifyServerCertificate) {
trustKeyStore = _keyStoreLoader.load(_trustStoreType, _trustStorePath, _trustStorePassword);
if (trustKeyStore == null) {
if (_log.isDebugEnabled()) {
_log.debug("Use system defaults because there is no custom " + "trust store");
}
return SSLConnectionSocketFactory.getSystemSocketFactory();
}
} else {
trustStrategy = new TrustSelfSignedStrategy();
}
HostnameVerifier hostnameVerifier = null;
if (_verifyServerHostname) {
hostnameVerifier = SSLConnectionSocketFactory.getDefaultHostnameVerifier();
}
SSLContextBuilder sslContextBuilder = SSLContexts.custom();
sslContextBuilder.loadKeyMaterial(keyStore, _keyStorePassword);
sslContextBuilder.loadTrustMaterial(trustStrategy);
SSLContext sslContext = sslContextBuilder.build();
try {
return new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
} catch (Exception e) {
if (_log.isWarnEnabled()) {
_log.warn("Use system defaults because the custom SSL socket " + "factory was not able to initialize", e);
}
return SSLConnectionSocketFactory.getSystemSocketFactory();
}
}Example 33
| Project: light-4j-master File: Client.java View source code |
private SSLContext sslContext() throws ClientException, IOException, NoSuchAlgorithmException, KeyManagementException {
SSLContext sslContext = null;
Map<String, Object> tlsMap = (Map) config.get(TLS);
if (tlsMap != null) {
SSLContextBuilder builder = SSLContexts.custom();
// load trust store, this is the server public key certificate
// first check if javax.net.ssl.trustStore system properties is set. It is only necessary if the server
// certificate doesn't have the entire chain.
Boolean loadTrustStore = (Boolean) tlsMap.get(LOAD_TRUST_STORE);
if (loadTrustStore != null && loadTrustStore) {
String trustStoreName = System.getProperty(TRUST_STORE_PROPERTY);
String trustStorePass = System.getProperty(TRUST_STORE_PASSWORD_PROPERTY);
if (trustStoreName != null && trustStorePass != null) {
logger.info("Loading trust store from system property at " + Encode.forJava(trustStoreName));
} else {
trustStoreName = (String) tlsMap.get(TRUST_STORE);
trustStorePass = (String) tlsMap.get(TRUST_PASS);
logger.info("Loading trust store from config at " + Encode.forJava(trustStoreName));
}
KeyStore trustStore;
if (trustStoreName != null && trustStorePass != null) {
InputStream trustStream = Config.getInstance().getInputStreamFromFile(trustStoreName);
if (trustStream != null) {
try {
trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
trustStore.load(trustStream, trustStorePass.toCharArray());
builder.loadTrustMaterial(trustStore, new TrustSelfSignedStrategy());
} catch (CertificateException ce) {
logger.error("CertificateException: Unable to load trust store.", ce);
throw new ClientException("CertificateException: Unable to load trust store.", ce);
} catch (KeyStoreException kse) {
logger.error("KeyStoreException: Unable to load trust store.", kse);
throw new ClientException("KeyStoreException: Unable to load trust store.", kse);
} finally {
trustStream.close();
}
}
}
}
// load key store for client certificate if two way ssl is used.
Boolean loadKeyStore = (Boolean) tlsMap.get(LOAD_KEY_STORE);
if (loadKeyStore != null && loadKeyStore) {
String keyStoreName = (String) tlsMap.get(KEY_STORE);
String keyStorePass = (String) tlsMap.get(KEY_PASS);
KeyStore keyStore;
if (keyStoreName != null && keyStorePass != null) {
InputStream keyStream = Config.getInstance().getInputStreamFromFile(keyStoreName);
if (keyStream != null) {
try {
keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(keyStream, keyStorePass.toCharArray());
builder.loadKeyMaterial(keyStore, keyStorePass.toCharArray());
} catch (CertificateException ce) {
logger.error("CertificateException: Unable to load key store.", ce);
throw new ClientException("CertificateException: Unable to load key store.", ce);
} catch (KeyStoreException kse) {
logger.error("KeyStoreException: Unable to load key store.", kse);
throw new ClientException("KeyStoreException: Unable to load key store.", kse);
} catch (UnrecoverableKeyException uke) {
logger.error("UnrecoverableKeyException: Unable to load key store.", uke);
throw new ClientException("UnrecoverableKeyException: Unable to load key store.", uke);
} finally {
keyStream.close();
}
}
}
}
sslContext = builder.build();
}
return sslContext;
}Example 34
| Project: puppetdb-javaclient-master File: AbstractSSLSocketFactoryProvider.java View source code |
/**
* Creates a new SSL socket factory
*
* @return The created factory
*/
@Override
public SSLSocketFactory get() {
try {
// We need a factory that can generate a X.509 certificate using BouncyCastleProvideer
CertificateFactory factory = CertificateFactory.getInstance("X.509");
KeyStore trustStore = getTrustStore(factory);
TrustStrategy trustStrategy = trustStore == null ? new TrustSelfSignedStrategy() : null;
return new SSLSocketFactory(SSLSocketFactory.TLS, getKeyStore(factory, PASSWORD), PASSWORD, trustStore, null, trustStrategy, getHostnameVerifier());
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new ProvisionException("Unable to create SSLSocketFactory", e);
}
}Example 35
| Project: Resteasy-master File: HttpClientBuilder43.java View source code |
/**
* Create ClientHttpEngine using Apache 4.3.x+ apis.
* @return
*/
protected static ClientHttpEngine initDefaultEngine43(ResteasyClientBuilder that) {
HttpClient httpClient = null;
HostnameVerifier verifier = null;
if (that.verifier != null) {
verifier = new ResteasyClientBuilder.VerifierWrapper(that.verifier);
} else {
switch(that.policy) {
case ANY:
verifier = new NoopHostnameVerifier();
break;
case WILDCARD:
verifier = new DefaultHostnameVerifier();
break;
case STRICT:
verifier = new DefaultHostnameVerifier();
break;
}
}
try {
SSLConnectionSocketFactory sslsf = null;
SSLContext theContext = that.sslContext;
if (that.disableTrustManager) {
theContext = SSLContext.getInstance("SSL");
theContext.init(null, new TrustManager[] { new PassthroughTrustManager() }, new SecureRandom());
verifier = new NoopHostnameVerifier();
sslsf = new SSLConnectionSocketFactory(theContext, verifier);
} else if (theContext != null) {
sslsf = new SSLConnectionSocketFactory(theContext, verifier) {
@Override
protected void prepareSocket(SSLSocket socket) throws IOException {
that.prepareSocketForSni(socket);
}
};
} else if (that.clientKeyStore != null || that.truststore != null) {
SSLContext ctx = SSLContexts.custom().useProtocol(SSLConnectionSocketFactory.TLS).setSecureRandom(null).loadKeyMaterial(that.clientKeyStore, that.clientPrivateKeyPassword != null ? that.clientPrivateKeyPassword.toCharArray() : null).loadTrustMaterial(that.truststore, TrustSelfSignedStrategy.INSTANCE).build();
sslsf = new SSLConnectionSocketFactory(ctx, verifier) {
@Override
protected void prepareSocket(SSLSocket socket) throws IOException {
that.prepareSocketForSni(socket);
}
};
} else {
final SSLContext tlsContext = SSLContext.getInstance(SSLConnectionSocketFactory.TLS);
tlsContext.init(null, null, null);
sslsf = new SSLConnectionSocketFactory(tlsContext, verifier);
}
final Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.getSocketFactory()).register("https", sslsf).build();
HttpClientConnectionManager cm = null;
if (that.connectionPoolSize > 0) {
PoolingHttpClientConnectionManager tcm = new PoolingHttpClientConnectionManager(registry, null, null, null, that.connectionTTL, that.connectionTTLUnit);
tcm.setMaxTotal(that.connectionPoolSize);
if (that.maxPooledPerRoute == 0) {
that.maxPooledPerRoute = that.connectionPoolSize;
}
tcm.setDefaultMaxPerRoute(that.maxPooledPerRoute);
cm = tcm;
} else {
cm = new BasicHttpClientConnectionManager(registry);
}
RequestConfig.Builder rcBuilder = RequestConfig.custom();
if (that.socketTimeout > -1) {
rcBuilder.setSocketTimeout((int) that.socketTimeoutUnits.toMillis(that.socketTimeout));
}
if (that.establishConnectionTimeout > -1) {
rcBuilder.setConnectTimeout((int) that.establishConnectionTimeoutUnits.toMillis(that.establishConnectionTimeout));
}
if (that.connectionCheckoutTimeoutMs > -1) {
rcBuilder.setConnectionRequestTimeout(that.connectionCheckoutTimeoutMs);
}
httpClient = HttpClientBuilder.create().setConnectionManager(cm).setDefaultRequestConfig(rcBuilder.build()).setProxy(that.defaultProxy).disableContentCompression().build();
ApacheHttpClient43Engine engine = (ApacheHttpClient43Engine) ApacheHttpClient4EngineFactory.create(httpClient, true);
engine.setResponseBufferSize(that.responseBufferSize);
engine.setHostnameVerifier(verifier);
// this may be null. We can't really support this with Apache Client.
engine.setSslContext(theContext);
return engine;
} catch (Exception e) {
throw new RuntimeException(e);
}
}Example 36
| Project: XPagesExtensionLibrary-master File: RestUtil.java View source code |
private void registerSslSocketFactory(HttpClient httpClient) {
try {
SSLSocketFactory socketFactory = new SSLSocketFactory(new TrustSelfSignedStrategy(), STRICT_HOSTNAME_VERIFIER);
httpClient.getConnectionManager().getSchemeRegistry().register(new Scheme("https", 443, socketFactory));
} catch (GeneralSecurityException gse) {
throw new RuntimeException("An error occurred setting up the SSLSocketFactory", gse);
}
}Example 37
| Project: DataCleaner-master File: SecurityUtils.java View source code |
/**
* Creates a {@link SSLConnectionSocketFactory} which is careless about SSL
* certificate checks. Use with caution!
*
* @return
*/
@SuppressWarnings("checkstyle:AbbreviationAsWordInName")
public static SSLConnectionSocketFactory createUnsafeSSLConnectionSocketFactory() {
try {
final SSLContextBuilder builder = new SSLContextBuilder();
builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
return new SSLConnectionSocketFactory(builder.build(), new NaiveHostnameVerifier());
} catch (final Exception e) {
throw new IllegalStateException(e);
}
}Example 38
| Project: kaa-master File: RestLogAppender.java View source code |
@Override
protected void initFromConfiguration(LogAppenderDto appender, RestConfig configuration) {
this.configuration = configuration;
this.executor = Executors.newFixedThreadPool(configuration.getConnectionPoolSize());
target = new HttpHost(configuration.getHost(), configuration.getPort(), configuration.getSsl() ? "https" : "http");
HttpClientBuilder builder = HttpClients.custom();
if (configuration.getUsername() != null && configuration.getPassword() != null) {
LOG.info("Adding basic auth credentials provider");
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(new AuthScope(target.getHostName(), target.getPort()), new UsernamePasswordCredentials(configuration.getUsername(), configuration.getPassword()));
builder.setDefaultCredentialsProvider(credsProvider);
}
if (!configuration.getVerifySslCert()) {
LOG.info("Adding trustful ssl context");
SSLContextBuilder sslBuilder = new SSLContextBuilder();
try {
sslBuilder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslBuilder.build());
builder.setSSLSocketFactory(sslsf);
} catch (NoSuchAlgorithmExceptionKeyStoreException | KeyManagementException | ex) {
LOG.error("Failed to init socket factory {}", ex.getMessage(), ex);
}
}
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
cm.setDefaultMaxPerRoute(configuration.getConnectionPoolSize());
cm.setMaxTotal(configuration.getConnectionPoolSize());
builder.setConnectionManager(cm);
this.client = builder.build();
}Example 39
| Project: kylo-master File: MetadataProviderSelectorService.java View source code |
/**
* Taken from NiFi GetHttp Processor
*/
private SSLContext createSSLContext(final SSLContextService service) throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException, KeyManagementException, UnrecoverableKeyException {
final SSLContextBuilder sslContextBuilder = new SSLContextBuilder();
if (StringUtils.isNotBlank(service.getTrustStoreFile())) {
final KeyStore truststore = KeyStore.getInstance(service.getTrustStoreType());
try (final InputStream in = new FileInputStream(new File(service.getTrustStoreFile()))) {
truststore.load(in, service.getTrustStorePassword().toCharArray());
}
sslContextBuilder.loadTrustMaterial(truststore, new TrustSelfSignedStrategy());
}
if (StringUtils.isNotBlank(service.getKeyStoreFile())) {
final KeyStore keystore = KeyStore.getInstance(service.getKeyStoreType());
try (final InputStream in = new FileInputStream(new File(service.getKeyStoreFile()))) {
keystore.load(in, service.getKeyStorePassword().toCharArray());
}
sslContextBuilder.loadKeyMaterial(keystore, service.getKeyStorePassword().toCharArray());
}
sslContextBuilder.useProtocol(service.getSslAlgorithm());
return sslContextBuilder.build();
}Example 40
| Project: nifi-master File: PostHTTP.java View source code |
private SSLContext createSSLContext(final SSLContextService service) throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException, KeyManagementException, UnrecoverableKeyException {
SSLContextBuilder builder = SSLContexts.custom();
final String trustFilename = service.getTrustStoreFile();
if (trustFilename != null) {
final KeyStore truststore = KeyStoreUtils.getTrustStore(service.getTrustStoreType());
try (final InputStream in = new FileInputStream(new File(service.getTrustStoreFile()))) {
truststore.load(in, service.getTrustStorePassword().toCharArray());
}
builder = builder.loadTrustMaterial(truststore, new TrustSelfSignedStrategy());
}
final String keyFilename = service.getKeyStoreFile();
if (keyFilename != null) {
final KeyStore keystore = KeyStoreUtils.getKeyStore(service.getKeyStoreType());
try (final InputStream in = new FileInputStream(new File(service.getKeyStoreFile()))) {
keystore.load(in, service.getKeyStorePassword().toCharArray());
}
builder = builder.loadKeyMaterial(keystore, service.getKeyStorePassword().toCharArray());
}
builder = builder.useProtocol(service.getSslAlgorithm());
final SSLContext sslContext = builder.build();
return sslContext;
}Example 41
| Project: Repository-master File: HttpClientManagerImplIT.java View source code |
private void setSSL(HttpClientBuilder builder) throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException {
SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(this.getClass().getClassLoader().getResource("testkeystore"), "password".toCharArray(), new TrustSelfSignedStrategy()).build();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new String[] { "TLSv1" }, null, SSLConnectionSocketFactory.getDefaultHostnameVerifier());
builder.setSSLSocketFactory(sslsf);
}Example 42
| Project: rhizome-master File: CassandraPod.java View source code |
public static Builder clusterBuilder(CassandraConfiguration cassandraConfiguration) {
Builder builder = new Cluster.Builder();
builder.withCompression(cassandraConfiguration.getCompression()).withSocketOptions(getSocketOptions()).withQueryOptions(new QueryOptions().setConsistencyLevel(cassandraConfiguration.getConsistencyLevel())).withPoolingOptions(getPoolingOptions()).withProtocolVersion(ProtocolVersion.V4).addContactPoints(cassandraConfiguration.getCassandraSeedNodes());
if (cassandraConfiguration.isSslEnabled()) {
SSLContext context = null;
try {
context = SSLContextBuilder.create().loadTrustMaterial(new TrustSelfSignedStrategy()).build();
} catch (NoSuchAlgorithmExceptionKeyStoreException | KeyManagementException | e) {
logger.error("Unable to configure SSL for Cassanda Java Driver");
}
builder.withSSL(JdkSSLOptions.builder().withSSLContext(context).build());
}
return builder;
}Example 43
| Project: spring-hadoop-master File: YarnRestTemplateAutoConfigurationTests.java View source code |
@Bean(name = YarnSystemConstants.DEFAULT_ID_RESTTEMPLATE)
public RestTemplate restTemplate() throws Exception {
HttpClientBuilder builder = HttpClientBuilder.create();
SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build());
builder.setSSLSocketFactory(sslSocketFactory);
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("username", "password");
BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(new AuthScope(null, -1, null), credentials);
builder.setDefaultCredentialsProvider(credentialsProvider);
HttpClient httpClient = builder.build();
return new RestTemplate(new HttpComponentsClientHttpRequestFactory(httpClient));
}Example 44
| Project: syncope-master File: HttpUtils.java View source code |
private static CloseableHttpClient createHttpsClient() {
CloseableHttpClient chc = null;
try {
final SSLContextBuilder builder = new SSLContextBuilder();
builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
chc = HttpClients.custom().setSSLSocketFactory(new SSLConnectionSocketFactory(builder.build(), SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER)).build();
} catch (Exception ex) {
}
return chc;
}Example 45
| Project: TeamCity-HipChat-Notifier-master File: HipChatApiProcessor.java View source code |
private CloseableHttpClient createClient() throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
if (this.configuration.getBypassSslCheck()) {
logger.warn("SSL check being bypassed");
SSLContextBuilder sslContextBuilder = new SSLContextBuilder();
sslContextBuilder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslContextBuilder.build(), SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
HttpClientBuilder httpClientBuilder = HttpClients.custom().setSSLSocketFactory(socketFactory);
CloseableHttpClient client = httpClientBuilder.build();
return client;
} else {
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
String proxyHost = systemProperties.getProperty("http.proxyHost");
if (proxyHost != null) {
logger.info("Proxy configuration detected");
logger.debug(String.format("Host: %s", proxyHost));
int proxyPort = 80;
String proxyPortString = systemProperties.getProperty("http.proxyPort");
if (proxyPortString != null) {
proxyPort = Integer.parseInt(proxyPortString);
}
HttpHost proxy = new HttpHost(proxyHost, proxyPort, "http");
DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
httpClientBuilder.setRoutePlanner(routePlanner);
logger.info(String.format("Proxy configured: %s:%s", proxyHost, proxyPort));
}
return httpClientBuilder.build();
}
}Example 46
| Project: coprhd-controller-master File: WinRMTarget.java View source code |
private HttpClientConnectionManager createClientConnectionManager() throws Exception {
SSLContextBuilder contextBuilder = SSLContexts.custom();
try {
contextBuilder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build(), SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.INSTANCE).register("https", socketFactory).build();
return (new PoolingHttpClientConnectionManager(registry));
} catch (Exception e) {
throw new HttpException(e.getMessage());
}
}Example 47
| Project: ec2-plugin-master File: WinRMClient.java View source code |
public void setUseHTTPS(boolean useHTTPS) {
this.useHTTPS = useHTTPS;
if (useHTTPS) {
SSLSocketFactory socketFactory;
try {
socketFactory = new SSLSocketFactory(new TrustSelfSignedStrategy(), new AllowAllHostnameVerifier());
httpsScheme = new Scheme("https", 443, socketFactory);
} catch (KeyManagementException e) {
} catch (UnrecoverableKeyException e) {
} catch (NoSuchAlgorithmException e) {
} catch (KeyStoreException e) {
}
} else {
httpsScheme = null;
}
}Example 48
| Project: gerbil-master File: TagMeAnnotator.java View source code |
protected void init() throws GerbilException {
HttpClientBuilder builder = HttpManagement.getInstance().generateHttpClientBuilder();
try {
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
InputStream instream = this.getClass().getClassLoader().getResourceAsStream(KEY_STORE_RESOURCE_NAME);
try {
keyStore.load(instream, KEY_STORE_PASSWORD);
} finally {
instream.close();
}
SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(keyStore, new TrustSelfSignedStrategy()).build();
builder.setSSLContext(sslcontext);
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" }, null, SSLConnectionSocketFactory.getDefaultHostnameVerifier());
builder.setSSLSocketFactory(sslsf);
CloseableHttpClient localClient = builder.build();
this.setClient(localClient);
} catch (Exception e) {
throw new GerbilException("Couldn't initialize SSL context.", e, ErrorTypes.ANNOTATOR_LOADING_ERROR);
}
this.setClient(builder.build());
}Example 49
| Project: incubator-streams-master File: SimpleHttpProvider.java View source code |
@Override
public void prepare(Object configurationObject) {
mapper = StreamsJacksonMapper.getInstance();
uriBuilder = new URIBuilder().setScheme(this.configuration.getProtocol()).setHost(this.configuration.getHostname()).setPort(this.configuration.getPort().intValue()).setPath(this.configuration.getResourcePath());
SSLContextBuilder builder = new SSLContextBuilder();
SSLConnectionSocketFactory sslsf = null;
try {
builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
sslsf = new SSLConnectionSocketFactory(builder.build(), SSLConnectionSocketFactory.getDefaultHostnameVerifier());
} catch (NoSuchAlgorithmExceptionKeyManagementException | KeyStoreException | ex) {
LOGGER.warn(ex.getMessage());
}
httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
executor = Executors.newSingleThreadExecutor();
}Example 50
| Project: knox-master File: KnoxCLI.java View source code |
@Override
public void execute() {
attempts++;
SSLContext ctx = null;
CloseableHttpClient client;
String http = "http://";
String https = "https://";
GatewayConfig conf = getGatewayConfig();
String gatewayPort;
String host;
if (cluster == null) {
printKnoxShellUsage();
out.println("A --cluster argument is required.");
return;
}
if (hostname != null) {
host = hostname;
} else {
try {
host = InetAddress.getLocalHost().getHostAddress();
} catch (UnknownHostException e) {
out.println(e.toString());
out.println("Defaulting address to localhost. Use --hostname option to specify a different hostname");
host = "localhost";
}
}
if (port != null) {
gatewayPort = port;
} else if (conf.getGatewayPort() > -1) {
gatewayPort = Integer.toString(conf.getGatewayPort());
} else {
out.println("Could not get port. Please supply it using the --port option");
return;
}
String path = "/" + conf.getGatewayPath();
String topology = "/" + cluster;
String httpServiceTestURL = http + host + ":" + gatewayPort + path + topology + "/service-test";
String httpsServiceTestURL = https + host + ":" + gatewayPort + path + topology + "/service-test";
String authString = "";
// Create Authorization String
if (user != null && pass != null) {
authString = "Basic " + Base64.encodeBase64String((user + ":" + pass).getBytes());
} else {
out.println("Username and/or password not supplied. Expect HTTP 401 Unauthorized responses.");
}
// Attempt to build SSL context for HTTP client.
try {
ctx = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build();
} catch (Exception e) {
out.println(e.toString());
}
// Initialize the HTTP client
if (ctx == null) {
client = HttpClients.createDefault();
} else {
client = HttpClients.custom().setSslcontext(ctx).build();
}
HttpGet request;
if (ssl) {
request = new HttpGet(httpsServiceTestURL);
} else {
request = new HttpGet(httpServiceTestURL);
}
request.setHeader("Authorization", authString);
request.setHeader("Accept", MediaType.APPLICATION_JSON.getMediaType());
try {
out.println(request.toString());
CloseableHttpResponse response = client.execute(request);
switch(response.getStatusLine().getStatusCode()) {
case 200:
response.getEntity().writeTo(out);
break;
case 404:
out.println("Could not find service-test resource");
out.println("Make sure you have configured the SERVICE-TEST service in your topology.");
break;
case 500:
out.println("HTTP 500 Server error");
break;
default:
out.println("Unexpected HTTP response code.");
out.println(response.getStatusLine().toString());
response.getEntity().writeTo(out);
break;
}
response.close();
request.releaseConnection();
} catch (ClientProtocolException e) {
out.println(e.toString());
if (debug) {
e.printStackTrace(out);
}
} catch (SSLException e) {
out.println(e.toString());
retryRequest();
} catch (IOException e) {
out.println(e.toString());
retryRequest();
if (debug) {
e.printStackTrace(out);
}
} finally {
try {
client.close();
} catch (IOException e) {
out.println(e.toString());
}
}
}Example 51
| Project: openelisglobal-core-master File: ExternalPatientSearch.java View source code |
// protected for unit testing called from synchronized block
protected void doSearch() {
HttpClient httpclient = new DefaultHttpClient();
setTimeout(httpclient);
HttpGet httpget = new HttpGet(connectionString);
URI getUri = buildConnectionString(httpget.getURI());
httpget.setURI(getUri);
try {
// Ignore hostname mismatches and allow trust of self-signed certs
SSLSocketFactory sslsf = new SSLSocketFactory(new TrustSelfSignedStrategy(), SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
Scheme https = new Scheme("https", 443, sslsf);
ClientConnectionManager ccm = httpclient.getConnectionManager();
ccm.getSchemeRegistry().register(https);
HttpResponse getResponse = httpclient.execute(httpget);
returnStatus = getResponse.getStatusLine().getStatusCode();
setPossibleErrors();
setResults(IOUtils.toString(getResponse.getEntity().getContent(), "UTF-8"));
} catch (SocketTimeoutException e) {
errors.add("Response from patient information server took too long.");
LogEvent.logError("ExternalPatientSearch", "doSearch()", e.toString());
} catch (ConnectException e) {
errors.add("Unable to connect to patient information form service. Service may not be running");
LogEvent.logError("ExternalPatientSearch", "doSearch()", e.toString());
} catch (IOException e) {
errors.add("IO error trying to read input stream.");
LogEvent.logError("ExternalPatientSearch", "doSearch()", e.toString());
} catch (KeyManagementException e) {
errors.add("Key management error trying to connect to external search service.");
LogEvent.logError("ExternalPatientSearch", "doSearch()", e.toString());
} catch (UnrecoverableKeyException e) {
errors.add("Unrecoverable key error trying to connect to external search service.");
LogEvent.logError("ExternalPatientSearch", "doSearch()", e.toString());
} catch (NoSuchAlgorithmException e) {
errors.add("No such encyrption algorithm error trying to connect to external search service.");
LogEvent.logError("ExternalPatientSearch", "doSearch()", e.toString());
} catch (KeyStoreException e) {
errors.add("Keystore error trying to connect to external search service.");
LogEvent.logError("ExternalPatientSearch", "doSearch()", e.toString());
} catch (RuntimeException e) {
errors.add("Runtime error trying to retrieve patient information.");
LogEvent.logError("ExternalPatientSearch", "doSearch()", e.toString());
httpget.abort();
throw e;
} finally {
httpclient.getConnectionManager().shutdown();
}
}Example 52
| Project: rest-utils-master File: SslTest.java View source code |
// returns the http response status code.
private int makeGetRequest(String url, String clientKeystoreLocation, String clientKeystorePassword, String clientKeyPassword) throws Exception {
log.debug("Making GET " + url);
HttpGet httpget = new HttpGet(url);
CloseableHttpClient httpclient;
if (url.startsWith("http://")) {
httpclient = HttpClients.createDefault();
} else {
// trust all self-signed certs.
SSLContextBuilder sslContextBuilder = SSLContexts.custom().loadTrustMaterial(new TrustSelfSignedStrategy());
// add the client keystore if it's configured.
if (clientKeystoreLocation != null) {
sslContextBuilder.loadKeyMaterial(new File(clientKeystoreLocation), clientKeystorePassword.toCharArray(), clientKeyPassword.toCharArray());
}
SSLContext sslContext = sslContextBuilder.build();
SSLConnectionSocketFactory sslSf = new SSLConnectionSocketFactory(sslContext, new String[] { "TLSv1" }, null, SSLConnectionSocketFactory.getDefaultHostnameVerifier());
httpclient = HttpClients.custom().setSSLSocketFactory(sslSf).build();
}
int statusCode = -1;
CloseableHttpResponse response = null;
try {
response = httpclient.execute(httpget);
statusCode = response.getStatusLine().getStatusCode();
} finally {
if (response != null) {
response.close();
}
httpclient.close();
}
return statusCode;
}Example 53
| Project: threatconnect-java-master File: ConnectionUtil.java View source code |
/**
* Adds the ability to trust self signed certificates for this HttpClientBuilder
*
* @param httpClientBuilder
* the HttpClientBuilder to apply these settings to
*/
public static void trustSelfSignedCerts(final HttpClientBuilder httpClientBuilder) {
logger.debug("Trusting self-signed certs.");
try {
SSLContextBuilder builder = new SSLContextBuilder();
builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build(), new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
// allow all
return true;
}
});
httpClientBuilder.setSSLSocketFactory(sslsf);
} catch (NoSuchAlgorithmExceptionKeyStoreException | KeyManagementException | ex) {
logger.error("Error adding SSLSocketFactory to HttpClientBuilder", ex);
}
}Example 54
| Project: belladati-sdk-java-master File: BellaDatiClient.java View source code |
/**
* Builds the HTTP client to connect to the server.
*
* @param trustSelfSigned <tt>true</tt> if the client should accept
* self-signed certificates
* @return a new client instance
*/
private CloseableHttpClient buildClient(boolean trustSelfSigned) {
try {
// if required, define custom SSL context allowing self-signed certs
SSLContext sslContext = !trustSelfSigned ? SSLContexts.createSystemDefault() : SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build();
// set timeouts for the HTTP client
int globalTimeout = readFromProperty("bdTimeout", 100000);
int connectTimeout = readFromProperty("bdConnectTimeout", globalTimeout);
int connectionRequestTimeout = readFromProperty("bdConnectionRequestTimeout", globalTimeout);
int socketTimeout = readFromProperty("bdSocketTimeout", globalTimeout);
RequestConfig requestConfig = RequestConfig.copy(RequestConfig.DEFAULT).setConnectTimeout(connectTimeout).setSocketTimeout(socketTimeout).setConnectionRequestTimeout(connectionRequestTimeout).build();
// configure caching
CacheConfig cacheConfig = CacheConfig.copy(CacheConfig.DEFAULT).setSharedCache(false).setMaxCacheEntries(1000).setMaxObjectSize(2 * 1024 * 1024).build();
// configure connection pooling
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(RegistryBuilder.<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.getSocketFactory()).register("https", new SSLConnectionSocketFactory(sslContext)).build());
int connectionLimit = readFromProperty("bdMaxConnections", 40);
// there's only one server to connect to, so max per route matters
connManager.setMaxTotal(connectionLimit);
connManager.setDefaultMaxPerRoute(connectionLimit);
// create the HTTP client
return CachingHttpClientBuilder.create().setCacheConfig(cacheConfig).setDefaultRequestConfig(requestConfig).setConnectionManager(connManager).build();
} catch (GeneralSecurityException e) {
throw new InternalConfigurationException("Failed to set up SSL context", e);
}
}Example 55
| Project: haogrgr-test-master File: HttpUtils.java View source code |
/**
* 获�支�Https的HttpClient对象
* @param proxy 代�host
* @param threadSafe 是�使用线程安全的HttpClient
* @param keyStoreFile 信任�书库文件
* @param pwd è¯?书库密ç ?
* @return
*/
public static CloseableHttpClient getSSLClient(HttpHost proxy, boolean threadSafe, File keyStoreFile, String pwd) {
HttpClientBuilder builder = getClientBuilder(proxy);
try {
KeyStore trustStore = getTrustKeyStore(keyStoreFile, pwd);
SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build();
SSLConnectionSocketFactory sslConnFactory = new SSLConnectionSocketFactory(sslContext);
RegistryBuilder<ConnectionSocketFactory> registryBuilder = RegistryBuilder.create();
Registry<ConnectionSocketFactory> registry = registryBuilder.register("https", sslConnFactory).build();
HttpClientConnectionManager cm = null;
if (threadSafe) {
cm = new PoolingHttpClientConnectionManager(registry);
((PoolingHttpClientConnectionManager) cm).setMaxTotal(DEFAULT_CONN_POOL_SIZE);
} else {
cm = new BasicHttpClientConnectionManager(registry);
}
builder.setConnectionManager(cm);
} catch (Exception e) {
throw new RuntimeException("�始化HttpClient实例失败!", e);
}
return builder.build();
}Example 56
| Project: loklak_server-master File: ClientConnection.java View source code |
private static PoolingHttpClientConnectionManager getConnctionManager(boolean useAuthentication) {
// allow opportunistic encryption if needed
boolean trustAllCerts = !"none".equals(DAO.getConfig("httpsclient.trustselfsignedcerts", "peers")) && (!useAuthentication || "all".equals(DAO.getConfig("httpsclient.trustselfsignedcerts", "peers")));
Registry<ConnectionSocketFactory> socketFactoryRegistry = null;
if (trustAllCerts) {
try {
SSLConnectionSocketFactory trustSelfSignedSocketFactory = new SSLConnectionSocketFactory(new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build(), new TrustAllHostNameVerifier());
socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create().register("http", new PlainConnectionSocketFactory()).register("https", trustSelfSignedSocketFactory).build();
} catch (KeyManagementExceptionNoSuchAlgorithmException | KeyStoreException | e) {
Log.getLog().warn(e);
}
}
PoolingHttpClientConnectionManager cm = (trustAllCerts && socketFactoryRegistry != null) ? new PoolingHttpClientConnectionManager(socketFactoryRegistry) : new PoolingHttpClientConnectionManager();
// twitter specific options
cm.setMaxTotal(200);
cm.setDefaultMaxPerRoute(20);
HttpHost twitter = new HttpHost("twitter.com", 443);
cm.setMaxPerRoute(new HttpRoute(twitter), 50);
return cm;
}Example 57
| Project: lucene-solr-master File: SSLTestConfig.java View source code |
/**
* Builds a new SSLContext for HTTP <b>clients</b> to use when communicating with servers which have
* been configured based on the settings of this object.
*
* NOTE: Uses a completely insecure {@link SecureRandom} instance to prevent tests from blocking
* due to lack of entropy, also explicitly allows the use of self-signed
* certificates (since that's what is almost always used during testing).
*/
public SSLContext buildClientSSLContext() throws KeyManagementException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException {
assert isSSLMode();
SSLContextBuilder builder = SSLContexts.custom();
builder.setSecureRandom(NotSecurePsuedoRandom.INSTANCE);
// NOTE: KeyStore & TrustStore are swapped because they are from configured from server perspective...
// we are a client - our keystore contains the keys the server trusts, and vice versa
builder.loadTrustMaterial(buildKeyStore(keyStore, getKeyStorePassword()), new TrustSelfSignedStrategy()).build();
if (isClientAuthMode()) {
builder.loadKeyMaterial(buildKeyStore(trustStore, getTrustStorePassword()), getTrustStorePassword().toCharArray());
}
return builder.build();
}Example 58
| Project: pom-version-manipulator-master File: InputUtils.java View source code |
private static void setupClient() throws VManException {
if (client == null) {
SSLSocketFactory sslSocketFactory;
try {
sslSocketFactory = new SSLSocketFactory(SSLSocketFactory.TLS, null, null, trustKs, null, new TrustSelfSignedStrategy(), SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
// sslSocketFactory =
// new SSLSocketFactory( SSLSocketFactory.TLS, null, null, trustKs, null, null,
// SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER );
} catch (final KeyManagementException e) {
logger.error("Failed to setup SSL socket factory: {}", e, e.getMessage());
throw new VManException("Failed to setup SSL socket factory: %s", e, e.getMessage());
} catch (final UnrecoverableKeyException e) {
logger.error("Failed to setup SSL socket factory: {}", e, e.getMessage());
throw new VManException("Failed to setup SSL socket factory: %s", e, e.getMessage());
} catch (final NoSuchAlgorithmException e) {
logger.error("Failed to setup SSL socket factory: {}", e, e.getMessage());
throw new VManException("Failed to setup SSL socket factory: %s", e, e.getMessage());
} catch (final KeyStoreException e) {
logger.error("Failed to setup SSL socket factory: {}", e, e.getMessage());
throw new VManException("Failed to setup SSL socket factory: %s", e, e.getMessage());
}
final ThreadSafeClientConnManager ccm = new ThreadSafeClientConnManager();
ccm.getSchemeRegistry().register(new Scheme("https", 443, sslSocketFactory));
final DefaultHttpClient hc = new DefaultHttpClient(ccm);
hc.setRedirectStrategy(new DefaultRedirectStrategy());
final String proxyHost = System.getProperty("http.proxyHost");
final int proxyPort = Integer.parseInt(System.getProperty("http.proxyPort", "-1"));
if (proxyHost != null && proxyPort > 0) {
final HttpHost proxy = new HttpHost(proxyHost, proxyPort);
hc.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY, proxy);
}
client = hc;
}
}Example 59
| Project: restclient-tool-master File: Hitter.java View source code |
private Scheme getSSLScheme(boolean disableVerifyCert, boolean disableVerifyHost) throws NoSuchAlgorithmException, KeyManagementException, UnrecoverableKeyException, KeyStoreException {
SSLSocketFactory sslFactory = null;
if (isUseSelfSignedCertVerifier()) {
TrustSelfSignedStrategy selfSignedStrategy = new TrustSelfSignedStrategy();
// are StrictHostnameVerifier and BrowserCompatHostnameVerifier.
if (disableVerifyHost)
sslFactory = new SSLSocketFactory(selfSignedStrategy, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
else
// BROWSER_COMPATIBLE_HOSTNAME_VERIFIER is used by default
sslFactory = new SSLSocketFactory(selfSignedStrategy);
} else {
SSLContext sslContext = SSLContext.getInstance("TLS");
if (disableVerifyCert)
sslContext.init(null, new TrustManager[] { getNoCheckTrustManager() }, null);
else
sslContext.init(null, null, null);
if (disableVerifyHost)
sslFactory = new SSLSocketFactory(sslContext, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
else
sslFactory = new SSLSocketFactory(sslContext);
}
return new Scheme("https", RCConstants.SSL_SOCKET_PORT, sslFactory);
}Example 60
| Project: ScriptSpider-master File: HttpUtils.java View source code |
/**
* 创建httpclientè¿žæŽ¥æ± ï¼Œå¹¶åˆ?始化httpclient
*/
public void init() {
try {
SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build();
HostnameVerifier hostnameVerifier = SSLConnectionSocketFactory.getDefaultHostnameVerifier();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, hostnameVerifier);
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.getSocketFactory()).register("https", sslsf).build();
httpClientConnectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
// Increase max total connection to 200
httpClientConnectionManager.setMaxTotal(maxTotalPool);
// Increase default max connection per route to 20
httpClientConnectionManager.setDefaultMaxPerRoute(maxConPerRoute);
SocketConfig socketConfig = SocketConfig.custom().setSoTimeout(socketTimeout).build();
httpClientConnectionManager.setDefaultSocketConfig(socketConfig);
} catch (Exception e) {
}
}Example 61
| Project: stash-plugin-master File: StashApiClient.java View source code |
private HttpClient getHttpClient() {
HttpClientBuilder builder = HttpClientBuilder.create().useSystemProperties();
if (this.ignoreSsl) {
try {
SSLContextBuilder sslContextBuilder = new SSLContextBuilder();
sslContextBuilder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContextBuilder.build(), NoopHostnameVerifier.INSTANCE);
builder.setSSLSocketFactory(sslsf);
} catch (NoSuchAlgorithmException e) {
logger.log(Level.SEVERE, "Failing to setup the SSLConnectionFactory: " + e.toString());
throw new RuntimeException(e);
} catch (KeyStoreException e) {
logger.log(Level.SEVERE, "Failing to setup the SSLConnectionFactory: " + e.toString());
throw new RuntimeException(e);
} catch (KeyManagementException e) {
logger.log(Level.SEVERE, "Failing to setup the SSLConnectionFactory: " + e.toString());
throw new RuntimeException(e);
}
}
return builder.build();
}Example 62
| Project: Web-Karma-master File: ElasticSearchPublishServlet.java View source code |
private CloseableHttpClient getHttpClient(ElasticSearchConfig esConfig) throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
if (esConfig.getProtocol().equalsIgnoreCase("https")) {
SSLContextBuilder builder = new SSLContextBuilder();
builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build());
return HttpClients.custom().setSSLSocketFactory(sslsf).build();
} else if (esConfig.getProtocol().equalsIgnoreCase("http"))
return HttpClients.createDefault();
return null;
}Example 63
| Project: wisdom-master File: ServerTest.java View source code |
/**
* This methods checks HTTP, HTTPS and HTTPS with Mutual Authentication.
*/
@Test
public void testCreationOfThreeServersFromConfiguration() throws InterruptedException, IOException, KeyStoreException, CertificateException, NoSuchAlgorithmException, KeyManagementException, UnrecoverableKeyException {
FakeConfiguration s1 = new FakeConfiguration(ImmutableMap.<String, Object>builder().put("port", 0).put("ssl", false).put("authentication", false).build());
FakeConfiguration s2 = new FakeConfiguration(ImmutableMap.<String, Object>builder().put("port", 0).put("ssl", true).put("authentication", false).build());
FakeConfiguration s3 = new FakeConfiguration(ImmutableMap.<String, Object>builder().put("port", 0).put("ssl", true).put("authentication", true).build());
// Server HTTPS
File root = new File("");
final File serverKeyStore = new File(root.getAbsolutePath() + "/src/test/resources/keystore/server/server.jks");
assertThat(serverKeyStore).isFile();
when(application.get("https.keyStore")).thenReturn(serverKeyStore.getAbsolutePath());
when(application.get("https.trustStore")).thenReturn(new File(root.getAbsolutePath() + "/src/test/resources/keystore/server/server.jks").getAbsolutePath());
when(application.getWithDefault("https.keyStoreType", "JKS")).thenReturn("JKS");
when(application.getWithDefault("https.trustStoreType", "JKS")).thenReturn("JKS");
when(application.getWithDefault("https.keyStorePassword", "")).thenReturn("wisdom");
when(application.getWithDefault("https.trustStorePassword", "")).thenReturn("wisdom");
when(application.getWithDefault("https.keyStoreAlgorithm", KeyManagerFactory.getDefaultAlgorithm())).thenReturn(KeyManagerFactory.getDefaultAlgorithm());
when(application.getWithDefault("https.trustStoreAlgorithm", KeyManagerFactory.getDefaultAlgorithm())).thenReturn(KeyManagerFactory.getDefaultAlgorithm());
when(application.getConfiguration("vertx.servers")).thenReturn(new FakeConfiguration(ImmutableMap.<String, Object>of("s1", s1, "s2", s2, "s3", s3)));
Controller controller = new DefaultController() {
@SuppressWarnings("unused")
public Result index() {
return ok("Alright");
}
};
Route route = new RouteBuilder().route(HttpMethod.GET).on("/").to(controller, "index");
when(router.getRouteFor(anyString(), anyString(), any(Request.class))).thenReturn(route);
wisdom.start();
waitForStart(wisdom);
waitForHttpsStart(wisdom);
assertThat(wisdom.servers).hasSize(3);
// Check rendering
for (Server server : wisdom.servers) {
String r;
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
FileInputStream instream = new FileInputStream("src/test/resources/keystore/client/client1.jks");
trustStore.load(instream, "wisdom".toCharArray());
// Trust own CA and all self-signed certs
SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).loadKeyMaterial(trustStore, "wisdom".toCharArray()).build();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1", "SSLv3" }, null, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
if (server.ssl()) {
HttpGet httpget = new HttpGet("https://localhost:" + server.port());
final CloseableHttpResponse response = httpclient.execute(httpget);
r = EntityUtils.toString(response.getEntity());
} else {
r = org.apache.http.client.fluent.Request.Get("http://localhost:" + server.port()).execute().returnContent().asString();
}
assertThat(r).isEqualToIgnoringCase("Alright");
}
}Example 64
| Project: incubator-brooklyn-master File: HttpTool.java View source code |
public HttpClient build() {
final DefaultHttpClient httpClient = new DefaultHttpClient(clientConnectionManager);
httpClient.setParams(httpParams);
// http://stackoverflow.com/questions/3658721/httpclient-4-error-302-how-to-redirect
if (laxRedirect) {
httpClient.setRedirectStrategy(new LaxRedirectStrategy());
}
if (reuseStrategy != null) {
httpClient.setReuseStrategy(reuseStrategy);
}
if (https == Boolean.TRUE || (uri != null && uri.toString().startsWith("https:"))) {
try {
if (port == null) {
port = (uri != null && uri.getPort() >= 0) ? uri.getPort() : 443;
}
if (socketFactory == null) {
if (trustAll) {
TrustStrategy trustStrategy = new TrustAllStrategy();
X509HostnameVerifier hostnameVerifier = SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
socketFactory = new SSLSocketFactory(trustStrategy, hostnameVerifier);
} else if (trustSelfSigned) {
TrustStrategy trustStrategy = new TrustSelfSignedStrategy();
X509HostnameVerifier hostnameVerifier = SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
socketFactory = new SSLSocketFactory(trustStrategy, hostnameVerifier);
} else {
// Using default https scheme: based on default java truststore, which is pretty strict!
}
}
if (socketFactory != null) {
Scheme sch = new Scheme("https", port, socketFactory);
httpClient.getConnectionManager().getSchemeRegistry().register(sch);
}
} catch (Exception e) {
LOG.warn("Error setting trust for uri {}", uri);
throw Exceptions.propagate(e);
}
}
// Set credentials
if (uri != null && credentials != null) {
String hostname = uri.getHost();
int port = uri.getPort();
httpClient.getCredentialsProvider().setCredentials(new AuthScope(hostname, port), credentials);
}
if (uri == null && credentials != null) {
LOG.warn("credentials have no effect in builder unless URI for host is specified");
}
return httpClient;
}Example 65
| Project: geode-master File: RestAPIsWithSSLDUnitTest.java View source code |
private CloseableHttpClient getSSLBasedHTTPClient(Properties properties) throws Exception {
KeyStore clientKeys = KeyStore.getInstance("JKS");
File keystoreJKSForPath = findKeyStoreJKS(properties);
clientKeys.load(new FileInputStream(keystoreJKSForPath), "password".toCharArray());
KeyStore clientTrust = KeyStore.getInstance("JKS");
File trustStoreJKSForPath = findTrustStoreJKSForPath(properties);
clientTrust.load(new FileInputStream(trustStoreJKSForPath), "password".toCharArray());
// this is needed
SSLContextBuilder custom = SSLContexts.custom();
SSLContextBuilder sslContextBuilder = custom.loadTrustMaterial(clientTrust, new TrustSelfSignedStrategy());
SSLContext sslcontext = sslContextBuilder.loadKeyMaterial(clientKeys, "password".toCharArray(), ( aliases, socket) -> {
if (aliases.size() == 1) {
return aliases.keySet().stream().findFirst().get();
}
if (!StringUtils.isEmpty(properties.getProperty(INVALID_CLIENT_ALIAS))) {
return properties.getProperty(INVALID_CLIENT_ALIAS);
} else {
return properties.getProperty(SSL_WEB_ALIAS);
}
}).build();
// Host checking is disabled here , as tests might run on multiple hosts and
// host entries can not be assumed
SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslcontext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
return HttpClients.custom().setSSLSocketFactory(sslConnectionSocketFactory).build();
}Example 66
| Project: openhab1-addons-master File: Tr064Comm.java View source code |
/***
* Creates a apache HTTP Client object, ignoring SSL Exceptions like self signed certificates
* and sets Auth. Scheme to Digest Auth
*
* @param fboxUrl the URL from config file of fbox to connect to
* @return the ready-to-use httpclient for tr064 requests
*/
private CloseableHttpClient createTr064HttpClient(String fboxUrl) {
CloseableHttpClient hc = null;
// Convert URL String from config in easy explotable URI object
URIBuilder uriFbox = null;
try {
uriFbox = new URIBuilder(fboxUrl);
} catch (URISyntaxException e) {
logger.error("Invalid FritzBox URL! {}", e.getMessage());
return null;
}
// Create context of the http client
_httpClientContext = HttpClientContext.create();
CookieStore cookieStore = new BasicCookieStore();
_httpClientContext.setCookieStore(cookieStore);
// SETUP AUTH
// Auth is specific for this target
HttpHost target = new HttpHost(uriFbox.getHost(), uriFbox.getPort(), uriFbox.getScheme());
// Add digest authentication with username/pw from global config
CredentialsProvider credp = new BasicCredentialsProvider();
credp.setCredentials(new AuthScope(target.getHostName(), target.getPort()), new UsernamePasswordCredentials(_user, _pw));
// Create AuthCache instance. Manages authentication based on server response
AuthCache authCache = new BasicAuthCache();
// Generate DIGEST scheme object, initialize it and add it to the local auth cache. Digeste is standard for fbox
// auth SOAP
DigestScheme digestAuth = new DigestScheme();
// known from fbox specification
digestAuth.overrideParamter("realm", "HTTPS Access");
// never known at first request
digestAuth.overrideParamter("nonce", "");
authCache.put(target, digestAuth);
// Add AuthCache to the execution context
_httpClientContext.setAuthCache(authCache);
// SETUP SSL TRUST
SSLContextBuilder sslContextBuilder = new SSLContextBuilder();
SSLConnectionSocketFactory sslsf = null;
try {
// accept self signed certs
sslContextBuilder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
// dont
sslsf = new SSLConnectionSocketFactory(sslContextBuilder.build(), null, null, new NoopHostnameVerifier());
// verify
// hostname
// against
// cert
// CN
} catch (Exception ex) {
logger.error(ex.getMessage());
}
// Set timeout values
RequestConfig rc = RequestConfig.copy(RequestConfig.DEFAULT).setSocketTimeout(4000).setConnectTimeout(4000).setConnectionRequestTimeout(4000).build();
// BUILDER
// setup builder with parameters defined before
hc = // set the SSL options which trust every self signed
HttpClientBuilder.create().setSSLSocketFactory(sslsf).setDefaultCredentialsProvider(// cert
credp).setDefaultRequestConfig(// set auth options using digest
rc).build();
return hc;
}Example 67
| Project: spring-boot-master File: TestRestTemplate.java View source code |
private HttpClient createSslHttpClient() {
try {
SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build());
return HttpClients.custom().setSSLSocketFactory(socketFactory).build();
} catch (Exception ex) {
throw new IllegalStateException("Unable to create SSL HttpClient", ex);
}
}Example 68
| Project: geoserver-master File: XMPPClient.java View source code |
@Override
public void init() throws Exception {
// Initializes the XMPP Client and starts the communication. It also
// register GeoServer as "manager" to the service channels on the MUC
// (Multi
// User Channel) Rooms
LOGGER.info(String.format("Initializing connection to server %1$s port %2$d", server, port));
int packetReplyTimeout = DEFAULT_PACKET_REPLY_TIMEOUT;
if (getConfiguration().get("xmpp_packet_reply_timeout") != null) {
packetReplyTimeout = Integer.parseInt(getConfiguration().get("xmpp_packet_reply_timeout"));
}
SmackConfiguration.setDefaultPacketReplyTimeout(packetReplyTimeout);
config = new ConnectionConfiguration(server, port);
checkSecured(getConfiguration());
// Trust own CA and all self-signed certs
SSLContext sslcontext = null;
if (this.certificateFile != null && this.certificatePassword != null) {
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
FileInputStream instream = new FileInputStream(this.certificateFile);
try {
trustStore.load(instream, this.certificatePassword.toCharArray());
} finally {
instream.close();
}
sslcontext = SSLContexts.custom().loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build();
}
if (sslcontext != null) {
// config.setSASLAuthenticationEnabled(false);
config.setSecurityMode(SecurityMode.enabled);
config.setCustomSSLContext(sslcontext);
} else {
config.setSecurityMode(SecurityMode.disabled);
}
// Actually performs the connection to the XMPP Server
for (int testConn = 0; testConn < 5; testConn++) {
try {
// Try first the TCP Endpoint
connection = new XMPPTCPConnection(config);
connection.connect();
break;
} catch (NoResponseException e) {
connection = null;
if (testConn >= 5) {
LOGGER.warning("No XMPP TCP Endpoint available or could not get any response from the Server. Falling back to BOSH Endpoint.");
} else {
LOGGER.log(Level.WARNING, "Tentative #" + (testConn + 1) + " - Error while trying to connect to XMPP TCP Endpoint.", e);
Thread.sleep(500);
}
}
}
if (connection == null || !connection.isConnected()) {
for (int testConn = 0; testConn < 5; testConn++) {
try {
// Falling back to BOSH Endpoint
BOSHConfiguration boshConfig = new BOSHConfiguration((sslcontext != null), server, port, null, getConfiguration().get("xmpp_domain"));
if (sslcontext != null) {
// boshConfig.setSASLAuthenticationEnabled(false);
boshConfig.setSecurityMode(SecurityMode.enabled);
boshConfig.setCustomSSLContext(sslcontext);
} else {
boshConfig.setSecurityMode(SecurityMode.disabled);
}
connection = new XMPPBOSHConnection(boshConfig);
connection.connect();
break;
} catch (NoResponseException e) {
connection = null;
if (testConn >= 5) {
LOGGER.warning("No XMPP BOSH Endpoint available or could not get any response from the Server. The XMPP Client won't be available.");
} else {
LOGGER.log(Level.WARNING, "Tentative #" + (testConn + 1) + " - Error while trying to connect to XMPP BOSH Endpoint.", e);
Thread.sleep(500);
}
}
}
}
LOGGER.info("Connected: " + connection.isConnected());
// and registration is not yet performed at this time
if (connection.isConnected()) {
chatManager = ChatManager.getInstanceFor(connection);
discoStu = ServiceDiscoveryManager.getInstanceFor(connection);
// Add features to our XMPP client
discoProperties();
// Performs login with "admin" user credentials
performLogin(getConfiguration().get("xmpp_manager_username"), getConfiguration().get("xmpp_manager_password"));
// Start "ping" task in order to maintain alive the connection
startPingTask();
// Send invitation to the registered endpoints
sendInvitations();
//
getEndpointsLoadAverages();
//
checkPendingRequests();
} else {
setEnabled(false);
LOGGER.warning("Not connected! The XMPP client has been disabled.");
}
}Example 69
| Project: sensor-integration-framework-master File: ASERestServicesClient.java View source code |
/**
* Get an SSL connection factory that trusts all certificates and allows hostname mismatches.
* WARNING: This is NOT recommended for a production system as it exposes the application to
* man in the middle attacks. In production, the following should be done:
*
* 1. The public key should be imported to the appropriate truststore on the client machine,
* as in this example command:
*
* keytool -import -alias appscan -file mycert.cer -keystore cacertspersonal
*
* Refer to the documentation for your release of AppScan Source to locate the truststore.
*
* 2. The certificate should be created using the correct subjectAlternativeName
* (see http://tools.ietf.org/search/rfc6125) so that it matches the host.
*
* For example:
*
* <pre>
* keytool -genkeypair \
* -keystore keystore.jks \
* -dname "CN=example.com, OU=Sun Java System Application Server, O=Sun Microsystems, L=Santa Clara, ST=California, C=US" \
* -keypass changeit \
* -storepass changeit \
* -keyalg RSA \
* -keysize 2048 \
* -alias example \
* -ext SAN=DNS:example.com \
* -validity 9999
* </pre>
* @return
* @throws KeyManagementException
* @throws NoSuchAlgorithmException
* @throws KeyStoreException
*/
protected SSLConnectionSocketFactory getSSLSocketFactoryTrustingAllCerts() throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException {
SSLConnectionSocketFactory factory = null;
SSLContextBuilder builder = new SSLContextBuilder();
builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
// factory = new SSLConnectionSocketFactory(builder.build());
factory = new SSLConnectionSocketFactory(builder.build(), SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
return factory;
}Example 70
| Project: ofbiz-master File: UtilHttp.java View source code |
public static CloseableHttpClient getAllowAllHttpClient(String jksStoreFileName, String jksStorePassword) {
try {
// Trust own CA and all self-signed certs
SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(FileUtil.getFile(jksStoreFileName), jksStorePassword.toCharArray(), new TrustSelfSignedStrategy()).build();
// No host name verifier
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
return httpClient;
} catch (Exception e) {
return HttpClients.createDefault();
}
}Example 71
| Project: geppetto-master File: StandaloneCommonModule.java View source code |
@Provides
public SSLSocketFactory provideSSLSocketFactory() {
try {
return new SSLSocketFactory(new TrustSelfSignedStrategy());
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new ProvisionException("Unable to create SSLSocketFactory", e);
}
}Example 72
| Project: java-json-client-master File: HttpSSLClientBuilder.java View source code |
private SSLContext createSSLContext() {
try {
return SSLContexts.custom().loadTrustMaterial(createKeyStore(), new TrustSelfSignedStrategy()).build();
} catch (Exception e) {
throw new RuntimeException("Could not create SSL context", e);
}
}Example 73
| Project: eclipse-integration-commons-master File: RestUtils.java View source code |
private static javax.net.ssl.SSLContext buildSslContext() {
try {
return new SSLContextBuilder().useSSL().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build();
} catch (GeneralSecurityException gse) {
throw new RuntimeException("An error occurred setting up the SSLContext", gse);
}
}Example 74
| Project: glaze-http-master File: DefaultSyncClient.java View source code |
@Override
public void trustSelfSignedCertificates() {
try {
SSLSocketFactory sslsf = new SSLSocketFactory(new TrustSelfSignedStrategy(), SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
registerScheme(new Scheme("https", 443, sslsf));
} catch (Exception e) {
throw new GlazeException(e);
}
}Example 75
| Project: heliosearch-master File: SSLTestConfig.java View source code |
/**
* Builds a new SSLContext with the given configuration and allows the uses of
* self-signed certificates during testing.
*/
protected SSLContext buildSSLContext() throws KeyManagementException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException {
return SSLContexts.custom().loadKeyMaterial(buildKeyStore(getKeyStore(), getKeyStorePassword()), getKeyStorePassword().toCharArray()).loadTrustMaterial(buildKeyStore(getTrustStore(), getTrustStorePassword()), new TrustSelfSignedStrategy()).build();
}Example 76
| Project: lightblue-client-master File: SslSocketFactories.java View source code |
/**
* @return A default SSL socket factory that does not connect using an
* authenticated Lightblue certificate, but instead trust's self signed SSL
* certificates.
*/
public static SSLConnectionSocketFactory defaultNoAuthSocketFactory() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
SSLContextBuilder sslCtxBuilder = new SSLContextBuilder();
sslCtxBuilder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
return new SSLConnectionSocketFactory(sslCtxBuilder.build());
}Example 77
| Project: spring-ide-master File: CloudAppDashElement.java View source code |
private javax.net.ssl.SSLContext buildSslContext() {
try {
return new SSLContextBuilder().useSSL().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build();
} catch (GeneralSecurityException gse) {
throw new RuntimeException("An error occurred setting up the SSLContext", gse);
}
}