List of usage examples for org.apache.http.conn.ssl TrustStrategy TrustStrategy
TrustStrategy
From source file:com.clustercontrol.http.util.GetHttpResponse.java
private CloseableHttpClient getHttpClient() throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException { if (m_client == null) { List<Header> headers = new ArrayList<>(); HttpClientBuilder builder = HttpClients.custom().setDefaultCredentialsProvider(m_cledentialProvider) .setDefaultHeaders(headers); if (!this.m_needAuthSSLCert) { // SSL ?? TrustStrategy trustStrategy = new TrustStrategy() { @Override// w ww . ja v a 2 s. c o m public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { return true; } }; builder.setSSLSocketFactory(new SSLConnectionSocketFactory( new SSLContextBuilder().loadTrustMaterial(null, trustStrategy).build(), new NoopHostnameVerifier())); } RequestConfig requestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT) .setConnectTimeout(m_connectTimeout).setSocketTimeout(m_requestTimeout).build(); builder.setDefaultRequestConfig(requestConfig); if (m_proxyHost != null) { HttpHost proxy = new HttpHost(m_proxyHost, m_proxyPort, m_proxyScheme == null ? "https" : m_proxyScheme); if (m_proxyUser != null && m_proxyPassword != null) { m_cledentialProvider.setCredentials(new AuthScope(proxy.getHostName(), proxy.getPort()), new UsernamePasswordCredentials(m_proxyUser, m_proxyPassword)); } builder.setProxy(proxy); } if (m_userAgent != null) { headers.add(new BasicHeader(HTTP.USER_AGENT, m_userAgent)); } if (m_cancelProxyCache) { // ? // https://www.ipa.go.jp/security/awareness/vendor/programmingv2/contents/405.html headers.add(new BasicHeader("Cache-Control", "no-cache")); headers.add(new BasicHeader("Pragma", "no-cache")); } if (keepAlive) { headers.add(new BasicHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_KEEP_ALIVE)); } else { headers.add(new BasicHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_CLOSE)); } m_client = builder.build(); } return m_client; }
From source file:eu.vital.TrustManager.connectors.dms.DMSManager.java
private String query2(String DMS_endpoint, String postObject) throws NoSuchAlgorithmException, KeyStoreException, IOException, KeyManagementException { SSLContextBuilder builder = new SSLContextBuilder(); builder.loadTrustMaterial(null, new TrustStrategy() { @Override/* w w w . j a va 2s. com*/ public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { return true; } }); SSLConnectionSocketFactory sslSF = new SSLConnectionSocketFactory(builder.build(), SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); CloseableHttpClient httpClient = HttpClients.custom().setRedirectStrategy(new LaxRedirectStrategy()) .setSSLSocketFactory(sslSF).build(); HttpPost postRequest = new HttpPost(dms_URL + "/" + DMS_endpoint); postRequest.addHeader("Content-Type", "application/json"); postRequest.addHeader("vitalAccessToken", cookie.substring(17)); HttpEntity entityPost = new StringEntity(postObject, StandardCharsets.UTF_8); postRequest.setEntity(entityPost); CloseableHttpResponse response = httpClient.execute(postRequest); try { //(CloseableHttpResponse response = (CloseableHttpResponse) httpClient.execute(postRequest)) //System.out.println(response.getStatusLine()); HttpEntity entity = response.getEntity(); if (entity == null) return null; return EntityUtils.toString(entity); //EntityUtils.consume(entity); } catch (IOException | ParseException e) { //logger.error(e.toString()); //throw new ConnectionErrorException("Error in connection with DMSManager"); } return null; }
From source file:com.cloud.network.resource.NccHttpCode.java
public static HttpClient getHttpClient() { HttpClient httpClient = null;//from w ww .j av a 2 s .c o m TrustStrategy easyStrategy = new TrustStrategy() { @Override public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { return true; } }; try { SSLSocketFactory sf = new SSLSocketFactory(easyStrategy, new AllowAllHostnameVerifier()); SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("https", DEFAULT_PORT, sf)); ClientConnectionManager ccm = new BasicClientConnectionManager(registry); httpClient = new DefaultHttpClient(ccm); } catch (KeyManagementException e) { s_logger.error("failed to initialize http client " + e.getMessage()); } catch (UnrecoverableKeyException e) { s_logger.error("failed to initialize http client " + e.getMessage()); } catch (NoSuchAlgorithmException e) { s_logger.error("failed to initialize http client " + e.getMessage()); } catch (KeyStoreException e) { s_logger.error("failed to initialize http client " + e.getMessage()); } return httpClient; }
From source file:com.cloud.network.resource.NccHttpCode.java
public static String postHttpRequest(final String jsonCmd, final URI agentUri, String sessionID) throws ExecutionException { // Using Apache's HttpClient for HTTP POST // Java-only approach discussed at on StackOverflow concludes with // comment to use Apache HttpClient // http://stackoverflow.com/a/2793153/939250, but final comment is to // use Apache. String logMessage = StringEscapeUtils.unescapeJava(jsonCmd); logMessage = cleanPassword(logMessage); s_logger.debug("POST request to " + agentUri.toString() + " with contents " + logMessage); // Create request HttpClient httpClient = getHttpClient(); TrustStrategy easyStrategy = new TrustStrategy() { @Override public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { return true; }/*w w w .j a v a 2 s . com*/ }; try { SSLSocketFactory sf = new SSLSocketFactory(easyStrategy, new AllowAllHostnameVerifier()); SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("https", DEFAULT_PORT, sf)); ClientConnectionManager ccm = new BasicClientConnectionManager(registry); httpClient = new DefaultHttpClient(ccm); } catch (KeyManagementException e) { s_logger.error("failed to initialize http client " + e.getMessage()); } catch (UnrecoverableKeyException e) { s_logger.error("failed to initialize http client " + e.getMessage()); } catch (NoSuchAlgorithmException e) { s_logger.error("failed to initialize http client " + e.getMessage()); } catch (KeyStoreException e) { s_logger.error("failed to initialize http client " + e.getMessage()); } String result = null; // TODO: are there timeout settings and worker thread settings to tweak? try { HttpPost request = new HttpPost(agentUri); // JSON encode command // Assumes command sits comfortably in a string, i.e. not used for // large data transfers StringEntity cmdJson = new StringEntity(jsonCmd); request.addHeader("content-type", "application/json"); request.addHeader("Cookie", "SessId=" + sessionID); request.setEntity(cmdJson); s_logger.debug("Sending cmd to " + agentUri.toString() + " cmd data:" + logMessage + "SEssion id: " + sessionID); HttpResponse response = httpClient.execute(request); // Unsupported commands will not route. if (response.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_FOUND) { String errMsg = "Failed : HTTP error code : " + response.getStatusLine().getStatusCode(); throw new ExecutionException(NccHttpCode.NOT_FOUND); } else if ((response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) && (response.getStatusLine().getStatusCode() != HttpStatus.SC_CREATED)) { String errMsg = "Command Not Success " + agentUri.toString() + " : HTTP error code : " + response.getStatusLine().getStatusCode(); s_logger.error(errMsg); throw new ExecutionException(NccHttpCode.INTERNAL_ERROR + " " + errMsg); } else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { //Successfully created the resource in the NCC, Now get the Job ID and send to the response // make login request and store new session id throw new ExecutionException(NccHttpCode.UNAUTHORIZED); } else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED) { //Successfully created the resource in the NCC, Now get the Job ID and send to the response result = response.getFirstHeader(NccHttpCode.JOB_ID).getValue(); } else { result = EntityUtils.toString(response.getEntity()); String logResult = cleanPassword(StringEscapeUtils.unescapeJava(result)); s_logger.debug("POST response is " + logResult); } } catch (ClientProtocolException protocolEx) { // Problem with HTTP message exchange s_logger.error(protocolEx); } catch (IOException connEx) { // Problem with underlying communications s_logger.error(connEx); } finally { httpClient.getConnectionManager().shutdown(); } return result; }
From source file:org.dasein.cloud.vcloud.vCloudMethod.java
protected @Nonnull HttpClient getClient(boolean forAuthentication) throws CloudException, InternalException { ProviderContext ctx = provider.getContext(); if (ctx == null) { throw new CloudException("No context was defined for this request"); }//w ww . ja v a 2 s . c o m String endpoint = ctx.getCloud().getEndpoint(); if (endpoint == null) { throw new CloudException("No cloud endpoint was defined"); } boolean ssl = endpoint.startsWith("https"); int targetPort; URI uri; try { uri = new URI(endpoint); targetPort = uri.getPort(); if (targetPort < 1) { targetPort = (ssl ? 443 : 80); } } catch (URISyntaxException e) { throw new CloudException(e); } HttpHost targetHost = new HttpHost(uri.getHost(), targetPort, uri.getScheme()); HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); //noinspection deprecation HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); HttpProtocolParams.setUserAgent(params, ""); params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000); params.setParameter(CoreConnectionPNames.SO_TIMEOUT, 300000); Properties p = ctx.getCustomProperties(); if (p != null) { String proxyHost = p.getProperty("proxyHost"); String proxyPort = p.getProperty("proxyPort"); if (proxyHost != null) { int port = 0; if (proxyPort != null && proxyPort.length() > 0) { port = Integer.parseInt(proxyPort); } params.setParameter(ConnRoutePNames.DEFAULT_PROXY, new HttpHost(proxyHost, port, ssl ? "https" : "http")); } } DefaultHttpClient client = new DefaultHttpClient(params); if (provider.isInsecure()) { try { client.getConnectionManager().getSchemeRegistry() .register(new Scheme("https", 443, new SSLSocketFactory(new TrustStrategy() { public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { return true; } }, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER))); } catch (Throwable t) { t.printStackTrace(); } } if (forAuthentication) { String accessPublic = null; String accessPrivate = null; try { List<ContextRequirements.Field> fields = provider.getContextRequirements().getConfigurableValues(); for (ContextRequirements.Field f : fields) { if (f.type.equals(ContextRequirements.FieldType.KEYPAIR)) { byte[][] keyPair = (byte[][]) provider.getContext().getConfigurationValue(f); accessPublic = new String(keyPair[0], "utf-8"); accessPrivate = new String(keyPair[1], "utf-8"); } } } catch (UnsupportedEncodingException e) { throw new InternalException(e); } String password = accessPrivate; String userName; if (matches(getAPIVersion(), "0.8", "0.8")) { userName = accessPublic; } else { userName = accessPublic + "@" + ctx.getAccountNumber(); } client.getCredentialsProvider().setCredentials( new AuthScope(targetHost.getHostName(), targetHost.getPort()), new UsernamePasswordCredentials(userName, password)); } return client; }
From source file:com.infinities.skyport.openstack.nova.os.SkyportNovaMethod.java
@Override protected @Nonnull HttpClient getClient() throws CloudException, InternalException { ProviderContext ctx = provider.getContext(); if (ctx == null) { throw new InternalException("No context was defined for this request"); }//w w w .j a v a 2 s .c om String endpoint = ctx.getCloud().getEndpoint(); if (endpoint == null) { throw new InternalException("No cloud endpoint was defined"); } boolean ssl = endpoint.startsWith("https"); HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); // noinspection deprecation HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); HttpProtocolParams.setUserAgent(params, ""); Properties p = ctx.getCustomProperties(); if (p != null) { String proxyHost = p.getProperty("proxyHost"); String proxyPort = p.getProperty("proxyPort"); if (proxyHost != null) { int port = 0; if (proxyPort != null && proxyPort.length() > 0) { port = Integer.parseInt(proxyPort); } params.setParameter(ConnRoutePNames.DEFAULT_PROXY, new HttpHost(proxyHost, port, ssl ? "https" : "http")); } } DefaultHttpClient client = new DefaultHttpClient(params); if (provider.isInsecure()) { try { client.getConnectionManager().getSchemeRegistry() .register(new Scheme("https", 443, new SSLSocketFactory(new TrustStrategy() { @Override public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { return true; } }, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER))); } catch (Throwable t) { t.printStackTrace(); } } return client; }
From source file:org.opendedup.sdfs.filestore.cloud.BatchAwsS3ChunkStore.java
@Override public boolean checkAccess(String username, String password, Properties props) throws Exception { BasicAWSCredentials _cred = new BasicAWSCredentials(username, password); if (props.containsKey("default-bucket-location")) { bucketLocation = RegionUtils.getRegion(props.getProperty("default-bucket-location")); }/*from www .j av a 2s . c o m*/ ClientConfiguration clientConfig = new ClientConfiguration(); clientConfig.setMaxConnections(Main.dseIOThreads * 2); clientConfig.setConnectionTimeout(10000); clientConfig.setSocketTimeout(10000); String s3Target = null; if (props.containsKey("s3-target")) { s3Target = props.getProperty("s3-target"); } if (props.containsKey("proxy-host")) { clientConfig.setProxyHost(props.getProperty("proxy-host")); } if (props.containsKey("proxy-domain")) { clientConfig.setProxyDomain(props.getProperty("proxy-domain")); } if (props.containsKey("proxy-password")) { clientConfig.setProxyPassword(props.getProperty("proxy-password")); } if (props.containsKey("proxy-port")) { clientConfig.setProxyPort(Integer.parseInt(props.getProperty("proxy-port"))); } if (props.containsKey("proxy-username")) { clientConfig.setProxyUsername(props.getProperty("proxy-username")); } s3Service = new AmazonS3Client(_cred, clientConfig); if (s3Target != null) { TrustStrategy acceptingTrustStrategy = new TrustStrategy() { @Override public boolean isTrusted(X509Certificate[] certificate, String authType) { return true; } }; SSLSocketFactory sf = new SSLSocketFactory(acceptingTrustStrategy, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); clientConfig.getApacheHttpClientConfig().withSslSocketFactory(sf); s3Service.setEndpoint(s3Target); } s3Service.listBuckets(); return true; }
From source file:com.cloud.hypervisor.hyperv.resource.HypervDirectConnectResource.java
public static String postHttpRequest(final String jsonCmd, final URI agentUri) { // Using Apache's HttpClient for HTTP POST // Java-only approach discussed at on StackOverflow concludes with // comment to use Apache HttpClient // http://stackoverflow.com/a/2793153/939250, but final comment is to // use Apache. String logMessage = StringEscapeUtils.unescapeJava(jsonCmd); logMessage = cleanPassword(logMessage); s_logger.debug("POST request to " + agentUri.toString() + " with contents " + logMessage); // Create request HttpClient httpClient = null;// w ww .j ava 2 s . c om final TrustStrategy easyStrategy = new TrustStrategy() { @Override public boolean isTrusted(final X509Certificate[] chain, final String authType) throws CertificateException { return true; } }; try { final SSLSocketFactory sf = new SSLSocketFactory(easyStrategy, new AllowAllHostnameVerifier()); final SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("https", DEFAULT_AGENT_PORT, sf)); final ClientConnectionManager ccm = new BasicClientConnectionManager(registry); httpClient = new DefaultHttpClient(ccm); } catch (final KeyManagementException e) { s_logger.error("failed to initialize http client " + e.getMessage()); } catch (final UnrecoverableKeyException e) { s_logger.error("failed to initialize http client " + e.getMessage()); } catch (final NoSuchAlgorithmException e) { s_logger.error("failed to initialize http client " + e.getMessage()); } catch (final KeyStoreException e) { s_logger.error("failed to initialize http client " + e.getMessage()); } String result = null; // TODO: are there timeout settings and worker thread settings to tweak? try { final HttpPost request = new HttpPost(agentUri); // JSON encode command // Assumes command sits comfortably in a string, i.e. not used for // large data transfers final StringEntity cmdJson = new StringEntity(jsonCmd); request.addHeader("content-type", "application/json"); request.setEntity(cmdJson); s_logger.debug("Sending cmd to " + agentUri.toString() + " cmd data:" + logMessage); final HttpResponse response = httpClient.execute(request); // Unsupported commands will not route. if (response.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_FOUND) { final String errMsg = "Failed to send : HTTP error code : " + response.getStatusLine().getStatusCode(); s_logger.error(errMsg); final String unsupportMsg = "Unsupported command " + agentUri.getPath() + ". Are you sure you got the right type of" + " server?"; final Answer ans = new UnsupportedAnswer(null, unsupportMsg); s_logger.error(ans); result = s_gson.toJson(new Answer[] { ans }); } else if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { final String errMsg = "Failed send to " + agentUri.toString() + " : HTTP error code : " + response.getStatusLine().getStatusCode(); s_logger.error(errMsg); return null; } else { result = EntityUtils.toString(response.getEntity()); final String logResult = cleanPassword(StringEscapeUtils.unescapeJava(result)); s_logger.debug("POST response is " + logResult); } } catch (final ClientProtocolException protocolEx) { // Problem with HTTP message exchange s_logger.error(protocolEx); } catch (final IOException connEx) { // Problem with underlying communications s_logger.error(connEx); } finally { httpClient.getConnectionManager().shutdown(); } return result; }
From source file:nl.opengeogroep.safetymaps.routing.service.OpenRouteService.java
private static CloseableHttpClient getClient() throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException { return HttpClients.custom().setHostnameVerifier(new AllowAllHostnameVerifier()) .setSslcontext(new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() { @Override/*from w ww . j a v a 2 s.com*/ public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { return true; } }).build()) .setDefaultRequestConfig( RequestConfig.custom().setConnectTimeout(5 * 1000).setSocketTimeout(10 * 1000).build()) .build(); }