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 lombok.extern.slf4j.Slf4j;
18 import org.apache.http.*;
19 import org.apache.http.client.config.RequestConfig;
20 import org.apache.http.client.entity.UrlEncodedFormEntity;
21 import org.apache.http.client.methods.*;
22 import org.apache.http.config.Registry;
23 import org.apache.http.config.RegistryBuilder;
24 import org.apache.http.conn.socket.ConnectionSocketFactory;
25 import org.apache.http.conn.socket.PlainConnectionSocketFactory;
26 import org.apache.http.conn.ssl.NoopHostnameVerifier;
27 import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
28 import org.apache.http.conn.ssl.TrustStrategy;
29 import org.apache.http.impl.client.CloseableHttpClient;
30 import org.apache.http.impl.client.HttpClientBuilder;
31 import org.apache.http.impl.client.HttpClients;
32 import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
33 import org.apache.http.message.BasicNameValuePair;
34 import org.apache.http.ssl.SSLContextBuilder;
35 import org.apache.http.util.EntityUtils;
36 import org.jvnet.hk2.annotations.Service;
37 import org.onap.holmes.common.config.MicroServiceConfig;
38 import org.onap.holmes.common.exception.CorrelationException;
40 import java.io.IOException;
41 import java.security.cert.CertificateException;
42 import java.security.cert.X509Certificate;
43 import java.util.ArrayList;
44 import java.util.List;
49 public class HttpsUtils {
50 private static final String HTTP = "http";
51 private static final String HTTPS = "https";
52 private static SSLConnectionSocketFactory sslConnectionSocketFactory = null;
53 private static PoolingHttpClientConnectionManager connectionManager = null;
54 private static SSLContextBuilder sslContextBuilder = null;
55 public static final int DEFUALT_TIMEOUT = 30000;
59 sslContextBuilder = new SSLContextBuilder();
60 sslContextBuilder.loadTrustMaterial(null, new TrustStrategy() {
61 public boolean isTrusted(X509Certificate[] x509Certificates, String s)
62 throws CertificateException {
66 sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContextBuilder.build(),
67 new String[]{"SSLv3", "TLSv1", "TLSv1.2"}, null,
68 NoopHostnameVerifier.INSTANCE);
69 Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
70 .register(HTTP, new PlainConnectionSocketFactory())
71 .register(HTTPS, sslConnectionSocketFactory)
73 connectionManager = new PoolingHttpClientConnectionManager(registry);
74 connectionManager.setMaxTotal(200);
75 } catch (Exception e) {
76 log.error("Failed to initialize the ssl builder: " + e.getMessage(), e);
80 public static HttpResponse get(HttpGet httpGet, Map<String, String> header, CloseableHttpClient httpClient) throws CorrelationException {
81 return getGetAndDeleteResponse(httpGet, header, httpClient);
84 public static HttpResponse post(HttpPost httpPost, Map<String, String> header, Map<String, String> param,
85 HttpEntity entity, CloseableHttpClient httpClient) throws CorrelationException {
86 return getPostAndPutResponse(httpPost, header, param, entity, httpClient);
89 public static HttpResponse put(HttpPut httpPut, Map<String, String> header, Map<String, String> param,
90 HttpEntity entity, CloseableHttpClient httpClient) throws CorrelationException {
91 return getPostAndPutResponse(httpPut, header, param, entity, httpClient);
94 public static HttpResponse delete(HttpDelete httpDelete, Map<String, String> header, CloseableHttpClient httpClient) throws CorrelationException {
95 return getGetAndDeleteResponse(httpDelete, header, httpClient);
98 private static void addParams(Map<String, String> param, HttpEntityEnclosingRequestBase requestBase) {
99 if (!param.isEmpty()) {
100 List<NameValuePair> formparams = new ArrayList<>();
101 for (Map.Entry<String, String> entry : param.entrySet()) {
102 formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
104 UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(formparams,
106 requestBase.setEntity(urlEncodedFormEntity);
110 private static HttpRequestBase addHeaders(Map<String, String> header, HttpRequestBase httpRequestBase) {
111 if (!header.isEmpty()) {
112 for (Map.Entry<String, String> entry : header.entrySet()) {
113 httpRequestBase.addHeader(entry.getKey(), entry.getValue());
116 return httpRequestBase;
119 private static HttpResponse getPostAndPutResponse(HttpEntityEnclosingRequestBase requestBase,
120 Map<String, String> header, Map<String, String> param, HttpEntity entity,
121 CloseableHttpClient httpClient) throws CorrelationException {
123 addHeaders(header, requestBase);
124 addParams(param, requestBase);
125 if (entity != null) {
126 requestBase.setEntity(entity);
128 return executeRequest(httpClient, requestBase);
129 } catch (Exception e) {
130 throw new CorrelationException("Failed to connect to server", e);
134 private static HttpResponse getGetAndDeleteResponse(HttpRequestBase requestBase,
135 Map<String, String> header, CloseableHttpClient httpClient) throws CorrelationException {
137 addHeaders(header, requestBase);
138 return executeRequest(httpClient, requestBase);
139 } catch (Exception e) {
140 throw new CorrelationException("Failed to connect to server", e);
144 public static String extractResponseEntity(HttpResponse httpResponse)
145 throws CorrelationException, IOException {
147 if (httpResponse != null) {
148 int statusCode = httpResponse.getStatusLine().getStatusCode();
149 if (statusCode == HttpStatus.SC_OK) {
150 HttpEntity resEntity = httpResponse.getEntity();
151 result = EntityUtils.toString(resEntity);
153 throw new CorrelationException("Get an error status from server : " + statusCode);
159 private static HttpResponse executeRequest(CloseableHttpClient httpClient, HttpRequestBase httpRequest)
160 throws CorrelationException, IOException {
161 HttpResponse httpResponse;
163 httpResponse = httpClient.execute(httpRequest);
164 } catch (Exception e) {
165 throw new CorrelationException("Failed to get data from server", e);
170 public static CloseableHttpClient getConditionalHttpsClient(int timeout) {
171 HttpClientBuilder builder = getHttpClientBuilder(timeout);
172 if (isHttpsEnabled()) {
173 builder.setSSLSocketFactory(sslConnectionSocketFactory);
176 return builder.build();
179 public static CloseableHttpClient getHttpsClient(int timeout) {
180 HttpClientBuilder builder = getHttpClientBuilder(timeout);
181 return builder.setSSLSocketFactory(sslConnectionSocketFactory).build();
184 private static HttpClientBuilder getHttpClientBuilder(int timeout) {
185 RequestConfig defaultRequestConfig = RequestConfig.custom()
186 .setSocketTimeout(timeout)
187 .setConnectTimeout(timeout)
188 .setConnectionRequestTimeout(timeout)
191 return HttpClients.custom()
192 .setDefaultRequestConfig(defaultRequestConfig)
193 .setConnectionManager(connectionManager)
194 .setConnectionManagerShared(true);
197 public static boolean isHttpsEnabled() {
198 return Boolean.valueOf(MicroServiceConfig.getEnv("ENABLE_ENCRYPT"));