Change HTTP Requests into HTTPS Ones
[holmes/common.git] / holmes-actions / src / main / java / org / onap / holmes / common / utils / HttpsUtils.java
1 /**
2  * Copyright 2017 ZTE Corporation.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
5  * in compliance with the License. You may obtain a copy of the License at
6  *
7  * http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software distributed under the License
10  * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
11  * or implied. See the License for the specific language governing permissions and limitations under
12  * the License.
13  */
14
15 package org.onap.holmes.common.utils;
16
17 import java.io.IOException;
18 import java.security.cert.CertificateException;
19 import java.security.cert.X509Certificate;
20 import java.util.ArrayList;
21 import java.util.List;
22 import java.util.Map;
23 import lombok.extern.slf4j.Slf4j;
24 import org.apache.http.Consts;
25 import org.apache.http.HttpEntity;
26 import org.apache.http.HttpResponse;
27 import org.apache.http.HttpStatus;
28 import org.apache.http.NameValuePair;
29 import org.apache.http.client.config.RequestConfig;
30 import org.apache.http.client.entity.UrlEncodedFormEntity;
31 import org.apache.http.client.methods.HttpDelete;
32 import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
33 import org.apache.http.client.methods.HttpGet;
34 import org.apache.http.client.methods.HttpPost;
35 import org.apache.http.client.methods.HttpPut;
36 import org.apache.http.client.methods.HttpRequestBase;
37 import org.apache.http.config.Registry;
38 import org.apache.http.config.RegistryBuilder;
39 import org.apache.http.conn.socket.ConnectionSocketFactory;
40 import org.apache.http.conn.socket.PlainConnectionSocketFactory;
41 import org.apache.http.conn.ssl.NoopHostnameVerifier;
42 import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
43 import org.apache.http.conn.ssl.TrustStrategy;
44 import org.apache.http.impl.client.CloseableHttpClient;
45 import org.apache.http.impl.client.HttpClients;
46 import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
47 import org.apache.http.message.BasicNameValuePair;
48 import org.apache.http.ssl.SSLContextBuilder;
49 import org.apache.http.util.EntityUtils;
50 import org.jvnet.hk2.annotations.Service;
51 import org.onap.holmes.common.exception.CorrelationException;
52
53 @Slf4j
54 @Service
55 public class HttpsUtils {
56     private static final String HTTP = "http";
57     private static final String HTTPS = "https";
58     private static final int DEFUALT_TIMEOUT = 30000;
59     private static SSLConnectionSocketFactory sslConnectionSocketFactory = null;
60     private static PoolingHttpClientConnectionManager connectionManager = null;
61     private static SSLContextBuilder sslContextBuilder = null;
62
63     static{
64         try {
65             sslContextBuilder = new SSLContextBuilder();
66             sslContextBuilder.loadTrustMaterial(null, new TrustStrategy() {
67                 public boolean isTrusted(X509Certificate[] x509Certificates, String s)
68                         throws CertificateException {
69                     return true;
70                 }
71             });
72             sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContextBuilder.build(),
73                     new String[]{"SSLv2Hello", "SSLv3", "TLSv1", "TLSv1.2"}, null,
74                     NoopHostnameVerifier.INSTANCE);
75             Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
76                     .register(HTTP, new PlainConnectionSocketFactory())
77                     .register(HTTPS, sslConnectionSocketFactory)
78                     .build();
79             connectionManager = new PoolingHttpClientConnectionManager(registry);
80             connectionManager.setMaxTotal(200);
81         } catch (Exception e) {
82             log.error("Failed to initialize the ssl builder: " + e.getMessage(), e);
83         }
84     }
85
86     public static HttpResponse post(String url, Map<String, String> header, Map<String, String> param,
87             HttpEntity entity) throws CorrelationException {
88         return post(url, header, param, entity, DEFUALT_TIMEOUT);
89     }
90
91     public static HttpResponse post(String url, Map<String, String> header, Map<String, String> param,
92             HttpEntity entity, int timeout) throws CorrelationException {
93         HttpResponse response;
94         HttpPost httpPost = new HttpPost(url);
95         try {
96             CloseableHttpClient httpClient = getHttpClient(timeout);
97             addHeaders(header, httpPost);
98             addParams(param, httpPost);
99             if (entity != null) {
100                 httpPost.setEntity(entity);
101             }
102             response = executeRequest(httpClient, httpPost);
103         } catch (Exception e) {
104             throw new CorrelationException("Failed to query data from server through POST method!");
105         }
106         return response;
107     }
108
109     public static HttpResponse put(String url, Map<String, String> header, Map<String, String> param,
110             HttpEntity entity) throws CorrelationException {
111         return put(url, header, param, entity, DEFUALT_TIMEOUT);
112     }
113
114     public static HttpResponse put(String url, Map<String, String> header, Map<String, String> param,
115             HttpEntity entity, int timeout) throws CorrelationException {
116         HttpResponse response;
117         HttpPut httpPut = new HttpPut(url);
118         try {
119             CloseableHttpClient httpClient = getHttpClient(timeout);
120             addHeaders(header, httpPut);
121             addParams(param, httpPut);
122             if (entity != null) {
123                 httpPut.setEntity(entity);
124             }
125             response = executeRequest(httpClient, httpPut);
126         } catch (Exception e) {
127             throw new CorrelationException("Failed to query data from server through PUT method!");
128         }
129         return response;
130     }
131
132     public static HttpResponse get(String url, Map<String, String> header) throws CorrelationException {
133         return get(url, header, DEFUALT_TIMEOUT);
134     }
135
136     public static HttpResponse get(String url, Map<String, String> header, int timeout) throws CorrelationException {
137         HttpResponse response;
138         HttpGet httpGet = new HttpGet(url);
139         try {
140             CloseableHttpClient httpClient = getHttpClient(timeout);
141             addHeaders(header, httpGet);
142             response = executeRequest(httpClient, httpGet);
143         } catch (Exception e) {
144             throw new CorrelationException("Failed to query data from server through GET method!");
145         }
146         return response;
147     }
148
149     public static HttpResponse delete(String url, Map<String, String> header) throws CorrelationException {
150         return delete(url, header, DEFUALT_TIMEOUT);
151     }
152
153     public static HttpResponse delete(String url, Map<String, String> header, int timeout) throws CorrelationException {
154         HttpResponse response;
155         HttpDelete httpDelete = new HttpDelete(url);
156         try {
157             CloseableHttpClient httpClient = getHttpClient(timeout);
158             addHeaders(header, httpDelete);
159             response = executeRequest(httpClient, httpDelete);
160         } catch (Exception e) {
161             throw new CorrelationException("Failed to query data from server through DELETE method!");
162         }
163         return response;
164     }
165
166     private static void addParams(Map<String, String> param, HttpEntityEnclosingRequestBase requestBase) {
167         if (!param.isEmpty()) {
168             List<NameValuePair> formparams = new ArrayList<>();
169             for (Map.Entry<String, String> entry : param.entrySet()) {
170                 formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
171             }
172             UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(formparams,
173                     Consts.UTF_8);
174             requestBase.setEntity(urlEncodedFormEntity);
175         }
176     }
177
178     private static HttpRequestBase addHeaders(Map<String, String> header, HttpRequestBase httpRequestBase) {
179         if (!header.isEmpty()) {
180             for (Map.Entry<String, String> entry : header.entrySet()) {
181                 httpRequestBase.addHeader(entry.getKey(), entry.getValue());
182             }
183         }
184         return httpRequestBase;
185     }
186
187     public static String extractResponseEntity(HttpResponse httpResponse)
188             throws CorrelationException, IOException {
189         String result = "";
190         if (httpResponse != null) {
191             int statusCode = httpResponse.getStatusLine().getStatusCode();
192             if (statusCode == HttpStatus.SC_OK) {
193                 HttpEntity resEntity = httpResponse.getEntity();
194                 result = EntityUtils.toString(resEntity);
195             } else {
196                 throw new CorrelationException("Get a error status from server : " + statusCode);
197             }
198         }
199         return result;
200     }
201
202     private static HttpResponse executeRequest(CloseableHttpClient httpClient, HttpRequestBase httpRequest)
203             throws Exception {
204         HttpResponse httpResponse;
205         try {
206             httpResponse = httpClient.execute(httpRequest);
207         } catch (Exception e) {
208             throw new CorrelationException("Failed to get data from server");
209         } finally {
210             if (httpRequest != null) {
211                 httpRequest.releaseConnection();
212             }
213             if (httpClient != null) {
214                 httpClient.close();
215             }
216         }
217         return httpResponse;
218     }
219
220     private static CloseableHttpClient getHttpClient(int timeout) throws Exception {
221         RequestConfig defaultRequestConfig = RequestConfig.custom()
222                 .setSocketTimeout(timeout)
223                 .setConnectTimeout(timeout)
224                 .setConnectionRequestTimeout(timeout)
225                 .build();
226         CloseableHttpClient httpClient = HttpClients.custom()
227                 .setDefaultRequestConfig(defaultRequestConfig)
228                 .setSSLSocketFactory(sslConnectionSocketFactory)
229                 .setConnectionManager(connectionManager)
230                 .setConnectionManagerShared(true)
231                 .build();
232         return httpClient;
233     }
234 }