Change HTTP Requests into HTTPS Ones
[holmes/common.git] / holmes-actions / src / main / java / org / onap / holmes / common / utils / HttpsUtils.java
index 3ef1201..41db955 100644 (file)
@@ -18,20 +18,22 @@ import java.io.IOException;
 import java.security.cert.CertificateException;
 import java.security.cert.X509Certificate;
 import java.util.ArrayList;
-import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
 import lombok.extern.slf4j.Slf4j;
 import org.apache.http.Consts;
-import org.apache.http.HeaderIterator;
 import org.apache.http.HttpEntity;
 import org.apache.http.HttpResponse;
 import org.apache.http.HttpStatus;
 import org.apache.http.NameValuePair;
-import org.apache.http.ParseException;
+import org.apache.http.client.config.RequestConfig;
 import org.apache.http.client.entity.UrlEncodedFormEntity;
+import org.apache.http.client.methods.HttpDelete;
+import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
 import org.apache.http.client.methods.HttpGet;
 import org.apache.http.client.methods.HttpPost;
+import org.apache.http.client.methods.HttpPut;
+import org.apache.http.client.methods.HttpRequestBase;
 import org.apache.http.config.Registry;
 import org.apache.http.config.RegistryBuilder;
 import org.apache.http.conn.socket.ConnectionSocketFactory;
@@ -45,16 +47,20 @@ import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
 import org.apache.http.message.BasicNameValuePair;
 import org.apache.http.ssl.SSLContextBuilder;
 import org.apache.http.util.EntityUtils;
+import org.jvnet.hk2.annotations.Service;
 import org.onap.holmes.common.exception.CorrelationException;
 
 @Slf4j
