[SO] Create changes for SO-API and BPMN-INFRA to support CNF's through ASD
[so.git] / mso-api-handlers / mso-api-handler-infra / src / main / java / org / onap / so / apihandlerinfra / RequestHandlerUtils.java
index 75b7e74..4338e61 100644 (file)
@@ -11,9 +11,9 @@
  * 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.
@@ -33,27 +33,27 @@ import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
+import java.util.Map.Entry;
 import java.util.Optional;
+import java.util.Set;
+import java.util.stream.Collectors;
 import javax.ws.rs.container.ContainerRequestContext;
 import javax.ws.rs.core.MultivaluedMap;
 import javax.ws.rs.core.Response;
 import org.apache.commons.lang.StringUtils;
-import org.apache.http.HttpResponse;
 import org.apache.http.HttpStatus;
-import org.camunda.bpm.engine.history.HistoricProcessInstance;
 import org.camunda.bpm.engine.impl.persistence.entity.HistoricProcessInstanceEntity;
+import org.onap.logging.filter.base.ErrorCode;
 import org.onap.logging.ref.slf4j.ONAPLogConstants;
 import org.onap.so.apihandler.camundabeans.CamundaResponse;
+import org.onap.so.apihandler.common.CamundaClient;
 import org.onap.so.apihandler.common.CommonConstants;
 import org.onap.so.apihandler.common.ErrorNumbers;
-import org.onap.so.apihandler.common.RequestClient;
-import org.onap.so.apihandler.common.RequestClientFactory;
 import org.onap.so.apihandler.common.RequestClientParameter;
 import org.onap.so.apihandler.common.ResponseBuilder;
 import org.onap.so.apihandler.common.ResponseHandler;
 import org.onap.so.apihandlerinfra.exceptions.ApiException;
 import org.onap.so.apihandlerinfra.exceptions.BPMNFailureException;
-import org.onap.so.apihandlerinfra.exceptions.ClientConnectionException;
 import org.onap.so.apihandlerinfra.exceptions.ContactCamundaException;
 import org.onap.so.apihandlerinfra.exceptions.DuplicateRequestException;
 import org.onap.so.apihandlerinfra.exceptions.RecipeNotFoundException;
@@ -74,9 +74,7 @@ import org.onap.so.db.catalog.beans.VnfResource;
 import org.onap.so.db.catalog.beans.VnfResourceCustomization;
 import org.onap.so.db.catalog.client.CatalogDbClient;
 import org.onap.so.db.request.beans.InfraActiveRequests;
-import org.onap.so.db.request.client.RequestsDbClient;
 import org.onap.so.exceptions.ValidationException;
-import org.onap.so.logger.ErrorCode;
 import org.onap.so.logger.LogConstants;
 import org.onap.so.logger.MessageEnum;
 import org.onap.so.serviceinstancebeans.CloudConfiguration;
