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.HashMap;
22 import java.util.List;
25 import lombok.extern.slf4j.Slf4j;
26 import org.apache.http.Consts;
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.client.config.RequestConfig;
32 import org.apache.http.client.entity.UrlEncodedFormEntity;
33 import org.apache.http.client.methods.HttpDelete;
34 import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
35 import org.apache.http.client.methods.HttpGet;
36 import org.apache.http.client.methods.HttpPost;
37 import org.apache.http.client.methods.HttpPut;
38 import org.apache.http.client.methods.HttpRequestBase;
39 import org.apache.http.config.Registry;
40 import org.apache.http.config.RegistryBuilder;
41 import org.apache.http.conn.socket.ConnectionSocketFactory;
42 import org.apache.http.conn.socket.PlainConnectionSocketFactory;
43 import org.apache.http.conn.ssl.NoopHostnameVerifier;
44 import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
45 import org.apache.http.conn.ssl.TrustStrategy;
46 import org.apache.http.impl.client.CloseableHttpClient;
47 import org.apache.http.impl.client.HttpClientBuilder;
48 import org.apache.http.impl.client.HttpClients;
49 import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
50 import org.apache.http.message.BasicNameValuePair;
51 import org.apache.http.ssl.SSLContextBuilder;
52 import org.apache.http.util.EntityUtils;
53 import org.jvnet.hk2.annotations.Service;
54 import org.onap.holmes.common.config.MicroServiceConfig;
55 import org.onap.holmes.common.exception.CorrelationException;
59 public class HttpsUtils {
60 private static final String HTTP = "http";
61 private static final String HTTPS = "https";
62 private static SSLConnectionSocketFactory sslConnectionSocketFactory = null;
63 private static PoolingHttpClientConnectionManager connectionManager = null;
64 private static SSLContextBuilder sslContextBuilder = null;
65 public static final int DEFUALT_TIMEOUT = 30000;
69 sslContextBuilder = new SSLContextBuilder();
70 sslContextBuilder.loadTrustMaterial(null, new TrustStrategy() {
71 public boolean isTrusted(X509Certificate[] x509Certificates, String s)
72 throws CertificateException {
76 sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContextBuilder.build(),
77 new String[]{"SSLv3", "TLSv1", "TLSv1.2"}, null,
78 NoopHostnameVerifier.INSTANCE);
79 Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
80 .register(HTTP, new PlainConnectionSocketFactory())
81 .register(HTTPS, sslConnectionSocketFactory)
83 connectionManager = new PoolingHttpClientConnectionManager(registry);
84 connectionManager.setMaxTotal(200);
85 } catch (Exception e) {
86 log.error("Failed to initialize the ssl builder: " + e.getMessage(), e);
90 public static HttpResponse get(HttpGet httpGet, Map<String, String> header, CloseableHttpClient httpClient) throws CorrelationException {
91 return getGetAndDeleteResponse(httpGet, header, httpClient);
94 public static HttpResponse post(HttpPost httpPost, Map<String, String> header, Map<String, String> param,
95 HttpEntity entity, CloseableHttpClient httpClient) throws CorrelationException {
96 return getPostAndPutResponse(httpPost, header, param, entity, httpClient);
99 public static HttpResponse put(HttpPut httpPut, Map<String, String> header, Map<String, String> param,
100 HttpEntity entity, CloseableHttpClient httpClient) throws CorrelationException {
101 return getPostAndPutResponse(httpPut, header, param, entity, httpClient);
104 public static HttpResponse delete(HttpDelete httpDelete, Map<String, String> header, CloseableHttpClient httpClient) throws CorrelationException {
105 return getGetAndDeleteResponse(httpDelete, header, httpClient);
108 private static void addParams(Map<String, String> param, HttpEntityEnclosingRequestBase requestBase) {
109 if (!param.isEmpty()) {
110 List<NameValuePair> formparams = new ArrayList<>();
111 for (Map.Entry<String, String> entry : param.entrySet()) {
112 formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
114 UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(formparams,
116 requestBase.setEntity(urlEncodedFormEntity);
120 private static HttpRequestBase addHeaders(Map<String, String> header, HttpRequestBase httpRequestBase) {
121 if (!header.isEmpty()) {
122 for (Map.Entry<String, String> entry : header.entrySet()) {
123 httpRequestBase.addHeader(entry.getKey(), entry.getValue());
126 return httpRequestBase;
129 private static HttpResponse getPostAndPutResponse(HttpEntityEnclosingRequestBase requestBase,
130 Map<String, String> header, Map<String, String> param, HttpEntity entity,
131 CloseableHttpClient httpClient) throws CorrelationException {
133 addHeaders(header, requestBase);
134 addParams(param, requestBase);
135 if (entity != null) {
136 requestBase.setEntity(entity);
138 return executeRequest(httpClient, requestBase);
139 } catch (Exception e) {
140 throw new CorrelationException("Failed to connect to server", e);
144 private static HttpResponse getGetAndDeleteResponse(HttpRequestBase requestBase,
145 Map<String, String> header, CloseableHttpClient httpClient) throws CorrelationException {
147 addHeaders(header, requestBase);
148 return executeRequest(httpClient, requestBase);
149 } catch (Exception e) {
150 throw new CorrelationException("Failed to connect to server", e);
154 public static String extractResponseEntity(HttpResponse httpResponse)
155 throws CorrelationException, IOException {
157 if (httpResponse != null) {
158 int statusCode = httpResponse.getStatusLine().getStatusCode();
159 if (statusCode == HttpStatus.SC_OK) {
160 HttpEntity resEntity = httpResponse.getEntity();
161 result = EntityUtils.toString(resEntity);
163 throw new CorrelationException("Get an error status from server : " + statusCode);
169 private static HttpResponse executeRequest(CloseableHttpClient httpClient, HttpRequestBase httpRequest)
170 throws CorrelationException, IOException {
171 HttpResponse httpResponse;
173 httpResponse = httpClient.execute(httpRequest);
174 } catch (Exception e) {
175 throw new CorrelationException("Failed to get data from server", e);
180 public static CloseableHttpClient getConditionalHttpsClient(int timeout) {
181 HttpClientBuilder builder = getHttpClientBuilder(timeout);
182 if (isHttpsEnabled()) {
183 builder.setSSLSocketFactory(sslConnectionSocketFactory);
186 return builder.build();
189 public static CloseableHttpClient getHttpsClient(int timeout) {
190 HttpClientBuilder builder = getHttpClientBuilder(timeout);
191 return builder.setSSLSocketFactory(sslConnectionSocketFactory).build();
194 private static HttpClientBuilder getHttpClientBuilder(int timeout) {
195 RequestConfig defaultRequestConfig = RequestConfig.custom()
196 .setSocketTimeout(timeout)
197 .setConnectTimeout(timeout)
198 .setConnectionRequestTimeout(timeout)
201 return HttpClients.custom()
202 .setDefaultRequestConfig(defaultRequestConfig)
203 .setConnectionManager(connectionManager)
204 .setConnectionManagerShared(true);
207 public static boolean isHttpsEnabled() {
208 return Boolean.valueOf(MicroServiceConfig.getEnv("ENABLE_ENCRYPT"));