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