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