Fix DCAE connection issue 83/22183/1
authorDeterme, Sebastien (sd378r) <sd378r@intl.att.com>
Sun, 5 Nov 2017 19:46:52 +0000 (20:46 +0100)
committerDeterme, Sebastien (sd378r) <sd378r@intl.att.com>
Sun, 5 Nov 2017 19:46:52 +0000 (20:46 +0100)
Code has been added to support http/https protocols for DCAE

Change-Id: Ib1259310b801a19cacd08c22292509156624ac9b
Issue-ID: CLAMP-65
Signed-off-by: Determe, Sebastien (sd378r) <sd378r@intl.att.com>
pom.xml
src/main/java/org/onap/clamp/clds/client/DcaeDispatcherServices.java
src/main/java/org/onap/clamp/clds/client/DcaeHttpConnectionManager.java [new file with mode: 0644]
src/main/java/org/onap/clamp/clds/client/DcaeInventoryServices.java
src/test/java/org/onap/clamp/clds/it/DcaeHttpConnectionManagerItCase.java [new file with mode: 0644]

diff --git a/pom.xml b/pom.xml
index 85d3223..b85d18a 100644 (file)
--- a/pom.xml
+++ b/pom.xml
         </exclusion>
       </exclusions>
     </dependency>
+    <dependency>
+      <groupId>com.fasterxml.jackson.core</groupId>
+      <artifactId>jackson-databind</artifactId>
+      <version>2.6.3</version>
+    </dependency>
     <dependency>
       <groupId>com.fasterxml.jackson.dataformat</groupId>
       <artifactId>jackson-dataformat-yaml</artifactId>
index f285dc2..51e4abc 100644 (file)
@@ -27,17 +27,7 @@ import com.att.eelf.configuration.EELFLogger;
 import com.att.eelf.configuration.EELFManager;\r
 import com.fasterxml.jackson.databind.node.ObjectNode;\r
 \r
-import java.io.BufferedReader;\r
-import java.io.DataOutputStream;\r
-import java.io.IOException;\r
-import java.io.InputStream;\r
-import java.io.InputStreamReader;\r
-import java.net.URL;\r
 import java.util.Date;\r
-import java.util.stream.Collectors;\r
-\r
-import javax.net.ssl.HttpsURLConnection;\r
-import javax.ws.rs.BadRequestException;\r
 \r
 import org.json.simple.JSONObject;\r
 import org.json.simple.parser.JSONParser;\r
