Fixed various sonar identified code smells
[clamp.git] / src / main / java / org / onap / clamp / clds / client / DcaeDispatcherServices.java
index e5144bf..83401a3 100644 (file)
-/*-\r
- * ============LICENSE_START=======================================================\r
- * ONAP CLAMP\r
- * ================================================================================\r
- * Copyright (C) 2017 AT&T Intellectual Property. All rights\r
- *                             reserved.\r
- * ================================================================================\r
- * Licensed under the Apache License, Version 2.0 (the "License");\r
- * you may not use this file except in compliance with the License.\r
- * You may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * Unless required by applicable law or agreed to in writing, software\r
- * distributed under the License is distributed on an "AS IS" BASIS,\r
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
- * See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- * ============LICENSE_END============================================\r
- * ===================================================================\r
- * ECOMP is a trademark and service mark of AT&T Intellectual Property.\r
- */\r
-\r
-package org.onap.clamp.clds.client;\r
-\r
-import java.io.BufferedReader;\r
-import java.io.DataOutputStream;\r
-import java.io.InputStream;\r
-import java.io.InputStreamReader;\r
-import java.net.URL;\r
-import java.util.stream.Collectors;\r
-\r
-import javax.net.ssl.HttpsURLConnection;\r
-\r
-import org.json.simple.JSONObject;\r
-import org.json.simple.parser.JSONParser;\r
-import org.onap.clamp.clds.model.refprop.RefProp;\r
-import org.springframework.beans.factory.annotation.Autowired;\r
-\r
-import com.att.eelf.configuration.EELFLogger;\r
-import com.att.eelf.configuration.EELFManager;\r
-\r
-/**\r
- *\r
- *\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
-    @Autowired\r
-    private RefProp                 refProp;\r
-\r
-    /**\r
-     *\r
-     * @param deploymentId\r
-     * @return\r
-     * @throws Exception\r
-     */\r
-    public String deleteDeployment(String deploymentId) throws Exception {\r
-\r
-        String statusUrl = null;\r
-        InputStream in = null;\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.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
-                StringBuffer response = new StringBuffer();\r
-                while ((inputLine = bufferedReader.readLine()) != null) {\r
-                    response.append(inputLine);\r
-                }\r
-                responseStr = response.toString();\r
-            }\r
-\r
-            if (responseStr != null) {\r
-                if (requestFailed) {\r
-                    logger.error("requestFailed - responseStr=" + responseStr);\r
-                    throw new Exception(responseStr);\r
-                }\r
-            }\r
-\r
-            logger.debug("response code " + responseCode);\r
-            in = conn.getInputStream();\r
-            logger.debug("res:" + responseStr);\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
-        } catch (Exception e) {\r
-            logger.error(e.getClass().getName() + " " + e.getMessage());\r
-            throw e;\r
-        } finally {\r
-            if (in != null) {\r
-                in.close();\r
-            }\r
-        }\r
-\r
-        return statusUrl;\r
-\r
-    }\r
-\r
-    /**\r
-     *\r
-     * @param statusUrl\r
-     * @return\r
-     * @throws Exception\r
-     */\r
-    public String getOperationStatus(String statusUrl) throws Exception {\r
-\r
-        //Assigning processing status to monitor operation status further\r
-        String opStatus = "processing";\r
-        InputStream in = null;\r
-        try {\r
-            URL obj = new URL(statusUrl);\r
-            HttpsURLConnection conn = (HttpsURLConnection) obj.openConnection();\r
-            conn.setRequestMethod("GET");\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
-        } catch (Exception e) {\r
-            logger.debug(e.getClass().getName() + " " + e.getMessage());\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
-        }\r
-\r
-        return opStatus;\r
-    }\r
-\r
-    /**\r
-     *\r
-     * @throws Exception\r
-     */\r
-    public void getDeployments() throws Exception {\r
-        InputStream in = null;\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
-            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
-        } catch (Exception e) {\r
-            logger.error("Exception occurred during DCAE communication", e);\r
-            throw e;\r
-        } finally {\r
-            if (in != null) {\r
-                in.close();\r
-            }\r
-        }\r
-    }\r
-\r
-    /**\r
-     * Returns status URL for deployment operation\r
-     *\r
-     * @param deploymentId\r
-     * @param serviceTypeId\r
-     * @return\r
-     * @throws Exception\r
-     */\r
-    public String createNewDeployment(String deploymentId, String serviceTypeId) throws Exception {\r
-\r
-        String statusUrl = null;\r
-        InputStream inStream = null;\r
-        BufferedReader in = null;\r
-        try {\r
-            String apiBodyString = "{\"serviceTypeId\": \"" + serviceTypeId + "\"}";\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("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
-                StringBuffer response = new StringBuffer();\r
-\r
-                while ((inputLine = in.readLine()) != null) {\r
-                    response.append(inputLine);\r
-                }\r
-\r
-                responseStr = response.toString();\r
-            }\r
-\r
-            if (responseStr != null) {\r
-                if (requestFailed) {\r
-                    logger.error("requestFailed - responseStr=" + responseStr);\r
-                    throw new Exception(responseStr);\r
-                }\r
-            }\r
-\r
-            logger.debug("response code " + responseCode);\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
-        } catch (Exception e) {\r
-            logger.error("Exception occurred during the DCAE communication", e);\r
-            throw e;\r
-        } finally {\r
-            if (inStream != null) {\r
-                inStream.close();\r
-            }\r
-            if (in != null) {\r
-                in.close();\r
-            }\r
-        }\r
-        return statusUrl;\r
-    }\r
-\r
-    /**\r
-     *\r
-     * @param deploymentId\r
-     * @param serviceTypeId\r
-     * @return\r
-     * @throws Exception\r
-     */\r
-    public String deleteExistingDeployment(String deploymentId, String serviceTypeId) throws Exception {\r
-\r
-        String statusUrl = null;\r
-        InputStream in = null;\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("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
-            JSONParser parser = new JSONParser();\r
-            Object obj0 = parser.parse(res);\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
-        } catch (Exception e) {\r
-            logger.error("Exception occurred during DCAE communication", e);\r
-            throw e;\r
-        } finally {\r
-            if (in != null) {\r
-                in.close();\r
-            }\r
-        }\r
-        return statusUrl;\r
-    }\r
-\r
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP CLAMP
+ * ================================================================================
+ * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights
+ *                             reserved.
+ * ================================================================================
+ * Modifications Copyright (c) 2019 Samsung
+ * ================================================================================
+ * 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============================================
+ * ===================================================================
+ *
+ */
+
+package org.onap.clamp.clds.client;
+
+import com.att.eelf.configuration.EELFLogger;
+import com.att.eelf.configuration.EELFManager;
+
+import com.google.gson.JsonObject;
+import java.io.IOException;
+import java.util.Date;
+
+import org.json.simple.JSONObject;
+import org.json.simple.parser.JSONParser;
+import org.json.simple.parser.ParseException;
+import org.onap.clamp.clds.config.ClampProperties;
+import org.onap.clamp.clds.exception.dcae.DcaeDeploymentException;
+import org.onap.clamp.clds.util.LoggingUtils;
+import org.onap.clamp.util.HttpConnectionManager;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+
+/**
+ * This class implements the communication with DCAE for the service
+ * deployments.
+ */
+@Component
+public class DcaeDispatcherServices {
+
+    protected static final EELFLogger logger = EELFManager.getInstance().getLogger(DcaeDispatcherServices.class);
+    protected static final EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger();
+    private final ClampProperties refProp;
+    private final HttpConnectionManager dcaeHttpConnectionManager;
+    private static final String STATUS_URL_LOG = "Status URL extracted: ";
+    private static final String DCAE_URL_PREFIX = "/dcae-deployments/";
+    private static final String DCAE_URL_PROPERTY_NAME = "dcae.dispatcher.url";
+    private static final String DCAE_LINK_FIELD = "links";
+    private static final String DCAE_STATUS_FIELD = "status";
+
+    @Autowired
+    public DcaeDispatcherServices(ClampProperties refProp, HttpConnectionManager dcaeHttpConnectionManager) {
+        this.refProp = refProp;
+        this.dcaeHttpConnectionManager = dcaeHttpConnectionManager;
+    }
+
+    /**
+     * Get the Operation Status from a specified URL with retry.
+     * @param operationStatusUrl
+     *        The URL of the DCAE
+     * @return The status
+     * @throws InterruptedException Exception during the retry
+     */
+    public String getOperationStatusWithRetry(String operationStatusUrl) throws InterruptedException {
+        String operationStatus = "";
+        for (int i = 0; i < Integer.valueOf(refProp.getStringValue("dcae.dispatcher.retry.limit")); i++) {
+            logger.info("Trying to get Operation status on DCAE for url:" + operationStatusUrl);
+            operationStatus = getOperationStatus(operationStatusUrl);
+            logger.info("Current Status is:" + operationStatus);
+            if (!"processing".equalsIgnoreCase(operationStatus)) {
+                return operationStatus;
+            } else {
+                Thread.sleep(Integer.valueOf(refProp.getStringValue("dcae.dispatcher.retry.interval")));
+            }
+        }
+        logger.warn("Number of attempts on DCAE is over, stopping the getOperationStatus method");
+        return operationStatus;
+    }
+
+    /**
+     * Get the Operation Status from a specified URL.
+     * @param statusUrl
+     *        The URL provided by a previous DCAE Query
+     * @return The status
+     */
+    public String getOperationStatus(String statusUrl) {
+        // Assigning processing status to monitor operation status further
+        String opStatus = "processing";
+        Date startTime = new Date();
+        LoggingUtils.setTargetContext("DCAE", "getOperationStatus");
+        try {
+            String responseStr = dcaeHttpConnectionManager.doHttpRequest(statusUrl, "GET", null,
+                                                                         null, "DCAE", null,
+                                                                         null);
+            JSONObject jsonObj = parseResponse(responseStr);
+            String operationType = (String) jsonObj.get("operationType");
+            String status = (String) jsonObj.get(DCAE_STATUS_FIELD);
+            logger.info("Operation Type - " + operationType + ", Status " + status);
+            LoggingUtils.setResponseContext("0", "Get operation status success", this.getClass().getName());
+            opStatus = status;
+        } catch (Exception e) {
+            LoggingUtils.setResponseContext("900", "Get operation status failed", this.getClass().getName());
+            LoggingUtils.setErrorContext("900", "Get operation status error");
+            logger.error("Exception occurred during getOperationStatus Operation with DCAE", e);
+        } finally {
+            LoggingUtils.setTimeContext(startTime, new Date());
+            metricsLogger.info("getOperationStatus complete");
+        }
+        return opStatus;
+    }
+
+    /**
+     * Returns status URL for createNewDeployment operation.
+     * @param deploymentId
+     *        The deployment ID
+     * @param serviceTypeId
+     *        Service type ID
+     * @param blueprintInputJson
+     *        The value for each blueprint parameters in a flat JSON
+     * @return The status URL
+     */
+    public String createNewDeployment(String deploymentId, String serviceTypeId, JsonObject blueprintInputJson) {
+        Date startTime = new Date();
+        LoggingUtils.setTargetContext("DCAE", "createNewDeployment");
+        try {
+            JsonObject rootObject = refProp.getJsonTemplate("dcae.deployment.template").getAsJsonObject();
+            rootObject.addProperty("serviceTypeId", serviceTypeId);
+            if (blueprintInputJson != null) {
+                rootObject.add("inputs", blueprintInputJson);
+            }
+            String apiBodyString = rootObject.toString();
+            logger.info("Dcae api Body String - " + apiBodyString);
+            String url = refProp.getStringValue(DCAE_URL_PROPERTY_NAME) + DCAE_URL_PREFIX + deploymentId;
+            String statusUrl = getDcaeResponse(url, "PUT", apiBodyString, "application/json", DCAE_LINK_FIELD,
+                DCAE_STATUS_FIELD);
+            LoggingUtils.setResponseContext("0", "Create new deployment failed", this.getClass().getName());
+            return statusUrl;
+        } catch (Exception e) {
+            LoggingUtils.setResponseContext("900", "Create new deployment failed", this.getClass().getName());
+            LoggingUtils.setErrorContext("900", "Create new deployment error");
+            logger.error("Exception occurred during createNewDeployment Operation with DCAE", e);
+            throw new DcaeDeploymentException("Exception occurred during createNewDeployment Operation with DCAE", e);
+        } finally {
+            LoggingUtils.setTimeContext(startTime, new Date());
+            metricsLogger.info("createNewDeployment complete");
+        }
+    }
+
+    /***
+     * Returns status URL for deleteExistingDeployment operation.
+     *
+     * @param deploymentId
+     *        The deployment ID
+     * @param serviceTypeId
+     *        The service Type ID
+     * @return The status URL
+     */
+    public String deleteExistingDeployment(String deploymentId, String serviceTypeId) {
+        Date startTime = new Date();
+        LoggingUtils.setTargetContext("DCAE", "deleteExistingDeployment");
+        try {
+            String apiBodyString = "{\"serviceTypeId\": \"" + serviceTypeId + "\"}";
+            logger.info("Dcae api Body String - " + apiBodyString);
+            String url = refProp.getStringValue(DCAE_URL_PROPERTY_NAME) + DCAE_URL_PREFIX + deploymentId;
+            String statusUrl = getDcaeResponse(url, "DELETE", apiBodyString, "application/json", DCAE_LINK_FIELD,
+                DCAE_STATUS_FIELD);
+            LoggingUtils.setResponseContext("0", "Delete existing deployment success", this.getClass().getName());
+            return statusUrl;
+
+        } catch (Exception e) {
+            LoggingUtils.setResponseContext("900", "Delete existing deployment failed", this.getClass().getName());
+            LoggingUtils.setErrorContext("900", "Delete existing deployment error");
+            logger.error("Exception occurred during deleteExistingDeployment Operation with DCAE", e);
+            throw new DcaeDeploymentException("Exception occurred during deleteExistingDeployment Operation with DCAE",
+                e);
+        } finally {
+            LoggingUtils.setTimeContext(startTime, new Date());
+            metricsLogger.info("deleteExistingDeployment complete");
+        }
+    }
+
+    private String getDcaeResponse(String url, String requestMethod, String payload, String contentType, String node,
+        String nodeAttr) throws IOException, ParseException {
+        Date startTime = new Date();
+        try {
+            String responseStr = dcaeHttpConnectionManager.doHttpRequest(url, requestMethod, payload, contentType, "DCAE", null, null);
+            JSONObject jsonObj = parseResponse(responseStr);
+            JSONObject linksObj = (JSONObject) jsonObj.get(node);
+            String statusUrl = (String) linksObj.get(nodeAttr);
+            logger.info(STATUS_URL_LOG + statusUrl);
+            return statusUrl;
+        } catch (IOException | ParseException e) {
+            logger.error("Exception occurred getting response from DCAE", e);
+            throw e;
+        } finally {
+            LoggingUtils.setTimeContext(startTime, new Date());
+            metricsLogger.info("getDcaeResponse complete");
+        }
+    }
+
+    private JSONObject parseResponse(String responseStr) throws ParseException {
+        JSONParser parser = new JSONParser();
+        return (JSONObject) parser.parse(responseStr);
+    }
 }
\ No newline at end of file