Changes for design service
[appc.git] / appc-inbound / appc-design-services / provider / src / main / java / org / onap / appc / design / dbervices / DesignDBService.java
index 5a20c06..4e6375b 100644 (file)
@@ -2,23 +2,23 @@
  * ============LICENSE_START=======================================================
  * ONAP : APPC
  * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
  * ================================================================================
  * Copyright (C) 2017 Amdocs
+ * ================================================================================
+ * Modifications (C) 2019 Ericsson
  * =============================================================================
  * 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.
- * 
- * ECOMP is a trademark and service mark of AT&T Intellectual Property.
  * ============LICENSE_END=========================================================
  */
 
@@ -33,6 +33,8 @@ import java.sql.ResultSet;
 import java.sql.SQLException;
 import java.util.ArrayList;
 import java.util.List;
+
+import org.json.JSONObject;
 import org.onap.appc.design.data.ArtifactInfo;
 import org.onap.appc.design.data.DesignInfo;
 import org.onap.appc.design.data.DesignResponse;
@@ -41,6 +43,7 @@ import org.onap.appc.design.services.util.ArtifactHandlerClient;
 import org.onap.appc.design.services.util.DesignServiceConstants;
 import org.onap.ccsdk.sli.adaptors.resource.sql.SqlResource;
 import org.onap.ccsdk.sli.core.sli.SvcLogicResource;
