Sonar clean code
[externalapi/nbi.git] / src / main / java / org / onap / nbi / apis / serviceorder / workflow / SOTaskProcessor.java
index 2cbfd32..d63de11 100644 (file)
@@ -1,48 +1,29 @@
 /**
+ * Copyright (c) 2018 Orange
  *
- *     Copyright (c) 2017 Orange.  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
  *
- *     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
  *
- *         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.
+ * 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.
  */
 package org.onap.nbi.apis.serviceorder.workflow;
 
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Date;
-import java.util.LinkedHashMap;
-import java.util.List;
 import org.onap.nbi.apis.serviceorder.SoClient;
 import org.onap.nbi.apis.serviceorder.model.ServiceCharacteristic;
 import org.onap.nbi.apis.serviceorder.model.ServiceOrder;
 import org.onap.nbi.apis.serviceorder.model.ServiceOrderItem;
 import org.onap.nbi.apis.serviceorder.model.StateType;
-import org.onap.nbi.apis.serviceorder.model.consumer.CloudConfiguration;
-import org.onap.nbi.apis.serviceorder.model.consumer.CreateServiceInstanceResponse;
-import org.onap.nbi.apis.serviceorder.model.consumer.GetRequestStatusResponse;
-import org.onap.nbi.apis.serviceorder.model.consumer.ModelInfo;
-import org.onap.nbi.apis.serviceorder.model.consumer.RequestDetails;
-import org.onap.nbi.apis.serviceorder.model.consumer.RequestInfo;
-import org.onap.nbi.apis.serviceorder.model.consumer.RequestParameters;
-import org.onap.nbi.apis.serviceorder.model.consumer.RequestState;
-import org.onap.nbi.apis.serviceorder.model.consumer.SubscriberInfo;
-import org.onap.nbi.apis.serviceorder.model.consumer.UserParams;
+import org.onap.nbi.apis.serviceorder.model.consumer.*;
 import org.onap.nbi.apis.serviceorder.model.orchestrator.ExecutionTask;
 import org.onap.nbi.apis.serviceorder.model.orchestrator.ServiceOrderInfo;
-import org.onap.nbi.apis.serviceorder.model.orchestrator.ServiceOrderInfoJson;
 import org.onap.nbi.apis.serviceorder.repositories.ExecutionTaskRepository;
 import org.onap.nbi.apis.serviceorder.repositories.ServiceOrderRepository;
 import org.onap.nbi.apis.serviceorder.utils.JsonEntityConverter;
+import org.onap.nbi.exceptions.TechnicalException;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.springframework.beans.factory.annotation.Autowired;
@@ -52,6 +33,9 @@ import org.springframework.http.ResponseEntity;
 import org.springframework.stereotype.Service;
 import org.springframework.util.CollectionUtils;
 
