Add the Stacktrace into the Log
[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.entity.UrlEncodedFormEntity;
30 import org.apache.http.client.methods.HttpGet;
31 import org.apache.http.client.methods.HttpPost;
32 import org.apache.http.client.methods.HttpRequestBase;
33 import org.apache.http.config.Registry;
34 import org.apache.http.config.RegistryBuilder;
35 import org.apache.http.conn.socket.ConnectionSocketFactory;
36 import org.apache.http.conn.socket.PlainConnectionSocketFactory;
37 import org.apache.http.conn.ssl.NoopHostnameVerifier;
38 import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
39 import org.apache.http.conn.ssl.TrustStrategy;
40 import org.apache.http.impl.client.CloseableHttpClient;
41 import org.apache.http.impl.client.HttpClients;
42 import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
43 import org.apache.http.message.BasicNameValuePair;
44 import org.apache.http.ssl.SSLContextBuilder;
45 import org.apache.http.util.EntityUtils;
46 import org.jvnet.hk2.annotations.Service;
47 import org.onap.holmes.common.exception.CorrelationException;
48
49 @Slf4j
50 @Service
51 public class HttpsUtils {
52     private static final String HTTP = "http";
53     private static final String HTTPS = "https";
54     private static SSLConnectionSocketFactory sslConnectionSocketFactory = null;
55     private static PoolingHttpClientConnectionManager connectionManager = null;
56     private static SSLContextBuilder sslContextBuilder = null;
57
58     static{
59         try {
60             sslContextBuilder = new SSLContextBuilder();
61             sslContextBuilder.loadTrustMaterial(null, new TrustStrategy() {
62                 public boolean isTrusted(X509Certificate[] x509Certificates, String s)
63                         throws CertificateException {
64                     return true;
65                 }
66             });
67             sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContextBuilder.build(),
68                     new String[]{"SSLv2Hello", "SSLv3", "TLSv1", "TLSv1.2"}, null,
69                     NoopHostnameVerifier.INSTANCE);
70             Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
71                     .register(HTTP, new PlainConnectionSocketFactory())
72                     .register(HTTPS, sslConnectionSocketFactory)
73                     .build();
74             connectionManager = new PoolingHttpClientConnectionManager(registry);
75             connectionManager.setMaxTotal(200);
76         } catch (Exception e) {
77             log.error("Failed to initialize the ssl builder: " + e.getMessage(), e);
78         }
79     }
80
81     public static String post(String url, Map<String, String> header, Map<String, String> param,
82             HttpEntity entity) throws Exception {
83         HttpResponse httpResponse = null;
84         try {
85             CloseableHttpClient httpClient = getHttpClient();
86             HttpPost httpPost = getHttpPost(url, header, param, entity);
87             httpResponse = getHttpResponse(httpClient, httpPost);
88         } catch (Exception e) {
89             throw new CorrelationException("Failed to use post method query data from server");
90         }
91         return getResponseEntity(httpResponse);
92     }
93
94     public static String get(String url, Map<String, String> header) throws Exception {
95         HttpResponse httpResponse = null;
96         CloseableHttpClient httpClient = null;
97         HttpGet httpGet = null;
98         String response = "";
99         try {
100             httpClient = getHttpClient();
101             httpGet = getHttpGet(url, header);
102             httpResponse = getHttpResponse(httpClient, httpGet);
103             response = getResponseEntity(httpResponse);
104         } catch (Exception e) {
105             throw new CorrelationException("Failed to use get method query data from server");
106         } finally {
107             if (httpGet != null) {
108                 httpGet.releaseConnection();
109             }
110             if (httpResponse != null) {
111                 httpClient.close();
112             }
113         }
114         return response;
115     }
116
117     private static HttpPost getHttpPost(String url, Map<String, String> header,
118             Map<String, String> param, HttpEntity entity) {
119         HttpPost httpPost = new HttpPost(url);
120         if (!header.isEmpty()) {
121             for (Map.Entry<String, String> entry : header.entrySet()) {
122                 httpPost.addHeader(entry.getKey(), entry.getValue());
123             }
124         }
125         if (!param.isEmpty()) {
126             List<NameValuePair> formparams = new ArrayList<>();
127             for (Map.Entry<String, String> entry : param.entrySet()) {
128                 formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
129             }
130             UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(formparams,
131                     Consts.UTF_8);
132             httpPost.setEntity(urlEncodedFormEntity);
133         }
134         if (entity != null) {
135             httpPost.setEntity(entity);
136         }
137         return httpPost;
138     }
139
140     private static HttpGet getHttpGet(String url, Map<String, String> header) {
141         HttpGet httpGet = new HttpGet(url);
142         if (!header.isEmpty()) {
143             for (Map.Entry<String, String> entry : header.entrySet()) {
144                 httpGet.addHeader(entry.getKey(), entry.getValue());
145             }
146         }
147         return httpGet;
148     }
149
150     private static String getResponseEntity(HttpResponse httpResponse) throws IOException {
151         String result = "";
152         if (httpResponse != null) {
153             int statusCode = httpResponse.getStatusLine().getStatusCode();
154             if (statusCode == HttpStatus.SC_OK) {
155                 HttpEntity resEntity = httpResponse.getEntity();
156                 result = EntityUtils.toString(resEntity);
157             }
158         }
159         return result;
160     }
161
162     private static HttpResponse getHttpResponse(CloseableHttpClient httpClient, HttpRequestBase httpRequest)
163             throws Exception {
164         HttpResponse httpResponse = null;
165         try {
166             httpResponse = httpClient.execute(httpRequest);
167         } catch (Exception e) {
168             throw new CorrelationException("Failed to get data from server");
169         }
170         return httpResponse;
171     }
172
173     private static CloseableHttpClient getHttpClient() throws Exception {
174         CloseableHttpClient httpClient = HttpClients.custom()
175                 .setSSLSocketFactory(sslConnectionSocketFactory)
176                 .setConnectionManager(connectionManager)
177                 .setConnectionManagerShared(true)
178                 .build();
179         return httpClient;
180     }
181 }