add httpsutil and modify query from aai
[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.HeaderIterator;
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.ParseException;
32 import org.apache.http.client.entity.UrlEncodedFormEntity;
33 import org.apache.http.client.methods.HttpGet;
34 import org.apache.http.client.methods.HttpPost;
35 import org.apache.http.config.Registry;
36 import org.apache.http.config.RegistryBuilder;
37 import org.apache.http.conn.socket.ConnectionSocketFactory;
38 import org.apache.http.conn.socket.PlainConnectionSocketFactory;
39 import org.apache.http.conn.ssl.NoopHostnameVerifier;
40 import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
41 import org.apache.http.conn.ssl.TrustStrategy;
42 import org.apache.http.impl.client.CloseableHttpClient;
43 import org.apache.http.impl.client.HttpClients;
44 import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
45 import org.apache.http.message.BasicNameValuePair;
46 import org.apache.http.ssl.SSLContextBuilder;
47 import org.apache.http.util.EntityUtils;
48 import org.onap.holmes.common.exception.CorrelationException;
49
50 @Slf4j
51 public class HttpsUtils {
52     private static final String HTTP = "http";
53     private static final String HTTPS = "https";
54     private static SSLConnectionSocketFactory sslConnectionSocketFactory = null;
55     private static PoolingHttpClientConnectionManager connectionManager = null;
56     private static SSLContextBuilder sslContextBuilder = null;
57     static {
58         try {
59             sslContextBuilder = new SSLContextBuilder();
60             sslContextBuilder.loadTrustMaterial(null, new TrustStrategy() {
61                 public boolean isTrusted(X509Certificate[] x509Certificates, String s)
62                         throws CertificateException {
63                     return true;
64                 }
65             });
66             sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContextBuilder.build(),
67                     new String[]{"SSLv2Hello", "SSLv3", "TLSv1", "TLSv1.2"}, null,
68                     NoopHostnameVerifier.INSTANCE);
69             Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
70                     .register(HTTP, new PlainConnectionSocketFactory())
71                     .register(HTTPS, sslConnectionSocketFactory)
72                     .build();
73             connectionManager = new PoolingHttpClientConnectionManager(registry);
74             connectionManager.setMaxTotal(200);
75         } catch (Exception e) {
76             log.error("Failed to init ssl builder" + e.getMessage());
77         }
78     }
79
80     public static String post(String url, Map<String, String> header, Map<String, String> param,
81             HttpEntity entity) throws Exception {
82         String result = "";
83         CloseableHttpClient httpClient = null;
84         try {
85             httpClient = getHttpClient();
86             HttpPost httpPost = new HttpPost(url);
87             if (!header.isEmpty()) {
88                 for (Map.Entry<String, String> entry : header.entrySet()) {
89                     httpPost.addHeader(entry.getKey(), entry.getValue());
90                 }
91             }
92             if (!param.isEmpty()) {
93                 List<NameValuePair> formparams = new ArrayList<>();
94                 for (Map.Entry<String, String> entry : param.entrySet()) {
95                     formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
96                 }
97                 UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(formparams,
98                         Consts.UTF_8);
99                 httpPost.setEntity(urlEncodedFormEntity);
100             }
101             if (entity != null) {
102                 httpPost.setEntity(entity);
103             }
104             HttpResponse httpResponse = httpClient.execute(httpPost);
105             int statusCode = httpResponse.getStatusLine().getStatusCode();
106             if (statusCode == HttpStatus.SC_OK) {
107                 HttpEntity resEntity = httpResponse.getEntity();
108                 result = EntityUtils.toString(resEntity);
109             } else {
110                 readHttpResponse(httpResponse);
111             }
112         } catch (Exception e) {
113             throw new CorrelationException("Failed to use post method to get data from server");
114         } finally {
115             if (httpClient != null) {
116                 httpClient.close();
117             }
118         }
119         return result;
120     }
121
122     public static String get(String url, Map<String, String> header) throws Exception {
123         String result = "";
124         CloseableHttpClient httpClient = null;
125         try {
126             httpClient = getHttpClient();
127             HttpGet httpGet = new HttpGet(url);
128             if (!header.isEmpty()) {
129                 for (Map.Entry<String, String> entry : header.entrySet()) {
130                     httpGet.addHeader(entry.getKey(), entry.getValue());
131                 }
132             }
133             HttpResponse httpResponse = httpClient.execute(httpGet);
134             int statusCode = httpResponse.getStatusLine().getStatusCode();
135             if (statusCode == HttpStatus.SC_OK) {
136                 HttpEntity resEntity = httpResponse.getEntity();
137                 result = EntityUtils.toString(resEntity);
138             } else {
139                 readHttpResponse(httpResponse);
140             }
141         } catch (Exception e) {
142             throw new CorrelationException("Failed to use get method get data from server");
143         } finally {
144             if (httpClient != null) {
145                 httpClient.close();
146             }
147         }
148         return result;
149     }
150
151     private static CloseableHttpClient getHttpClient() throws Exception {
152         CloseableHttpClient httpClient = HttpClients.custom()
153                 .setSSLSocketFactory(sslConnectionSocketFactory)
154                 .setConnectionManager(connectionManager)
155                 .setConnectionManagerShared(true)
156                 .build();
157         return httpClient;
158     }
159
160     private static String readHttpResponse(HttpResponse httpResponse)
161             throws ParseException, IOException {
162         StringBuilder builder = new StringBuilder();
163         HttpEntity entity = httpResponse.getEntity();
164         builder.append("status:" + httpResponse.getStatusLine());
165         builder.append("headers:");
166         HeaderIterator iterator = httpResponse.headerIterator();
167         while (iterator.hasNext()) {
168             builder.append("\t" + iterator.next());
169         }
170         if (entity != null) {
171             String responseString = EntityUtils.toString(entity);
172             builder.append("response length:" + responseString.length());
173             builder.append("response content:" + responseString.replace("\r\n", ""));
174         }
175         return builder.toString();
176     }
177 }