2aa569524ec0d8c5d0e21622c7409771f73bf1f2
[holmes/common.git] / holmes-actions / src / main / java / org / onap / holmes / common / utils / HttpsUtils.java
1 /**
2  * Copyright 2017 ZTE Corporation.
3  * <p>
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  * <p>
7  * http://www.apache.org/licenses/LICENSE-2.0
8  * <p>
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.HashMap;
22 import java.util.List;
23 import java.util.Map;
24
25 import lombok.extern.slf4j.Slf4j;
26 import org.apache.http.Consts;
27 import org.apache.http.HttpEntity;
28 import org.apache.http.HttpResponse;
29 import org.apache.http.HttpStatus;
30 import org.apache.http.NameValuePair;
31 import org.apache.http.client.config.RequestConfig;
32 import org.apache.http.client.entity.UrlEncodedFormEntity;
33 import org.apache.http.client.methods.HttpDelete;
34 import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
35 import org.apache.http.client.methods.HttpGet;
36 import org.apache.http.client.methods.HttpPost;
37 import org.apache.http.client.methods.HttpPut;
38 import org.apache.http.client.methods.HttpRequestBase;
39 import org.apache.http.config.Registry;
40 import org.apache.http.config.RegistryBuilder;
41 import org.apache.http.conn.socket.ConnectionSocketFactory;
42 import org.apache.http.conn.socket.PlainConnectionSocketFactory;
43 import org.apache.http.conn.ssl.NoopHostnameVerifier;
44 import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
45 import org.apache.http.conn.ssl.TrustStrategy;
46 import org.apache.http.impl.client.CloseableHttpClient;
47 import org.apache.http.impl.client.HttpClientBuilder;
48 import org.apache.http.impl.client.HttpClients;
49 import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
50 import org.apache.http.message.BasicNameValuePair;
51 import org.apache.http.ssl.SSLContextBuilder;
52 import org.apache.http.util.EntityUtils;
53 import org.jvnet.hk2.annotations.Service;
54 import org.onap.holmes.common.config.MicroServiceConfig;
55 import org.onap.holmes.common.exception.CorrelationException;
56
57 @Slf4j
58 @Service
59 public class HttpsUtils {
60     private static final String HTTP = "http";
61     private static final String HTTPS = "https";
62     private static SSLConnectionSocketFactory sslConnectionSocketFactory = null;
63     private static PoolingHttpClientConnectionManager connectionManager = null;
64     private static SSLContextBuilder sslContextBuilder = null;
65     public static final int DEFUALT_TIMEOUT = 30000;
66
67     static {
68         try {
69             sslContextBuilder = new SSLContextBuilder();
70             sslContextBuilder.loadTrustMaterial(null, new TrustStrategy() {
71                 public boolean isTrusted(X509Certificate[] x509Certificates, String s)
72                         throws CertificateException {
73                     return true;
74                 }
75             });
76             sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContextBuilder.build(),
77                     new String[]{"SSLv3", "TLSv1", "TLSv1.2"}, null,
78                     NoopHostnameVerifier.INSTANCE);
79             Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
80                     .register(HTTP, new PlainConnectionSocketFactory())
81                     .register(HTTPS, sslConnectionSocketFactory)
82                     .build();
83             connectionManager = new PoolingHttpClientConnectionManager(registry);
84             connectionManager.setMaxTotal(200);
85         } catch (Exception e) {
86             log.error("Failed to initialize the ssl builder: " + e.getMessage(), e);
87         }
88     }
89
90     public static HttpResponse get(HttpGet httpGet, Map<String, String> header, CloseableHttpClient httpClient) throws CorrelationException {
91         return getGetAndDeleteResponse(httpGet, header, httpClient);
92     }
93
94     public static HttpResponse post(HttpPost httpPost, Map<String, String> header, Map<String, String> param,
95                                     HttpEntity entity, CloseableHttpClient httpClient) throws CorrelationException {
96         return getPostAndPutResponse(httpPost, header, param, entity, httpClient);
97     }
98
99     public static HttpResponse put(HttpPut httpPut, Map<String, String> header, Map<String, String> param,
100                                    HttpEntity entity, CloseableHttpClient httpClient) throws CorrelationException {
101         return getPostAndPutResponse(httpPut, header, param, entity, httpClient);
102     }
103
104     public static HttpResponse delete(HttpDelete httpDelete, Map<String, String> header, CloseableHttpClient httpClient) throws CorrelationException {
105         return getGetAndDeleteResponse(httpDelete, header, httpClient);
106     }
107
108     private static void addParams(Map<String, String> param, HttpEntityEnclosingRequestBase requestBase) {
109         if (!param.isEmpty()) {
110             List<NameValuePair> formparams = new ArrayList<>();
111             for (Map.Entry<String, String> entry : param.entrySet()) {
112                 formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
113             }
114             UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(formparams,
115                     Consts.UTF_8);
116             requestBase.setEntity(urlEncodedFormEntity);
117         }
118     }
119
120     private static HttpRequestBase addHeaders(Map<String, String> header, HttpRequestBase httpRequestBase) {
121         if (!header.isEmpty()) {
122             for (Map.Entry<String, String> entry : header.entrySet()) {
123                 httpRequestBase.addHeader(entry.getKey(), entry.getValue());
124             }
125         }
126         return httpRequestBase;
127     }
128
129     private static HttpResponse getPostAndPutResponse(HttpEntityEnclosingRequestBase requestBase,
130                                                       Map<String, String> header, Map<String, String> param, HttpEntity entity,
131                                                       CloseableHttpClient httpClient) throws CorrelationException {
132         try {
133             addHeaders(header, requestBase);
134             addParams(param, requestBase);
135             if (entity != null) {
136                 requestBase.setEntity(entity);
137             }
138             return executeRequest(httpClient, requestBase);
139         } catch (Exception e) {
140             throw new CorrelationException("Failed to connect to server", e);
141         }
142     }
143
144     private static HttpResponse getGetAndDeleteResponse(HttpRequestBase requestBase,
145                                                         Map<String, String> header, CloseableHttpClient httpClient) throws CorrelationException {
146         try {
147             addHeaders(header, requestBase);
148             return executeRequest(httpClient, requestBase);
149         } catch (Exception e) {
150             throw new CorrelationException("Failed to connect to server", e);
151         }
152     }
153
154     public static String extractResponseEntity(HttpResponse httpResponse)
155             throws CorrelationException, IOException {
156         String result = "";
157         if (httpResponse != null) {
158             int statusCode = httpResponse.getStatusLine().getStatusCode();
159             if (statusCode == HttpStatus.SC_OK) {
160                 HttpEntity resEntity = httpResponse.getEntity();
161                 result = EntityUtils.toString(resEntity);
162             } else {
163                 throw new CorrelationException("Get an error status from server : " + statusCode);
164             }
165         }
166         return result;
167     }
168
169     private static HttpResponse executeRequest(CloseableHttpClient httpClient, HttpRequestBase httpRequest)
170             throws CorrelationException, IOException {
171         HttpResponse httpResponse;
172         try {
173             httpResponse = httpClient.execute(httpRequest);
174         } catch (Exception e) {
175             throw new CorrelationException("Failed to get data from server", e);
176         }
177         return httpResponse;
178     }
179
180     public static CloseableHttpClient getConditionalHttpsClient(int timeout) {
181         HttpClientBuilder builder = getHttpClientBuilder(timeout);
182         if (isHttpsEnabled()) {
183             builder.setSSLSocketFactory(sslConnectionSocketFactory);
184         }
185
186         return builder.build();
187     }
188
189     public static CloseableHttpClient getHttpsClient(int timeout) {
190         HttpClientBuilder builder = getHttpClientBuilder(timeout);
191         return builder.setSSLSocketFactory(sslConnectionSocketFactory).build();
192     }
193
194     private static HttpClientBuilder getHttpClientBuilder(int timeout) {
195         RequestConfig defaultRequestConfig = RequestConfig.custom()
196                 .setSocketTimeout(timeout)
197                 .setConnectTimeout(timeout)
198                 .setConnectionRequestTimeout(timeout)
199                 .build();
200
201         return HttpClients.custom()
202                 .setDefaultRequestConfig(defaultRequestConfig)
203                 .setConnectionManager(connectionManager)
204                 .setConnectionManagerShared(true);
205     }
206
207     public static boolean isHttpsEnabled() {
208         return Boolean.valueOf(MicroServiceConfig.getEnv("ENABLE_ENCRYPT"));
209     }
210 }