@@ -52,11 +42,16 @@ import org.springframework.beans.factory.annotation.Autowired;
  *\r
  */\r
 public class DcaeDispatcherServices {\r
-    protected static final EELFLogger logger        = EELFManager.getInstance().getLogger(DcaeDispatcherServices.class);\r
-    protected static final EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger();\r
-\r
+    protected static final EELFLogger logger                 = EELFManager.getInstance()\r
+            .getLogger(DcaeDispatcherServices.class);\r
+    protected static final EELFLogger metricsLogger          = EELFManager.getInstance().getMetricsLogger();\r
     @Autowired\r
     private RefProp                   refProp;\r
+    private static final String       STATUS_URL_LOG         = "Status URL extracted: ";\r
+    private static final String       DCAE_URL_PREFIX        = "/dcae-deployments/";\r
+    private static final String       DCAE_URL_PROPERTY_NAME = "DCAE_DISPATCHER_URL";\r
+    private static final String       DCAE_LINK_FIELD        = "links";\r
+    private static final String       DCAE_STATUS_FIELD      = "status";\r
 \r
     /**\r
      * Delete the deployment on DCAE.\r
@@ -64,74 +59,27 @@ public class DcaeDispatcherServices {
      * @param deploymentId\r
      *            The deployment ID\r
      * @return Return the URL Status\r
-     * @throws IOException\r
-     *             In case of issues with the Stream\r
      */\r
-    public String deleteDeployment(String deploymentId) throws IOException {\r
-\r
-        String statusUrl = null;\r
-        InputStream in = null;\r
+    public String deleteDeployment(String deploymentId) {\r
         Date startTime = new Date();\r
         LoggingUtils.setTargetContext("DCAE", "deleteDeployment");\r
         try {\r
-            String url = refProp.getStringValue("DCAE_DISPATCHER_URL") + "/dcae-deployments/" + deploymentId;\r
-            logger.info("Dcae Dispatcher url - " + url);\r
-            URL obj = new URL(url);\r
-            HttpsURLConnection conn = (HttpsURLConnection) obj.openConnection();\r
-            conn.setRequestProperty("X-ECOMP-RequestID", LoggingUtils.getRequestId());\r
-            conn.setRequestMethod("DELETE");\r
-            int responseCode = conn.getResponseCode();\r
-\r
-            boolean requestFailed = true;\r
-            logger.info("responseCode=" + responseCode);\r
-            if (responseCode == 200 || responseCode == 202) {\r
-                requestFailed = false;\r
-            }\r
-\r
-            InputStream inStream = conn.getErrorStream();\r
-            if (inStream == null) {\r
-                inStream = conn.getInputStream();\r
-            }\r
-\r
-            String responseStr = null;\r
-            if (inStream != null) {\r
-                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inStream));\r
-                String inputLine = null;\r
-                StringBuilder response = new StringBuilder();\r
-                while ((inputLine = bufferedReader.readLine()) != null) {\r
-                    response.append(inputLine);\r
-                }\r
-                responseStr = response.toString();\r
-            }\r
-\r
-            if (responseStr != null && requestFailed) {\r
-                logger.error("requestFailed - responseStr=" + responseStr);\r
-                throw new BadRequestException(responseStr);\r
-            }\r
-\r
-            logger.debug("response code " + responseCode);\r
-            in = conn.getInputStream();\r
-            logger.debug("res:" + responseStr);\r
+            String url = refProp.getStringValue(DCAE_URL_PROPERTY_NAME) + DCAE_URL_PREFIX + deploymentId;\r
+            String responseStr = DcaeHttpConnectionManager.doDcaeHttpQuery(url, "DELETE", null, null);\r
             JSONParser parser = new JSONParser();\r
             Object obj0 = parser.parse(responseStr);\r
             JSONObject jsonObj = (JSONObject) obj0;\r
-            JSONObject linksObj = (JSONObject) jsonObj.get("links");\r
-            statusUrl = (String) linksObj.get("status");\r
-            logger.debug("Status URL: " + statusUrl);\r
-\r
+            JSONObject linksObj = (JSONObject) jsonObj.get(DCAE_LINK_FIELD);\r
+            String statusUrl = (String) linksObj.get(DCAE_STATUS_FIELD);\r
+            logger.info(STATUS_URL_LOG + statusUrl);\r
+            return statusUrl;\r
         } catch (Exception e) {\r
             logger.error("Exception occurred during Delete Deployment Operation with DCAE", e);\r
             throw new DcaeDeploymentException("Exception occurred during Delete Deployment Operation with DCAE", e);\r
         } finally {\r
-            if (in != null) {\r
-                in.close();\r
-            }\r
             LoggingUtils.setTimeContext(startTime, new Date());\r
             metricsLogger.info("deleteDeployment complete");\r
         }\r
-\r
-        return statusUrl;\r
-\r
     }\r
 \r
     /**\r
@@ -140,43 +88,25 @@ public class DcaeDispatcherServices {
      * @param statusUrl\r
      *            The URL provided by a previous DCAE Query\r
      * @return The status\r
-     * @throws IOException\r
-     *             In case of issues with the Stream\r
      * \r
      */\r
