Trust any certificate by API tests
[vid.git] / vid-automation / src / main / java / vid / automation / test / utils / InsecureHttpsClient.java
1 package vid.automation.test.utils;
2
3 import javax.net.ssl.SSLContext;
4 import javax.ws.rs.client.Client;
5 import javax.ws.rs.client.ClientBuilder;
6 import org.apache.commons.lang3.exception.ExceptionUtils;
7 import org.apache.http.conn.ssl.NoopHostnameVerifier;
8 import org.apache.http.conn.ssl.TrustAllStrategy;
9 import org.apache.http.impl.client.CloseableHttpClient;
10 import org.apache.http.impl.client.HttpClients;
11 import org.apache.http.ssl.SSLContextBuilder;
12 import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
13 import org.springframework.web.client.RestTemplate;
14
15 public class InsecureHttpsClient {
16
17     public static RestTemplate newRestTemplate() {
18
19         CloseableHttpClient insecureTLSHttpClient = HttpClients.custom()
20             .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
21             .setSSLContext(trustAllCertificates())
22             .build();
23
24         HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(insecureTLSHttpClient);
25         return new RestTemplate(factory);
26     }
27
28     private static SSLContext trustAllCertificates() {
29         try {
30             return new SSLContextBuilder()
31                 .loadTrustMaterial(null, TrustAllStrategy.INSTANCE)
32                 .build();
33         } catch (Exception e) {
34             return ExceptionUtils.rethrow(e);
35         }
36     }
37
38     public static Client newJaxrsClient() {
39         return ClientBuilder.newBuilder()
40             .hostnameVerifier(NoopHostnameVerifier.INSTANCE)
41             .sslContext(trustAllCertificates())
42             .build();
43     }
44
45 }