@@ -116,9 +114,6 @@ public class RequestHandlerUtils extends AbstractRestHandler {
     @Autowired
     private Environment env;
 
-    @Autowired
-    private RequestClientFactory reqClientFactory;
-
     @Autowired
     private ResponseBuilder builder;
 
@@ -131,122 +126,62 @@ public class RequestHandlerUtils extends AbstractRestHandler {
     @Autowired
     private CatalogDbClient catalogDbClient;
 
-    public Response postBPELRequest(InfraActiveRequests currentActiveReq, RequestClientParameter requestClientParameter,
-            String orchestrationUri, String requestScope) throws ApiException {
-        HttpResponse response = null;
-        RequestClient requestClient = null;
-
-        try {
-            requestClient = reqClientFactory.getRequestClient(orchestrationUri);
-            response = requestClient.post(requestClientParameter);
-        } catch (Exception e) {
-            logger.error("Error posting request to BPMN", e);
-            ErrorLoggerInfo errorLoggerInfo =
-                    new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, ErrorCode.AvailabilityError)
-                            .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
-            String url = requestClient != null ? requestClient.getUrl() : "";
-            ClientConnectionException clientException =
-                    new ClientConnectionException.Builder(url, HttpStatus.SC_BAD_GATEWAY,
-                            ErrorNumbers.SVC_NO_SERVER_RESOURCES).cause(e).errorInfo(errorLoggerInfo).build();
-            updateStatus(currentActiveReq, Status.FAILED, clientException.getMessage());
-            throw clientException;
-        }
-
-        if (response == null) {
+    @Autowired
+    private CamundaClient camundaClient;
 
-            ErrorLoggerInfo errorLoggerInfo =
-                    new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, ErrorCode.BusinessProcessError)
-                            .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
-            ClientConnectionException clientException = new ClientConnectionException.Builder(requestClient.getUrl(),
-                    HttpStatus.SC_BAD_GATEWAY, ErrorNumbers.SVC_NO_SERVER_RESOURCES).errorInfo(errorLoggerInfo).build();
-            updateStatus(currentActiveReq, Status.FAILED, clientException.getMessage());
-            throw clientException;
-        }
+    @Autowired
+    private ResponseHandler responseHandler;
 
-        ResponseHandler respHandler = null;
-        int bpelStatus = 500;
+    protected ResponseEntity<String> postRequest(InfraActiveRequests currentActiveReq,
+            RequestClientParameter requestClientParameter, String orchestrationUri) throws ApiException {
         try {
-            respHandler = new ResponseHandler(response, requestClient.getType());
-            bpelStatus = respHandler.getStatus();
+            return camundaClient.post(requestClientParameter, orchestrationUri);
         } catch (ApiException e) {
-            logger.error("Exception occurred", e);
-            ErrorLoggerInfo errorLoggerInfo =
-                    new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, ErrorCode.SchemaError)
-                            .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
-            ValidateException validateException =
-                    new ValidateException.Builder("Exception caught mapping Camunda JSON response to object",
-                            HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_BAD_PARAMETER).cause(e)
-                                    .errorInfo(errorLoggerInfo).build();
-            updateStatus(currentActiveReq, Status.FAILED, validateException.getMessage());
-            throw validateException;
+            updateStatus(currentActiveReq, Status.FAILED, e.getMessage());
+            throw e;
         }
+    }
 