-    public String getOperationStatus(String statusUrl) throws IOException {\r
-\r
+    public String getOperationStatus(String statusUrl) {\r
         // Assigning processing status to monitor operation status further\r
         String opStatus = "processing";\r
-        InputStream in = null;\r
         Date startTime = new Date();\r
         LoggingUtils.setTargetContext("DCAE", "getOperationStatus");\r
         try {\r
-            URL obj = new URL(statusUrl);\r
-            HttpsURLConnection conn = (HttpsURLConnection) obj.openConnection();\r
-            conn.setRequestMethod("GET");\r
-            conn.setRequestProperty("X-ECOMP-RequestID", LoggingUtils.getRequestId());\r
-            int responseCode = conn.getResponseCode();\r
-            logger.debug("Deployment operation status response code - " + responseCode);\r
-            if (responseCode == 200) {\r
-                in = conn.getInputStream();\r
-                String res = new BufferedReader(new InputStreamReader(in)).lines().collect(Collectors.joining("\n"));\r
-                JSONParser parser = new JSONParser();\r
-                Object obj0 = parser.parse(res);\r
-                JSONObject jsonObj = (JSONObject) obj0;\r
-                String operationType = (String) jsonObj.get("operationType");\r
-                String status = (String) jsonObj.get("status");\r
-                logger.debug("Operation Type - " + operationType + ", Status " + status);\r
-                opStatus = status;\r
-            }\r
+            String responseStr = DcaeHttpConnectionManager.doDcaeHttpQuery(statusUrl, "GET", null, null);\r
+            JSONParser parser = new JSONParser();\r
+            Object obj0 = parser.parse(responseStr);\r
+            JSONObject jsonObj = (JSONObject) obj0;\r
+            String operationType = (String) jsonObj.get("operationType");\r
+            String status = (String) jsonObj.get("status");\r
+            logger.info("Operation Type - " + operationType + ", Status " + status);\r
+            opStatus = status;\r
         } catch (Exception e) {\r
             logger.error("Exception occurred during getOperationStatus Operation with DCAE", e);\r
-            logger.debug(e.getMessage()\r
-                    + " : got exception while retrieving status, trying again until we get 200 response code");\r
         } finally {\r
-            if (in != null) {\r
-                in.close();\r
-            }\r
             LoggingUtils.setTimeContext(startTime, new Date());\r
             metricsLogger.info("getOperationStatus complete");\r
         }\r
@@ -186,32 +116,17 @@ public class DcaeDispatcherServices {
     /**\r
      * This method send a getDeployments operation to DCAE.\r
      * \r
-     * @throws IOException\r
-     *             In case of issues with the Stream\r
      */\r
-    public void getDeployments() throws IOException {\r
-        InputStream in = null;\r
+    public void getDeployments() {\r
         Date startTime = new Date();\r
         LoggingUtils.setTargetContext("DCAE", "getDeployments");\r
         try {\r
-            String url = refProp.getStringValue("DCAE_DISPATCHER_URL") + "/dcae-deployments";\r
-            logger.info("Dcae Dispatcher deployments url - " + url);\r
-            URL obj = new URL(url);\r
-            HttpsURLConnection conn = (HttpsURLConnection) obj.openConnection();\r
-            conn.setRequestMethod("GET");\r
-            conn.setRequestProperty("X-ECOMP-RequestID", LoggingUtils.getRequestId());\r
-            int responseCode = conn.getResponseCode();\r
-            logger.debug("response code " + responseCode);\r
-            in = conn.getInputStream();\r
-            String res = new BufferedReader(new InputStreamReader(in)).lines().collect(Collectors.joining("\n"));\r
-            logger.debug("res:" + res);\r
+            String url = refProp.getStringValue(DCAE_URL_PROPERTY_NAME) + DCAE_URL_PREFIX;\r
+            DcaeHttpConnectionManager.doDcaeHttpQuery(url, "GET", null, null);\r
         } catch (Exception e) {\r
             logger.error("Exception occurred during getDeployments Operation with DCAE", e);\r
             throw new DcaeDeploymentException("Exception occurred during getDeployments Operation with DCAE", e);\r
         } finally {\r
-            if (in != null) {\r
-                in.close();\r
-            }\r
             LoggingUtils.setTimeContext(startTime, new Date());\r
             metricsLogger.info("getDeployments complete");\r
         }\r
@@ -225,88 +140,32 @@ public class DcaeDispatcherServices {
      * @param serviceTypeId\r
      *            Service type ID\r
      * @return The status URL\r
-     * @throws IOException\r
-     *             In case of issues with the Stream\r
      */\r
-    public String createNewDeployment(String deploymentId, String serviceTypeId) throws IOException {\r
-\r
-        String statusUrl = null;\r
-        InputStream inStream = null;\r
-        BufferedReader in = null;\r
+    public String createNewDeployment(String deploymentId, String serviceTypeId) {\r
         Date startTime = new Date();\r
         LoggingUtils.setTargetContext("DCAE", "createNewDeployment");\r
         try {\r
             ObjectNode rootNode = (ObjectNode) refProp.getJsonTemplate("dcae.deployment.template");\r
-            ((ObjectNode) rootNode).put("serviceTypeId", serviceTypeId);\r
+            rootNode.put("serviceTypeId", serviceTypeId);\r
             String apiBodyString = rootNode.toString();\r
-\r
             logger.info("Dcae api Body String - " + apiBodyString);\r
-            String url = refProp.getStringValue("DCAE_DISPATCHER_URL") + "/dcae-deployments/" + deploymentId;\r
-            logger.info("Dcae Dispatcher Service url - " + url);\r
-            URL obj = new URL(url);\r
-            HttpsURLConnection conn = (HttpsURLConnection) obj.openConnection();\r
-            conn.setRequestMethod("PUT");\r
-            conn.setRequestProperty("X-ECOMP-RequestID", LoggingUtils.getRequestId());\r
-            conn.setRequestProperty("Content-Type", "application/json");\r
-            conn.setDoOutput(true);\r
-            try (DataOutputStream wr = new DataOutputStream(conn.getOutputStream())) {\r
-                wr.writeBytes(apiBodyString);\r
-                wr.flush();\r
-            }\r
-\r
-            boolean requestFailed = true;\r
-            int responseCode = conn.getResponseCode();\r
-            logger.info("responseCode=" + responseCode);\r
-            if (responseCode == 200 || responseCode == 202) {\r
-                requestFailed = false;\r
-            }\r
-\r
-            inStream = conn.getErrorStream();\r
-            if (inStream == null) {\r
-                inStream = conn.getInputStream();\r
-            }\r
-\r
-            String responseStr = null;\r
-            if (inStream != null) {\r
-                in = new BufferedReader(new InputStreamReader(inStream));\r
-\r
-                String inputLine = null;\r
-\r
-                StringBuilder response = new StringBuilder();\r
-\r
-                while ((inputLine = in.readLine()) != null) {\r
-                    response.append(inputLine);\r
-                }\r
-\r
-                responseStr = response.toString();\r
-            }\r
-\r
-            if (responseStr != null && requestFailed) {\r
-                logger.error("requestFailed - responseStr=" + responseStr);\r
-                throw new BadRequestException(responseStr);\r
-            }\r
-\r
-            logger.debug("response code " + responseCode);\r
+            String url = refProp.getStringValue(DCAE_URL_PROPERTY_NAME) + DCAE_URL_PREFIX + deploymentId;\r
+            String responseStr = DcaeHttpConnectionManager.doDcaeHttpQuery(url, "PUT", apiBodyString,\r
+                    "application/json");\r
             JSONParser parser = new JSONParser();\r
             Object obj0 = parser.parse(responseStr);\r
             JSONObject jsonObj = (JSONObject) obj0;\r
-            JSONObject linksObj = (JSONObject) jsonObj.get("links");\r
-            statusUrl = (String) linksObj.get("status");\r
-            logger.debug("Status URL: " + statusUrl);\r
+            JSONObject linksObj = (JSONObject) jsonObj.get(DCAE_LINK_FIELD);\r
+            String statusUrl = (String) linksObj.get(DCAE_STATUS_FIELD);\r
+            logger.info(STATUS_URL_LOG + statusUrl);\r
+            return statusUrl;\r
         } catch (Exception e) {\r
             logger.error("Exception occurred during createNewDeployment Operation with DCAE", e);\r
             throw new DcaeDeploymentException("Exception occurred during createNewDeployment Operation with DCAE", e);\r
         } finally {\r
-            if (inStream != null) {\r
-                inStream.close();\r
-            }\r
-            if (in != null) {\r
-                in.close();\r
-            }\r
             LoggingUtils.setTimeContext(startTime, new Date());\r
             metricsLogger.info("createNewDeployment complete");\r
         }\r
-        return statusUrl;\r
     }\r
 \r
     /**\r
@@ -317,53 +176,30 @@ public class DcaeDispatcherServices {
      * @param serviceTypeId\r
      *            The service Type ID\r
      * @return The status URL\r
-     * @throws IOException\r
-     *             In case of issues with the Stream\r
      */\r
-    public String deleteExistingDeployment(String deploymentId, String serviceTypeId) throws IOException {\r
-\r
-        String statusUrl = null;\r
-        InputStream in = null;\r
+    public String deleteExistingDeployment(String deploymentId, String serviceTypeId) {\r
         Date startTime = new Date();\r
         LoggingUtils.setTargetContext("DCAE", "deleteExistingDeployment");\r
         try {\r
             String apiBodyString = "{\"serviceTypeId\": \"" + serviceTypeId + "\"}";\r
-            logger.debug(apiBodyString);\r
-            String url = refProp.getStringValue("DCAE_DISPATCHER_URL") + "/dcae-deployments/" + deploymentId;\r
-            logger.info("Dcae Dispatcher deployments url - " + url);\r
-            URL obj = new URL(url);\r
-            HttpsURLConnection conn = (HttpsURLConnection) obj.openConnection();\r
-            conn.setRequestMethod("DELETE");\r
-            conn.setRequestProperty("X-ECOMP-RequestID", LoggingUtils.getRequestId());\r
-            conn.setRequestProperty("Content-Type", "application/json");\r
-            conn.setDoOutput(true);\r
-            DataOutputStream wr = new DataOutputStream(conn.getOutputStream());\r
-            wr.writeBytes(apiBodyString);\r
-            wr.flush();\r
-\r
-            int responseCode = conn.getResponseCode();\r
-            logger.debug("response code " + responseCode);\r
-            in = conn.getInputStream();\r
-            String res = new BufferedReader(new InputStreamReader(in)).lines().collect(Collectors.joining("\n"));\r
-            logger.debug("res:" + res);\r
+            logger.info("Dcae api Body String - " + apiBodyString);\r
+            String url = refProp.getStringValue(DCAE_URL_PROPERTY_NAME) + DCAE_URL_PREFIX + deploymentId;\r
+            String responseStr = DcaeHttpConnectionManager.doDcaeHttpQuery(url, "DELETE", apiBodyString,\r
+                    "application/json");\r
             JSONParser parser = new JSONParser();\r
-            Object obj0 = parser.parse(res);\r
+            Object obj0 = parser.parse(responseStr);\r
             JSONObject jsonObj = (JSONObject) obj0;\r
-            JSONObject linksObj = (JSONObject) jsonObj.get("links");\r
-            statusUrl = (String) linksObj.get("status");\r
-            logger.debug("Status URL: " + statusUrl);\r
+            JSONObject linksObj = (JSONObject) jsonObj.get(DCAE_LINK_FIELD);\r
+            String statusUrl = (String) linksObj.get(DCAE_STATUS_FIELD);\r
+            logger.info(STATUS_URL_LOG + statusUrl);\r
+            return statusUrl;\r
         } catch (Exception e) {\r
             logger.error("Exception occurred during deleteExistingDeployment Operation with DCAE", e);\r
             throw new DcaeDeploymentException("Exception occurred during deleteExistingDeployment Operation with DCAE",\r
                     e);\r
         } finally {\r
-            if (in != null) {\r
-                in.close();\r
-            }\r
             LoggingUtils.setTimeContext(startTime, new Date());\r
             metricsLogger.info("deleteExistingDeployment complete");\r
         }\r
-        return statusUrl;\r
     }\r
-\r
 }
\ No newline at end of file
diff --git a/src/main/java/org/onap/clamp/clds/client/DcaeHttpConnectionManager.java b/src/main/java/org/onap/clamp/clds/client/DcaeHttpConnectionManager.java
new file mode 100644 (file)
index 0000000..cff955f
--- /dev/null
@@ -0,0 +1,208 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP CLAMP
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights
+ *                             reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END============================================
+ * ===================================================================
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+
+package org.onap.clamp.clds.client;
+
+import com.att.eelf.configuration.EELFLogger;
+import com.att.eelf.configuration.EELFManager;
+
+import java.io.BufferedReader;
+import java.io.DataOutputStream;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.net.HttpURLConnection;
+import java.net.URL;
+import java.security.KeyManagementException;
+import java.security.NoSuchAlgorithmException;
+import java.security.cert.CertificateException;
+import java.security.cert.X509Certificate;
+
+import javax.net.ssl.HostnameVerifier;
+import javax.net.ssl.HttpsURLConnection;
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.SSLSession;
+import javax.net.ssl.TrustManager;
+import javax.net.ssl.X509TrustManager;
+import javax.ws.rs.BadRequestException;
+
+import org.apache.commons.io.IOUtils;
+import org.onap.clamp.clds.util.LoggingUtils;
+
+public class DcaeHttpConnectionManager {
+    protected static final EELFLogger logger                  = EELFManager.getInstance()
+            .getLogger(DcaeHttpConnectionManager.class);
+    protected static final EELFLogger metricsLogger           = EELFManager.getInstance().getMetricsLogger();
+    private static final String       DCAE_REQUEST_FAILED_LOG = "Request Failed - response payload=";
+
+    private DcaeHttpConnectionManager() {
+    }
+
+    static TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
+        @Override
+        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
+            return null;
+        }
+
+        @Override
+        public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
+        }
+
+        @Override
+        public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
+        }
+    } };
+
+    private static void enableSslNoCheck() {
+        try {
+            SSLContext sc = SSLContext.getInstance("SSL");
+            sc.init(null, trustAllCerts, new java.security.SecureRandom());
+            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
+            HostnameVerifier allHostsValid = new HostnameVerifier() {
+                @Override
+                public boolean verify(String hostname, SSLSession session) {
+                    return true;
+                }
+            };
+            // set the allTrusting verifier
+            HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
+        } catch (KeyManagementException | NoSuchAlgorithmException e) {
+            logger.error("Error when disabling security on SSL", e);
+        }
+    }
+
+    private static String doHttpsQuery(URL url, String requestMethod, String payload, String contentType)
+            throws IOException {
+        logger.info("Using HTTPS URL to contact DCAE:" + url.toString());
+        HttpsURLConnection secureConnection = (HttpsURLConnection) url.openConnection();
+        secureConnection.setRequestMethod(requestMethod);
+        secureConnection.setRequestProperty("X-ECOMP-RequestID", LoggingUtils.getRequestId());
+        if (payload != null && contentType != null) {
+            secureConnection.setRequestProperty("Content-Type", contentType);
+            secureConnection.setDoOutput(true);
+            try (DataOutputStream wr = new DataOutputStream(secureConnection.getOutputStream())) {
+                wr.writeBytes(payload);
+                wr.flush();
+            }
+        }
+        int responseCode = secureConnection.getResponseCode();
+        logger.info("Response Code: " + responseCode);
+        if (responseCode < 400) {
+            try (BufferedReader reader = new BufferedReader(new InputStreamReader(secureConnection.getInputStream()))) {
+                String responseStr = IOUtils.toString(reader);
+                logger.info("Response Content: " + responseStr);
+                return responseStr;
+            }
+        } else {
+            // In case of connection failure just check whether there is a
+            // content or not
+            try (BufferedReader reader = new BufferedReader(new InputStreamReader(secureConnection.getErrorStream()))) {
+                String responseStr = IOUtils.toString(reader);
+                logger.error(DCAE_REQUEST_FAILED_LOG + responseStr);
+                throw new BadRequestException(responseStr);
+            }
+        }
+    }
+
+    private static String doHttpQuery(URL url, String requestMethod, String payload, String contentType)
+            throws IOException {
+        logger.info("Using HTTP URL to contact DCAE:" + url);
+        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
+        connection.setRequestMethod(requestMethod);
+        connection.setRequestProperty("X-ECOMP-RequestID", LoggingUtils.getRequestId());
+        if (payload != null && contentType != null) {
+            connection.setRequestProperty("Content-Type", contentType);
+            connection.setDoOutput(true);
+            try (DataOutputStream wr = new DataOutputStream(connection.getOutputStream())) {
+                wr.writeBytes(payload);
+                wr.flush();
+            }
+        }
+        int responseCode = connection.getResponseCode();
+        logger.info("Response Code: " + responseCode);
+        if (responseCode < 400) {
+            try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
+                String responseStr = IOUtils.toString(reader);
+                logger.info("Response Content: " + responseStr);
+                return responseStr;
+            }
+        } else {
+            // In case of connection failure just check whether there is a
+            // content or not
+            try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getErrorStream()))) {
+                String responseStr = IOUtils.toString(reader);
+                logger.error(DCAE_REQUEST_FAILED_LOG + responseStr);
+                throw new BadRequestException(responseStr);
+            }
+        }
+    }
+
+    /**
+     * This method does a HTTP query to DCAE with parameters specified.
+     * 
+     * @param url
+     *            The string HTTP or HTTPS that mustr be used to connect
+     * @param requestMethod
+     *            The Request Method (PUT, POST, GET, DELETE, etc ...)
+     * @param payload
+     *            The payload if any, in that case an ouputstream is opened
+     * @param contentType
+     *            The "application/json or application/xml, or whatever"
+     * @return The payload of the answer
+     * @throws IOException
+     *             In case of issue with the streams
+     */
+    public static String doDcaeHttpQuery(String url, String requestMethod, String payload, String contentType)
+            throws IOException {
+        return doDcaeHttpQuery(url, requestMethod, payload, contentType, false);
+    }
+
+    /**
+     * This method does a HTTP/HTTPS query to DCAE with parameters specified.
+     * 
+     * @param url
+     *            The string HTTP or HTTPS that mustr be used to connect
+     * @param requestMethod
+     *            The Request Method (PUT, POST, GET, DELETE, etc ...)
+     * @param payload
+     *            The payload if any, in that case an ouputstream is opened
+     * @param contentType
+     *            The "application/json or application/xml, or whatever"
+     * @param withoutSecurity
+     *            Disable or not the SSL security (certificate,hostname, etc...)
+     * @return The payload of the answer
+     * @throws IOException
+     *             In case of issue with the streams
+     */
+    public static String doDcaeHttpQuery(String url, String requestMethod, String payload, String contentType,
+            boolean withoutSecurity) throws IOException {
+        URL urlObj = new URL(url);
+        if (url.contains("https://")) { // Support for HTTPS
+            if (withoutSecurity) {
+                enableSslNoCheck();
+            }
+            return doHttpsQuery(urlObj, requestMethod, payload, contentType);
+        } else { // Support for HTTP
+            return doHttpQuery(urlObj, requestMethod, payload, contentType);
+        }
+    }
+}
index a53ea64..7662a9f 100644 (file)
@@ -27,17 +27,11 @@ import com.att.eelf.configuration.EELFLogger;
 import com.att.eelf.configuration.EELFManager;\r
 import com.fasterxml.jackson.core.JsonProcessingException;\r
 \r
