use of org.apache.http.conn.ssl.TrustStrategy in project irontest by zheng-wang.
the class SOAPTeststepRunner method run.
protected BasicTeststepRun run(Teststep teststep) throws Exception {
BasicTeststepRun basicTeststepRun = new BasicTeststepRun();
Endpoint endpoint = teststep.getEndpoint();
// set request HTTP headers
HttpPost httpPost = new HttpPost(endpoint.getUrl());
SOAPTeststepProperties otherProperties = (SOAPTeststepProperties) teststep.getOtherProperties();
if (otherProperties != null) {
for (HTTPHeader httpHeader : otherProperties.getHttpHeaders()) {
httpPost.setHeader(httpHeader.getName(), httpHeader.getValue());
}
}
// set HTTP basic auth
if (!"".equals(StringUtils.trimToEmpty(endpoint.getUsername()))) {
String auth = endpoint.getUsername() + ":" + getDecryptedEndpointPassword();
String encodedAuth = Base64.encodeBase64String(auth.getBytes());
String authHeader = "Basic " + encodedAuth;
httpPost.setHeader(HttpHeaders.AUTHORIZATION, authHeader);
}
// set request HTTP body
httpPost.setEntity(new StringEntity((String) teststep.getRequest(), "UTF-8"));
final SOAPAPIResponse apiResponse = new SOAPAPIResponse();
ResponseHandler<Void> responseHandler = new ResponseHandler<Void>() {
public Void handleResponse(final HttpResponse httpResponse) throws IOException {
LOGGER.info(httpResponse.toString());
apiResponse.getHttpHeaders().add(new HTTPHeader("*Status-Line*", httpResponse.getStatusLine().toString()));
Header[] headers = httpResponse.getAllHeaders();
for (Header header : headers) {
apiResponse.getHttpHeaders().add(new HTTPHeader(header.getName(), header.getValue()));
}
HttpEntity entity = httpResponse.getEntity();
apiResponse.setHttpBody(entity != null ? EntityUtils.toString(entity) : null);
return null;
}
};
// build HTTP Client instance
// trust all SSL certificates
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(new TrustStrategy() {
public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
return true;
}
}).build();
HttpClient httpClient = HttpClients.custom().setSSLContext(sslContext).build();
// invoke the web service
httpClient.execute(httpPost, responseHandler);
basicTeststepRun.setResponse(apiResponse);
return basicTeststepRun;
}
use of org.apache.http.conn.ssl.TrustStrategy in project openhab1-addons by openhab.
the class Util method getConnection.
public static Sardine getConnection(CalDavConfig config) {
if (config.isDisableCertificateVerification()) {
if (config.getUrl().startsWith(HTTP_URL_PREFIX)) {
log.error("do not use '{}' if no ssl is used", CalDavLoaderImpl.PROP_DISABLE_CERTIFICATE_VERIFICATION);
}
log.trace("connecting to caldav '{}' with disabled certificate verification (url={}, username={}, password={})", config.getKey(), config.getUrl(), config.getUsername(), config.getPassword());
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create().setHostnameVerifier(new AllowAllHostnameVerifier());
try {
httpClientBuilder.setSslcontext(new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
return true;
}
}).build());
} catch (KeyManagementException e) {
log.error("error verifying certificate", e);
} catch (NoSuchAlgorithmException e) {
log.error("error verifying certificate", e);
} catch (KeyStoreException e) {
log.error("error verifying certificate", e);
}
if (StringUtils.isEmpty(config.getUsername()) && StringUtils.isEmpty(config.getPassword())) {
log.trace("connecting without credentials for '{}'", config.getKey());
return new SardineImpl(httpClientBuilder);
} else {
return new SardineImpl(httpClientBuilder, config.getUsername(), config.getPassword());
}
} else {
log.trace("connecting to caldav '{}' (url={}, username={}, password={})", config.getKey(), config.getUrl(), config.getUsername(), config.getPassword());
if (StringUtils.isEmpty(config.getUsername()) && StringUtils.isEmpty(config.getPassword())) {
log.trace("connecting without credentials for '{}'", config.getKey());
return new SardineImpl();
} else {
return new SardineImpl(config.getUsername(), config.getPassword());
}
}
}
use of org.apache.http.conn.ssl.TrustStrategy in project ats-framework by Axway.
the class HttpClient method setupSSL.
/**
* Setup SSL. Pass the trusted certificates and client private key and certificate,
* if applicable.
*
* @param httpClientBuilder The client builder
* @throws HttpException
*/
private void setupSSL(HttpClientBuilder httpClientBuilder) throws HttpException {
try {
SSLContextBuilder sslContextBuilder = SSLContexts.custom();
sslContextBuilder.loadTrustMaterial(convertToKeyStore(trustedServerCertificates), new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
return checkIsTrusted(chain);
}
});
if (clientSSLKeyStore != null) {
sslContextBuilder.loadKeyMaterial(clientSSLKeyStore, "".toCharArray());
}
SSLContext sslContext = sslContextBuilder.build();
// Allow all supported protocols
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, supportedProtocols, supportedCipherSuites, new NoopHostnameVerifier());
httpClientBuilder.setSSLSocketFactory(sslsf);
} catch (Exception e) {
throw new HttpException("Exception occurred when setting up SSL.", e);
}
}
use of org.apache.http.conn.ssl.TrustStrategy in project chassis by Kixeye.
the class HttpTransportTest method testHttpServiceWithJsonWithHTTPS.
@Test
public void testHttpServiceWithJsonWithHTTPS() throws Exception {
Map<String, Object> properties = new HashMap<String, Object>();
properties.put("https.enabled", "true");
properties.put("https.port", "" + SocketUtils.findAvailableTcpPort());
properties.put("https.hostname", "localhost");
properties.put("https.selfSigned", "true");
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
StandardEnvironment environment = new StandardEnvironment();
environment.getPropertySources().addFirst(new MapPropertySource("default", properties));
context.setEnvironment(environment);
context.register(PropertySourcesPlaceholderConfigurer.class);
context.register(TransportConfiguration.class);
context.register(TestRestService.class);
try {
context.refresh();
final MessageSerDe serDe = context.getBean(JsonJacksonMessageSerDe.class);
SSLContextBuilder builder = SSLContexts.custom();
builder.loadTrustMaterial(null, new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
return true;
}
});
SSLContext sslContext = builder.build();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new X509HostnameVerifier() {
@Override
public void verify(String host, SSLSocket ssl) throws IOException {
}
@Override
public void verify(String host, X509Certificate cert) throws SSLException {
}
@Override
public void verify(String host, String[] cns, String[] subjectAlts) throws SSLException {
}
@Override
public boolean verify(String s, SSLSession sslSession) {
return true;
}
});
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create().register("https", sslsf).build();
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
requestFactory.setHttpClient(HttpClients.custom().setConnectionManager(cm).build());
RestTemplate httpClient = new RestTemplate(requestFactory);
httpClient.setErrorHandler(new ResponseErrorHandler() {
public boolean hasError(ClientHttpResponse response) throws IOException {
return response.getRawStatusCode() == HttpStatus.OK.value();
}
public void handleError(ClientHttpResponse response) throws IOException {
}
});
httpClient.setInterceptors(Lists.newArrayList(LOGGING_INTERCEPTOR));
httpClient.setMessageConverters(new ArrayList<HttpMessageConverter<?>>(Lists.newArrayList(new SerDeHttpMessageConverter(serDe))));
TestObject response = httpClient.getForObject(new URI("https://localhost:" + properties.get("https.port") + "/stuff/"), TestObject.class);
Assert.assertNotNull(response);
Assert.assertEquals("stuff", response.value);
response = httpClient.postForObject(new URI("https://localhost:" + properties.get("https.port") + "/stuff/"), new TestObject("more stuff"), TestObject.class);
Assert.assertNotNull(response);
Assert.assertEquals("stuff", response.value);
response = httpClient.getForObject(new URI("https://localhost:" + properties.get("https.port") + "/stuff/"), TestObject.class);
Assert.assertNotNull(response);
Assert.assertEquals("more stuff", response.value);
response = httpClient.getForObject(new URI("https://localhost:" + properties.get("https.port") + "/stuff/getFuture"), TestObject.class);
Assert.assertNotNull(response);
Assert.assertEquals("more stuff", response.value);
response = httpClient.getForObject(new URI("https://localhost:" + properties.get("https.port") + "/stuff/getObservable"), TestObject.class);
Assert.assertNotNull(response);
Assert.assertEquals("more stuff", response.value);
ResponseEntity<ServiceError> error = httpClient.postForEntity(new URI("https://localhost:" + properties.get("https.port") + "/stuff/"), new TestObject(RandomStringUtils.randomAlphabetic(100)), ServiceError.class);
Assert.assertNotNull(response);
Assert.assertEquals(HttpStatus.BAD_REQUEST, error.getStatusCode());
Assert.assertEquals(ExceptionServiceErrorMapper.VALIDATION_ERROR_CODE, error.getBody().code);
error = httpClient.getForEntity(new URI("https://localhost:" + properties.get("https.port") + "/stuff/expectedError"), ServiceError.class);
Assert.assertNotNull(response);
Assert.assertEquals(TestRestService.EXPECTED_EXCEPTION_HTTP_CODE, error.getStatusCode());
Assert.assertEquals(TestRestService.EXPECTED_EXCEPTION.code, error.getBody().code);
Assert.assertEquals(TestRestService.EXPECTED_EXCEPTION.description, error.getBody().description);
error = httpClient.getForEntity(new URI("https://localhost:" + properties.get("https.port") + "/stuff/unexpectedError"), ServiceError.class);
Assert.assertNotNull(response);
Assert.assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, error.getStatusCode());
Assert.assertEquals(ExceptionServiceErrorMapper.UNKNOWN_ERROR_CODE, error.getBody().code);
} finally {
context.close();
}
}
use of org.apache.http.conn.ssl.TrustStrategy in project chassis by Kixeye.
the class HttpTransportTest method testHttpServiceWithJsonWithHTTPSAndHTTP.
@Test
public void testHttpServiceWithJsonWithHTTPSAndHTTP() throws Exception {
Map<String, Object> properties = new HashMap<String, Object>();
properties.put("http.enabled", "true");
properties.put("http.port", "" + SocketUtils.findAvailableTcpPort());
properties.put("http.hostname", "localhost");
properties.put("https.enabled", "true");
properties.put("https.port", "" + SocketUtils.findAvailableTcpPort());
properties.put("https.hostname", "localhost");
properties.put("https.selfSigned", "true");
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
StandardEnvironment environment = new StandardEnvironment();
environment.getPropertySources().addFirst(new MapPropertySource("default", properties));
context.setEnvironment(environment);
context.register(PropertySourcesPlaceholderConfigurer.class);
context.register(TransportConfiguration.class);
context.register(TestRestService.class);
try {
context.refresh();
final MessageSerDe serDe = context.getBean(JsonJacksonMessageSerDe.class);
SSLContextBuilder builder = SSLContexts.custom();
builder.loadTrustMaterial(null, new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
return true;
}
});
SSLContext sslContext = builder.build();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new X509HostnameVerifier() {
@Override
public void verify(String host, SSLSocket ssl) throws IOException {
}
@Override
public void verify(String host, X509Certificate cert) throws SSLException {
}
@Override
public void verify(String host, String[] cns, String[] subjectAlts) throws SSLException {
}
@Override
public boolean verify(String s, SSLSession sslSession) {
return true;
}
});
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create().register("https", sslsf).register("http", new PlainConnectionSocketFactory()).build();
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
requestFactory.setHttpClient(HttpClients.custom().setConnectionManager(cm).build());
RestTemplate httpClient = new RestTemplate(requestFactory);
httpClient.setErrorHandler(new ResponseErrorHandler() {
public boolean hasError(ClientHttpResponse response) throws IOException {
return response.getRawStatusCode() == HttpStatus.OK.value();
}
public void handleError(ClientHttpResponse response) throws IOException {
}
});
httpClient.setInterceptors(Lists.newArrayList(LOGGING_INTERCEPTOR));
httpClient.setMessageConverters(new ArrayList<HttpMessageConverter<?>>(Lists.newArrayList(new SerDeHttpMessageConverter(serDe))));
TestObject response = httpClient.getForObject(new URI("https://localhost:" + properties.get("https.port") + "/stuff/"), TestObject.class);
Assert.assertNotNull(response);
Assert.assertEquals("stuff", response.value);
response = httpClient.postForObject(new URI("https://localhost:" + properties.get("https.port") + "/stuff/"), new TestObject("more stuff"), TestObject.class);
Assert.assertNotNull(response);
Assert.assertEquals("stuff", response.value);
response = httpClient.getForObject(new URI("https://localhost:" + properties.get("https.port") + "/stuff/"), TestObject.class);
Assert.assertNotNull(response);
Assert.assertEquals("more stuff", response.value);
response = httpClient.getForObject(new URI("https://localhost:" + properties.get("https.port") + "/stuff/getFuture"), TestObject.class);
Assert.assertNotNull(response);
Assert.assertEquals("more stuff", response.value);
response = httpClient.getForObject(new URI("https://localhost:" + properties.get("https.port") + "/stuff/getObservable"), TestObject.class);
Assert.assertNotNull(response);
Assert.assertEquals("more stuff", response.value);
ResponseEntity<ServiceError> error = httpClient.postForEntity(new URI("https://localhost:" + properties.get("https.port") + "/stuff/"), new TestObject(RandomStringUtils.randomAlphabetic(100)), ServiceError.class);
Assert.assertNotNull(response);
Assert.assertEquals(HttpStatus.BAD_REQUEST, error.getStatusCode());
Assert.assertEquals(ExceptionServiceErrorMapper.VALIDATION_ERROR_CODE, error.getBody().code);
error = httpClient.getForEntity(new URI("https://localhost:" + properties.get("https.port") + "/stuff/expectedError"), ServiceError.class);
Assert.assertNotNull(response);
Assert.assertEquals(TestRestService.EXPECTED_EXCEPTION_HTTP_CODE, error.getStatusCode());
Assert.assertEquals(TestRestService.EXPECTED_EXCEPTION.code, error.getBody().code);
Assert.assertEquals(TestRestService.EXPECTED_EXCEPTION.description, error.getBody().description);
error = httpClient.getForEntity(new URI("https://localhost:" + properties.get("https.port") + "/stuff/unexpectedError"), ServiceError.class);
Assert.assertNotNull(response);
Assert.assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, error.getStatusCode());
Assert.assertEquals(ExceptionServiceErrorMapper.UNKNOWN_ERROR_CODE, error.getBody().code);
response = httpClient.getForObject(new URI("http://localhost:" + properties.get("http.port") + "/stuff/"), TestObject.class);
Assert.assertNotNull(response);
Assert.assertEquals("more stuff", response.value);
response = httpClient.postForObject(new URI("http://localhost:" + properties.get("http.port") + "/stuff/"), new TestObject("stuff"), TestObject.class);
Assert.assertNotNull(response);
Assert.assertEquals("more stuff", response.value);
response = httpClient.getForObject(new URI("http://localhost:" + properties.get("http.port") + "/stuff/"), TestObject.class);
Assert.assertNotNull(response);
Assert.assertEquals("stuff", response.value);
response = httpClient.getForObject(new URI("http://localhost:" + properties.get("http.port") + "/stuff/getFuture"), TestObject.class);
Assert.assertNotNull(response);
Assert.assertEquals("stuff", response.value);
response = httpClient.getForObject(new URI("http://localhost:" + properties.get("http.port") + "/stuff/getObservable"), TestObject.class);
Assert.assertNotNull(response);
Assert.assertEquals("stuff", response.value);
error = httpClient.postForEntity(new URI("http://localhost:" + properties.get("http.port") + "/stuff/"), new TestObject(RandomStringUtils.randomAlphabetic(100)), ServiceError.class);
Assert.assertNotNull(response);
Assert.assertEquals(HttpStatus.BAD_REQUEST, error.getStatusCode());
Assert.assertEquals(ExceptionServiceErrorMapper.VALIDATION_ERROR_CODE, error.getBody().code);
error = httpClient.getForEntity(new URI("http://localhost:" + properties.get("http.port") + "/stuff/expectedError"), ServiceError.class);
Assert.assertNotNull(response);
Assert.assertEquals(TestRestService.EXPECTED_EXCEPTION_HTTP_CODE, error.getStatusCode());
Assert.assertEquals(TestRestService.EXPECTED_EXCEPTION.code, error.getBody().code);
Assert.assertEquals(TestRestService.EXPECTED_EXCEPTION.description, error.getBody().description);
error = httpClient.getForEntity(new URI("http://localhost:" + properties.get("http.port") + "/stuff/unexpectedError"), ServiceError.class);
Assert.assertNotNull(response);
Assert.assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, error.getStatusCode());
Assert.assertEquals(ExceptionServiceErrorMapper.UNKNOWN_ERROR_CODE, error.getBody().code);
} finally {
context.close();
}
}
Aggregations