-        // BPEL accepted the request, the request is in progress
-        if (bpelStatus == HttpStatus.SC_ACCEPTED) {
-            ServiceInstancesResponse jsonResponse;
-            CamundaResponse camundaResp = respHandler.getResponse();
-
-            if ("Success".equalsIgnoreCase(camundaResp.getMessage())) {
-                try {
-                    ObjectMapper mapper = new ObjectMapper();
-                    jsonResponse = mapper.readValue(camundaResp.getResponse(), ServiceInstancesResponse.class);
-                    jsonResponse.getRequestReferences().setRequestId(requestClientParameter.getRequestId());
-                    Optional<URL> selfLinkUrl =
-                            buildSelfLinkUrl(currentActiveReq.getRequestUrl(), requestClientParameter.getRequestId());
-                    if (selfLinkUrl.isPresent()) {
-                        jsonResponse.getRequestReferences().setRequestSelfLink(selfLinkUrl.get());
-                    } else {
-                        jsonResponse.getRequestReferences().setRequestSelfLink(null);
-                    }
-                } catch (IOException e) {
-                    logger.error("Exception occurred", e);
-                    ErrorLoggerInfo errorLoggerInfo =
-                            new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, ErrorCode.SchemaError)
-                                    .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
-                    ValidateException validateException =
-                            new ValidateException.Builder("Exception caught mapping Camunda JSON response to object",
-                                    HttpStatus.SC_NOT_ACCEPTABLE, ErrorNumbers.SVC_BAD_PARAMETER).cause(e)
-                                            .errorInfo(errorLoggerInfo).build();
-                    updateStatus(currentActiveReq, Status.FAILED, validateException.getMessage());
-                    throw validateException;
+    public Response postBPELRequest(InfraActiveRequests currentActiveReq, RequestClientParameter requestClientParameter,
+            String orchestrationUri, String requestScope) throws ApiException {
+        ObjectMapper mapper = new ObjectMapper();
+        ResponseEntity<String> response = postRequest(currentActiveReq, requestClientParameter, orchestrationUri);
+        ServiceInstancesResponse jsonResponse = null;
+        int bpelStatus = responseHandler.setStatus(response.getStatusCodeValue());
+        try {
+            responseHandler.acceptedResponse(response);
+            CamundaResponse camundaResponse = responseHandler.getCamundaResponse(response);
+            String responseBody = camundaResponse.getResponse();
+            if ("Success".equalsIgnoreCase(camundaResponse.getMessage())) {
+                jsonResponse = mapper.readValue(responseBody, ServiceInstancesResponse.class);
+                jsonResponse.getRequestReferences().setRequestId(requestClientParameter.getRequestId());
+                Optional<URL> selfLinkUrl =
+                        buildSelfLinkUrl(currentActiveReq.getRequestUrl(), requestClientParameter.getRequestId());
+                if (selfLinkUrl.isPresent()) {
+                    jsonResponse.getRequestReferences().setRequestSelfLink(selfLinkUrl.get());
+                } else {
+                    jsonResponse.getRequestReferences().setRequestSelfLink(null);
                 }
-                return builder.buildResponse(HttpStatus.SC_ACCEPTED, requestClientParameter.getRequestId(),
-                        jsonResponse, requestClientParameter.getApiVersion());
+            } else {
+                BPMNFailureException bpmnException =
+                        new BPMNFailureException.Builder(String.valueOf(bpelStatus) + responseBody, bpelStatus,
+                                ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).build();
+                updateStatus(currentActiveReq, Status.FAILED, bpmnException.getMessage());
+                throw bpmnException;
             }
+        } catch (ApiException e) {
+            updateStatus(currentActiveReq, Status.FAILED, e.getMessage());
+            throw e;
+        } catch (IOException e) {
+            logger.error("Exception caught mapping Camunda JSON response to object: ", e);
+            updateStatus(currentActiveReq, Status.FAILED, e.getMessage());
+            throw new ValidateException.Builder("Exception caught mapping Camunda JSON response to object",
+                    HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_BAD_PARAMETER).cause(e).build();
         }
-
-        List<String> variables = new ArrayList<>();
-        variables.add(bpelStatus + "");
-        String camundaJSONResponseBody = respHandler.getResponseBody();
-        if (camundaJSONResponseBody != null && !camundaJSONResponseBody.isEmpty()) {
-
-            ErrorLoggerInfo errorLoggerInfo =
-                    new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, ErrorCode.BusinessProcessError)
-                            .errorSource(requestClient.getUrl()).build();
-            BPMNFailureException bpmnException =
-                    new BPMNFailureException.Builder(String.valueOf(bpelStatus) + camundaJSONResponseBody, bpelStatus,
-                            ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo).build();
-
-            updateStatus(currentActiveReq, Status.FAILED, bpmnException.getMessage());
-
-            throw bpmnException;
-        } else {
-
-            ErrorLoggerInfo errorLoggerInfo =
-                    new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, ErrorCode.BusinessProcessError)
-                            .errorSource(requestClient.getUrl()).build();
-
-
-            BPMNFailureException servException = new BPMNFailureException.Builder(String.valueOf(bpelStatus),
-                    bpelStatus, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo).build();
-            updateStatus(currentActiveReq, Status.FAILED, servException.getMessage());
-
-            throw servException;
-        }
+        return builder.buildResponse(HttpStatus.SC_ACCEPTED, requestClientParameter.getRequestId(), jsonResponse,
+                requestClientParameter.getApiVersion());
     }
 
-
-
     @Override
     public void updateStatus(InfraActiveRequests aq, Status status, String errorMessage)
             throws RequestDbFailureException {
@@ -329,8 +264,8 @@ public class RequestHandlerUtils extends AbstractRestHandler {
         }
     }
 