-import java.io.BufferedReader;\r
 import java.io.IOException;\r
-import java.io.InputStreamReader;\r
-import java.net.HttpURLConnection;\r
-import java.net.URL;\r
 import java.security.GeneralSecurityException;\r
 import java.util.Date;\r
 import java.util.List;\r
 \r
-import javax.ws.rs.BadRequestException;\r
-\r
 import org.json.simple.JSONArray;\r
 import org.json.simple.JSONObject;\r
 import org.json.simple.parser.JSONParser;\r
@@ -67,8 +61,6 @@ public class DcaeInventoryServices {
     private RefProp                   refProp;\r
     @Autowired\r
     private CldsDao                   cldsDao;\r
-    @Autowired\r
-    private SdcCatalogServices        sdcCatalogServices;\r
 \r
     /**\r
      * \r
@@ -117,7 +109,7 @@ public class DcaeInventoryServices {
         } catch (JsonProcessingException e) {\r
             logger.error("Error during JSON decoding", e);\r
         } catch (IOException ex) {\r
-            logger.error("Error during JSON decoding", ex);\r
+            logger.error("Error during DCAE communication", ex);\r
         } finally {\r
             LoggingUtils.setTimeContext(startTime, new Date());\r
             metricsLogger.info("setEventInventory complete");\r
@@ -160,9 +152,7 @@ public class DcaeInventoryServices {
      *            The resource UUID\r
      * @return The DCAE inventory for the artifact\r
      * @throws IOException\r
-     *             In case of issues with the stream\r
      * @throws ParseException\r
-     *             In case of issues with the Json parsing\r
      * \r
      */\r
     public String getDcaeInformation(String artifactName, String serviceUuid, String resourceUuid)\r
@@ -174,34 +164,9 @@ public class DcaeInventoryServices {
         String fullUrl = refProp.getStringValue("DCAE_INVENTORY_URL") + "/dcae-service-types" + queryString;\r
         logger.info("Dcae Inventory Service full url - " + fullUrl);\r
         String daceInventoryResponse = null;\r
-        URL inventoryUrl = new URL(fullUrl);\r
-        HttpURLConnection conn = (HttpURLConnection) inventoryUrl.openConnection();\r
-        conn.setRequestMethod("GET");\r
-        String reqid = LoggingUtils.getRequestId();\r
-        logger.info("reqid set to " + reqid);\r
-        conn.setRequestProperty("X-ECOMP-RequestID", reqid);\r
-        boolean requestFailed = true;\r
-        int responseCode = conn.getResponseCode();\r
-        if (responseCode == 200) {\r
-            requestFailed = false;\r
-        }\r
-        StringBuilder response = new StringBuilder();\r
-        try (BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()))) {\r
-            String inputLine = null;\r
-            while ((inputLine = in.readLine()) != null) {\r
-                response.append(inputLine);\r
-            }\r
-        }\r
-        String responseStr = response.toString();\r
-        if (responseStr != null) {\r
-            if (requestFailed) {\r
-                logger.error("requestFailed - responseStr=" + response);\r
-                throw new BadRequestException(responseStr);\r
-            }\r
-        }\r
-        String jsonResponseString = response.toString();\r
+        String responseStr = DcaeHttpConnectionManager.doDcaeHttpQuery(fullUrl, "GET", null, null);\r
         JSONParser parser = new JSONParser();\r