+@Service
 public class HttpsUtils {
     private static final String HTTP = "http";
     private static final String HTTPS = "https";
+    private static final int DEFUALT_TIMEOUT = 30000;
     private static SSLConnectionSocketFactory sslConnectionSocketFactory = null;
     private static PoolingHttpClientConnectionManager connectionManager = null;
     private static SSLContextBuilder sslContextBuilder = null;
-    static {
+
+    static{
         try {
             sslContextBuilder = new SSLContextBuilder();
             sslContextBuilder.loadTrustMaterial(null, new TrustStrategy() {
@@ -73,105 +79,156 @@ public class HttpsUtils {
             connectionManager = new PoolingHttpClientConnectionManager(registry);
             connectionManager.setMaxTotal(200);
         } catch (Exception e) {
-            log.error("Failed to init ssl builder" + e.getMessage());
+            log.error("Failed to initialize the ssl builder: " + e.getMessage(), e);
         }
     }
 
-    public static String post(String url, Map<String, String> header, Map<String, String> param,
-            HttpEntity entity) throws Exception {
-        String result = "";
-        CloseableHttpClient httpClient = null;
+    public static HttpResponse post(String url, Map<String, String> header, Map<String, String> param,
+            HttpEntity entity) throws CorrelationException {
+        return post(url, header, param, entity, DEFUALT_TIMEOUT);
+    }
+
+    public static HttpResponse post(String url, Map<String, String> header, Map<String, String> param,
+            HttpEntity entity, int timeout) throws CorrelationException {
+        HttpResponse response;
+        HttpPost httpPost = new HttpPost(url);
         try {
-            httpClient = getHttpClient();
-            HttpPost httpPost = new HttpPost(url);
-            if (!header.isEmpty()) {
-                for (Map.Entry<String, String> entry : header.entrySet()) {
-                    httpPost.addHeader(entry.getKey(), entry.getValue());
-                }
-            }
-            if (!param.isEmpty()) {
-                List<NameValuePair> formparams = new ArrayList<>();
-                for (Map.Entry<String, String> entry : param.entrySet()) {
-                    formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
-                }
-                UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(formparams,
-                        Consts.UTF_8);
-                httpPost.setEntity(urlEncodedFormEntity);
-            }
+            CloseableHttpClient httpClient = getHttpClient(timeout);
+            addHeaders(header, httpPost);
+            addParams(param, httpPost);
             if (entity != null) {
                 httpPost.setEntity(entity);
             }
-            HttpResponse httpResponse = httpClient.execute(httpPost);
-            int statusCode = httpResponse.getStatusLine().getStatusCode();
-            if (statusCode == HttpStatus.SC_OK) {
-                HttpEntity resEntity = httpResponse.getEntity();
-                result = EntityUtils.toString(resEntity);
-            } else {
-                readHttpResponse(httpResponse);
-            }
+            response = executeRequest(httpClient, httpPost);
         } catch (Exception e) {
-            throw new CorrelationException("Failed to use post method to get data from server");
-        } finally {
-            if (httpClient != null) {
-                httpClient.close();
+            throw new CorrelationException("Failed to query data from server through POST method!");
+        }
+        return response;
+    }
+
+    public static HttpResponse put(String url, Map<String, String> header, Map<String, String> param,
+            HttpEntity entity) throws CorrelationException {
+        return put(url, header, param, entity, DEFUALT_TIMEOUT);
+    }
+
+    public static HttpResponse put(String url, Map<String, String> header, Map<String, String> param,
+            HttpEntity entity, int timeout) throws CorrelationException {
+        HttpResponse response;
+        HttpPut httpPut = new HttpPut(url);
+        try {
+            CloseableHttpClient httpClient = getHttpClient(timeout);
+            addHeaders(header, httpPut);
+            addParams(param, httpPut);
+            if (entity != null) {
+                httpPut.setEntity(entity);
             }
+            response = executeRequest(httpClient, httpPut);
+        } catch (Exception e) {
+            throw new CorrelationException("Failed to query data from server through PUT method!");
         }
-        return result;
+        return response;
     }
 
-    public static String get(String url, Map<String, String> header) throws Exception {
-        String result = "";
-        CloseableHttpClient httpClient = null;
+    public static HttpResponse get(String url, Map<String, String> header) throws CorrelationException {
+        return get(url, header, DEFUALT_TIMEOUT);
+    }
+
+    public static HttpResponse get(String url, Map<String, String> header, int timeout) throws CorrelationException {
+        HttpResponse response;
+        HttpGet httpGet = new HttpGet(url);
         try {
-            httpClient = getHttpClient();
-            HttpGet httpGet = new HttpGet(url);
-            if (!header.isEmpty()) {
-                for (Map.Entry<String, String> entry : header.entrySet()) {
-                    httpGet.addHeader(entry.getKey(), entry.getValue());
-                }
+            CloseableHttpClient httpClient = getHttpClient(timeout);
+            addHeaders(header, httpGet);
+            response = executeRequest(httpClient, httpGet);
+        } catch (Exception e) {
+            throw new CorrelationException("Failed to query data from server through GET method!");
+        }
+        return response;
+    }
+
+    public static HttpResponse delete(String url, Map<String, String> header) throws CorrelationException {
+        return delete(url, header, DEFUALT_TIMEOUT);
+    }
+
+    public static HttpResponse delete(String url, Map<String, String> header, int timeout) throws CorrelationException {
+        HttpResponse response;
+        HttpDelete httpDelete = new HttpDelete(url);
+        try {
+            CloseableHttpClient httpClient = getHttpClient(timeout);
+            addHeaders(header, httpDelete);
+            response = executeRequest(httpClient, httpDelete);
+        } catch (Exception e) {
+            throw new CorrelationException("Failed to query data from server through DELETE method!");
+        }
+        return response;
+    }
+
+    private static void addParams(Map<String, String> param, HttpEntityEnclosingRequestBase requestBase) {
+        if (!param.isEmpty()) {
+            List<NameValuePair> formparams = new ArrayList<>();
+            for (Map.Entry<String, String> entry : param.entrySet()) {
+                formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
             }
-            HttpResponse httpResponse = httpClient.execute(httpGet);
+            UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(formparams,
+                    Consts.UTF_8);
+            requestBase.setEntity(urlEncodedFormEntity);
+        }
+    }
+
+    private static HttpRequestBase addHeaders(Map<String, String> header, HttpRequestBase httpRequestBase) {
+        if (!header.isEmpty()) {
+            for (Map.Entry<String, String> entry : header.entrySet()) {
+                httpRequestBase.addHeader(entry.getKey(), entry.getValue());
+            }
+        }
+        return httpRequestBase;
+    }
+
+    public static String extractResponseEntity(HttpResponse httpResponse)
+            throws CorrelationException, IOException {
+        String result = "";
+        if (httpResponse != null) {
             int statusCode = httpResponse.getStatusLine().getStatusCode();
             if (statusCode == HttpStatus.SC_OK) {
                 HttpEntity resEntity = httpResponse.getEntity();
                 result = EntityUtils.toString(resEntity);
             } else {
-                readHttpResponse(httpResponse);
+                throw new CorrelationException("Get a error status from server : " + statusCode);
             }
+        }
+        return result;
+    }
+
+    private static HttpResponse executeRequest(CloseableHttpClient httpClient, HttpRequestBase httpRequest)
+            throws Exception {
+        HttpResponse httpResponse;
+        try {
+            httpResponse = httpClient.execute(httpRequest);
         } catch (Exception e) {
-            throw new CorrelationException("Failed to use get method get data from server");
+            throw new CorrelationException("Failed to get data from server");
         } finally {
+            if (httpRequest != null) {
+                httpRequest.releaseConnection();
+            }
             if (httpClient != null) {
                 httpClient.close();
             }
         }
-        return result;
+        return httpResponse;
     }
 
-    private static CloseableHttpClient getHttpClient() throws Exception {
+    private static CloseableHttpClient getHttpClient(int timeout) throws Exception {
+        RequestConfig defaultRequestConfig = RequestConfig.custom()
+                .setSocketTimeout(timeout)
+                .setConnectTimeout(timeout)
+                .setConnectionRequestTimeout(timeout)
+                .build();
         CloseableHttpClient httpClient = HttpClients.custom()
+                .setDefaultRequestConfig(defaultRequestConfig)
                 .setSSLSocketFactory(sslConnectionSocketFactory)
                 .setConnectionManager(connectionManager)
                 .setConnectionManagerShared(true)
                 .build();
         return httpClient;
     }
-
-    private static String readHttpResponse(HttpResponse httpResponse)
-            throws ParseException, IOException {
-        StringBuilder builder = new StringBuilder();
-        HttpEntity entity = httpResponse.getEntity();
-        builder.append("status:" + httpResponse.getStatusLine());
-        builder.append("headers:");
-        HeaderIterator iterator = httpResponse.headerIterator();
-        while (iterator.hasNext()) {
-            builder.append("\t" + iterator.next());
-        }
-        if (entity != null) {
-            String responseString = EntityUtils.toString(entity);
-            builder.append("response length:" + responseString.length());
-            builder.append("response content:" + responseString.replace("\r\n", ""));
-        }
-        return builder.toString();
-    }
 }