-    public InfraActiveRequests duplicateCheck(Actions action, HashMap<String, String> instanceIdMap,
-            String instanceName, String requestScope, InfraActiveRequests currentActiveReq) throws ApiException {
+    public InfraActiveRequests duplicateCheck(Actions action, Map<String, String> instanceIdMap, String instanceName,
+            String requestScope, InfraActiveRequests currentActiveReq) throws ApiException {
         InfraActiveRequests dup = null;
         try {
             if (!(instanceName == null && "service".equals(requestScope) && (action == Action.createInstance
@@ -394,13 +329,13 @@ public class RequestHandlerUtils extends AbstractRestHandler {
             String requestScope = requestScopeFromUri(requestUri);
 
             msoRequest.createErrorRequestRecord(Status.FAILED, requestId, validateException.getMessage(), action,
-                    requestScope, requestJSON);
+                    requestScope, requestJSON, null, null);
 
             throw validateException;
         }
     }
 
-    public void parseRequest(ServiceInstancesRequest sir, HashMap<String, String> instanceIdMap, Actions action,
+    public void parseRequest(ServiceInstancesRequest sir, Map<String, String> instanceIdMap, Actions action,
             String version, String requestJSON, Boolean aLaCarte, String requestId,
             InfraActiveRequests currentActiveReq) throws ValidateException, RequestDbFailureException {
         int reqVersion = Integer.parseInt(version.substring(1));
@@ -422,7 +357,7 @@ public class RequestHandlerUtils extends AbstractRestHandler {
     }
 
     public void buildErrorOnDuplicateRecord(InfraActiveRequests currentActiveReq, Actions action,
-            HashMap<String, String> instanceIdMap, String instanceName, String requestScope, InfraActiveRequests dup)
+            Map<String, String> instanceIdMap, String instanceName, String requestScope, InfraActiveRequests dup)
             throws ApiException {
 
         String instance = null;
@@ -471,7 +406,8 @@ public class RequestHandlerUtils extends AbstractRestHandler {
         if (StringUtils.isNotBlank(instanceId)) {
             if (ModelType.service.name().equalsIgnoreCase(requestScope)) {
                 currentActiveReq.setServiceInstanceId(instanceId);
-            } else if (ModelType.vnf.name().equalsIgnoreCase(requestScope)) {
+            } else if (ModelType.vnf.name().equalsIgnoreCase(requestScope)
+                    || ModelType.cnf.name().equalsIgnoreCase(requestScope)) {
                 currentActiveReq.setVnfId(instanceId);
             } else if (ModelType.vfModule.name().equalsIgnoreCase(requestScope)) {
                 currentActiveReq.setVfModuleId(instanceId);
@@ -506,8 +442,8 @@ public class RequestHandlerUtils extends AbstractRestHandler {
             if (instanceIdMap.get(CommonConstants.INSTANCE_GROUP_INSTANCE_ID) != null) {
                 currentActiveReq.setInstanceGroupId(instanceIdMap.get(CommonConstants.INSTANCE_GROUP_INSTANCE_ID));
             }
-            if (instanceIdMap.get("PnfId") != null) {
-                currentActiveReq.setPnfId(instanceIdMap.get("PnfId"));
+            if (instanceIdMap.get("pnfName") != null) {
+                currentActiveReq.setPnfName(instanceIdMap.get("pnfName"));
             }
         }
     }
@@ -586,20 +522,16 @@ public class RequestHandlerUtils extends AbstractRestHandler {
     }
 
     protected String setServiceInstanceId(String requestScope, ServiceInstancesRequest sir) {
+        String serviceInstanceId = null;
         if (sir.getServiceInstanceId() != null) {
-            return sir.getServiceInstanceId();
-        } else if (requestScope.equalsIgnoreCase(ModelType.instanceGroup.toString())) {
-            RelatedInstanceList[] relatedInstances = sir.getRequestDetails().getRelatedInstanceList();
-            if (relatedInstances != null) {
-                for (RelatedInstanceList relatedInstanceList : relatedInstances) {
-                    RelatedInstance relatedInstance = relatedInstanceList.getRelatedInstance();
-                    if (relatedInstance.getModelInfo().getModelType() == ModelType.service) {
-                        return relatedInstance.getInstanceId();
-                    }
-                }
+            serviceInstanceId = sir.getServiceInstanceId();
+        } else {
+            Optional<String> serviceInstanceIdForInstance = getServiceInstanceIdForInstanceGroup(requestScope, sir);
+            if (serviceInstanceIdForInstance.isPresent()) {
+                serviceInstanceId = serviceInstanceIdForInstance.get();
             }
         }
-        return null;
+        return serviceInstanceId;
     }
 
     private String requestScopeFromUri(String requestUri) {
@@ -616,6 +548,9 @@ public class RequestHandlerUtils extends AbstractRestHandler {
             requestScope = ModelType.vnf.name();
         } else if (requestUri.contains(ModelType.pnf.name())) {
             requestScope = ModelType.pnf.name();
+
+        } else if (requestUri.contains(ModelType.cnf.name())) {
+            requestScope = ModelType.cnf.name();
         } else {
             requestScope = ModelType.service.name();
         }
@@ -790,8 +725,14 @@ public class RequestHandlerUtils extends AbstractRestHandler {
 
                 throw validateException;
             }
+        }
+
+        else if (modelInfo.getModelType().equals(ModelType.pnf)) {
+            recipeLookupResult = new RecipeLookupResult("/mso/async/services/WorkflowActionBB", 180);
         } else if (modelInfo.getModelType().equals(ModelType.instanceGroup)) {
             recipeLookupResult = new RecipeLookupResult("/mso/async/services/WorkflowActionBB", 180);
+        } else if (modelInfo.getModelType().equals(ModelType.cnf)) {
+            recipeLookupResult = new RecipeLookupResult("/mso/async/services/WorkflowActionBB", 180);
         }
 
         if (recipeLookupResult == null) {
@@ -913,7 +854,11 @@ public class RequestHandlerUtils extends AbstractRestHandler {
             if (params.containsKey("service")) {
                 Service service = serviceMapper(params);
 
-                addUserParams(userParams, service.getInstanceParams());
+                // Filter out non-string params for backward compatibility
+                Map<String, String> svcStrParams = service.getInstanceParams().stream().map(Map::entrySet)
+                        .flatMap(Set::stream).filter(e -> e.getValue() instanceof String)
+                        .collect(Collectors.toMap(Entry::getKey, e -> (String) e.getValue()));
+                userParams.putAll(svcStrParams);
 
                 for (Networks network : service.getResources().getNetworks()) {
                     addUserParams(userParams, network.getInstanceParams());
@@ -984,6 +929,30 @@ public class RequestHandlerUtils extends AbstractRestHandler {
         return null;
     }
 
+    protected Optional<String> getServiceInstanceIdForValidationError(ServiceInstancesRequest sir,
+            HashMap<String, String> instanceIdMap, String requestScope) {
+        if (instanceIdMap != null && !instanceIdMap.isEmpty() && instanceIdMap.get("serviceInstanceId") != null) {
+            return Optional.of(instanceIdMap.get("serviceInstanceId"));
+        } else {
+            return getServiceInstanceIdForInstanceGroup(requestScope, sir);
+        }
+    }
+
+    protected Optional<String> getServiceInstanceIdForInstanceGroup(String requestScope, ServiceInstancesRequest sir) {
+        if (requestScope.equalsIgnoreCase(ModelType.instanceGroup.toString())) {
+            RelatedInstanceList[] relatedInstances = sir.getRequestDetails().getRelatedInstanceList();
+            if (relatedInstances != null) {
+                for (RelatedInstanceList relatedInstanceList : relatedInstances) {
+                    RelatedInstance relatedInstance = relatedInstanceList.getRelatedInstance();
+                    if (relatedInstance.getModelInfo().getModelType() == ModelType.service) {
+                        return Optional.ofNullable(relatedInstance.getInstanceId());
+                    }
+                }
+            }
+        }
+        return Optional.empty();
+    }
+
     private RecipeLookupResult getDefaultVnfUri(ServiceInstancesRequest sir, Actions action) {
         String defaultSource = getDefaultModel(sir);
         VnfRecipe vnfRecipe = catalogDbClient.getFirstVnfRecipeByNfRoleAndAction(defaultSource, action.toString());
@@ -1232,7 +1201,7 @@ public class RequestHandlerUtils extends AbstractRestHandler {
                     throw new ValidationException("vfModuleCustomization");
                 } else if (vfModule == null && vfmc != null) {
                     vfModule = vfmc.getVfModule(); // can't be null as vfModuleModelUUID is not-null property in
-                                                   // VfModuleCustomization table
+                    // VfModuleCustomization table
                 }
 
                 if (modelInfo.getModelVersionId() == null) {