Merge changes from topics "VID-583", "VID-582"
[vid.git] / vid-app-common / src / main / java / org / onap / vid / services / ChangeManagementServiceImpl.java
index e4a6b39..214eec7 100644 (file)
@@ -1,23 +1,49 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * VID
+ * ================================================================================
+ * Copyright (C) 2017 - 2019 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=========================================================
+ */
+
 package org.onap.vid.services;
 
+import com.fasterxml.jackson.databind.node.ArrayNode;
+import com.fasterxml.jackson.databind.node.JsonNodeFactory;
 import org.apache.commons.lang3.tuple.ImmutablePair;
 import org.apache.commons.lang3.tuple.Pair;
 import org.hibernate.NonUniqueObjectException;
 import org.json.JSONObject;
-import org.json.simple.JSONArray;
-import org.json.simple.parser.JSONParser;
 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
 import org.onap.portalsdk.core.service.DataAccessService;
 import org.onap.portalsdk.core.util.SystemProperties;
 import org.onap.vid.changeManagement.*;
+import org.onap.vid.controller.ControllersUtils;
+import org.onap.vid.exceptions.GenericUncheckedException;
 import org.onap.vid.exceptions.NotFoundException;
 import org.onap.vid.model.VNFDao;
 import org.onap.vid.model.VidWorkflow;
 import org.onap.vid.mso.MsoBusinessLogic;
+import org.onap.vid.mso.MsoResponseWrapper;
 import org.onap.vid.mso.MsoResponseWrapperInterface;
+import org.onap.vid.mso.RestObject;
+import org.onap.vid.mso.RestObjectWithRequestInfo;
 import org.onap.vid.mso.rest.Request;
 import org.onap.vid.scheduler.SchedulerProperties;
 import org.onap.vid.scheduler.SchedulerRestInterfaceIfc;
+import org.onap.vid.utils.SystemPropertiesWrapper;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.http.HttpStatus;
 import org.springframework.http.ResponseEntity;
@@ -25,6 +51,7 @@ import org.springframework.stereotype.Service;
 import org.springframework.util.StringUtils;
 import org.springframework.web.multipart.MultipartFile;
 
+import javax.servlet.http.HttpServletRequest;
 import javax.ws.rs.BadRequestException;
 import java.io.IOException;
 import java.util.*;
@@ -34,26 +61,29 @@ import java.util.stream.Collectors;
 @Service
 public class ChangeManagementServiceImpl implements ChangeManagementService {
 
-    private final static String PRIMARY_KEY = "payload";
-    private final static Set<String> REQUIRED_KEYS = new HashSet<>(Arrays.asList("request-parameters", "configuration-parameters"));
+    private static final String PRIMARY_KEY = "payload";
+    private static final Set<String> REQUIRED_KEYS = new HashSet<>(Arrays.asList("request-parameters", "configuration-parameters"));
     private final DataAccessService dataAccessService;
     private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ChangeManagementServiceImpl.class);
     private MsoBusinessLogic msoBusinessLogic;
     private final SchedulerRestInterfaceIfc restClient;
+    private final CloudOwnerService cloudOwnerService;
+    private final SystemPropertiesWrapper systemPropertiesWrapper;
 
     @Autowired
     private CsvService csvService;
 
     @Autowired
