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