441261fe47d0912a338ec1def2af05fe4c685b35
[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.HashMap;
22 import java.util.List;
23 import java.util.Map;
24 import lombok.extern.slf4j.Slf4j;
25 import org.apache.http.Consts;
26 import org.apache.http.HeaderIterator;
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.ParseException;
32 import org.apache.http.client.entity.UrlEncodedFormEntity;
33 import org.apache.http.client.methods.HttpGet;
34 import org.apache.http.client.methods.HttpPost;
35 import org.apache.http.client.methods.HttpRequestBase;
36 import org.apache.http.config.Registry;
37 import org.apache.http.config.RegistryBuilder;
38 import org.apache.http.conn.socket.ConnectionSocketFactory;
39 import org.apache.http.conn.socket.PlainConnectionSocketFactory;
40 import org.apache.http.conn.ssl.NoopHostnameVerifier;
41 import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
42 import org.apache.http.conn.ssl.TrustStrategy;
43 import org.apache.http.impl.client.CloseableHttpClient;
44 import org.apache.http.impl.client.HttpClients;
45 import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
46 import org.apache.http.message.BasicNameValuePair;
47 import org.apache.http.ssl.SSLContextBuilder;
48 import org.apache.http.util.EntityUtils;
49 import org.onap.holmes.common.exception.CorrelationException;
50
51 @Slf4j
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     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 init ssl builder" + e.getMessage());
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
92         return getResponseEntity(httpResponse);
93     }
94
95     public static String get(String url, Map<String, String> header) throws Exception {
96         HttpResponse httpResponse = null;
97         try {
98             CloseableHttpClient httpClient = getHttpClient();
99             HttpGet httpGet = getHttpGet(url, header);
100             httpResponse = getHttpResponse(httpClient, httpGet);
101         } catch (Exception e) {
102             throw new CorrelationException("Failed to use get method query data from server");
103         }
104         return getResponseEntity(httpResponse);
105     }
106
107     private static HttpPost getHttpPost(String url, Map<String, String> header,
108             Map<String, String> param, HttpEntity entity) {
109         HttpPost httpPost = new HttpPost(url);
110         if (!header.isEmpty()) {
111             for (Map.Entry<String, String> entry : header.entrySet()) {
112                 httpPost.addHeader(entry.getKey(), entry.getValue());
113             }
114         }
115         if (!param.isEmpty()) {
116             List<NameValuePair> formparams = new ArrayList<>();
117             for (Map.Entry<String, String> entry : param.entrySet()) {
118                 formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
119             }
120             UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(formparams,
121                     Consts.UTF_8);
122             httpPost.setEntity(urlEncodedFormEntity);
123         }
124         if (entity != null) {
125             httpPost.setEntity(entity);
126         }
127         return httpPost;
128     }
129
130     private static HttpGet getHttpGet(String url, Map<String, String> header) {
131         HttpGet httpGet = new HttpGet(url);
132         if (!header.isEmpty()) {
133             for (Map.Entry<String, String> entry : header.entrySet()) {
134                 httpGet.addHeader(entry.getKey(), entry.getValue());
135             }
136         }
137         return httpGet;
138     }
139
140     private static String getResponseEntity(HttpResponse httpResponse) throws IOException {
141         String result = "";
142         if (httpResponse != null) {
143             int statusCode = httpResponse.getStatusLine().getStatusCode();
144             if (statusCode == HttpStatus.SC_OK) {
145                 HttpEntity resEntity = httpResponse.getEntity();
146                 result = EntityUtils.toString(resEntity);
147             }
148         }
149         return result;
150     }
151
152     private static HttpResponse getHttpResponse(CloseableHttpClient httpClient, HttpRequestBase httpRequest)
153             throws Exception {
154         HttpResponse httpResponse = null;
155         try {
156             httpResponse = httpClient.execute(httpRequest);
157         } catch (Exception e) {
158             throw new CorrelationException("Failed to get data from server");
159         } finally {
160             if (httpClient != null) {
161                 httpClient.close();
162             }
163         }
164         return httpResponse;
165     }
166
167     private static CloseableHttpClient getHttpClient() throws Exception {
168         CloseableHttpClient httpClient = HttpClients.custom()
169                 .setSSLSocketFactory(sslConnectionSocketFactory)
170                 .setConnectionManager(connectionManager)
171                 .setConnectionManagerShared(true)
172                 .build();
173         return httpClient;
174     }
175 }