Fix the ServiceTypeId null
[clamp.git] / src / main / java / org / onap / clamp / clds / client / DcaeInventoryServices.java
index 192dcdb..1e5deda 100644 (file)
@@ -2,7 +2,7 @@
  * ============LICENSE_START=======================================================\r
  * ONAP CLAMP\r
  * ================================================================================\r
- * Copyright (C) 2017 AT&T Intellectual Property. All rights\r
+ * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights\r
  *                             reserved.\r
  * ================================================================================\r
  * Licensed under the Apache License, Version 2.0 (the "License");\r
@@ -18,7 +18,7 @@
  * limitations under the License.\r
  * ============LICENSE_END============================================\r
  * ===================================================================\r
- * ECOMP is a trademark and service mark of AT&T Intellectual Property.\r
+ * \r
  */\r
 \r
 package org.onap.clamp.clds.client;\r
@@ -26,12 +26,9 @@ package org.onap.clamp.clds.client;
 import com.att.eelf.configuration.EELFLogger;\r
 import com.att.eelf.configuration.EELFManager;\r
 import com.fasterxml.jackson.core.JsonProcessingException;\r
+import com.fasterxml.jackson.databind.node.ObjectNode;\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.util.Date;\r
 import java.util.List;\r
 \r
@@ -41,33 +38,37 @@ import org.json.simple.JSONArray;
 import org.json.simple.JSONObject;\r
 import org.json.simple.parser.JSONParser;\r
 import org.json.simple.parser.ParseException;\r
+import org.onap.clamp.clds.config.ClampProperties;\r
 import org.onap.clamp.clds.dao.CldsDao;\r
 import org.onap.clamp.clds.model.CldsEvent;\r
 import org.onap.clamp.clds.model.CldsModel;\r
 import org.onap.clamp.clds.model.DcaeEvent;\r
-import org.onap.clamp.clds.model.prop.Global;\r
-import org.onap.clamp.clds.model.prop.ModelProperties;\r
-import org.onap.clamp.clds.model.refprop.RefProp;\r
+import org.onap.clamp.clds.model.dcae.DcaeInventoryResponse;\r
+import org.onap.clamp.clds.model.properties.Global;\r
+import org.onap.clamp.clds.model.properties.ModelProperties;\r
+import org.onap.clamp.clds.util.JacksonUtils;\r
 import org.onap.clamp.clds.util.LoggingUtils;\r
 import org.springframework.beans.factory.annotation.Autowired;\r
+import org.springframework.stereotype.Component;\r
 \r
 /**\r
  * This class implements the communication with DCAE for the service inventory.\r
- *\r
  */\r