+import org.apache.commons.lang.StringUtils;
 
 public class DesignDBService {
 
@@ -57,6 +60,7 @@ public class DesignDBService {
 
     private SvcLogicResource serviceLogic;
     private DbService dbservice;
+    private static ArtifactHandlerFactory artifactHandlerFactory = new ArtifactHandlerFactory();
 
     public static DesignDBService initialise() {
         if (dgGeneralDBService == null) {
@@ -81,6 +85,9 @@ public class DesignDBService {
             case DesignServiceConstants.GETDESIGNS:
                 response = getDesigns(payload, requestID);
                 break;
+            case DesignServiceConstants.GETAPPCTIMESTAMPUTC:
+                response =  getAppcTimestampUTC( requestID );
+                break;
             case DesignServiceConstants.ADDINCART:
                 response = setInCart(payload, requestID);
                 break;
@@ -105,13 +112,104 @@ public class DesignDBService {
             case DesignServiceConstants.SETPROTOCOLREFERENCE:
                 response = setProtocolReference(payload, requestID);
                 break;
+            case DesignServiceConstants.UPLOADADMINARTIFACT:
+                response = uploadAdminArtifact(payload, requestID);
+                break;
+            case DesignServiceConstants.CHECKVNF:
+                response = checkVNF(payload, requestID);
+                break;
             default:
-                throw new DBDesignException(" Action " + action + " not found while processing request ");
+                throw new DBException(" Action " + action + " not found while processing request ");
 
         }
         return response;
     }
 
+    private String checkVNF(String payload, String requestId) throws Exception {
+
+        log.info("Got into Check VNF Request with payload: " + payload);
+        if (StringUtils.isBlank(payload))
+            throw new DBException("Payload in CheckVNF request is null or Blank");
+        if (StringUtils.isBlank(requestId))
+            throw new DBException("requestId in CheckVNF request is null or Blank");
+        ObjectMapper objectMapper = new ObjectMapper();
+        JsonNode payloadObject = objectMapper.readTree(payload);
+        String vnfType = payloadObject.get("vnf-type").textValue();
+        log.info("Check VNF Request with VNF TYPE: " + vnfType);
+        ArrayList<String> argList = new ArrayList<>();
+        argList.add(vnfType);
+        String queryString = "SELECT DT_ACTION_STATUS_ID,USER FROM sdnctl.DT_ACTION_STATUS WHERE VNF_TYPE = ? ORDER BY DT_ACTION_STATUS_ID DESC LIMIT 1 ; ";
+        log.info(QUERY_STR + queryString);
+        ResultSet data = dbservice.getDBData(queryString, argList);
+        int rowCount = 0;
+        String user = null;
+        String dtActionStatusId = null;
+        while (data.next()) {
+            rowCount++;
+            user = data.getString("USER");
+            dtActionStatusId = data.getString("DT_ACTION_STATUS_ID");
+        }
+        log.debug("DT_ACTION_STATUS_ID-> " + dtActionStatusId + " user-> " + user);
+        JSONObject jObject = new JSONObject();
+        if (rowCount == 0) {
+            log.debug("vnf-type does not present in APPC DB, row Count:" + rowCount);
+            jObject.put("result", "No");
+        } else {
+            log.debug("vnf-type present in APPC DB, row Count:" + rowCount);
+            jObject.put("result", "Yes");
+            jObject.put("user", user);
+        }
+        log.info("Check VNF result: " + jObject.toString());
+
+        return jObject.toString();
+
+    }
+
+    private String uploadAdminArtifact(String payload, String requestId) throws Exception {
+
+        ObjectMapper objectMapper = new ObjectMapper();
+        objectMapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true);
+        JsonNode payloadObject = objectMapper.readTree(payload);
+        log.info("Got upload Admin Aritfact with  requestId : " + requestId + " & Payload" + payloadObject.asText());
+
+        if (StringUtils.isBlank(requestId)) {
+            throw new DBException("Request-id is missing in the uploadAdminArtifact payload . ");
+        }
+
+        ArtifactHandlerClient ac = new ArtifactHandlerClient();
+        String requestString = ac.createArtifactData(payload, requestId);
+        ac.execute(requestString, "POST");
+
+        int sdcArtifactId = getSDCArtifactIDbyRequestID(requestId);
+        if (sdcArtifactId == 0)
+            throw new DBException(
+                    "Error occured while validating/Saving the artifact to SDC_ARTIFACTS or getting SDC_ARTIFACTS_ID .");
+        JsonNode json = payloadObject.get(DesignServiceConstants.USER_ID);
+        if (json == null || json.asText().trim().isEmpty()) {
+            log.info("UserId in Admin Aritfact is null or blank, User Id : " + json.asText());
+            throw new DBException("User Id is null or blank");
+        }
+
+        int sdcReferenceId = 0;
+        createArtifactTrackingRecord(payload, requestId, sdcArtifactId, sdcReferenceId);
+
+        return SUCCESS_JSON;
+    }
+
+    private String getAppcTimestampUTC( String requestID) throws Exception
+    {
+      log.info("Starting getAppcTimestampUTC: requestID:" + requestID );
+      java.util.TimeZone gmtTZ= java.util.TimeZone.getTimeZone("GMT");
+      java.text.SimpleDateFormat formatter =
+        new java.text.SimpleDateFormat( "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" );
+      formatter.setTimeZone( gmtTZ );
+      java.util.Date dateVal= new java.util.Date();
+      log.info("getAppcTimestampUTC: current local Date:[" + dateVal+ "]");
+      String timeStr= formatter.format( dateVal );
+      log.info("getAppcTimestampUTC: returning:[" + timeStr + "]");
+      return timeStr;
+    }
+
     private String setInCart(String payload, String requestID) throws Exception {
 
         ObjectMapper objectMapper = new ObjectMapper();
@@ -135,7 +233,7 @@ public class DesignDBService {
         boolean data = dbservice.updateDBData(queryString, argList);
 
         if (!data) {
-            throw new DBDesignException("Error while updating ProtocolReference");
+            throw new DBException("Error while updating ProtocolReference");
         }
         return SUCCESS_JSON;
     }
@@ -177,7 +275,7 @@ public class DesignDBService {
         data = dbservice.updateDBData(queryString, argList);
 
         if (!data) {
-            throw new DBDesignException("Error while updating ProtocolReference");
+            throw new DBException("Error while updating ProtocolReference");
         }
         return SUCCESS_JSON;
     }
@@ -189,7 +287,7 @@ public class DesignDBService {
         JsonNode payloadObject = objectMapper.readTree(payload);
         log.info("Got upload Aritfact with Payload : " + payloadObject.asText());
         try {
-            ArtifactHandlerClient ac = new ArtifactHandlerClient();
+            ArtifactHandlerClient ac = artifactHandlerFactory.ahi();
             String requestString = ac.createArtifactData(payload, requestID);
             ac.execute(requestString, "POST");
             int sdcArtifactId = getSDCArtifactIDbyRequestID(requestID);
@@ -197,7 +295,8 @@ public class DesignDBService {
             createArtifactTrackingRecord(payload, requestID, sdcArtifactId, sdcReferenceId);
             String status = getDataFromActionStatus(payload, STATUS);
             if (status == null || status.isEmpty()) {
-                setActionStatus(payload, "Not Tested");
+              log.info("Action Status is: "+ status);
+              setActionStatus(payload, "Not Tested");
             }
             linkstatusRelationShip(sdcArtifactId, sdcReferenceId, payload);
 
@@ -227,15 +326,15 @@ public class DesignDBService {
 
         if (payloadObject.get(DesignServiceConstants.VNFC_TYPE) != null && !payloadObject
             .get(DesignServiceConstants.VNFC_TYPE).textValue().isEmpty()) {
-            queryString = queryString + " AND  VNFC_TYPE =  ? ) )";
+            queryString = queryString + " AND  VNFC_TYPE =  ? GROUP BY VNF_TYPE HAVING COUNT(VNF_TYPE)>=1 ) )";
         } else {
-            queryString = queryString + " ) ) ";
+            queryString = queryString + " GROUP BY VNF_TYPE HAVING COUNT(VNF_TYPE)>=1 ) ) ";
         }
         log.info(QUERY_STR + queryString);
         boolean data = dbservice.updateDBData(queryString, argList);
 
         if (!data) {
-            throw new DBDesignException("Error while updating RelationShip table");
+            throw new DBException("Error while updating RelationShip table");
         }
 
     }
@@ -310,6 +409,7 @@ public class DesignDBService {
         if (payloadObject.get(DesignServiceConstants.VNFC_TYPE) != null && !payloadObject
             .get(DesignServiceConstants.VNFC_TYPE).textValue().isEmpty()) {
             argList.add(payloadObject.get(DesignServiceConstants.VNFC_TYPE).textValue());
+            log.info("Vnfc-Type: " + payloadObject.get(DesignServiceConstants.VNFC_TYPE).textValue());
         } else {
             argList.add(null);
         }
@@ -322,9 +422,11 @@ public class DesignDBService {
         }
         argList.add(status);
 
+        log.info("QueryString: " + insertQuery);
+        log.info("Arguments List: " + argList);
         boolean updateStatus = dbservice.updateDBData(insertQuery, argList);
         if (!updateStatus)
-            throw new DBDesignException("Error while updating Action Status");
+            throw new DBException("Error while updating Action Status");
     }
 
     private void createArtifactTrackingRecord(String payload, String requestID, int sdcArtifactId, int sdcReferenceId)
@@ -356,7 +458,7 @@ public class DesignDBService {
         log.info(QUERY_STR + queryString);
         boolean data = dbservice.updateDBData(queryString, argList);
         if (!data) {
-            throw new DBDesignException("Error Updating DT_ARTIFACT_TRACKING ");
+            throw new DBException("Error Updating DT_ARTIFACT_TRACKING ");
         }
     }
 
@@ -367,7 +469,7 @@ public class DesignDBService {
             ArrayList<String> argList = new ArrayList<>();
             argList.add("TLSUUID" + requestID);
             String queryString = " SELECT ASDC_ARTIFACTS_ID FROM ASDC_ARTIFACTS where SERVICE_UUID = ? ";
-            log.info(QUERY_STR + queryString);
+            log.info(QUERY_STR + queryString+ " & UUID or" + "TLSUUID :" + requestID);
             ResultSet data = dbservice.getDBData(queryString, argList);
             while (data.next()) {
                 artifactId = data.getInt("ASDC_ARTIFACTS_ID");
@@ -386,26 +488,33 @@ public class DesignDBService {
         try {
             ObjectMapper objectMapper = new ObjectMapper();
             JsonNode payloadObject = objectMapper.readTree(payload);
+            String artifactName = payloadObject.get("artifact-name").textValue();
             ArrayList<String> argList = new ArrayList<>();
-            argList.add(payloadObject.get("artifact-name").textValue());
+            argList.add(artifactName);
             argList.add(payloadObject.get("artifact-type").textValue());
 
-            String queryString = "SELECT INTERNAL_VERSION, ARTIFACT_CONTENT FROM ASDC_ARTIFACTS where " +
-                " ARTIFACT_NAME = ? AND ARTIFACT_TYPE = ?  ";
-
+            String queryString = "SELECT INTERNAL_VERSION, ARTIFACT_CONTENT FROM ASDC_ARTIFACTS where "
+                    + " ARTIFACT_NAME = ? AND ARTIFACT_TYPE = ?  ";
             log.info(QUERY_STR + queryString);
             ResultSet data = dbservice.getDBData(queryString, argList);
             String artifactContent = null;
+            int rowCount = 0;
             int hightestVerion = -1;
             while (data.next()) {
+                rowCount++;
                 int version = data.getInt("INTERNAL_VERSION");
                 if (hightestVerion < version) {
                     artifactContent = data.getString("ARTIFACT_CONTENT");
+                    hightestVerion = version;
                 }
             }
+            log.debug("No of rows: " + rowCount + " highest Inetrnal Version" + hightestVerion);
+            if (rowCount == 0) {
+                throw new DBException("Sorry !!!APPC DB doesn't have any artifact Named : " + artifactName);
+            }
             if (artifactContent == null || artifactContent.isEmpty()) {
-                throw new DBDesignException(
-                    "Sorry !!! I dont have any artifact Named : " + payloadObject.get("artifact-name").textValue());
+                throw new DBException("Sorry !!! Artifact Content is stored blank in APPC DB for " + artifactName
+                        + " and Internal version " + hightestVerion);
             }
             DesignResponse designResponse = new DesignResponse();
             List<ArtifactInfo> artifactInfoList = new ArrayList<>();
@@ -415,7 +524,7 @@ public class DesignDBService {
             designResponse.setArtifactInfo(artifactInfoList);
             ObjectMapper mapper = new ObjectMapper();
             String jsonString = mapper.writeValueAsString(designResponse);
-            log.info(INFO_STR + jsonString);
+            log.debug("End of getArtifact:" + INFO_STR + jsonString);
             return jsonString;
         } catch (Exception e) {
             log.error(DB_OPERATION_ERROR, e);
@@ -454,7 +563,7 @@ public class DesignDBService {
             designResponse.setUserId(payloadObject.get(USER_ID).textValue());
             boolean update = dbservice.updateDBData(queryString, argList);
             if (!update) {
-                throw new DBDesignException("Sorry .....Something went wrong while updating the Status");
+                throw new DBException("Sorry .....Something went wrong while updating the Status");
             }
 
             ObjectMapper mapper = new ObjectMapper();
@@ -511,7 +620,7 @@ public class DesignDBService {
             }
 
             if (statusInfoList.isEmpty()) {
-                throw new DBDesignException(
+                throw new DBException(
                     "OOPS !!!! No VNF information available for VNF-TYPE : " + vnfType + " for User : " + userID);
             }
             designResponse.setStatusInfoList(statusInfoList);
@@ -587,7 +696,7 @@ public class DesignDBService {
                 designInfoList.add(designInfo);
             }
             if (designInfoList.isEmpty()) {
-                throw new DBDesignException(
+                throw new DBException(
                     " Welcome to CDT, Looks like you dont have Design Yet... Lets create some....");
             }
             designResponse.setDesignInfoList(designInfoList);
@@ -600,6 +709,11 @@ public class DesignDBService {
             throw e;
         }
     }
-}
 
+    public static class ArtifactHandlerFactory {
 
+        public ArtifactHandlerClient ahi() throws Exception{
+            return new ArtifactHandlerClient();
+        }
+    }
+}