-    public ChangeManagementServiceImpl(DataAccessService dataAccessService, MsoBusinessLogic msoBusinessLogic, SchedulerRestInterfaceIfc schedulerRestInterface) {
+    public ChangeManagementServiceImpl(DataAccessService dataAccessService, MsoBusinessLogic msoBusinessLogic, SchedulerRestInterfaceIfc schedulerRestInterface, CloudOwnerService cloudOwnerService, SystemPropertiesWrapper systemPropertiesWrapper) {
         this.dataAccessService = dataAccessService;
         this.msoBusinessLogic = msoBusinessLogic;
         this.restClient = schedulerRestInterface;
+        this.cloudOwnerService = cloudOwnerService;
+        this.systemPropertiesWrapper = systemPropertiesWrapper;
     }
 
     @Override
     public Collection<Request> getMSOChangeManagements() {
-        Collection<Request> result = null;
             return msoBusinessLogic.getOrchestrationRequestsForDashboard();
     }
 
@@ -86,14 +116,17 @@ public class ChangeManagementServiceImpl implements ChangeManagementService {
             try {
                 switch (requestType.toLowerCase()) {
                     case ChangeManagementRequest.UPDATE: {
+                        cloudOwnerService.enrichRequestWithCloudOwner(currentRequestDetails);
                         msoResponseWrapperObject = msoBusinessLogic.updateVnf(currentRequestDetails, serviceInstanceId, vnfInstanceId);
                         break;
                     }
                     case ChangeManagementRequest.REPLACE: {
+                        cloudOwnerService.enrichRequestWithCloudOwner(currentRequestDetails);
                         msoResponseWrapperObject = msoBusinessLogic.replaceVnf(currentRequestDetails, serviceInstanceId, vnfInstanceId);
                         break;
                     }
                     case ChangeManagementRequest.VNF_IN_PLACE_SOFTWARE_UPDATE: {
+                        cloudOwnerService.enrichRequestWithCloudOwner(currentRequestDetails);
                         msoResponseWrapperObject = msoBusinessLogic.updateVnfSoftware(currentRequestDetails, serviceInstanceId, vnfInstanceId);
                         break;
                     }
@@ -105,10 +138,10 @@ public class ChangeManagementServiceImpl implements ChangeManagementService {
                         msoResponseWrapperObject = msoBusinessLogic.scaleOutVfModuleInstance(currentRequestDetails, serviceInstanceId, vnfInstanceId);
                         break;
                     }
-                                       default:
-                        logger.error("Failure during doChangeManagement with request " + request.toString());
+                    default:
+                        throw new GenericUncheckedException("Failure during doChangeManagement with request " + request.toString());
                 }
-                response = new ResponseEntity<String>(msoResponseWrapperObject.getResponse(), HttpStatus.OK);
+                response = new ResponseEntity<>(msoResponseWrapperObject.getResponse(), HttpStatus.OK);
                 return response;
             } catch (Exception e) {
                 logger.error("Failure during doChangeManagement with request " + request.toString(), e);
@@ -116,8 +149,6 @@ public class ChangeManagementServiceImpl implements ChangeManagementService {
             }
 
         }
-
-        // AH:TODO: return ChangeManagementResponse
         return null;
     }
 
@@ -129,44 +160,44 @@ public class ChangeManagementServiceImpl implements ChangeManagementService {
         return currentRequestDetails.getVnfInstanceId();
     }
 
-    protected String extractServiceInstanceId(RequestDetails currentRequestDetails, String requestType) {
+    protected String extractServiceInstanceId(RequestDetails currentRequestDetails,
+            String requestType) {
         try {
-            String serviceInstanceId = currentRequestDetails.getRelatedInstList().get(0).getRelatedInstance().getInstanceId();
-            serviceInstanceId.toString(); //throw exception in case that serviceInstanceId is null...
+            String serviceInstanceId = currentRequestDetails.getRelatedInstList().get(0)
+                    .getRelatedInstance().getInstanceId();
+            if (serviceInstanceId == null) {
+                logger.error("Failed to extract serviceInstanceId");
+                throw new BadRequestException("No instanceId in request " + requestType);
+            }
             return serviceInstanceId;
-        } catch (Exception e) {
+        }
+        catch (Exception e) {
             logger.error("Failed to extract serviceInstanceId");
             throw new BadRequestException("No instanceId in request " + requestType);
         }
     }
 
     @Override
-    public JSONArray getSchedulerChangeManagements() {
-        JSONArray result = null;
-        try {
-            String path = SystemProperties.getProperty(SchedulerProperties.SCHEDULER_GET_SCHEDULES);
-            org.onap.vid.scheduler.RestObject<String> restObject = new org.onap.vid.scheduler.RestObject<>();
-
-            String str = new String();
-            restObject.set(str);
-            restClient.Get(str, "", path, restObject);
-            String restCallResult = restObject.get();
-            JSONParser parser = new JSONParser();
-            Object parserResult = parser.parse(restCallResult);
-            result = (JSONArray) parserResult;
-        } catch (Exception e) {
-            e.printStackTrace();
-        }
+    public RestObjectWithRequestInfo<ArrayNode> getSchedulerChangeManagementsWithRequestInfo() {
+        String path = SystemProperties.getProperty(SchedulerProperties.SCHEDULER_GET_SCHEDULES);
+        RestObject<ArrayNode> restObject = new RestObject<>();
+        ArrayNode jsonArray = new ArrayNode(new JsonNodeFactory(true));
+        restObject.set(jsonArray);
+        return restClient.Get(jsonArray, path, restObject);
+    }
 
-        return result;
+    @Override
+    public ArrayNode getSchedulerChangeManagements() {
+        RestObjectWithRequestInfo<ArrayNode> responseWithRequestInfo = getSchedulerChangeManagementsWithRequestInfo();
+        return responseWithRequestInfo.getRestObject().get();
     }
 
     @Override
     public Pair<String, Integer> deleteSchedule(String scheduleId) {
         try {
             String path = String.format(SystemProperties.getProperty(SchedulerProperties.SCHEDULER_DELETE_SCHEDULE), scheduleId);
-            org.onap.vid.scheduler.RestObject<String> restObject = new org.onap.vid.scheduler.RestObject<>();
-            String str = new String();
+            RestObject<String> restObject = new RestObject<>();
+            String str = "";
             restObject.set(str);
             restClient.Delete(str, "", path, restObject);
             String restCallResult = restObject.get();
@@ -187,11 +218,11 @@ public class ChangeManagementServiceImpl implements ChangeManagementService {
                 continue;
             }
             @SuppressWarnings("unchecked") List<VNFDao> vnfList = dataAccessService.getList(VNFDao.class, getVnfQueryString(workflowsDetail.getVnfDetails().getUUID(), workflowsDetail.getVnfDetails().getInvariantUUID()), null, null);
-            if (vnfList.size() == 0) {
+            if (vnfList.isEmpty()) {
                 vnfList.add(saveNewVnf(workflowsDetail));
             }
             @SuppressWarnings("unchecked") List<VidWorkflow> workflowList = dataAccessService.getList(VidWorkflow.class, String.format(" where wokflowName = '%s'", workflowsDetail.getWorkflowName()), null, null);
-            if (workflowList.size() == 0) {
+            if (workflowList.isEmpty()) {
                 vnfWorkflowRelationResponse.getErrors().add("Not Found instance of workflow " + workflowsDetail.getWorkflowName() + " for vnf with UUID " + workflowsDetail.getVnfDetails().getUUID() + " and with invariantUUID " + workflowsDetail.getVnfDetails().getInvariantUUID());
                 continue;
             }
@@ -200,6 +231,7 @@ public class ChangeManagementServiceImpl implements ChangeManagementService {
                 dataAccessService.saveDomainObject(vnfList.get(0), null);
             } catch (NonUniqueObjectException e) {
                 //In case the relation already exists, we continue running on the list
+                logger.debug("NonUniqueObjectException in addVnfWorkflowRelation", e);
             }
         }
         return vnfWorkflowRelationResponse;
@@ -306,9 +338,18 @@ public class ChangeManagementServiceImpl implements ChangeManagementService {
         return json.toString();
     }
 
+    @Override
+    public MsoResponseWrapper invokeVnfWorkflow(HttpServletRequest request,WorkflowRequestDetail requestBody, UUID serviceInstanceId, UUID vnfInstanceId, UUID workflow_UUID) {
+        String userId = new ControllersUtils(systemPropertiesWrapper).extractUserId(request);
+        return msoBusinessLogic.invokeVnfWorkflow(requestBody, userId, serviceInstanceId, vnfInstanceId, workflow_UUID);
+    }
+
     private boolean validateJsonOutput(org.json.JSONObject json) {
-        if (!json.has(PRIMARY_KEY) || !json.getJSONObject(PRIMARY_KEY).keySet().containsAll(REQUIRED_KEYS))
-            return false;
-        return true;
+        boolean isValid = true;
+        if (!json.has(PRIMARY_KEY)
+                || !json.getJSONObject(PRIMARY_KEY).keySet().containsAll(REQUIRED_KEYS)) {
+            isValid = false;
+        }
+        return isValid;
     }
 }