fix https bug
[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 SSLConnectionSocketFactory sslConnectionSocketFactory = null;
59     private static PoolingHttpClientConnectionManager connectionManager = null;
60     private static SSLContextBuilder sslContextBuilder = null;
61     public static final int DEFUALT_TIMEOUT = 30000;
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[]{"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, CloseableHttpClient httpClient) throws CorrelationException {
88         HttpResponse response;
89         HttpPost httpPost = new HttpPost(url);
90         try {
91             addHeaders(header, httpPost);
92             addParams(param, httpPost);
93             if (entity != null) {
94                 httpPost.setEntity(entity);
95             }
96             response = executeRequest(httpClient, httpPost);
97         } catch (Exception e) {
98             throw new CorrelationException("Failed to query data from server through POST method!");
99         }
100         return response;
101     }
102
103     public static HttpResponse put(String url, Map<String, String> header, Map<String, String> param,
104             HttpEntity entity, CloseableHttpClient httpClient) throws CorrelationException {
105         HttpResponse response;
106         HttpPut httpPut = new HttpPut(url);
107         try {
108             addHeaders(header, httpPut);
109             addParams(param, httpPut);
110             if (entity != null) {
111                 httpPut.setEntity(entity);
112             }
113             response = executeRequest(httpClient, httpPut);
114         } catch (Exception e) {
115             throw new CorrelationException("Failed to query data from server through PUT method!");
116         }
117         return response;
118     }
119
120     public static HttpResponse get(String url, Map<String, String> header, CloseableHttpClient httpClient) throws CorrelationException {
121         HttpResponse response;
122         HttpGet httpGet = new HttpGet(url);
123         try {
124             addHeaders(header, httpGet);
125             response = executeRequest(httpClient, httpGet);
126         } catch (Exception e) {
127             throw new CorrelationException("Failed to query data from server through GET method!");
128         }
129         return response;
130     }
131
132     public static HttpResponse delete(String url, Map<String, String> header, CloseableHttpClient httpClient) throws CorrelationException {
133         HttpResponse response;
134         HttpDelete httpDelete = new HttpDelete(url);
135         try {
136             addHeaders(header, httpDelete);
137             response = executeRequest(httpClient, httpDelete);
138         } catch (Exception e) {
139             throw new CorrelationException("Failed to query data from server through DELETE method!");
140         }
141         return response;
142     }
143
144     private static void addParams(Map<String, String> param, HttpEntityEnclosingRequestBase requestBase) {
145         if (!param.isEmpty()) {
146             List<NameValuePair> formparams = new ArrayList<>();
147             for (Map.Entry<String, String> entry : param.entrySet()) {
148                 formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
149             }
150             UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(formparams,
151                     Consts.UTF_8);
152             requestBase.setEntity(urlEncodedFormEntity);
153         }
154     }
155
156     private static HttpRequestBase addHeaders(Map<String, String> header, HttpRequestBase httpRequestBase) {
157         if (!header.isEmpty()) {
158             for (Map.Entry<String, String> entry : header.entrySet()) {
159                 httpRequestBase.addHeader(entry.getKey(), entry.getValue());
160             }
161         }
162         return httpRequestBase;
163     }
164
165     public static String extractResponseEntity(HttpResponse httpResponse)
166             throws CorrelationException, IOException {
167         String result = "";
168         if (httpResponse != null) {
169             int statusCode = httpResponse.getStatusLine().getStatusCode();
170             if (statusCode == HttpStatus.SC_OK) {
171                 HttpEntity resEntity = httpResponse.getEntity();
172                 result = EntityUtils.toString(resEntity);
173             } else {
174                 throw new CorrelationException("Get an error status from server : " + statusCode);
175             }
176         }
177         return result;
178     }
179
180     private static HttpResponse executeRequest(CloseableHttpClient httpClient, HttpRequestBase httpRequest)
181             throws CorrelationException, IOException {
182         HttpResponse httpResponse;
183         try {
184             httpResponse = httpClient.execute(httpRequest);
185         } catch (Exception e) {
186             e.printStackTrace();
187             throw new CorrelationException("Failed to get data from server" ,e);
188         } finally {
189             if (httpRequest != null) {
190                 httpRequest.releaseConnection();
191             }
192             if (httpClient != null) {
193                 httpClient.close();
194             }
195         }
196         return httpResponse;
197     }
198
199     public static CloseableHttpClient getHttpClient(int timeout) {
200         RequestConfig defaultRequestConfig = RequestConfig.custom()
201                 .setSocketTimeout(timeout)
202                 .setConnectTimeout(timeout)
203                 .setConnectionRequestTimeout(timeout)
204                 .build();
205         CloseableHttpClient httpClient = HttpClients.custom()
206                 .setDefaultRequestConfig(defaultRequestConfig)
207                 .setSSLSocketFactory(sslConnectionSocketFactory)
208                 .setConnectionManager(connectionManager)
209                 .setConnectionManagerShared(true)
210                 .build();
211         return httpClient;
212     }
213 }