2 * Copyright 2017 ZTE Corporation.
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
7 * http://www.apache.org/licenses/LICENSE-2.0
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
15 package org.onap.holmes.common.utils;
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;
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;
55 public class HttpsUtils {
56 private static final String HTTP = "http";
57 private static final String HTTPS = "https";
58 private static final int DEFUALT_TIMEOUT = 30000;
59 private static SSLConnectionSocketFactory sslConnectionSocketFactory = null;
60 private static PoolingHttpClientConnectionManager connectionManager = null;
61 private static SSLContextBuilder sslContextBuilder = null;
65 sslContextBuilder = new SSLContextBuilder();
66 sslContextBuilder.loadTrustMaterial(null, new TrustStrategy() {
67 public boolean isTrusted(X509Certificate[] x509Certificates, String s)
68 throws CertificateException {
72 sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContextBuilder.build(),
73 new String[]{"SSLv2Hello", "SSLv3", "TLSv1", "TLSv1.2"}, null,
74 NoopHostnameVerifier.INSTANCE);
75 Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
76 .register(HTTP, new PlainConnectionSocketFactory())
77 .register(HTTPS, sslConnectionSocketFactory)
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);
86 public static HttpResponse post(String url, Map<String, String> header, Map<String, String> param,
87 HttpEntity entity) throws CorrelationException {
88 return post(url, header, param, entity, DEFUALT_TIMEOUT);
91 public static HttpResponse post(String url, Map<String, String> header, Map<String, String> param,
92 HttpEntity entity, int timeout) throws CorrelationException {
93 HttpResponse response;
94 HttpPost httpPost = new HttpPost(url);
96 CloseableHttpClient httpClient = getHttpClient(timeout);
97 addHeaders(header, httpPost);
98 addParams(param, httpPost);
100 httpPost.setEntity(entity);
102 response = executeRequest(httpClient, httpPost);
103 } catch (Exception e) {
104 throw new CorrelationException("Failed to query data from server through POST method!");
109 public static HttpResponse put(String url, Map<String, String> header, Map<String, String> param,
110 HttpEntity entity) throws CorrelationException {
111 return put(url, header, param, entity, DEFUALT_TIMEOUT);
114 public static HttpResponse put(String url, Map<String, String> header, Map<String, String> param,
115 HttpEntity entity, int timeout) throws CorrelationException {
116 HttpResponse response;
117 HttpPut httpPut = new HttpPut(url);
119 CloseableHttpClient httpClient = getHttpClient(timeout);
120 addHeaders(header, httpPut);
121 addParams(param, httpPut);
122 if (entity != null) {
123 httpPut.setEntity(entity);
125 response = executeRequest(httpClient, httpPut);
126 } catch (Exception e) {
127 throw new CorrelationException("Failed to query data from server through PUT method!");
132 public static HttpResponse get(String url, Map<String, String> header) throws CorrelationException {
133 return get(url, header, DEFUALT_TIMEOUT);
136 public static HttpResponse get(String url, Map<String, String> header, int timeout) throws CorrelationException {
137 HttpResponse response;
138 HttpGet httpGet = new HttpGet(url);
140 CloseableHttpClient httpClient = getHttpClient(timeout);
141 addHeaders(header, httpGet);
142 response = executeRequest(httpClient, httpGet);
143 } catch (Exception e) {
144 throw new CorrelationException("Failed to query data from server through GET method!");
149 public static HttpResponse delete(String url, Map<String, String> header) throws CorrelationException {
150 return delete(url, header, DEFUALT_TIMEOUT);
153 public static HttpResponse delete(String url, Map<String, String> header, int timeout) throws CorrelationException {
154 HttpResponse response;
155 HttpDelete httpDelete = new HttpDelete(url);
157 CloseableHttpClient httpClient = getHttpClient(timeout);
158 addHeaders(header, httpDelete);
159 response = executeRequest(httpClient, httpDelete);
160 } catch (Exception e) {
161 throw new CorrelationException("Failed to query data from server through DELETE method!");
166 private static void addParams(Map<String, String> param, HttpEntityEnclosingRequestBase requestBase) {
167 if (!param.isEmpty()) {
168 List<NameValuePair> formparams = new ArrayList<>();
169 for (Map.Entry<String, String> entry : param.entrySet()) {
170 formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
172 UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(formparams,
174 requestBase.setEntity(urlEncodedFormEntity);
178 private static HttpRequestBase addHeaders(Map<String, String> header, HttpRequestBase httpRequestBase) {
179 if (!header.isEmpty()) {
180 for (Map.Entry<String, String> entry : header.entrySet()) {
181 httpRequestBase.addHeader(entry.getKey(), entry.getValue());
184 return httpRequestBase;
187 public static String extractResponseEntity(HttpResponse httpResponse)
188 throws CorrelationException, IOException {
190 if (httpResponse != null) {
191 int statusCode = httpResponse.getStatusLine().getStatusCode();
192 if (statusCode == HttpStatus.SC_OK) {
193 HttpEntity resEntity = httpResponse.getEntity();
194 result = EntityUtils.toString(resEntity);
196 throw new CorrelationException("Get a error status from server : " + statusCode);
202 private static HttpResponse executeRequest(CloseableHttpClient httpClient, HttpRequestBase httpRequest)
203 throws CorrelationException, IOException {
204 HttpResponse httpResponse;
206 httpResponse = httpClient.execute(httpRequest);
207 } catch (Exception e) {
208 throw new CorrelationException("Failed to get data from server");
210 if (httpRequest != null) {
211 httpRequest.releaseConnection();
213 if (httpClient != null) {
220 private static CloseableHttpClient getHttpClient(int timeout) throws Exception {
221 RequestConfig defaultRequestConfig = RequestConfig.custom()
222 .setSocketTimeout(timeout)
223 .setConnectTimeout(timeout)
224 .setConnectionRequestTimeout(timeout)
226 CloseableHttpClient httpClient = HttpClients.custom()
227 .setDefaultRequestConfig(defaultRequestConfig)
228 .setSSLSocketFactory(sslConnectionSocketFactory)
229 .setConnectionManager(connectionManager)
230 .setConnectionManagerShared(true)