-        Object obj0 = parser.parse(jsonResponseString);\r
+        Object obj0 = parser.parse(responseStr);\r
         JSONObject jsonObj = (JSONObject) obj0;\r
         Long totalCount = (Long) jsonObj.get("totalCount");\r
         int numServices = totalCount.intValue();\r
diff --git a/src/test/java/org/onap/clamp/clds/it/DcaeHttpConnectionManagerItCase.java b/src/test/java/org/onap/clamp/clds/it/DcaeHttpConnectionManagerItCase.java
new file mode 100644 (file)
index 0000000..7714270
--- /dev/null
@@ -0,0 +1,94 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP CLAMP
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights
+ *                             reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License"); 
+ * you may not use this file except in compliance with the License. 
+ * You may obtain a copy of the License at
+ * 
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software 
+ * distributed under the License is distributed on an "AS IS" BASIS, 
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
+ * See the License for the specific language governing permissions and 
+ * limitations under the License.
+ * ============LICENSE_END============================================
+ * ===================================================================
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+
+package org.onap.clamp.clds.it;
+
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
+import java.io.IOException;
+
+import javax.ws.rs.BadRequestException;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.onap.clamp.clds.AbstractItCase;
+import org.onap.clamp.clds.client.DcaeHttpConnectionManager;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
+import org.springframework.test.context.TestPropertySource;
+import org.springframework.test.context.junit4.SpringRunner;
+
+/**
+ * Test HTTP and HTTPS settings + redirection of HTTP to HTTPS.
+ */
+@RunWith(SpringRunner.class)
+@SpringBootTest(webEnvironment = WebEnvironment.DEFINED_PORT)
+@TestPropertySource(locations = "classpath:https/https-test.properties")
+public class DcaeHttpConnectionManagerItCase extends AbstractItCase {
+    @Value("${server.port}")
+    private String httpsPort;
+    @Value("${server.http-to-https-redirection.port}")
+    private String httpPort;
+
+    @Test
+    public void testHttpGet() throws Exception {
+        String response = DcaeHttpConnectionManager
+                .doDcaeHttpQuery("http://localhost:" + this.httpPort + "/designer/index.html", "GET", null, null, true);
+        assertNotNull(response);
+        // Should be a redirection so 302, so empty
+        assertTrue(response.isEmpty());
+    }
+
+    @Test
+    public void testHttpsGet() throws Exception {
+        String response = DcaeHttpConnectionManager.doDcaeHttpQuery(
+                "https://localhost:" + this.httpsPort + "/designer/index.html", "GET", null, null, true);
+        assertNotNull(response);
+        // Should contain something
+        assertTrue(!response.isEmpty());
+    }
+
+    @Test(expected = BadRequestException.class)
+    public void testHttpsGet404() throws IOException {
+        DcaeHttpConnectionManager.doDcaeHttpQuery("https://localhost:" + this.httpsPort + "/designer/index1.html",
+                "GET", null, null, true);
+        fail("Should have raised an BadRequestException exception");
+    }
+
+    @Test(expected = BadRequestException.class)
+    public void testHttpsPost404() throws IOException {
+        DcaeHttpConnectionManager.doDcaeHttpQuery("https://localhost:" + this.httpsPort + "/designer/index1.html",
+                "POST", "", "application/json", true);
+        fail("Should have raised an BadRequestException exception");
+    }
+
+    @Test(expected = IOException.class)
+    public void testHttpException() throws IOException {
+        DcaeHttpConnectionManager.doDcaeHttpQuery("http://localhost:" + this.httpsPort + "/designer/index.html", "GET",
+                null, null, true);
+        fail("Should have raised an IOException exception");
+    }
+}