+@Component\r
 public class DcaeInventoryServices {\r
-    protected static final EELFLogger logger        = EELFManager.getInstance().getLogger(DcaeInventoryServices.class);\r
-    protected static final EELFLogger auditLogger   = EELFManager.getInstance().getAuditLogger();\r
-    protected static final EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger();\r
-\r
-    @Autowired\r
-    private RefProp                   refProp;\r
 \r
+    protected static final EELFLogger logger = EELFManager.getInstance().getLogger(DcaeInventoryServices.class);\r
+    protected static final EELFLogger auditLogger = EELFManager.getInstance().getAuditLogger();\r
+    protected static final EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger();\r
+    public static final String DCAE_INVENTORY_URL = "dcae.inventory.url";\r
+    public static final String DCAE_INVENTORY_RETRY_INTERVAL = "dcae.intentory.retry.interval";\r
+    public static final String DCAE_INVENTORY_RETRY_LIMIT = "dcae.intentory.retry.limit";\r
+    public static final String DCAE_TYPE_NAME = "typeName";\r
+    public static final String DCAE_TYPE_ID = "typeId";\r
     @Autowired\r
-    private CldsDao                   cldsDao;\r
-\r
+    private ClampProperties refProp;\r
     @Autowired\r
-    private SdcCatalogServices        sdcCatalogServices;\r
+    private CldsDao cldsDao;\r
 \r
     /**\r
      * Set the event inventory.\r
@@ -77,65 +78,64 @@ public class DcaeInventoryServices {
      * @param userId\r
      *            The user ID\r
      * @throws ParseException\r
-     *             In case of issues during the parsing of DCAE answer\r
+     *             In case of DCAE Json parse exception\r
      */\r
-    public void setEventInventory(CldsModel cldsModel, String userId) throws ParseException {\r
+    public void setEventInventory(CldsModel cldsModel, String userId) throws ParseException, InterruptedException {\r
         String artifactName = cldsModel.getControlName();\r
         DcaeEvent dcaeEvent = new DcaeEvent();\r
-        String isDcaeInfoAvailable = null;\r
+        DcaeInventoryResponse dcaeResponse = null;\r
         Date startTime = new Date();\r
         LoggingUtils.setTargetContext("DCAE", "setEventInventory");\r
         if (artifactName != null) {\r
             artifactName = artifactName + ".yml";\r
         }\r
         try {\r
-            /*\r
-             * Below are the properties required for calling the dcae inventory\r
-             * url call\r
-             */\r
+            // Below are the properties required for calling the dcae inventory\r
             ModelProperties prop = new ModelProperties(cldsModel.getName(), cldsModel.getControlName(), null, false,\r
                     "{}", cldsModel.getPropText());\r
             Global global = prop.getGlobal();\r
             String invariantServiceUuid = global.getService();\r
             List<String> resourceUuidList = global.getResourceVf();\r
-            String serviceUuid = sdcCatalogServices.getServiceUuidFromServiceInvariantId(invariantServiceUuid);\r
             String resourceUuid = "";\r
             if (resourceUuidList != null && !resourceUuidList.isEmpty()) {\r
-                resourceUuid = resourceUuidList.get(0).toString();\r
+                resourceUuid = resourceUuidList.get(0);\r
             }\r
-            /* Invemtory service url is called in this method */\r
-            isDcaeInfoAvailable = getDcaeInformation(artifactName, serviceUuid, resourceUuid);\r
-\r
+            /* Inventory service url is called in this method */\r
+            dcaeResponse = getDcaeInformation(artifactName, invariantServiceUuid, resourceUuid);\r
             /* set dcae events */\r
             dcaeEvent.setArtifactName(artifactName);\r
             dcaeEvent.setEvent(DcaeEvent.EVENT_DISTRIBUTION);\r
-\r
+            LoggingUtils.setResponseContext("0", "Set inventory success", this.getClass().getName());\r
         } catch (JsonProcessingException e) {\r
+            LoggingUtils.setResponseContext("900", "Set inventory failed", this.getClass().getName());\r
+            LoggingUtils.setErrorContext("900", "Set inventory error");\r
             logger.error("Error during JSON decoding", e);\r
         } catch (IOException ex) {\r
-            logger.error("Error during JSON decoding", ex);\r
+            LoggingUtils.setResponseContext("900", "Set inventory failed", this.getClass().getName());\r
+            LoggingUtils.setErrorContext("900", "Set inventory error");\r
+            logger.error("Error during DCAE communication", ex);\r
         } finally {\r
             LoggingUtils.setTimeContext(startTime, new Date());\r
             metricsLogger.info("setEventInventory complete");\r
         }\r
-        /* Null whether the DCAE has items lenght or not */\r
-        if (isDcaeInfoAvailable != null) {\r
-            /* Inserting Event in to DB */\r
-            logger.info(isDcaeInfoAvailable);\r
-            JSONParser parser = new JSONParser();\r
-            Object obj0 = parser.parse(isDcaeInfoAvailable);\r
-            JSONObject jsonObj = (JSONObject) obj0;\r
+        this.analyzeAndSaveDcaeResponse(dcaeResponse, cldsModel, dcaeEvent, userId);\r
+    }\r
+\r
+    private void analyzeAndSaveDcaeResponse(DcaeInventoryResponse dcaeResponse, CldsModel cldsModel,\r
+            DcaeEvent dcaeEvent, String userId) {\r
+        if (dcaeResponse != null) {\r
+            logger.info("Dcae Response for query on inventory: " + dcaeResponse);\r
             String oldTypeId = cldsModel.getTypeId();\r
             String newTypeId = "";\r
-            if (jsonObj.get("typeId") != null) {\r
-                newTypeId = jsonObj.get("typeId").toString();\r
-                cldsModel.setTypeId(jsonObj.get("typeId").toString());\r
+            if (dcaeResponse.getTypeId() != null) {\r
+                newTypeId = dcaeResponse.getTypeId();\r
+                cldsModel.setTypeId(dcaeResponse.getTypeId());\r
             }\r
-            // cldsModel.setTypeName(cldsModel.getControlName().toString()+".yml");\r
-            if (jsonObj.get("typeName") != null) {\r
-                cldsModel.setTypeName(jsonObj.get("typeName").toString());\r
+            if (dcaeResponse.getTypeName() != null) {\r
+                cldsModel.setTypeName(dcaeResponse.getTypeName());\r
             }\r
-            if (oldTypeId == null || !oldTypeId.equalsIgnoreCase(newTypeId)) {\r
+            if (oldTypeId == null || !oldTypeId.equalsIgnoreCase(newTypeId)\r
+                    || cldsModel.getEvent().getActionCd().equalsIgnoreCase(CldsEvent.ACTION_SUBMITDCAE)) {\r
                 CldsEvent.insEvent(cldsDao, dcaeEvent.getControlName(), userId, dcaeEvent.getCldsActionCd(),\r
                         CldsEvent.ACTION_STATE_RECEIVED, null);\r
             }\r
@@ -145,6 +145,25 @@ public class DcaeInventoryServices {
         }\r
     }\r
 \r
+    private int getTotalCountFromDcaeInventoryResponse(String responseStr) throws ParseException {\r
+        JSONParser parser = new JSONParser();\r
+        Object obj0 = parser.parse(responseStr);\r
+        JSONObject jsonObj = (JSONObject) obj0;\r
+        Long totalCount = (Long) jsonObj.get("totalCount");\r
+        return totalCount.intValue();\r
+    }\r
+\r
+    private DcaeInventoryResponse getItemsFromDcaeInventoryResponse(String responseStr)\r
+            throws ParseException, IOException {\r
+        JSONParser parser = new JSONParser();\r
+        Object obj0 = parser.parse(responseStr);\r
+        JSONObject jsonObj = (JSONObject) obj0;\r
+        JSONArray itemsArray = (JSONArray) jsonObj.get("items");\r
+        JSONObject dcaeServiceType0 = (JSONObject) itemsArray.get(0);\r
+        return JacksonUtils.getObjectMapperInstance().readValue(dcaeServiceType0.toString(),\r
+                DcaeInventoryResponse.class);\r
+    }\r
+\r
     /**\r
      * DO a query to DCAE to get some Information.\r
      * \r
@@ -154,72 +173,119 @@ public class DcaeInventoryServices {
      *            The service UUID\r
      * @param resourceUuid\r
      *            The resource UUID\r
-     * @return The DCAE inventory for the artifact\r
+     * @return The DCAE inventory for the artifact in DcaeInventoryResponse\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
-    public String getDcaeInformation(String artifactName, String serviceUuid, String resourceUuid)\r
-            throws IOException, ParseException {\r
+    public DcaeInventoryResponse getDcaeInformation(String artifactName, String serviceUuid, String resourceUuid)\r
+            throws IOException, ParseException, InterruptedException {\r
         Date startTime = new Date();\r
         LoggingUtils.setTargetContext("DCAE", "getDcaeInformation");\r
-        String queryString = "?sdcResourceId=" + resourceUuid + "&sdcServiceId=" + serviceUuid + "&typeName="\r
+        String queryString = "?asdcResourceId=" + resourceUuid + "&asdcServiceId=" + serviceUuid + "&typeName="\r
                 + artifactName;\r
-        String fullUrl = refProp.getStringValue("DCAE_INVENTORY_URL") + "/dcae-service-types" + queryString;\r
-\r
+        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
-\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
+        DcaeInventoryResponse response = queryDcaeInventory(fullUrl);\r
+        LoggingUtils.setResponseContext("0", "Get Dcae Information success", this.getClass().getName());\r
+        LoggingUtils.setTimeContext(startTime, new Date());\r
+        return response;\r
+    }\r
 \r
-        boolean requestFailed = true;\r
-        int responseCode = conn.getResponseCode();\r
-        if (responseCode == 200) {\r
-            requestFailed = false;\r
+    private DcaeInventoryResponse queryDcaeInventory(String fullUrl)\r
+            throws IOException, InterruptedException, ParseException {\r
+        int retryInterval = 0;\r
+        int retryLimit = 1;\r
+        if (refProp.getStringValue(DCAE_INVENTORY_RETRY_LIMIT) != null) {\r
+            retryLimit = Integer.valueOf(refProp.getStringValue(DCAE_INVENTORY_RETRY_LIMIT));\r
         }\r
-\r
-        StringBuilder response = new StringBuilder();\r
-\r
-        try (BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()))) {\r
-            String inputLine = null;\r
-\r
-            while ((inputLine = in.readLine()) != null) {\r
-                response.append(inputLine);\r
-            }\r
+        if (refProp.getStringValue(DCAE_INVENTORY_RETRY_INTERVAL) != null) {\r
+            retryInterval = Integer.valueOf(refProp.getStringValue(DCAE_INVENTORY_RETRY_INTERVAL));\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
+        for (int i = 0; i < retryLimit; i++) {\r
+            metricsLogger.info("Attempt n°" + i + " to contact DCAE inventory");\r
+            String response = DcaeHttpConnectionManager.doDcaeHttpQuery(fullUrl, "GET", null, null);\r
+            int totalCount = getTotalCountFromDcaeInventoryResponse(response);\r
+            metricsLogger.info("getDcaeInformation complete: totalCount returned=" + totalCount);\r
+            if (totalCount > 0) {\r
+                logger.info("getDcaeInformation, answer from DCAE inventory:" + response);\r
+                return getItemsFromDcaeInventoryResponse(response);\r
             }\r
+            logger.info(\r
+                    "Dcae inventory totalCount returned is 0, so waiting " + retryInterval + "ms before retrying ...");\r
+            // wait for a while and try to connect to DCAE again\r
+            Thread.sleep(retryInterval);\r
         }\r
-        String jsonResponseString = response.toString();\r
-        JSONParser parser = new JSONParser();\r
-        Object obj0 = parser.parse(jsonResponseString);\r
-\r
-        JSONObject jsonObj = (JSONObject) obj0;\r
-\r
-        Long totalCount = (Long) jsonObj.get("totalCount");\r
+        logger.warn("Dcae inventory totalCount returned is still 0, after " + retryLimit + " attempts, returning NULL");\r
+        return null;\r
+    }\r
 \r
-        int numServices = totalCount.intValue();\r
-        if (numServices == 0) {\r
-            daceInventoryResponse = null;\r
-        } else if (numServices > 0) {\r
-            JSONArray itemsArray = (JSONArray) jsonObj.get("items");\r
-            JSONObject dcaeServiceType0 = (JSONObject) itemsArray.get(0);\r
-            daceInventoryResponse = dcaeServiceType0.toString();\r
-            logger.info(daceInventoryResponse.toString());\r
+    /**\r
+     * Inserts a new DCAEServiceType or updates an existing instance. If the\r
+     * typeName is same second time(already exists) then the\r
+     * DCAEServiceTypeRequest is updated\r
+     * \r
+     * @param blueprintTemplate\r
+     *            blueprint content\r
+     * @param owner\r
+     *            owner of the data\r
+     * @param typeName\r
+     *            The type/artifact Name\r
+     * @param typeVersion\r
+     *            type version\r
+     * @param asdcServiceId\r
+     *            The service UUID\r
+     * @param asdcResourceId\r
+     *            The vf UUID\r
+     * @return The DCAE inventory type id\r
+     */\r
+    public String createupdateDCAEServiceType(String blueprintTemplate, String owner, String typeName, int typeVersion,\r
+            String asdcServiceId, String asdcResourceId) {\r
+        Date startTime = new Date();\r
+        LoggingUtils.setTargetContext("DCAE", "createDCAEServiceType");\r
+        String typeId = null;\r
+        try {\r
+            ObjectNode dcaeServiceTypeRequest = JacksonUtils.getObjectMapperInstance().createObjectNode();\r
+            dcaeServiceTypeRequest.put("blueprintTemplate", blueprintTemplate);\r
+            dcaeServiceTypeRequest.put("owner", owner);\r
+            dcaeServiceTypeRequest.put("typeName", typeName);\r
+            dcaeServiceTypeRequest.put("typeVersion", typeVersion);\r
+            dcaeServiceTypeRequest.put("asdcServiceId", asdcServiceId);\r
+            dcaeServiceTypeRequest.put("asdcResourceId", asdcResourceId);\r
+            String apiBodyString = dcaeServiceTypeRequest.toString();\r
+            logger.info("Dcae api Body String - " + apiBodyString);\r
+            String url = refProp.getStringValue(DCAE_INVENTORY_URL) + "/dcae-service-types";\r
+            String responseStr = DcaeHttpConnectionManager.doDcaeHttpQuery(url, "POST", apiBodyString,\r
+                    "application/json");\r
+            // If the DCAEServiceTypeRequest is created successfully it will\r
+            // return a json object responce containing a node for newly created\r
+            // "typeId"\r
+            // The newly generated DCAEServiceTypeRequest can then be accessed\r
+            // via URL: https://<DCAE_INVENTORY_URL>/dcae-service-types/<typeId>\r
+            JSONParser parser = new JSONParser();\r
+            Object obj0 = parser.parse(responseStr);\r
+            JSONObject jsonObj = (JSONObject) obj0;\r
+            typeId = (String) jsonObj.get("typeId"); // need to save this\r
+                                                     // as\r
+                                                     // service_type_id\r
+                                                     // in model table\r
+        } catch (IOException | ParseException e) {\r
+            logger.error("Exception occurred during createupdateDCAEServiceType Operation with DCAE", e);\r
+            throw new BadRequestException("Exception occurred during createupdateDCAEServiceType Operation with DCAE",\r
+                    e);\r
+        } finally {\r
+            if (typeId != null) {\r
+                LoggingUtils.setResponseContext("0", "Create update DCAE ServiceType success",\r
+                        this.getClass().getName());\r
+            } else {\r
+                LoggingUtils.setResponseContext("900", "Create update DCAE ServiceType failed",\r
+                        this.getClass().getName());\r
+                LoggingUtils.setErrorContext("900", "Create update DCAE ServiceType error");\r
+            }\r
+            LoggingUtils.setTimeContext(startTime, new Date());\r
+            metricsLogger.info("createupdateDCAEServiceType complete");\r
         }\r
-        LoggingUtils.setTimeContext(startTime, new Date());\r
-        metricsLogger.info("getDcaeInformation complete: number services returned=" + numServices);\r
-        return daceInventoryResponse;\r
+        return typeId;\r
     }\r
-\r
 }\r