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 SSLConnectionSocketFactory sslConnectionSocketFactory = null;
59 private static PoolingHttpClientConnectionManager connectionManager = null;
60 private static SSLContextBuilder sslContextBuilder = null;
61 public static final int DEFUALT_TIMEOUT = 30000;
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[]{"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, CloseableHttpClient httpClient) throws CorrelationException {
88 HttpResponse response;
89 HttpPost httpPost = new HttpPost(url);
91 addHeaders(header, httpPost);
92 addParams(param, httpPost);
94 httpPost.setEntity(entity);
96 response = executeRequest(httpClient, httpPost);
97 } catch (Exception e) {
98 throw new CorrelationException("Failed to query data from server through POST method!");
103 public static HttpResponse put(String url, Map<String, String> header, Map<String, String> param,
104 HttpEntity entity, CloseableHttpClient httpClient) throws CorrelationException {
105 HttpResponse response;
106 HttpPut httpPut = new HttpPut(url);
108 addHeaders(header, httpPut);
109 addParams(param, httpPut);
110 if (entity != null) {
111 httpPut.setEntity(entity);
113 response = executeRequest(httpClient, httpPut);
114 } catch (Exception e) {
115 throw new CorrelationException("Failed to query data from server through PUT method!");
120 public static HttpResponse get(String url, Map<String, String> header, CloseableHttpClient httpClient) throws CorrelationException {
121 HttpResponse response;
122 HttpGet httpGet = new HttpGet(url);
124 addHeaders(header, httpGet);
125 response = executeRequest(httpClient, httpGet);
126 } catch (Exception e) {
127 throw new CorrelationException("Failed to query data from server through GET method!");
132 public static HttpResponse delete(String url, Map<String, String> header, CloseableHttpClient httpClient) throws CorrelationException {
133 HttpResponse response;
134 HttpDelete httpDelete = new HttpDelete(url);
136 addHeaders(header, httpDelete);
137 response = executeRequest(httpClient, httpDelete);
138 } catch (Exception e) {
139 throw new CorrelationException("Failed to query data from server through DELETE method!");
144 private static void addParams(Map<String, String> param, HttpEntityEnclosingRequestBase requestBase) {
145 if (!param.isEmpty()) {
146 List<NameValuePair> formparams = new ArrayList<>();
147 for (Map.Entry<String, String> entry : param.entrySet()) {
148 formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
150 UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(formparams,
152 requestBase.setEntity(urlEncodedFormEntity);
156 private static HttpRequestBase addHeaders(Map<String, String> header, HttpRequestBase httpRequestBase) {
157 if (!header.isEmpty()) {
158 for (Map.Entry<String, String> entry : header.entrySet()) {
159 httpRequestBase.addHeader(entry.getKey(), entry.getValue());
162 return httpRequestBase;
165 public static String extractResponseEntity(HttpResponse httpResponse)
166 throws CorrelationException, IOException {
168 if (httpResponse != null) {
169 int statusCode = httpResponse.getStatusLine().getStatusCode();
170 if (statusCode == HttpStatus.SC_OK) {
171 HttpEntity resEntity = httpResponse.getEntity();
172 result = EntityUtils.toString(resEntity);
174 throw new CorrelationException("Get an error status from server : " + statusCode);
180 private static HttpResponse executeRequest(CloseableHttpClient httpClient, HttpRequestBase httpRequest)
181 throws CorrelationException, IOException {
182 HttpResponse httpResponse;
184 httpResponse = httpClient.execute(httpRequest);
185 } catch (Exception e) {
187 throw new CorrelationException("Failed to get data from server" ,e);
189 if (httpRequest != null) {
190 httpRequest.releaseConnection();
192 if (httpClient != null) {
199 public static CloseableHttpClient getHttpClient(int timeout) {
200 RequestConfig defaultRequestConfig = RequestConfig.custom()
201 .setSocketTimeout(timeout)
202 .setConnectTimeout(timeout)
203 .setConnectionRequestTimeout(timeout)
205 CloseableHttpClient httpClient = HttpClients.custom()
206 .setDefaultRequestConfig(defaultRequestConfig)
207 .setSSLSocketFactory(sslConnectionSocketFactory)
208 .setConnectionManager(connectionManager)
209 .setConnectionManagerShared(true)