+import java.io.IOException;
+import java.util.*;
+
 @Service
 public class SOTaskProcessor {
 
@@ -78,43 +62,31 @@ public class SOTaskProcessor {
 
     /**
      * Run the ServiceOrchestrator processing for a serviceOrderItem which with any sub relations
+     *
+     * @throws InterruptedException
      */
-    public void processOrderItem(ExecutionTask executionTask) {
+    public void processOrderItem(ExecutionTask executionTask) throws InterruptedException {
 
+        ServiceOrderInfo serviceOrderInfo = getServiceOrderInfo(executionTask);
 
-        ServiceOrderInfoJson serviceOrderInfoJson = executionTask.getServiceOrderInfoJson();
-        ServiceOrder serviceOrder = serviceOrderRepository.findOne(serviceOrderInfoJson.getServiceOrderId());
-        ServiceOrderItem serviceOrderItem = null;
-        for (ServiceOrderItem item : serviceOrder.getOrderItem()) {
-            if (item.getId().equals(executionTask.getOrderItemId())) {
-                serviceOrderItem = item;
-            }
-        }
-
-        ServiceOrderInfo serviceOrderInfo = null;
-        try {
-            serviceOrderInfo =
-                    JsonEntityConverter.convertJsonToServiceOrderInfo(serviceOrderInfoJson.getServiceOrderInfoJson());
-        } catch (IOException e) {
-            LOGGER.error("Unable to read ServiceOrderInfo Json for serviceOrderId " + serviceOrder.getId() + ", "
-                    + e.getMessage());
-        }
+        ServiceOrder serviceOrder = serviceOrderRepository.findOne(serviceOrderInfo.getServiceOrderId());
+        ServiceOrderItem serviceOrderItem = getServiceOrderItem(executionTask, serviceOrder);
 
         if (StateType.ACKNOWLEDGED == serviceOrderItem.getState()) {
 
-            ResponseEntity<CreateServiceInstanceResponse> response = postSORequest(serviceOrderItem, serviceOrderInfo);
-
-            updateServiceOrderItem(response.getBody(), serviceOrderItem);
+            ResponseEntity<CreateServiceInstanceResponse> response = postServiceOrderItem(serviceOrderInfo,
+                serviceOrderItem);
 
-            if (response.getStatusCode() != HttpStatus.CREATED || response.getBody() == null
-                    || response.getBody().getRequestReference() == null) {
+            if (response == null) {
+                LOGGER.warn("response=null for serviceOrderItem.id=" + serviceOrderItem.getId());
                 serviceOrderItem.setState(StateType.FAILED);
             } else {
-                serviceOrderItem.setState(StateType.INPROGRESS);
+                updateServiceOrderItem(response, serviceOrderItem);
             }
         }
 
-        if (executionTask.getNbRetries() > 0) {
+        if (executionTask.getNbRetries() > 0 && StateType.FAILED != serviceOrderItem.getState()
+            ) {
             // TODO lancer en asynchrone
             pollSoRequestStatus(serviceOrderItem);
             if (serviceOrderItem.getState().equals(StateType.COMPLETED)) {
@@ -129,23 +101,60 @@ public class SOTaskProcessor {
             updateFailedTask(executionTask, serviceOrder);
         }
 
-
         updateServiceOrder(serviceOrder);
     }
 
+    private ResponseEntity<CreateServiceInstanceResponse> postServiceOrderItem(ServiceOrderInfo serviceOrderInfo,
+        ServiceOrderItem serviceOrderItem) {
+        ResponseEntity<CreateServiceInstanceResponse> response = null;
+        try {
+            response = postSORequest(serviceOrderItem, serviceOrderInfo);
+        } catch (NullPointerException e) {
+            LOGGER.error("Unable to create service instance for serviceOrderItem.id=" + serviceOrderItem.getId(), e);
+            response = null;
+        }
+        return response;
+    }
+
+    private ServiceOrderItem getServiceOrderItem(ExecutionTask executionTask, ServiceOrder serviceOrder) {
+        for (ServiceOrderItem item : serviceOrder.getOrderItem()) {
+            if (item.getId().equals(executionTask.getOrderItemId())) {
+                return item;
+            }
+        }
+        throw new TechnicalException(
+            "Unable to retrieve serviceOrderItem forexecutionTaskId " + executionTask.getInternalId());
+    }
+
+    private ServiceOrderInfo getServiceOrderInfo(ExecutionTask executionTask) {
+        String serviceOrderInfoJson = executionTask.getServiceOrderInfoJson();
+        ServiceOrderInfo serviceOrderInfo = null;
+        try {
+            serviceOrderInfo =
+                JsonEntityConverter.convertJsonToServiceOrderInfo(serviceOrderInfoJson);
+        } catch (IOException e) {
+            LOGGER
+                .error("Unable to read ServiceOrderInfo Json for executionTaskId " + executionTask.getInternalId(), e);
+            throw new TechnicalException(
+                "Unable to read ServiceOrderInfo Json for executionTaskId " + executionTask.getInternalId());
+        }
+        return serviceOrderInfo;
+    }
+
     private ResponseEntity<CreateServiceInstanceResponse> postSORequest(ServiceOrderItem serviceOrderItem,
-            ServiceOrderInfo serviceOrderInfo) {
+        ServiceOrderInfo serviceOrderInfo) {
         RequestDetails requestDetails = buildSoRequest(serviceOrderItem,
-                serviceOrderInfo.getServiceOrderItemInfos().get(serviceOrderItem.getId()).getCatalogResponse(),
-                serviceOrderInfo.getSubscriberInfo());
+            serviceOrderInfo.getServiceOrderItemInfos().get(serviceOrderItem.getId()).getCatalogResponse(),
+            serviceOrderInfo.getSubscriberInfo());
+        MSOPayload msoPayload = new MSOPayload(requestDetails);
         ResponseEntity<CreateServiceInstanceResponse> response = null;
 
         switch (serviceOrderItem.getAction()) {
             case ADD:
-                response = soClient.callCreateServiceInstance(requestDetails);
+                response = soClient.callCreateServiceInstance(msoPayload);
                 break;
             case DELETE:
-                response = soClient.callDeleteServiceInstance(requestDetails, serviceOrderItem.getService().getId());
+                response = soClient.callDeleteServiceInstance(msoPayload, serviceOrderItem.getService().getId());
                 break;
             default:
                 break;
@@ -158,7 +167,6 @@ public class SOTaskProcessor {
         boolean atLeastOneNotFinished = false;
         boolean atLeastOneFailed = false;
 
-
         for (ServiceOrderItem serviceOrderItem : serviceOrder.getOrderItem()) {
             switch (serviceOrderItem.getState()) {
                 case COMPLETED:
@@ -198,7 +206,7 @@ public class SOTaskProcessor {
     /**
      * * @param orderItem
      */
-    private void pollSoRequestStatus(ServiceOrderItem orderItem) {
+    private void pollSoRequestStatus(ServiceOrderItem orderItem) throws InterruptedException {
         boolean stopPolling = false;
         String requestId = orderItem.getRequestId();
         GetRequestStatusResponse response = null;
@@ -210,11 +218,7 @@ public class SOTaskProcessor {
                 if (response.getRequest().getRequestStatus().getPercentProgress() != 100) {
                     nbRetries++;
                     orderItem.setState(StateType.INPROGRESS);
-                    try {
-                        Thread.sleep(1000);
-                    } catch (InterruptedException e) {
-                        e.printStackTrace();
-                    }
+                    Thread.sleep(1000);
                 } else if (RequestState.COMPLETE != response.getRequest().getRequestStatus().getRequestState()) {
                     orderItem.setState(StateType.FAILED);
                     stopPolling = true;
@@ -240,8 +244,8 @@ public class SOTaskProcessor {
      * @param subscriberInfo
      * @return
      */
-    private RequestDetails buildSoRequest(ServiceOrderItem orderItem, LinkedHashMap<String, Object> sdcInfos,
-            SubscriberInfo subscriberInfo) {
+    private RequestDetails buildSoRequest(ServiceOrderItem orderItem, Map<String, Object> sdcInfos,
+        SubscriberInfo subscriberInfo) {
         RequestDetails requestDetails = new RequestDetails();
 
         requestDetails.setSubscriberInfo(subscriberInfo);
@@ -250,6 +254,7 @@ public class SOTaskProcessor {
         modelInfo.setModelType("service");
         modelInfo.setModelInvariantId((String) sdcInfos.get("invariantUUID"));
         modelInfo.setModelNameVersionId(orderItem.getService().getServiceSpecification().getId());
+        modelInfo.setModelVersionId(orderItem.getService().getServiceSpecification().getId());
         modelInfo.setModelName((String) sdcInfos.get("name"));
         modelInfo.setModelVersion((String) sdcInfos.get("version"));
         requestDetails.setModelInfo(modelInfo);
@@ -258,12 +263,13 @@ public class SOTaskProcessor {
         requestInfo.setInstanceName(orderItem.getService().getName());
         requestInfo.setSource("VID");
         requestInfo.setSuppressRollback(false);
+        requestInfo.setRequestorId("NBI");
         requestDetails.setRequestInfo(requestInfo);
 
         RequestParameters requestParameters = new RequestParameters();
         requestParameters.setSubscriptionServiceType((String) sdcInfos.get("name"));
         requestParameters.setUserParams(
-                retrieveUserParamsFromServiceCharacteristics(orderItem.getService().getServiceCharacteristic()));
+            retrieveUserParamsFromServiceCharacteristics(orderItem.getService().getServiceCharacteristic()));
         requestParameters.setaLaCarte(true);
         requestDetails.setRequestParameters(requestParameters);
 
@@ -273,11 +279,7 @@ public class SOTaskProcessor {
     }
 
     /**
-     * Build a list of UserParams for the SO request by browsing a list of ServiceCharacteristics
-     * from SDC
-     *
-     * @param characteristics
-     * @return
+     * Build a list of UserParams for the SO request by browsing a list of ServiceCharacteristics from SDC
      */
     private List<UserParams> retrieveUserParamsFromServiceCharacteristics(List<ServiceCharacteristic> characteristics) {
         List<UserParams> userParams = new ArrayList<UserParams>();
@@ -285,7 +287,7 @@ public class SOTaskProcessor {
         if (!CollectionUtils.isEmpty(characteristics)) {
             for (ServiceCharacteristic characteristic : characteristics) {
                 UserParams userParam = new UserParams(characteristic.getName(),
-                        characteristic.getValue().getServiceCharacteristicValue());
+                    characteristic.getValue().getServiceCharacteristicValue());
                 userParams.add(userParam);
             }
         }
@@ -295,18 +297,25 @@ public class SOTaskProcessor {
 
 
     /**
-     * Update ServiceOrderItem with SO response by using serviceOrderRepository with the
-     * serviceOrderId
+     * Update ServiceOrderItem with SO response by using serviceOrderRepository with the serviceOrderId
      *
-     * @param createServiceInstanceResponse
+     * @param response
      * @param orderItem
      */
-    private void updateServiceOrderItem(CreateServiceInstanceResponse createServiceInstanceResponse,
-            ServiceOrderItem orderItem) {
+    private void updateServiceOrderItem(ResponseEntity<CreateServiceInstanceResponse> response,
+        ServiceOrderItem orderItem) {
 
+        CreateServiceInstanceResponse createServiceInstanceResponse = response.getBody();
         if (createServiceInstanceResponse != null && !orderItem.getState().equals(StateType.FAILED)) {
-            orderItem.getService().setId(createServiceInstanceResponse.getRequestReference().getInstanceId());
-            orderItem.setRequestId(createServiceInstanceResponse.getRequestReference().getRequestId());
+            orderItem.getService().setId(createServiceInstanceResponse.getRequestReferences().getInstanceId());
+            orderItem.setRequestId(createServiceInstanceResponse.getRequestReferences().getRequestId());
+        }
+
+        if (response.getStatusCode() != HttpStatus.CREATED || response.getBody() == null
+            || response.getBody().getRequestReferences() == null) {
+            orderItem.setState(StateType.FAILED);
+        } else {
+            orderItem.setState(StateType.INPROGRESS);
         }
     }
 
@@ -318,6 +327,7 @@ public class SOTaskProcessor {
     private void updateSuccessTask(ExecutionTask executionTask) {
         executionTaskRepository.delete(executionTask.getInternalId());
         executionTaskRepository.updateReliedTaskAfterDelete(executionTask.getInternalId());
+
     }
 
     /**
@@ -329,7 +339,6 @@ public class SOTaskProcessor {
         for (ExecutionTask taskId : executionTasksToDelete) {
             executionTaskRepository.delete(taskId);
         }
-
         for (ServiceOrderItem item : serviceOrder.getOrderItem()) {
             for (ExecutionTask taskToDelete : executionTasksToDelete) {
                 if (taskToDelete.getOrderItemId().equals(item.getId())) {
@@ -348,7 +357,7 @@ public class SOTaskProcessor {
         List<ExecutionTask> executionTasks = new ArrayList<>();
 
         List<ExecutionTask> tasksReliedToAnOrderItemId =
-                executionTaskRepository.findTasksReliedToAnOrderItemId(executionTask.getInternalId());
+            executionTaskRepository.findTasksReliedToAnOrderItemId(executionTask.getInternalId());
 
         if (CollectionUtils.isEmpty(tasksReliedToAnOrderItemId)) {
             return Arrays.asList(executionTask);