diff options
Diffstat (limited to 'mso-api-handlers/mso-api-handler-infra')
35 files changed, 2022 insertions, 359 deletions
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/Action.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/Action.java index 77dbff9ebb..d0302f2e59 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/Action.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/Action.java @@ -20,9 +20,30 @@ package org.onap.so.apihandlerinfra; -/* - * Enum for Status values returned by API Handler to Tail-F - */ + public enum Action implements Actions { - createInstance, updateInstance, deleteInstance, configureInstance, replaceInstance, activateInstance, deactivateInstance, enablePort, disablePort, addRelationships, removeRelationships, inPlaceSoftwareUpdate, applyUpdatedConfig, completeTask, assignInstance, unassignInstance, compareModel, scaleInstance, deactivateAndCloudDelete, scaleOut, recreateInstance, addMembers, removeMembers + createInstance, + updateInstance, + deleteInstance, + configureInstance, + replaceInstance, + replaceInstanceRetainAssignments, + activateInstance, + deactivateInstance, + enablePort, + disablePort, + addRelationships, + removeRelationships, + inPlaceSoftwareUpdate, + applyUpdatedConfig, + completeTask, + assignInstance, + unassignInstance, + compareModel, + scaleInstance, + deactivateAndCloudDelete, + scaleOut, + recreateInstance, + addMembers, + removeMembers } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/E2EServiceInstances.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/E2EServiceInstances.java index 449aa4ba3f..7ed1f9d5d0 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/E2EServiceInstances.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/E2EServiceInstances.java @@ -38,6 +38,7 @@ import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; +import com.google.common.base.Strings; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.json.JSONObject; @@ -228,8 +229,8 @@ public class E2EServiceInstances { Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_REQUEST, MsoException.ServiceException, "Mapping of request to JSON object failed. " + e.getMessage(), ErrorNumbers.SVC_BAD_PARAMETER, null, version); - logger.error("{} {} {} {}", MessageEnum.APIH_REQUEST_VALIDATION_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA, - ErrorCode.SchemaError.getValue(), requestJSON, e); + logger.error(Strings.repeat("{} ", 4), MessageEnum.APIH_REQUEST_VALIDATION_ERROR.toString(), + MSO_PROP_APIHANDLER_INFRA, ErrorCode.SchemaError.getValue(), requestJSON, e); logger.debug(END_OF_THE_TRANSACTION + response.getEntity().toString()); return response; @@ -280,8 +281,8 @@ public class E2EServiceInstances { Response resp = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_GATEWAY, MsoException.ServiceException, "bpelResponse is null", ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version); - logger.error("{} {} {} {}", MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA, - ErrorCode.BusinessProcesssError.getValue(), "Null response from BPEL"); + logger.error(Strings.repeat("{} ", 4), MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), + MSO_PROP_APIHANDLER_INFRA, ErrorCode.BusinessProcesssError.getValue(), "Null response from BPEL"); logger.debug(END_OF_THE_TRANSACTION + resp.getEntity().toString()); return resp; } @@ -306,7 +307,7 @@ public class E2EServiceInstances { try { operationStatus = requestsDbClient.getOneByServiceIdAndOperationId(serviceId, operationId); } catch (Exception e) { - logger.error("{} {} {} {}", MessageEnum.APIH_DB_ACCESS_EXC.toString(), MSO_PROP_APIHANDLER_INFRA, + logger.error(Strings.repeat("{} ", 4), MessageEnum.APIH_DB_ACCESS_EXC.toString(), MSO_PROP_APIHANDLER_INFRA, ErrorCode.AvailabilityError.getValue(), "Exception while communciate with Request DB - Infra Request Lookup", e); Response response = @@ -321,8 +322,8 @@ public class E2EServiceInstances { Response resp = msoRequest.buildServiceErrorResponse(HttpStatus.SC_NO_CONTENT, MsoException.ServiceException, "E2E serviceId " + serviceId + " is not found in DB", ErrorNumbers.SVC_DETAILED_SERVICE_ERROR, null, version); - logger.error("{} {} {} {}", MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA, - ErrorCode.BusinessProcesssError.getValue(), + logger.error(Strings.repeat("{} ", 4), MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), + MSO_PROP_APIHANDLER_INFRA, ErrorCode.BusinessProcesssError.getValue(), "Null response from RequestDB when searching by serviceId"); logger.debug(END_OF_THE_TRANSACTION + resp.getEntity()); return resp; @@ -350,8 +351,8 @@ public class E2EServiceInstances { Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_REQUEST, MsoException.ServiceException, "Mapping of request to JSON object failed. " + e.getMessage(), ErrorNumbers.SVC_BAD_PARAMETER, null, version); - logger.error("{} {} {} {}", MessageEnum.APIH_REQUEST_VALIDATION_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA, - ErrorCode.SchemaError.getValue(), requestJSON, e); + logger.error(Strings.repeat("{} ", 4), MessageEnum.APIH_REQUEST_VALIDATION_ERROR.toString(), + MSO_PROP_APIHANDLER_INFRA, ErrorCode.SchemaError.getValue(), requestJSON, e); logger.debug(END_OF_THE_TRANSACTION + response.getEntity()); return response; } @@ -375,8 +376,8 @@ public class E2EServiceInstances { return response; } if (recipeLookupResult == null) { - logger.error("{} {} {} {}", MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND.toString(), MSO_PROP_APIHANDLER_INFRA, - ErrorCode.DataError.getValue(), "No recipe found in DB"); + logger.error(Strings.repeat("{} ", 4), MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND.toString(), + MSO_PROP_APIHANDLER_INFRA, ErrorCode.DataError.getValue(), "No recipe found in DB"); Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_NOT_FOUND, MsoException.ServiceException, "Recipe does not exist in catalog DB", ErrorNumbers.SVC_GENERAL_SERVICE_ERROR, null, version); @@ -414,8 +415,9 @@ public class E2EServiceInstances { Response resp = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_GATEWAY, MsoException.ServiceException, "Failed calling bpmn " + e.getMessage(), ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version); - logger.error("{} {} {} {}", MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA, - ErrorCode.AvailabilityError.getValue(), "Exception while communicate with BPMN engine"); + logger.error(Strings.repeat("{} ", 4), MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), + MSO_PROP_APIHANDLER_INFRA, ErrorCode.AvailabilityError.getValue(), + "Exception while communicate with BPMN engine"); logger.debug("End of the transaction, the final response is: " + resp.getEntity()); return resp; } @@ -424,8 +426,8 @@ public class E2EServiceInstances { Response resp = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_GATEWAY, MsoException.ServiceException, "bpelResponse is null", ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version); - logger.error("{} {} {} {}", MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA, - ErrorCode.BusinessProcesssError.getValue(), "Null response from BPEL"); + logger.error(Strings.repeat("{} ", 4), MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), + MSO_PROP_APIHANDLER_INFRA, ErrorCode.BusinessProcesssError.getValue(), "Null response from BPEL"); logger.debug(END_OF_THE_TRANSACTION + resp.getEntity()); return resp; } @@ -455,8 +457,8 @@ public class E2EServiceInstances { Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_REQUEST, MsoException.ServiceException, "Mapping of request to JSON object failed. " + e.getMessage(), ErrorNumbers.SVC_BAD_PARAMETER, null, version); - logger.error("{} {} {} {}", MessageEnum.APIH_REQUEST_VALIDATION_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA, - ErrorCode.SchemaError.getValue(), requestJSON, e); + logger.error(Strings.repeat("{} ", 4), MessageEnum.APIH_REQUEST_VALIDATION_ERROR.toString(), + MSO_PROP_APIHANDLER_INFRA, ErrorCode.SchemaError.getValue(), requestJSON, e); logger.debug(END_OF_THE_TRANSACTION + response.getEntity()); return response; } @@ -473,8 +475,8 @@ public class E2EServiceInstances { if (requestId != null) { logger.debug("Logging failed message to the database"); } - logger.error("{} {} {} {}", MessageEnum.APIH_REQUEST_VALIDATION_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA, - ErrorCode.SchemaError.getValue(), requestJSON, e); + logger.error(Strings.repeat("{} ", 4), MessageEnum.APIH_REQUEST_VALIDATION_ERROR.toString(), + MSO_PROP_APIHANDLER_INFRA, ErrorCode.SchemaError.getValue(), requestJSON, e); logger.debug(END_OF_THE_TRANSACTION + response.getEntity()); return response; } @@ -483,7 +485,7 @@ public class E2EServiceInstances { try { recipeLookupResult = getServiceInstanceOrchestrationURI(e2eSir.getService().getServiceUuid(), action); } catch (Exception e) { - logger.error("{} {} {} {}", MessageEnum.APIH_DB_ACCESS_EXC.toString(), MSO_PROP_APIHANDLER_INFRA, + logger.error(Strings.repeat("{} ", 4), MessageEnum.APIH_DB_ACCESS_EXC.toString(), MSO_PROP_APIHANDLER_INFRA, ErrorCode.AvailabilityError.getValue(), "Exception while communciate with Catalog DB", e); Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_NOT_FOUND, MsoException.ServiceException, "No communication to catalog DB " + e.getMessage(), @@ -495,8 +497,8 @@ public class E2EServiceInstances { } if (recipeLookupResult == null) { - logger.error("{} {} {} {}", MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND.toString(), MSO_PROP_APIHANDLER_INFRA, - ErrorCode.DataError.getValue(), "No recipe found in DB"); + logger.error(Strings.repeat("{} ", 4), MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND.toString(), + MSO_PROP_APIHANDLER_INFRA, ErrorCode.DataError.getValue(), "No recipe found in DB"); Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_NOT_FOUND, MsoException.ServiceException, "Recipe does not exist in catalog DB", ErrorNumbers.SVC_GENERAL_SERVICE_ERROR, null, version); @@ -530,8 +532,9 @@ public class E2EServiceInstances { MsoException.ServiceException, "Failed calling bpmn " + e.getMessage(), ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version); - logger.error("{} {} {} {}", MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA, - ErrorCode.AvailabilityError.getValue(), "Exception while communicate with BPMN engine"); + logger.error(Strings.repeat("{} ", 4), MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), + MSO_PROP_APIHANDLER_INFRA, ErrorCode.AvailabilityError.getValue(), + "Exception while communicate with BPMN engine"); logger.debug(END_OF_THE_TRANSACTION + getBPMNResp.getEntity()); return getBPMNResp; @@ -541,8 +544,8 @@ public class E2EServiceInstances { Response getBPMNResp = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_GATEWAY, MsoException.ServiceException, "bpelResponse is null", ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version); - logger.error("{} {} {} {}", MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA, - ErrorCode.BusinessProcesssError.getValue(), "Null response from BPEL"); + logger.error(Strings.repeat("{} ", 4), MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), + MSO_PROP_APIHANDLER_INFRA, ErrorCode.BusinessProcesssError.getValue(), "Null response from BPEL"); logger.debug(END_OF_THE_TRANSACTION + getBPMNResp.getEntity()); return getBPMNResp; } @@ -572,8 +575,8 @@ public class E2EServiceInstances { Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_REQUEST, MsoException.ServiceException, "Mapping of request to JSON object failed. " + e.getMessage(), ErrorNumbers.SVC_BAD_PARAMETER, null, version); - logger.error("{} {} {} {}", MessageEnum.APIH_REQUEST_VALIDATION_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA, - ErrorCode.SchemaError.getValue(), requestJSON, e); + logger.error(Strings.repeat("{} ", 4), MessageEnum.APIH_REQUEST_VALIDATION_ERROR.toString(), + MSO_PROP_APIHANDLER_INFRA, ErrorCode.SchemaError.getValue(), requestJSON, e); logger.debug(END_OF_THE_TRANSACTION + response.getEntity()); return response; } @@ -590,8 +593,8 @@ public class E2EServiceInstances { if (requestId != null) { logger.debug("Logging failed message to the database"); } - logger.error("{} {} {} {}", MessageEnum.APIH_REQUEST_VALIDATION_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA, - ErrorCode.SchemaError.getValue(), requestJSON, e); + logger.error(Strings.repeat("{} ", 4), MessageEnum.APIH_REQUEST_VALIDATION_ERROR.toString(), + MSO_PROP_APIHANDLER_INFRA, ErrorCode.SchemaError.getValue(), requestJSON, e); logger.debug(END_OF_THE_TRANSACTION + response.getEntity()); return response; } @@ -600,7 +603,7 @@ public class E2EServiceInstances { try { recipeLookupResult = getServiceInstanceOrchestrationURI(e2eSir.getService().getServiceUuid(), action); } catch (Exception e) { - logger.error("{} {} {} {}", MessageEnum.APIH_DB_ACCESS_EXC.toString(), MSO_PROP_APIHANDLER_INFRA, + logger.error(Strings.repeat("{} ", 4), MessageEnum.APIH_DB_ACCESS_EXC.toString(), MSO_PROP_APIHANDLER_INFRA, ErrorCode.AvailabilityError.getValue(), "Exception while communciate with Catalog DB", e); Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_NOT_FOUND, MsoException.ServiceException, "No communication to catalog DB " + e.getMessage(), @@ -610,8 +613,8 @@ public class E2EServiceInstances { } if (recipeLookupResult == null) { - logger.error("{} {} {} {}", MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND.toString(), MSO_PROP_APIHANDLER_INFRA, - ErrorCode.DataError.getValue(), "No recipe found in DB"); + logger.error(Strings.repeat("{} ", 4), MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND.toString(), + MSO_PROP_APIHANDLER_INFRA, ErrorCode.DataError.getValue(), "No recipe found in DB"); Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_NOT_FOUND, MsoException.ServiceException, "Recipe does not exist in catalog DB", ErrorNumbers.SVC_GENERAL_SERVICE_ERROR, null, version); @@ -644,8 +647,9 @@ public class E2EServiceInstances { MsoException.ServiceException, "Failed calling bpmn " + e.getMessage(), ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version); - logger.error("{} {} {} {}", MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA, - ErrorCode.AvailabilityError.getValue(), "Exception while communicate with BPMN engine"); + logger.error(Strings.repeat("{} ", 4), MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), + MSO_PROP_APIHANDLER_INFRA, ErrorCode.AvailabilityError.getValue(), + "Exception while communicate with BPMN engine"); logger.debug(END_OF_THE_TRANSACTION + resp.getEntity()); return resp; } @@ -654,8 +658,8 @@ public class E2EServiceInstances { Response resp = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_GATEWAY, MsoException.ServiceException, "bpelResponse is null", ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version); - logger.error("{} {} {} {}", MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA, - ErrorCode.BusinessProcesssError.getValue(), "Null response from BPEL"); + logger.error(Strings.repeat("{} ", 4), MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), + MSO_PROP_APIHANDLER_INFRA, ErrorCode.BusinessProcesssError.getValue(), "Null response from BPEL"); logger.debug(END_OF_THE_TRANSACTION + resp.getEntity()); return resp; } @@ -684,8 +688,8 @@ public class E2EServiceInstances { Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_REQUEST, MsoException.ServiceException, "Mapping of request to JSON object failed. " + e.getMessage(), ErrorNumbers.SVC_BAD_PARAMETER, null, version); - logger.error("{} {} {} {}", MessageEnum.APIH_REQUEST_VALIDATION_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA, - ErrorCode.SchemaError.getValue(), requestJSON, e); + logger.error(Strings.repeat("{} ", 4), MessageEnum.APIH_REQUEST_VALIDATION_ERROR.toString(), + MSO_PROP_APIHANDLER_INFRA, ErrorCode.SchemaError.getValue(), requestJSON, e); logger.debug(END_OF_THE_TRANSACTION + response.getEntity()); return response; } @@ -695,7 +699,7 @@ public class E2EServiceInstances { // TODO Get the service template model version uuid from AAI. recipeLookupResult = getServiceInstanceOrchestrationURI(null, action); } catch (Exception e) { - logger.error("{} {} {} {}", MessageEnum.APIH_DB_ACCESS_EXC.toString(), MSO_PROP_APIHANDLER_INFRA, + logger.error(Strings.repeat("{} ", 4), MessageEnum.APIH_DB_ACCESS_EXC.toString(), MSO_PROP_APIHANDLER_INFRA, ErrorCode.AvailabilityError.getValue(), "Exception while communciate with Catalog DB", e); Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_NOT_FOUND, @@ -708,8 +712,8 @@ public class E2EServiceInstances { return response; } if (recipeLookupResult == null) { - logger.error("{} {} {} {}", MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND.toString(), MSO_PROP_APIHANDLER_INFRA, - ErrorCode.DataError.getValue(), "No recipe found in DB"); + logger.error(Strings.repeat("{} ", 4), MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND.toString(), + MSO_PROP_APIHANDLER_INFRA, ErrorCode.DataError.getValue(), "No recipe found in DB"); Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_NOT_FOUND, MsoException.ServiceException, "Recipe does not exist in catalog DB", @@ -747,8 +751,9 @@ public class E2EServiceInstances { MsoException.ServiceException, "Failed calling bpmn " + e.getMessage(), ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version); - logger.error("{} {} {} {}", MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA, - ErrorCode.AvailabilityError.getValue(), "Exception while communicate with BPMN engine", e); + logger.error(Strings.repeat("{} ", 4), MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), + MSO_PROP_APIHANDLER_INFRA, ErrorCode.AvailabilityError.getValue(), + "Exception while communicate with BPMN engine", e); logger.debug(END_OF_THE_TRANSACTION + resp.getEntity()); return resp; } @@ -757,8 +762,8 @@ public class E2EServiceInstances { Response resp = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_GATEWAY, MsoException.ServiceException, "bpelResponse is null", ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version); - logger.error("{} {} {} {}", MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA, - ErrorCode.BusinessProcesssError.getValue(), "Null response from BPEL"); + logger.error(Strings.repeat("{} ", 4), MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), + MSO_PROP_APIHANDLER_INFRA, ErrorCode.BusinessProcesssError.getValue(), "Null response from BPEL"); logger.debug(END_OF_THE_TRANSACTION + resp.getEntity()); return resp; } @@ -790,8 +795,8 @@ public class E2EServiceInstances { Response resp = msoRequest.buildServiceErrorResponse(bpelStatus, MsoException.ServiceException, "Request Failed due to BPEL error with HTTP Status= %1 " + '\n' + camundaJSONResponseBody, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR, variables, version); - logger.error("{} {} {} {}", MessageEnum.APIH_BPEL_RESPONSE_ERROR.toString(), requestClient.getUrl(), - ErrorCode.BusinessProcesssError.getValue(), + logger.error(Strings.repeat("{} ", 4), MessageEnum.APIH_BPEL_RESPONSE_ERROR.toString(), + requestClient.getUrl(), ErrorCode.BusinessProcesssError.getValue(), "Response from BPEL engine is failed with HTTP Status=" + bpelStatus); logger.debug(END_OF_THE_TRANSACTION + resp.getEntity()); return resp; @@ -928,21 +933,14 @@ public class E2EServiceInstances { // subscriptionServiceType requestParameters.setSubscriptionServiceType("MOG"); - // Userparams - // List<E2EUserParam> userParams; - // userParams = - // e2eSir.getService().getParameters().getRequestParameters().getUserParams(); + List<Map<String, Object>> userParamList = new ArrayList<>(); Map<String, Object> userParamMap = new HashMap<>(); // complete json request updated in the camunda userParamMap.put("UUIRequest", requestJSON); userParamMap.put("ServiceInstanceName", e2eSir.getService().getName()); - // Map<String, String> userParamMap3 = null; - // for (E2EUserParam userp : userParams) { - // userParamMap.put(userp.getName(), userp.getValue()); - // - // } + userParamList.add(userParamMap); requestParameters.setUserParams(userParamList); diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/GlobalHealthcheckHandler.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/GlobalHealthcheckHandler.java index 4d283f26b1..e3b297b5db 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/GlobalHealthcheckHandler.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/GlobalHealthcheckHandler.java @@ -25,6 +25,7 @@ package org.onap.so.apihandlerinfra; import java.net.URI; import java.util.Collections; +import com.google.common.base.Strings; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.MediaType; @@ -112,7 +113,7 @@ public class GlobalHealthcheckHandler { try { // Generated RequestId String requestId = requestContext.getProperty("requestId").toString(); - logger.info("{} {}", MessageEnum.APIH_GENERATED_REQUEST_ID.toString(), requestId); + logger.info(Strings.repeat("{} ", 2), MessageEnum.APIH_GENERATED_REQUEST_ID.toString(), requestId); // set APIH status, this is the main entry point rsp.setApih(HealthcheckStatus.UP.toString()); diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/InstanceManagement.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/InstanceManagement.java index dd6050bf60..c582e429ff 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/InstanceManagement.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/InstanceManagement.java @@ -115,8 +115,7 @@ public class InstanceManagement { String requestUri = requestHandlerUtils.getRequestUri(requestContext, uriPrefix); - sir = requestHandlerUtils.convertJsonToServiceInstanceRequest(requestJSON, action, startTime, sir, msoRequest, - requestId, requestUri); + sir = requestHandlerUtils.convertJsonToServiceInstanceRequest(requestJSON, action, requestId, requestUri); String requestScope = requestHandlerUtils.deriveRequestScope(action, sir, requestUri); InfraActiveRequests currentActiveReq = msoRequest.createRequestObject(sir, action, requestId, Status.IN_PROGRESS, requestJSON, requestScope); @@ -149,16 +148,15 @@ public class InstanceManagement { InfraActiveRequests dup = null; boolean inProgress = false; - dup = requestHandlerUtils.duplicateCheck(action, instanceIdMap, startTime, msoRequest, null, requestScope, - currentActiveReq); + dup = requestHandlerUtils.duplicateCheck(action, instanceIdMap, null, requestScope, currentActiveReq); if (dup != null) { inProgress = requestHandlerUtils.camundaHistoryCheck(dup, currentActiveReq); } if (dup != null && inProgress) { - requestHandlerUtils.buildErrorOnDuplicateRecord(currentActiveReq, action, instanceIdMap, startTime, - msoRequest, null, requestScope, dup); + requestHandlerUtils.buildErrorOnDuplicateRecord(currentActiveReq, action, instanceIdMap, null, requestScope, + dup); } ServiceInstancesResponse serviceResponse = new ServiceInstancesResponse(); diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/JerseyConfiguration.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/JerseyConfiguration.java index 67d6a0d1fc..7c0d327db7 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/JerseyConfiguration.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/JerseyConfiguration.java @@ -24,8 +24,8 @@ import javax.annotation.PostConstruct; import javax.ws.rs.ApplicationPath; import org.glassfish.jersey.server.ResourceConfig; import org.glassfish.jersey.servlet.ServletProperties; -import org.onap.so.apihandler.filters.RequestUriFilter; import org.onap.so.apihandler.filters.RequestIdFilter; +import org.onap.so.apihandler.filters.RequestUriFilter; import org.onap.so.apihandlerinfra.exceptions.ApiExceptionMapper; import org.onap.so.apihandlerinfra.tenantisolation.CloudOrchestration; import org.onap.so.apihandlerinfra.tenantisolation.CloudResourcesOrchestration; @@ -41,8 +41,6 @@ import io.swagger.jaxrs.listing.SwaggerSerializers; @ApplicationPath("/") public class JerseyConfiguration extends ResourceConfig { - - @PostConstruct public void setUp() { register(GlobalHealthcheckHandler.class); @@ -64,6 +62,7 @@ public class JerseyConfiguration extends ResourceConfig { register(E2EServiceInstances.class); register(WorkflowSpecificationsHandler.class); register(InstanceManagement.class); + register(ResumeOrchestrationRequest.class); // this registration seems to be needed to get predictable // execution behavior for the above JSON Exception Mappers register(com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider.class); diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/ManualTasks.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/ManualTasks.java index 3c06804594..169ec50a74 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/ManualTasks.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/ManualTasks.java @@ -34,6 +34,7 @@ import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; +import com.google.common.base.Strings; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.onap.so.apihandler.common.ErrorNumbers; @@ -91,7 +92,7 @@ public class ManualTasks { @PathParam("taskId") String taskId, @Context ContainerRequestContext requestContext) throws ApiException { String requestId = requestContext.getProperty("requestId").toString(); - logger.info("{} {}", MessageEnum.APIH_GENERATED_REQUEST_ID.toString(), requestId); + logger.info(Strings.repeat("{} ", 2), MessageEnum.APIH_GENERATED_REQUEST_ID.toString(), requestId); long startTime = System.currentTimeMillis(); logger.debug("requestId is: {}", requestId); TasksRequest taskRequest = null; diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/MsoRequest.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/MsoRequest.java index 277675f310..49572630ed 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/MsoRequest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/MsoRequest.java @@ -42,6 +42,7 @@ import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; +import com.google.common.base.Strings; import org.onap.so.apihandler.common.ResponseBuilder; import org.onap.so.apihandlerinfra.tasksbeans.TasksRequest; import org.onap.so.apihandlerinfra.validation.MembersValidation; @@ -151,7 +152,8 @@ public class MsoRequest { mapper.setSerializationInclusion(Include.NON_DEFAULT); requestErrorStr = mapper.writeValueAsString(re); } catch (Exception e) { - logger.error("{} {} {}", MessageEnum.APIH_VALIDATION_ERROR.toString(), ErrorCode.DataError.getValue(), + logger.error(Strings.repeat("{} ", 3), MessageEnum.APIH_VALIDATION_ERROR.toString(), + ErrorCode.DataError.getValue(), "Exception in buildServiceErrorResponse writing exceptionType to string ", e); } @@ -396,8 +398,8 @@ public class MsoRequest { aq.setRequestStatus(status.toString()); aq.setLastModifiedBy(Constants.MODIFIED_BY_APIHANDLER); } catch (Exception e) { - logger.error("{} {} {}", MessageEnum.APIH_DB_INSERT_EXC.toString(), ErrorCode.DataError.getValue(), - "Exception when creation record request", e); + logger.error(Strings.repeat("{} ", 3), MessageEnum.APIH_DB_INSERT_EXC.toString(), + ErrorCode.DataError.getValue(), "Exception when creation record request", e); if (!status.equals(Status.FAILED)) { throw e; @@ -437,8 +439,8 @@ public class MsoRequest { aq.setLastModifiedBy(Constants.MODIFIED_BY_APIHANDLER); } catch (Exception e) { - logger.error("{} {} {}", MessageEnum.APIH_DB_INSERT_EXC.toString(), ErrorCode.DataError.getValue(), - "Exception when creation record request", e); + logger.error(Strings.repeat("{} ", 3), MessageEnum.APIH_DB_INSERT_EXC.toString(), + ErrorCode.DataError.getValue(), "Exception when creation record request", e); if (!status.equals(Status.FAILED)) { throw e; @@ -465,7 +467,7 @@ public class MsoRequest { request.setRequestUrl(MDC.get(LogConstants.HTTP_URL)); requestsDbClient.save(request); } catch (Exception e) { - logger.error("{} {} {} {}", MessageEnum.APIH_DB_UPDATE_EXC.toString(), e.getMessage(), + logger.error(Strings.repeat("{} ", 4), MessageEnum.APIH_DB_UPDATE_EXC.toString(), e.getMessage(), ErrorCode.DataError.getValue(), "Exception when updating record in DB"); logger.debug("Exception: ", e); } @@ -547,8 +549,8 @@ public class MsoRequest { return null; } catch (Exception e) { - logger.error("{} {} {}", MessageEnum.APIH_DOM2STR_ERROR.toString(), ErrorCode.DataError.getValue(), - "Exception in domToStr", e); + logger.error(Strings.repeat("{} ", 3), MessageEnum.APIH_DOM2STR_ERROR.toString(), + ErrorCode.DataError.getValue(), "Exception in domToStr", e); } return null; } @@ -574,7 +576,7 @@ public class MsoRequest { throws JsonGenerationException, JsonMappingException, IOException { ObjectMapper mapper = new ObjectMapper(); mapper.setSerializationInclusion(Include.NON_NULL); - // mapper.configure(Feature.WRAP_ROOT_VALUE, true); + logger.debug("building sir from object {}", sir); String requestJSON = mapper.writeValueAsString(sir); @@ -636,7 +638,7 @@ public class MsoRequest { public String getVfModuleType(ServiceInstancesRequest sir, String requestScope, Actions action, int reqVersion) { String serviceInstanceType = null; - String networkType = null; + String vnfType = null; String vfModuleType = null; String vfModuleModelName = null; @@ -800,6 +802,7 @@ public class MsoRequest { selfLinkUrl = Optional.of(new URL(aUrl.getProtocol(), aUrl.getHost(), aUrl.getPort(), selfLinkPath)); } catch (Exception e) { selfLinkUrl = Optional.empty(); // ignore + logger.info(e.getMessage()); } return selfLinkUrl; } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/MsoSubsystems.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/MsoSubsystems.java index fd0df1d2b0..13f1e52068 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/MsoSubsystems.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/MsoSubsystems.java @@ -20,9 +20,14 @@ package org.onap.so.apihandlerinfra; public enum MsoSubsystems { - APIH("API Handler"), ASDC("ASDC Controller"), BPMN("BPMN Infra"), CATALOGDB("CatalogDb Adapter"), OPENSTACK( - "Openstack Adapter"), REQUESTDB( - "RequestDB Adapter"), REQUESTDBATT("RequestDB Adapter ATT Svc"), SDNC("SDNC Adapter"); + APIH("API Handler"), + ASDC("ASDC Controller"), + BPMN("BPMN Infra"), + CATALOGDB("CatalogDb Adapter"), + OPENSTACK("Openstack Adapter"), + REQUESTDB("RequestDB Adapter"), + REQUESTDBATT("RequestDB Adapter ATT Svc"), + SDNC("SDNC Adapter"); private String subsystem; private MsoSubsystems(String subsystem) { diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/NodeHealthcheckHandler.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/NodeHealthcheckHandler.java index 9810895ad9..07a0161e8f 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/NodeHealthcheckHandler.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/NodeHealthcheckHandler.java @@ -30,6 +30,7 @@ import javax.ws.rs.Produces; import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.core.Context; import javax.ws.rs.core.Response; +import com.google.common.base.Strings; import org.apache.http.HttpStatus; import org.onap.so.logger.MessageEnum; import org.slf4j.Logger; @@ -57,7 +58,7 @@ public class NodeHealthcheckHandler { public Response nodeHealthcheck(@Context ContainerRequestContext requestContext) throws UnknownHostException { // Generated RequestId String requestId = requestContext.getProperty("requestId").toString(); - logger.info("{} {}", MessageEnum.APIH_GENERATED_REQUEST_ID.toString(), requestId); + logger.info(Strings.repeat("{} ", 2), MessageEnum.APIH_GENERATED_REQUEST_ID.toString(), requestId); return HEALTH_CHECK_RESPONSE; } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/OrchestrationRequests.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/OrchestrationRequests.java index 34dcd4b0c4..e14b01792a 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/OrchestrationRequests.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/OrchestrationRequests.java @@ -35,6 +35,7 @@ import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; @@ -53,6 +54,7 @@ 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.MessageEnum; +import org.onap.so.serviceinstancebeans.CloudRequestData; import org.onap.so.serviceinstancebeans.GetOrchestrationListResponse; import org.onap.so.serviceinstancebeans.GetOrchestrationResponse; import org.onap.so.serviceinstancebeans.InstanceReferences; @@ -61,6 +63,7 @@ import org.onap.so.serviceinstancebeans.RequestDetails; import org.onap.so.serviceinstancebeans.RequestList; import org.onap.so.serviceinstancebeans.RequestStatus; import org.onap.so.serviceinstancebeans.ServiceInstancesRequest; +import org.onap.so.utils.UUIDChecker; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -76,7 +79,6 @@ public class OrchestrationRequests { private static Logger logger = LoggerFactory.getLogger(OrchestrationRequests.class); - @Autowired private RequestsDbClient requestsDbClient; @@ -92,14 +94,23 @@ public class OrchestrationRequests { @Produces(MediaType.APPLICATION_JSON) @Transactional public Response getOrchestrationRequest(@PathParam("requestId") String requestId, - @PathParam("version") String version) throws ApiException { + @PathParam("version") String version, @QueryParam("includeCloudRequest") boolean includeCloudRequest) + throws ApiException { String apiVersion = version.substring(1); GetOrchestrationResponse orchestrationResponse = new GetOrchestrationResponse(); - InfraActiveRequests infraActiveRequest = null; List<org.onap.so.db.request.beans.RequestProcessingData> requestProcessingData = null; + + if (!UUIDChecker.isValidUUID(requestId)) { + + ErrorLoggerInfo errorLoggerInfo = + new ErrorLoggerInfo.Builder(MessageEnum.APIH_VALIDATION_ERROR, ErrorCode.SchemaError) + .errorSource(Constants.MODIFIED_BY_APIHANDLER).build(); + throw new ValidateException.Builder("Request Id " + requestId + " is not a valid UUID", + HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).errorInfo(errorLoggerInfo).build(); + } try { infraActiveRequest = requestsDbClient.getInfraActiveRequestbyRequestId(requestId); requestProcessingData = requestsDbClient.getRequestProcessingDataBySoRequestId(requestId); @@ -109,14 +120,11 @@ public class OrchestrationRequests { ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ACCESS_EXC, ErrorCode.AvailabilityError).build(); - - ValidateException validateException = new ValidateException.Builder("Exception while communciate with Request DB - Infra Request Lookup", HttpStatus.SC_NOT_FOUND, ErrorNumbers.NO_COMMUNICATION_TO_REQUESTS_DB).cause(e) .errorInfo(errorLoggerInfo).build(); - throw validateException; } @@ -126,7 +134,6 @@ public class OrchestrationRequests { ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, ErrorCode.BusinessProcesssError).build(); - ValidateException validateException = new ValidateException.Builder("Orchestration RequestId " + requestId + " is not found in DB", HttpStatus.SC_NO_CONTENT, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR) @@ -135,7 +142,7 @@ public class OrchestrationRequests { throw validateException; } - Request request = mapInfraActiveRequestToRequest(infraActiveRequest); + Request request = mapInfraActiveRequestToRequest(infraActiveRequest, includeCloudRequest); if (!requestProcessingData.isEmpty()) { request.setRequestProcessingData(mapRequestProcessingData(requestProcessingData)); } @@ -150,8 +157,8 @@ public class OrchestrationRequests { @ApiOperation(value = "Find Orchestrated Requests for a URI Information", response = Response.class) @Produces(MediaType.APPLICATION_JSON) @Transactional - public Response getOrchestrationRequest(@Context UriInfo ui, @PathParam("version") String version) - throws ApiException { + public Response getOrchestrationRequest(@Context UriInfo ui, @PathParam("version") String version, + @QueryParam("includeCloudRequest") boolean includeCloudRequest) throws ApiException { long startTime = System.currentTimeMillis(); @@ -188,7 +195,7 @@ public class OrchestrationRequests { List<RequestProcessingData> requestProcessingData = requestsDbClient.getRequestProcessingDataBySoRequestId(infraActive.getRequestId()); RequestList requestList = new RequestList(); - Request request = mapInfraActiveRequestToRequest(infraActive); + Request request = mapInfraActiveRequestToRequest(infraActive, includeCloudRequest); if (!requestProcessingData.isEmpty()) { request.setRequestProcessingData(mapRequestProcessingData(requestProcessingData)); } @@ -200,7 +207,6 @@ public class OrchestrationRequests { return builder.buildResponse(HttpStatus.SC_OK, null, orchestrationList, apiVersion); } - @POST @Path("/{version: [vV][4-7]}/{requestId}/unlock") @Consumes(MediaType.APPLICATION_JSON) @@ -251,7 +257,6 @@ public class OrchestrationRequests { ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND, ErrorCode.BusinessProcesssError).build(); - ValidateException validateException = new ValidateException.Builder("Null response from RequestDB when searching by RequestId", HttpStatus.SC_NOT_FOUND, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo) @@ -273,7 +278,6 @@ public class OrchestrationRequests { new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND, ErrorCode.DataError) .build(); - ValidateException validateException = new ValidateException.Builder( "Orchestration RequestId " + requestId + " has a status of " + status + " and can not be unlocked", @@ -286,8 +290,8 @@ public class OrchestrationRequests { return Response.status(HttpStatus.SC_NO_CONTENT).entity("").build(); } - private Request mapInfraActiveRequestToRequest(InfraActiveRequests iar) throws ApiException { - + protected Request mapInfraActiveRequestToRequest(InfraActiveRequests iar, boolean includeCloudRequest) + throws ApiException { String requestBody = iar.getRequestBody(); Request request = new Request(); @@ -300,6 +304,10 @@ public class OrchestrationRequests { String flowStatusMessage = iar.getFlowStatus(); String retryStatusMessage = iar.getRetryStatusMessage(); + String originalRequestId = iar.getOriginalRequestId(); + if (originalRequestId != null) { + request.setOriginalRequestId(originalRequestId); + } InstanceReferences ir = new InstanceReferences(); if (iar.getNetworkId() != null) @@ -329,8 +337,6 @@ public class OrchestrationRequests { if (iar.getInstanceGroupName() != null) ir.setInstanceGroupName(iar.getInstanceGroupName()); - - request.setInstanceReferences(ir); RequestDetails requestDetails = null; @@ -401,7 +407,6 @@ public class OrchestrationRequests { status.setTimeStamp(timeStamp); } - if (iar.getRequestStatus() != null) { status.setRequestState(iar.getRequestStatus()); } @@ -410,8 +415,19 @@ public class OrchestrationRequests { status.setPercentProgress(iar.getProgress().intValue()); } - request.setRequestStatus(status); + if (iar.getCloudApiRequests() != null && !iar.getCloudApiRequests().isEmpty() && includeCloudRequest) { + iar.getCloudApiRequests().stream().forEach(cloudRequest -> { + try { + request.getCloudRequestData() + .add(new CloudRequestData(mapper.readValue(cloudRequest.getRequestBody(), Object.class), + cloudRequest.getCloudIdentifier())); + } catch (Exception e) { + logger.error("Error reading Cloud Request", e); + } + }); + } + request.setRequestStatus(status); return request; } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/RequestHandlerUtils.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/RequestHandlerUtils.java index bbcc120ab6..4e910e5382 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/RequestHandlerUtils.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/RequestHandlerUtils.java @@ -24,8 +24,20 @@ package org.onap.so.apihandlerinfra; -import com.fasterxml.jackson.annotation.JsonInclude.Include; -import com.fasterxml.jackson.databind.ObjectMapper; +import static org.onap.so.logger.HttpHeadersConstants.REQUESTOR_ID; +import java.io.IOException; +import java.net.URL; +import java.security.GeneralSecurityException; +import java.sql.Timestamp; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import javax.ws.rs.container.ContainerRequestContext; +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.core.Response; +import javax.xml.bind.DatatypeConverter; import org.apache.commons.lang.StringUtils; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; @@ -47,7 +59,9 @@ import org.onap.so.apihandlerinfra.exceptions.ContactCamundaException; import org.onap.so.apihandlerinfra.exceptions.DuplicateRequestException; import org.onap.so.apihandlerinfra.exceptions.RequestDbFailureException; import org.onap.so.apihandlerinfra.exceptions.ValidateException; +import org.onap.so.apihandlerinfra.exceptions.VfModuleNotFoundException; import org.onap.so.apihandlerinfra.logging.ErrorLoggerInfo; +import org.onap.so.db.catalog.beans.VfModule; import org.onap.so.db.catalog.client.CatalogDbClient; import org.onap.so.db.request.beans.InfraActiveRequests; import org.onap.so.db.request.client.RequestsDbClient; @@ -55,6 +69,7 @@ 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.ModelInfo; import org.onap.so.serviceinstancebeans.ModelType; import org.onap.so.serviceinstancebeans.RelatedInstance; import org.onap.so.serviceinstancebeans.RelatedInstanceList; @@ -76,20 +91,8 @@ import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Component; import org.springframework.web.client.HttpStatusCodeException; import org.springframework.web.client.RestTemplate; -import javax.ws.rs.container.ContainerRequestContext; -import javax.ws.rs.core.MultivaluedMap; -import javax.ws.rs.core.Response; -import javax.xml.bind.DatatypeConverter; -import static org.onap.so.logger.HttpHeadersConstants.REQUESTOR_ID; -import java.io.IOException; -import java.net.URL; -import java.security.GeneralSecurityException; -import java.sql.Timestamp; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Optional; +import com.fasterxml.jackson.annotation.JsonInclude.Include; +import com.fasterxml.jackson.databind.ObjectMapper; @Component public class RequestHandlerUtils { @@ -293,9 +296,8 @@ public class RequestHandlerUtils { return requestUri; } - public InfraActiveRequests duplicateCheck(Actions action, HashMap<String, String> instanceIdMap, long startTime, - MsoRequest msoRequest, String instanceName, String requestScope, InfraActiveRequests currentActiveReq) - throws ApiException { + public InfraActiveRequests duplicateCheck(Actions action, HashMap<String, String> instanceIdMap, + String instanceName, String requestScope, InfraActiveRequests currentActiveReq) throws ApiException { InfraActiveRequests dup = null; try { if (!(instanceName == null && requestScope.equals("service") && (action == Action.createInstance @@ -369,8 +371,7 @@ public class RequestHandlerUtils { } public ServiceInstancesRequest convertJsonToServiceInstanceRequest(String requestJSON, Actions action, - long startTime, ServiceInstancesRequest sir, MsoRequest msoRequest, String requestId, String requestUri) - throws ApiException { + String requestId, String requestUri) throws ApiException { try { ObjectMapper mapper = new ObjectMapper(); return mapper.readValue(requestJSON, ServiceInstancesRequest.class); @@ -415,8 +416,8 @@ public class RequestHandlerUtils { } public void buildErrorOnDuplicateRecord(InfraActiveRequests currentActiveReq, Actions action, - HashMap<String, String> instanceIdMap, long startTime, MsoRequest msoRequest, String instanceName, - String requestScope, InfraActiveRequests dup) throws ApiException { + HashMap<String, String> instanceIdMap, String instanceName, String requestScope, InfraActiveRequests dup) + throws ApiException { String instance = null; if (instanceName != null) { @@ -622,4 +623,88 @@ public class RequestHandlerUtils { return requestScope; } + protected InfraActiveRequests createNewRecordCopyFromInfraActiveRequest(InfraActiveRequests infraActiveRequest, + String requestId, Timestamp startTimeStamp, String source, String requestUri, String requestorId, + String originalRequestId) { + InfraActiveRequests request = new InfraActiveRequests(); + request.setRequestId(requestId); + request.setStartTime(startTimeStamp); + request.setSource(source); + request.setRequestUrl(requestUri); + request.setProgress(new Long(5)); + request.setRequestorId(requestorId); + request.setRequestStatus(Status.IN_PROGRESS.toString()); + request.setOriginalRequestId(originalRequestId); + request.setLastModifiedBy(Constants.MODIFIED_BY_APIHANDLER); + if (infraActiveRequest != null) { + request.setTenantId(infraActiveRequest.getTenantId()); + request.setRequestBody(infraActiveRequest.getRequestBody()); + request.setAicCloudRegion(infraActiveRequest.getAicCloudRegion()); + request.setRequestScope(infraActiveRequest.getRequestScope()); + request.setRequestAction(infraActiveRequest.getRequestAction()); + setInstanceIdAndName(infraActiveRequest, request); + } + return request; + } + + protected void setInstanceIdAndName(InfraActiveRequests infraActiveRequest, + InfraActiveRequests currentActiveRequest) { + String requestScope = infraActiveRequest.getRequestScope(); + try { + ModelType type = ModelType.valueOf(requestScope); + type.setName(currentActiveRequest, type.getName(infraActiveRequest)); + type.setId(currentActiveRequest, type.getId(infraActiveRequest)); + } catch (IllegalArgumentException e) { + logger.error( + "requestScope \"{}\" does not match a ModelType enum. Unable to set instanceId and instanceName from the original request.", + requestScope); + } + } + + protected Boolean getIsBaseVfModule(ModelInfo modelInfo, Actions action, String vnfType, + String sdcServiceModelVersion, InfraActiveRequests currentActiveReq) throws ApiException { + // Get VF Module-specific base module indicator + VfModule vfm = null; + String modelVersionId = modelInfo.getModelVersionId(); + Boolean isBaseVfModule = false; + + if (modelVersionId != null) { + vfm = catalogDbClient.getVfModuleByModelUUID(modelVersionId); + } else if (modelInfo.getModelInvariantId() != null && modelInfo.getModelVersion() != null) { + vfm = catalogDbClient.getVfModuleByModelInvariantUUIDAndModelVersion(modelInfo.getModelInvariantId(), + modelInfo.getModelVersion()); + } + + if (vfm != null) { + if (vfm.getIsBase()) { + isBaseVfModule = true; + } + } else if (action == Action.createInstance || action == Action.updateInstance) { + String serviceVersionText = ""; + if (sdcServiceModelVersion != null && !sdcServiceModelVersion.isEmpty()) { + serviceVersionText = " with version " + sdcServiceModelVersion; + } + String errorMessage = "VnfType " + vnfType + " and VF Module Model Name " + modelInfo.getModelName() + + serviceVersionText + " not found in MSO Catalog DB"; + ErrorLoggerInfo errorLoggerInfo = + new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND, ErrorCode.DataError) + .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); + VfModuleNotFoundException vfModuleException = new VfModuleNotFoundException.Builder(errorMessage, + HttpStatus.SC_NOT_FOUND, ErrorNumbers.SVC_BAD_PARAMETER).errorInfo(errorLoggerInfo).build(); + updateStatus(currentActiveReq, Status.FAILED, vfModuleException.getMessage()); + throw vfModuleException; + } + return isBaseVfModule; + } + + protected ModelType getModelType(Actions action, ModelInfo modelInfo) { + if (action == Action.applyUpdatedConfig || action == Action.inPlaceSoftwareUpdate) { + return ModelType.vnf; + } else if (action == Action.addMembers || action == Action.removeMembers) { + return ModelType.instanceGroup; + } else { + return modelInfo.getModelType(); + } + } + } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/ResumeOrchestrationRequest.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/ResumeOrchestrationRequest.java new file mode 100644 index 0000000000..32d2c50978 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/ResumeOrchestrationRequest.java @@ -0,0 +1,276 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 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.so.apihandlerinfra; + +import java.io.IOException; +import java.sql.Timestamp; +import java.util.HashMap; +import javax.transaction.Transactional; +import javax.ws.rs.Consumes; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.container.ContainerRequestContext; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import org.apache.http.HttpStatus; +import org.onap.logging.ref.slf4j.ONAPLogConstants; +import org.onap.so.apihandler.common.ErrorNumbers; +import org.onap.so.apihandler.common.RequestClientParameter; +import org.onap.so.apihandlerinfra.exceptions.ApiException; +import org.onap.so.apihandlerinfra.exceptions.RequestDbFailureException; +import org.onap.so.apihandlerinfra.exceptions.ValidateException; +import org.onap.so.apihandlerinfra.logging.ErrorLoggerInfo; +import org.onap.so.db.request.beans.InfraActiveRequests; +import org.onap.so.db.request.client.RequestsDbClient; +import org.onap.so.logger.ErrorCode; +import org.onap.so.logger.HttpHeadersConstants; +import org.onap.so.logger.LogConstants; +import org.onap.so.logger.MdcConstants; +import org.onap.so.logger.MessageEnum; +import org.onap.so.serviceinstancebeans.ModelInfo; +import org.onap.so.serviceinstancebeans.ModelType; +import org.onap.so.serviceinstancebeans.ServiceInstancesRequest; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.slf4j.MDC; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import org.springframework.web.client.HttpClientErrorException; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; + +@Path("onap/so/infra/orchestrationRequests") +@Api(value = "onap/so/infra/orchestrationRequests") +@Component +public class ResumeOrchestrationRequest { + private static Logger logger = LoggerFactory.getLogger(ResumeOrchestrationRequest.class); + private static final String SAVE_TO_DB = "save instance to db"; + private static String uriPrefix = "/orchestrationRequests/"; + + @Autowired + private RequestHandlerUtils requestHandlerUtils; + + @Autowired + private ServiceInstances serviceInstances; + + @Autowired + private RequestsDbClient requestsDbClient; + + @Autowired + private MsoRequest msoRequest; + + @POST + @Path("/{version:[vV][7]}/requests/{requestId}/resume") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Resume request for a given requestId", response = Response.class) + @Transactional + public Response resumeOrchestrationRequest(@PathParam("requestId") String requestId, + @PathParam("version") String version, @Context ContainerRequestContext requestContext) throws ApiException { + + Timestamp startTimeStamp = new Timestamp(System.currentTimeMillis()); + String currentRequestId = MDC.get(ONAPLogConstants.MDCs.REQUEST_ID); + logger.info("Beginning resume operation for new request: {}", currentRequestId); + InfraActiveRequests infraActiveRequest = null; + String source = MDC.get(MdcConstants.ORIGINAL_PARTNER_NAME); + String requestorId = MDC.get(HttpHeadersConstants.REQUESTOR_ID); + requestHandlerUtils.getRequestUri(requestContext, uriPrefix); + String requestUri = MDC.get(LogConstants.HTTP_URL); + version = version.substring(1); + + try { + infraActiveRequest = requestsDbClient.getInfraActiveRequestbyRequestId(requestId); + } catch (HttpClientErrorException e) { + logger.error("Error occurred while performing requestDb lookup by requestId: " + requestId, e); + ErrorLoggerInfo errorLoggerInfo = + new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ACCESS_EXC, ErrorCode.AvailabilityError).build(); + throw new ValidateException.Builder("Exception while performing requestDb lookup by requestId", + HttpStatus.SC_NOT_FOUND, ErrorNumbers.NO_COMMUNICATION_TO_REQUESTS_DB).cause(e) + .errorInfo(errorLoggerInfo).build(); + } + + InfraActiveRequests currentActiveRequest = requestHandlerUtils.createNewRecordCopyFromInfraActiveRequest( + infraActiveRequest, currentRequestId, startTimeStamp, source, requestUri, requestorId, requestId); + + if (infraActiveRequest == null) { + logger.error("No infraActiveRequest record found for requestId: {} in requesteDb lookup", requestId); + ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND, + ErrorCode.BusinessProcesssError).build(); + ValidateException validateException = new ValidateException.Builder( + "Null response from requestDB when searching by requestId: " + requestId, HttpStatus.SC_NOT_FOUND, + ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo).build(); + requestHandlerUtils.updateStatus(currentActiveRequest, Status.FAILED, validateException.getMessage()); + throw validateException; + + } + + return resumeRequest(infraActiveRequest, currentActiveRequest, version, requestUri); + } + + protected Response resumeRequest(InfraActiveRequests infraActiveRequest, InfraActiveRequests currentActiveRequest, + String version, String requestUri) throws ApiException { + String requestBody = infraActiveRequest.getRequestBody(); + Action action = Action.valueOf(infraActiveRequest.getRequestAction()); + String requestId = currentActiveRequest.getRequestId(); + String requestScope = infraActiveRequest.getRequestScope(); + String instanceName = getInstanceName(infraActiveRequest, requestScope, currentActiveRequest); + HashMap<String, String> instanceIdMap = setInstanceIdMap(infraActiveRequest, requestScope); + + checkForInProgressRequest(currentActiveRequest, instanceIdMap, requestScope, instanceName, action); + + ServiceInstancesRequest sir = null; + sir = requestHandlerUtils.convertJsonToServiceInstanceRequest(requestBody, action, requestId, requestUri); + Boolean aLaCarte = sir.getRequestDetails().getRequestParameters().getALaCarte(); + + String pnfCorrelationId = serviceInstances.getPnfCorrelationId(sir); + RecipeLookupResult recipeLookupResult = serviceInstances.getServiceInstanceOrchestrationURI(sir, action, + msoRequest.getAlacarteFlag(sir), currentActiveRequest); + + requestDbSave(currentActiveRequest); + + if (aLaCarte == null) { + aLaCarte = setALaCarteFlagIfNull(requestScope, action); + } + + RequestClientParameter requestClientParameter = setRequestClientParameter(recipeLookupResult, version, + infraActiveRequest, currentActiveRequest, pnfCorrelationId, aLaCarte, sir); + + return requestHandlerUtils.postBPELRequest(currentActiveRequest, requestClientParameter, + recipeLookupResult.getOrchestrationURI(), requestScope); + } + + protected Boolean setALaCarteFlagIfNull(String requestScope, Action action) { + Boolean aLaCarteFlag; + if (!requestScope.equalsIgnoreCase(ModelType.service.name()) && action != Action.recreateInstance) { + aLaCarteFlag = true; + } else { + aLaCarteFlag = false; + } + return aLaCarteFlag; + } + + protected HashMap<String, String> setInstanceIdMap(InfraActiveRequests infraActiveRequest, String requestScope) { + HashMap<String, String> instanceIdMap = new HashMap<>(); + ModelType type; + try { + type = ModelType.valueOf(requestScope); + instanceIdMap.put(type.name() + "InstanceId", type.getId(infraActiveRequest)); + } catch (IllegalArgumentException e) { + logger.error("requestScope \"{}\" does not match a ModelType enum.", requestScope); + } + return instanceIdMap; + } + + protected String getInstanceName(InfraActiveRequests infraActiveRequest, String requestScope, + InfraActiveRequests currentActiveRequest) throws ValidateException, RequestDbFailureException { + ModelType type; + String instanceName = ""; + try { + type = ModelType.valueOf(requestScope); + instanceName = type.getName(infraActiveRequest); + } catch (IllegalArgumentException e) { + logger.error("requestScope \"{}\" does not match a ModelType enum.", requestScope); + ValidateException validateException = new ValidateException.Builder( + "requestScope: \"" + requestScope + "\" from request: " + infraActiveRequest.getRequestId() + + " does not match a ModelType enum.", + HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).cause(e).build(); + requestHandlerUtils.updateStatus(currentActiveRequest, Status.FAILED, validateException.getMessage()); + throw validateException; + } + return instanceName; + } + + protected void checkForInProgressRequest(InfraActiveRequests currentActiveRequest, + HashMap<String, String> instanceIdMap, String requestScope, String instanceName, Action action) + throws ApiException { + boolean inProgress = false; + InfraActiveRequests requestInProgress = requestHandlerUtils.duplicateCheck(action, instanceIdMap, instanceName, + requestScope, currentActiveRequest); + if (requestInProgress != null) { + inProgress = requestHandlerUtils.camundaHistoryCheck(requestInProgress, currentActiveRequest); + } + if (inProgress) { + requestHandlerUtils.buildErrorOnDuplicateRecord(currentActiveRequest, action, instanceIdMap, instanceName, + requestScope, requestInProgress); + } + } + + protected void requestDbSave(InfraActiveRequests currentActiveRequest) throws RequestDbFailureException { + try { + requestsDbClient.save(currentActiveRequest); + } catch (Exception e) { + logger.error("Exception while saving request to requestDb", e); + ErrorLoggerInfo errorLoggerInfo = + new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ACCESS_EXC, ErrorCode.DataError) + .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); + throw new RequestDbFailureException.Builder(SAVE_TO_DB, e.toString(), HttpStatus.SC_INTERNAL_SERVER_ERROR, + ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).cause(e).errorInfo(errorLoggerInfo).build(); + } + } + + protected RequestClientParameter setRequestClientParameter(RecipeLookupResult recipeLookupResult, String version, + InfraActiveRequests infraActiveRequest, InfraActiveRequests currentActiveRequest, String pnfCorrelationId, + Boolean aLaCarte, ServiceInstancesRequest sir) throws ApiException { + RequestClientParameter requestClientParameter = null; + Action action = Action.valueOf(infraActiveRequest.getRequestAction()); + ModelInfo modelInfo = sir.getRequestDetails().getModelInfo(); + + Boolean isBaseVfModule = false; + if (requestHandlerUtils.getModelType(action, modelInfo).equals(ModelType.vfModule)) { + isBaseVfModule = requestHandlerUtils.getIsBaseVfModule(modelInfo, action, infraActiveRequest.getVnfType(), + msoRequest.getSDCServiceModelVersion(sir), currentActiveRequest); + } + + try { + requestClientParameter = + new RequestClientParameter.Builder().setRequestId(currentActiveRequest.getRequestId()) + .setBaseVfModule(isBaseVfModule).setRecipeTimeout(recipeLookupResult.getRecipeTimeout()) + .setRequestAction(infraActiveRequest.getRequestAction()) + .setServiceInstanceId(infraActiveRequest.getServiceInstanceId()) + .setPnfCorrelationId(pnfCorrelationId).setVnfId(infraActiveRequest.getVnfId()) + .setVfModuleId(infraActiveRequest.getVfModuleId()) + .setVolumeGroupId(infraActiveRequest.getVolumeGroupId()) + .setNetworkId(infraActiveRequest.getNetworkId()) + .setServiceType(infraActiveRequest.getServiceType()) + .setVnfType(infraActiveRequest.getVnfType()) + .setVfModuleType(msoRequest.getVfModuleType(sir, infraActiveRequest.getRequestScope(), + action, Integer.parseInt(version))) + .setNetworkType(infraActiveRequest.getNetworkType()) + .setRequestDetails(requestHandlerUtils + .mapJSONtoMSOStyle(infraActiveRequest.getRequestBody(), sir, aLaCarte, action)) + .setApiVersion(version).setALaCarte(aLaCarte) + .setRequestUri(currentActiveRequest.getRequestUrl()) + .setInstanceGroupId(infraActiveRequest.getInstanceGroupId()).build(); + } catch (IOException e) { + logger.error("IOException while generating requestClientParameter to send to BPMN", e); + ErrorLoggerInfo errorLoggerInfo = + new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, ErrorCode.SchemaError) + .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); + throw new ValidateException.Builder( + "IOException while generating requestClientParameter to send to BPMN: " + e.getMessage(), + HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_BAD_PARAMETER).errorInfo(errorLoggerInfo) + .build(); + } + return requestClientParameter; + } +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/ServiceInstances.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/ServiceInstances.java index 931a1eb52b..68fa6e4f56 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/ServiceInstances.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/ServiceInstances.java @@ -23,12 +23,24 @@ package org.onap.so.apihandlerinfra; -import com.fasterxml.jackson.core.JsonParseException; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.JsonMappingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import javax.transaction.Transactional; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.container.ContainerRequestContext; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; import org.apache.commons.lang.StringUtils; import org.apache.http.HttpStatus; import org.onap.so.apihandler.common.CommonConstants; @@ -74,24 +86,12 @@ import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; import org.springframework.stereotype.Component; -import javax.transaction.Transactional; -import javax.ws.rs.Consumes; -import javax.ws.rs.DELETE; -import javax.ws.rs.POST; -import javax.ws.rs.PUT; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.container.ContainerRequestContext; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; -import java.io.IOException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Optional; +import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; @Component @Path("/onap/so/infra/serviceInstantiation") @@ -765,8 +765,8 @@ public class ServiceInstances { ServiceInstancesRequest sir = null; String apiVersion = version.substring(1); - sir = requestHandlerUtils.convertJsonToServiceInstanceRequest(requestJSON, action, startTime, sir, msoRequest, - requestId, requestUri); + sir = requestHandlerUtils.convertJsonToServiceInstanceRequest(requestJSON, action, requestId, requestUri); + action = handleReplaceInstance(action, sir); String requestScope = requestHandlerUtils.deriveRequestScope(action, sir, requestUri); InfraActiveRequests currentActiveReq = msoRequest.createRequestObject(sir, action, requestId, Status.IN_PROGRESS, requestJSON, requestScope); @@ -797,16 +797,15 @@ public class ServiceInstances { InfraActiveRequests dup = null; boolean inProgress = false; - dup = requestHandlerUtils.duplicateCheck(action, instanceIdMap, startTime, msoRequest, instanceName, - requestScope, currentActiveReq); + dup = requestHandlerUtils.duplicateCheck(action, instanceIdMap, instanceName, requestScope, currentActiveReq); if (dup != null) { inProgress = requestHandlerUtils.camundaHistoryCheck(dup, currentActiveReq); } if (dup != null && inProgress) { - requestHandlerUtils.buildErrorOnDuplicateRecord(currentActiveReq, action, instanceIdMap, startTime, - msoRequest, instanceName, requestScope, dup); + requestHandlerUtils.buildErrorOnDuplicateRecord(currentActiveReq, action, instanceIdMap, instanceName, + requestScope, dup); } ServiceInstancesResponse serviceResponse = new ServiceInstancesResponse(); @@ -815,64 +814,20 @@ public class ServiceInstances { referencesResponse.setRequestId(requestId); serviceResponse.setRequestReferences(referencesResponse); - Boolean isBaseVfModule = false; - RecipeLookupResult recipeLookupResult = getServiceInstanceOrchestrationURI(sir, action, alaCarteFlag, currentActiveReq); String serviceInstanceType = requestHandlerUtils.getServiceType(requestScope, sir, alaCarteFlag); - ModelType modelType; - ModelInfo modelInfo = sir.getRequestDetails().getModelInfo(); - if (action == Action.applyUpdatedConfig || action == Action.inPlaceSoftwareUpdate) { - modelType = ModelType.vnf; - } else if (action == Action.addMembers || action == Action.removeMembers) { - modelType = ModelType.instanceGroup; - } else { - modelType = modelInfo.getModelType(); - } - if (modelType.equals(ModelType.vfModule)) { - - - // Get VF Module-specific base module indicator - VfModule vfm = null; - - String modelVersionId = modelInfo.getModelVersionId(); - - if (modelVersionId != null) { - vfm = catalogDbClient.getVfModuleByModelUUID(modelVersionId); - } else if (modelInfo.getModelInvariantId() != null && modelInfo.getModelVersion() != null) { - vfm = catalogDbClient.getVfModuleByModelInvariantUUIDAndModelVersion(modelInfo.getModelInvariantId(), - modelInfo.getModelVersion()); - } - - if (vfm != null) { - if (vfm.getIsBase()) { - isBaseVfModule = true; - } - } else if (action == Action.createInstance || action == Action.updateInstance) { - // There is no entry for this vfModuleType with this version, if specified, in VF_MODULE table in - // Catalog DB. - // This request cannot proceed - - String serviceVersionText = ""; - if (sdcServiceModelVersion != null && !sdcServiceModelVersion.isEmpty()) { - serviceVersionText = " with version " + sdcServiceModelVersion; - } + ModelInfo modelInfo = sir.getRequestDetails().getModelInfo(); + ModelType modelType = requestHandlerUtils.getModelType(action, modelInfo); - String errorMessage = "VnfType " + vnfType + " and VF Module Model Name " + modelInfo.getModelName() - + serviceVersionText + " not found in MSO Catalog DB"; - ErrorLoggerInfo errorLoggerInfo = - new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND, ErrorCode.DataError) - .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); - VfModuleNotFoundException vfModuleException = new VfModuleNotFoundException.Builder(errorMessage, - HttpStatus.SC_NOT_FOUND, ErrorNumbers.SVC_BAD_PARAMETER).errorInfo(errorLoggerInfo).build(); - requestHandlerUtils.updateStatus(currentActiveReq, Status.FAILED, vfModuleException.getMessage()); + Boolean isBaseVfModule = false; - throw vfModuleException; - } + if (modelType.equals(ModelType.vfModule)) { + isBaseVfModule = requestHandlerUtils.getIsBaseVfModule(modelInfo, action, vnfType, sdcServiceModelVersion, + currentActiveReq); } - serviceInstanceId = requestHandlerUtils.setServiceInstanceId(requestScope, sir); String vnfId = ""; String vfModuleId = ""; @@ -941,6 +896,20 @@ public class ServiceInstances { recipeLookupResult.getOrchestrationURI(), requestScope); } + /** + * @param action + * @param sir + * @return + */ + protected Actions handleReplaceInstance(Actions action, ServiceInstancesRequest sir) { + if (action != null && action.equals(Action.replaceInstance) + && sir.getRequestDetails().getRequestParameters().getRetainAssignments() != null + && sir.getRequestDetails().getRequestParameters().getRetainAssignments()) { + action = Action.replaceInstanceRetainAssignments; + } + return action; + } + public Response deleteInstanceGroups(Actions action, HashMap<String, String> instanceIdMap, String version, String requestId, String requestUri, ContainerRequestContext requestContext) throws ApiException { String instanceGroupId = instanceIdMap.get(CommonConstants.INSTANCE_GROUP_INSTANCE_ID); @@ -968,8 +937,8 @@ public class ServiceInstances { throw validateException; } - InfraActiveRequests dup = requestHandlerUtils.duplicateCheck(action, instanceIdMap, startTime, msoRequest, null, - requestScope, currentActiveReq); + InfraActiveRequests dup = + requestHandlerUtils.duplicateCheck(action, instanceIdMap, null, requestScope, currentActiveReq); boolean inProgress = false; if (dup != null) { @@ -977,8 +946,8 @@ public class ServiceInstances { } if (dup != null && inProgress) { - requestHandlerUtils.buildErrorOnDuplicateRecord(currentActiveReq, action, instanceIdMap, startTime, - msoRequest, null, requestScope, dup); + requestHandlerUtils.buildErrorOnDuplicateRecord(currentActiveReq, action, instanceIdMap, null, requestScope, + dup); } ServiceInstancesResponse serviceResponse = new ServiceInstancesResponse(); @@ -1011,13 +980,13 @@ public class ServiceInstances { recipeLookupResult.getOrchestrationURI(), requestScope); } - private String getPnfCorrelationId(ServiceInstancesRequest sir) { + protected String getPnfCorrelationId(ServiceInstancesRequest sir) { return Optional.of(sir).map(ServiceInstancesRequest::getRequestDetails) .map(RequestDetails::getRequestParameters).map(parameters -> parameters.getUserParamValue("pnfId")) .orElse(""); } - private RecipeLookupResult getServiceInstanceOrchestrationURI(ServiceInstancesRequest sir, Actions action, + protected RecipeLookupResult getServiceInstanceOrchestrationURI(ServiceInstancesRequest sir, Actions action, boolean alaCarteFlag, InfraActiveRequests currentActiveReq) throws ApiException { RecipeLookupResult recipeLookupResult = null; // if the aLaCarte flag is set to TRUE, the API-H should choose the VID_DEFAULT recipe for the requested action @@ -1103,8 +1072,8 @@ public class ServiceInstances { return recipeLookupResult; } - private RecipeLookupResult getServiceURI(ServiceInstancesRequest servInstReq, Actions action, boolean alaCarteFlag) - throws IOException { + protected RecipeLookupResult getServiceURI(ServiceInstancesRequest servInstReq, Actions action, + boolean alaCarteFlag) throws IOException { // SERVICE REQUEST // Construct the default service name // TODO need to make this a configurable property @@ -1598,8 +1567,7 @@ public class ServiceInstances { long startTime = System.currentTimeMillis(); ServiceInstancesRequest sir = null; - sir = requestHandlerUtils.convertJsonToServiceInstanceRequest(requestJSON, action, startTime, sir, msoRequest, - requestId, requestUri); + sir = requestHandlerUtils.convertJsonToServiceInstanceRequest(requestJSON, action, requestId, requestUri); String requestScope = requestHandlerUtils.deriveRequestScope(action, sir, requestUri); InfraActiveRequests currentActiveReq = msoRequest.createRequestObject(sir, action, requestId, Status.IN_PROGRESS, requestJSON, requestScope); @@ -1613,16 +1581,15 @@ public class ServiceInstances { InfraActiveRequests dup = null; - dup = requestHandlerUtils.duplicateCheck(action, instanceIdMap, startTime, msoRequest, instanceName, - requestScope, currentActiveReq); + dup = requestHandlerUtils.duplicateCheck(action, instanceIdMap, instanceName, requestScope, currentActiveReq); if (dup != null) { inProgress = requestHandlerUtils.camundaHistoryCheck(dup, currentActiveReq); } if (instanceIdMap != null && dup != null && inProgress) { - requestHandlerUtils.buildErrorOnDuplicateRecord(currentActiveReq, action, instanceIdMap, startTime, - msoRequest, instanceName, requestScope, dup); + requestHandlerUtils.buildErrorOnDuplicateRecord(currentActiveReq, action, instanceIdMap, instanceName, + requestScope, dup); } ServiceInstancesResponse serviceResponse = new ServiceInstancesResponse(); diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/E2ERequest.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/E2ERequest.java index 77abbbfa9a..6e77ce84a6 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/E2ERequest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/E2ERequest.java @@ -21,7 +21,7 @@ package org.onap.so.apihandlerinfra.e2eserviceinstancebeans; -import java.sql.Timestamp; + import com.fasterxml.jackson.databind.annotation.JsonSerialize; @JsonSerialize(include = JsonSerialize.Inclusion.NON_DEFAULT) diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/GetE2EServiceInstanceResponse.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/GetE2EServiceInstanceResponse.java index f7fa01aeb0..4fc6181bf8 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/GetE2EServiceInstanceResponse.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/GetE2EServiceInstanceResponse.java @@ -29,13 +29,7 @@ public class GetE2EServiceInstanceResponse { protected OperationStatus operation; - // public OperationStatus getOperationStatus() { - // return operation; - // } - // - // public void setOperationStatus(OperationStatus requestDB) { - // this.operation = requestDB; - // } + public OperationStatus getOperation() { return operation; diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/ResourceRequest.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/ResourceRequest.java index 44592ce2e4..ae462ebffa 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/ResourceRequest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/ResourceRequest.java @@ -39,6 +39,9 @@ public class ResourceRequest { @JsonProperty("resourceCustomizationUuid") private String resourceCustomizationUuid; + @JsonProperty("resourceIndex") + private String resourceIndex; + @JsonProperty("parameters") private E2EParameters parameters; @@ -98,4 +101,12 @@ public class ResourceRequest { public void setParameters(E2EParameters parameters) { this.parameters = parameters; } + + public String getResourceIndex() { + return resourceIndex; + } + + public void setResourceIndex(String resourceIndex) { + this.resourceIndex = resourceIndex; + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/CloudOrchestration.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/CloudOrchestration.java index d79d73c036..6f24bd4c4d 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/CloudOrchestration.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/CloudOrchestration.java @@ -38,6 +38,7 @@ import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; +import com.google.common.base.Strings; import org.apache.http.HttpStatus; import org.onap.so.apihandler.common.ErrorNumbers; import org.onap.so.apihandlerinfra.Constants; @@ -125,7 +126,7 @@ public class CloudOrchestration { private Response cloudOrchestration(String requestJSON, Action action, HashMap<String, String> instanceIdMap, String version, String requestId) throws ApiException { - logger.info("{} {}", MessageEnum.APIH_GENERATED_REQUEST_ID.toString(), requestId); + logger.info(Strings.repeat("{} ", 2), MessageEnum.APIH_GENERATED_REQUEST_ID.toString(), requestId); long startTime = System.currentTimeMillis(); CloudOrchestrationRequest cor = null; tenantIsolationRequest.setRequestId(requestId); diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/TenantIsolationRequest.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/TenantIsolationRequest.java index 696616099f..98c3f1f37f 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/TenantIsolationRequest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/TenantIsolationRequest.java @@ -28,6 +28,7 @@ import java.util.List; import java.util.Map; import java.util.Map.Entry; import javax.ws.rs.core.MultivaluedMap; +import com.google.common.base.Strings; import org.apache.commons.lang3.StringUtils; import org.onap.so.apihandlerinfra.Constants; import org.onap.so.apihandlerinfra.Status; @@ -356,7 +357,7 @@ public class TenantIsolationRequest { request.setLastModifiedBy(Constants.MODIFIED_BY_APIHANDLER); requestsDbClient.save(request); } catch (Exception e) { - logger.error("{} {} {} {}", MessageEnum.APIH_DB_UPDATE_EXC.toString(), e.getMessage(), + logger.error(Strings.repeat("{} ", 4), MessageEnum.APIH_DB_UPDATE_EXC.toString(), e.getMessage(), ErrorCode.DataError.getValue(), "Exception when updating record in DB"); logger.debug("Exception: ", e); } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/AAIClientHelper.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/AAIClientHelper.java index 8b3b91ae1a..6942d441e6 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/AAIClientHelper.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/AAIClientHelper.java @@ -34,15 +34,13 @@ import org.onap.so.client.aai.entities.AAIResultWrapper; import org.onap.so.client.aai.entities.uri.AAIResourceUri; import org.onap.so.client.aai.entities.uri.AAIUriFactory; import org.onap.so.client.graphinventory.entities.uri.Depth; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; @Component public class AAIClientHelper { - private static Logger logger = LoggerFactory.getLogger(AAIClientHelper.class); + /** * Get managing ECOMP Environment Info from A&AI @@ -63,7 +61,7 @@ public class AAIClientHelper { * Update managing ECOMP Environment Info from A&AI * * @param id = operationalEnvironmentId - * @param AAIOperationalEnvironment object + * @param aaiRequest object */ public void updateAaiOperationalEnvironment(String id, OperationalEnvironment aaiRequest) { @@ -75,7 +73,7 @@ public class AAIClientHelper { public void updateAaiOperationalEnvironment(String operationalEnvironmentId, Map<String, String> payload) - throws Exception { + throws AAIClientCallFailed { try { AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.OPERATIONAL_ENVIRONMENT, operationalEnvironmentId); @@ -90,7 +88,7 @@ public class AAIClientHelper { /** * Create an Operational Environment object in A&AI * - * @param AAIOperationalEnvironment object + * @param operationalEnvironment object */ public void createOperationalEnvironment(OperationalEnvironment operationalEnvironment) { diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/ActivateVnfDBHelper.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/ActivateVnfDBHelper.java index 98b49d39d7..1e5958c540 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/ActivateVnfDBHelper.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/ActivateVnfDBHelper.java @@ -31,7 +31,7 @@ import org.springframework.stereotype.Component; @Component public class ActivateVnfDBHelper { - private static Logger logger = LoggerFactory.getLogger(ActivateVnfDBHelper.class); + /** * Insert record to OperationalEnvServiceModelStatus table diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/Manifest.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/Manifest.java index 4c66a3118e..c50f18c594 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/Manifest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/Manifest.java @@ -34,7 +34,7 @@ public class Manifest implements Serializable { private static final long serialVersionUID = -3460949513229380541L; @JsonProperty("serviceModelList") - private List<ServiceModelList> serviceModelList = new ArrayList<ServiceModelList>(); + private List<ServiceModelList> serviceModelList = new ArrayList<>(); public List<ServiceModelList> getServiceModelList() { return serviceModelList; diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/InstanceIdMapValidation.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/InstanceIdMapValidation.java index 907bc942eb..2cf01f9390 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/InstanceIdMapValidation.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/InstanceIdMapValidation.java @@ -29,51 +29,59 @@ import org.onap.so.utils.UUIDChecker; public class InstanceIdMapValidation implements ValidationRule { + private static final String Service_InstanceId = "serviceInstanceId"; + private static final String Vnf_InstanceId = "vnfInstanceId"; + private static final String vfModule_InstanceId = "vfModuleInstanceId"; + + private static final String volume_Group_InstanceId = "volumeGroupInstanceId"; + private static final String Network_Instance_Id = "networkInstanceId"; + private static final String Configuration_Instance_Id = "configurationInstanceId"; + @Override public ValidationInformation validate(ValidationInformation info) throws ValidationException { HashMap<String, String> instanceIdMap = info.getInstanceIdMap(); ServiceInstancesRequest sir = info.getSir(); if (instanceIdMap != null) { - if (instanceIdMap.get("serviceInstanceId") != null) { - if (!UUIDChecker.isValidUUID(instanceIdMap.get("serviceInstanceId"))) { - throw new ValidationException("serviceInstanceId"); + if (instanceIdMap.get(Service_InstanceId) != null) { + if (!UUIDChecker.isValidUUID(instanceIdMap.get(Service_InstanceId))) { + throw new ValidationException(Service_InstanceId); } - sir.setServiceInstanceId(instanceIdMap.get("serviceInstanceId")); + sir.setServiceInstanceId(instanceIdMap.get(Service_InstanceId)); } - if (instanceIdMap.get("vnfInstanceId") != null) { - if (!UUIDChecker.isValidUUID(instanceIdMap.get("vnfInstanceId"))) { - throw new ValidationException("vnfInstanceId"); + if (instanceIdMap.get(Vnf_InstanceId) != null) { + if (!UUIDChecker.isValidUUID(instanceIdMap.get(Vnf_InstanceId))) { + throw new ValidationException(Vnf_InstanceId); } - sir.setVnfInstanceId(instanceIdMap.get("vnfInstanceId")); + sir.setVnfInstanceId(instanceIdMap.get(Vnf_InstanceId)); } - if (instanceIdMap.get("vfModuleInstanceId") != null) { - if (!UUIDChecker.isValidUUID(instanceIdMap.get("vfModuleInstanceId"))) { - throw new ValidationException("vfModuleInstanceId"); + if (instanceIdMap.get(vfModule_InstanceId) != null) { + if (!UUIDChecker.isValidUUID(instanceIdMap.get(vfModule_InstanceId))) { + throw new ValidationException(vfModule_InstanceId); } - sir.setVfModuleInstanceId(instanceIdMap.get("vfModuleInstanceId")); + sir.setVfModuleInstanceId(instanceIdMap.get(vfModule_InstanceId)); } - if (instanceIdMap.get("volumeGroupInstanceId") != null) { - if (!UUIDChecker.isValidUUID(instanceIdMap.get("volumeGroupInstanceId"))) { - throw new ValidationException("volumeGroupInstanceId"); + if (instanceIdMap.get(volume_Group_InstanceId) != null) { + if (!UUIDChecker.isValidUUID(instanceIdMap.get(volume_Group_InstanceId))) { + throw new ValidationException(volume_Group_InstanceId); } - sir.setVolumeGroupInstanceId(instanceIdMap.get("volumeGroupInstanceId")); + sir.setVolumeGroupInstanceId(instanceIdMap.get(volume_Group_InstanceId)); } - if (instanceIdMap.get("networkInstanceId") != null) { - if (!UUIDChecker.isValidUUID(instanceIdMap.get("networkInstanceId"))) { - throw new ValidationException("networkInstanceId"); + if (instanceIdMap.get(Network_Instance_Id) != null) { + if (!UUIDChecker.isValidUUID(instanceIdMap.get(Network_Instance_Id))) { + throw new ValidationException(Network_Instance_Id); } - sir.setNetworkInstanceId(instanceIdMap.get("networkInstanceId")); + sir.setNetworkInstanceId(instanceIdMap.get(Network_Instance_Id)); } - if (instanceIdMap.get("configurationInstanceId") != null) { - if (!UUIDChecker.isValidUUID(instanceIdMap.get("configurationInstanceId"))) { - throw new ValidationException("configurationInstanceId"); + if (instanceIdMap.get(Configuration_Instance_Id) != null) { + if (!UUIDChecker.isValidUUID(instanceIdMap.get(Configuration_Instance_Id))) { + throw new ValidationException(Configuration_Instance_Id); } - sir.setConfigurationId(instanceIdMap.get("configurationInstanceId")); + sir.setConfigurationId(instanceIdMap.get(Configuration_Instance_Id)); } if (instanceIdMap.get(CommonConstants.INSTANCE_GROUP_INSTANCE_ID) != null) { diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/ObjectFactory.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/ObjectFactory.java index 2236b09f2a..7a0a6fe633 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/ObjectFactory.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/ObjectFactory.java @@ -49,8 +49,7 @@ import javax.xml.namespace.QName; public class ObjectFactory { private final static QName _VnfParams_QNAME = new QName("http://org.onap/so/infra/vnf-request/v1", "vnf-params"); - private final static QName _NetworkParams_QNAME = - new QName("http://org.onap/so/infra/vnf-request/v1", "network-params"); + /** * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/OrchestrationRequestsTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/OrchestrationRequestsTest.java index 321ea3ac7d..f82f5ac746 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/OrchestrationRequestsTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/OrchestrationRequestsTest.java @@ -42,12 +42,12 @@ import java.util.Map; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.apache.http.HttpStatus; -import org.junit.Ignore; import org.junit.Test; import org.onap.so.apihandler.common.ErrorNumbers; 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.serviceinstancebeans.CloudRequestData; import org.onap.so.serviceinstancebeans.GetOrchestrationListResponse; import org.onap.so.serviceinstancebeans.GetOrchestrationResponse; import org.onap.so.serviceinstancebeans.Request; @@ -119,7 +119,7 @@ public class OrchestrationRequestsTest extends BaseTest { assertEquals("0", response.getHeaders().get("X-MinorVersion").get(0)); assertEquals("0", response.getHeaders().get("X-PatchVersion").get(0)); assertEquals("7.0.0", response.getHeaders().get("X-LatestVersion").get(0)); - assertEquals("00032ab7-na18-42e5-965d-8ea592502018", response.getHeaders().get("X-TransactionID").get(0)); + assertEquals("00032ab7-1a18-42e5-965d-8ea592502018", response.getHeaders().get("X-TransactionID").get(0)); assertNotNull(response.getBody().getRequest().getFinishTime()); } @@ -149,12 +149,22 @@ public class OrchestrationRequestsTest extends BaseTest { } @Test - public void testGetOrchestrationRequestRequestDetails() throws Exception { - setupTestGetOrchestrationRequestRequestDetails("00032ab7-3fb3-42e5-965d-8ea592502017", "COMPLETED"); + public void testGetOrchestrationRequestWithOpenstackDetails() throws Exception { + setupTestGetOrchestrationRequestOpenstackDetails("00032ab7-3fb3-42e5-965d-8ea592502017", "COMPLETED"); // Test request with modelInfo request body GetOrchestrationResponse testResponse = new GetOrchestrationResponse(); Request request = ORCHESTRATION_LIST.getRequestList().get(0).getRequest(); + List<CloudRequestData> cloudRequestData = new ArrayList<>(); + CloudRequestData cloudData = new CloudRequestData(); + cloudData.setCloudIdentifier("heatstackName/123123"); + ObjectMapper mapper = new ObjectMapper(); + Object reqData = mapper.readValue( + "{\r\n \"test\": \"00032ab7-3fb3-42e5-965d-8ea592502016\",\r\n \"test2\": \"deleteInstance\",\r\n \"test3\": \"COMPLETE\",\r\n \"test4\": \"Vf Module has been deleted successfully.\",\r\n \"test5\": 100\r\n}", + Object.class); + cloudData.setCloudRequest(reqData); + cloudRequestData.add(cloudData); + request.setCloudRequestData(cloudRequestData); testResponse.setRequest(request); String testRequestId = request.getRequestId(); @@ -163,13 +173,14 @@ public class OrchestrationRequestsTest extends BaseTest { headers.set("Content-Type", MediaType.APPLICATION_JSON); HttpEntity<Request> entity = new HttpEntity<Request>(null, headers); - UriComponentsBuilder builder = UriComponentsBuilder - .fromHttpUrl(createURLWithPort("/onap/so/infra/orchestrationRequests/v7/" + testRequestId)); + UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort( + "/onap/so/infra/orchestrationRequests/v7/" + testRequestId + "?includeCloudRequest=true")); ResponseEntity<GetOrchestrationResponse> response = restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, GetOrchestrationResponse.class); - + System.out.println("Response :" + response.getBody().toString()); assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value()); + assertThat(response.getBody(), sameBeanAs(testResponse).ignoring("request.startTime") .ignoring("request.finishTime").ignoring("request.requestStatus.timeStamp")); assertEquals("application/json", response.getHeaders().get(HttpHeaders.CONTENT_TYPE).get(0)); @@ -194,6 +205,29 @@ public class OrchestrationRequestsTest extends BaseTest { } @Test + public void testGetOrchestrationRequestInvalidRequestID() throws Exception { + setupTestGetOrchestrationRequest(); + // TEST INVALID REQUESTID + GetOrchestrationResponse testResponse = new GetOrchestrationResponse(); + + Request request = ORCHESTRATION_LIST.getRequestList().get(1).getRequest(); + testResponse.setRequest(request); + String testRequestId = "00032ab7-pfb3-42e5-965d-8ea592502016"; + HttpHeaders headers = new HttpHeaders(); + headers.set("Accept", MediaType.APPLICATION_JSON); + headers.set("Content-Type", MediaType.APPLICATION_JSON); + HttpEntity<Request> entity = new HttpEntity<Request>(null, headers); + + UriComponentsBuilder builder = UriComponentsBuilder + .fromHttpUrl(createURLWithPort("/onap/so/infra/orchestrationRequests/v7/" + testRequestId)); + + ResponseEntity<GetOrchestrationResponse> response = + restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, GetOrchestrationResponse.class); + + assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value()); + } + + @Test public void testGetOrchestrationRequestFilter() throws Exception { setupTestGetOrchestrationRequestFilter(); List<String> values = new ArrayList<>(); @@ -319,75 +353,11 @@ public class OrchestrationRequestsTest extends BaseTest { "/onap/so/infra/orchestrationRequests/v7/" + "5ffbabd6-b793-4377-a1ab-082670fbc7ac" + "/unlock")); response = restTemplate.exchange(builder.toUriString(), HttpMethod.POST, entity, String.class); - // Cannot assert anything further here, already have a wiremock in place which ensures that the post was + // Cannot assert anything further here, already have a wiremock in place + // which ensures that the post was // properly called to update. } - @Ignore // What is this testing? - @Test - public void testGetOrchestrationRequestRequestDetailsWhiteSpace() throws Exception { - InfraActiveRequests requests = new InfraActiveRequests(); - requests.setAction("create"); - requests.setRequestBody(" "); - requests.setRequestId("requestId"); - requests.setRequestScope("service"); - requests.setRequestType("createInstance"); - ObjectMapper mapper = new ObjectMapper(); - String json = mapper.writeValueAsString(requests); - - requestsDbClient.save(requests); - HttpHeaders headers = new HttpHeaders(); - headers.set("Accept", MediaType.APPLICATION_JSON); - headers.set("Content-Type", MediaType.APPLICATION_JSON); - HttpEntity<Request> entity = new HttpEntity<Request>(null, headers); - - UriComponentsBuilder builder = UriComponentsBuilder - .fromHttpUrl(createURLWithPort("/onap/so/infra/orchestrationRequests/v7/requestId")); - - ResponseEntity<GetOrchestrationResponse> response = - restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, GetOrchestrationResponse.class); - - assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value()); - assertEquals("application/json", response.getHeaders().get(HttpHeaders.CONTENT_TYPE).get(0)); - assertEquals("0", response.getHeaders().get("X-MinorVersion").get(0)); - assertEquals("0", response.getHeaders().get("X-PatchVersion").get(0)); - assertEquals("7.0.0", response.getHeaders().get("X-LatestVersion").get(0)); - assertEquals("requestId", response.getHeaders().get("X-TransactionID").get(0)); - } - - @Ignore // What is this testing? - @Test - public void testGetOrchestrationRequestRequestDetailsAlaCarte() throws IOException { - InfraActiveRequests requests = new InfraActiveRequests(); - - String requestJSON = new String( - Files.readAllBytes(Paths.get("src/test/resources/OrchestrationRequest/AlaCarteRequest.json"))); - - requests.setAction("create"); - requests.setRequestBody(requestJSON); - requests.setRequestId("requestId"); - requests.setRequestScope("service"); - requests.setRequestType("createInstance"); - // iar.save(requests); - HttpHeaders headers = new HttpHeaders(); - headers.set("Accept", MediaType.APPLICATION_JSON); - headers.set("Content-Type", MediaType.APPLICATION_JSON); - HttpEntity<Request> entity = new HttpEntity<Request>(null, headers); - - UriComponentsBuilder builder = UriComponentsBuilder - .fromHttpUrl(createURLWithPort("/onap/so/infra/orchestrationRequests/v7/requestId")); - - ResponseEntity<GetOrchestrationResponse> response = - restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, GetOrchestrationResponse.class); - - assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value()); - assertEquals("application/json", response.getHeaders().get(HttpHeaders.CONTENT_TYPE).get(0)); - assertEquals("0", response.getHeaders().get("X-MinorVersion").get(0)); - assertEquals("0", response.getHeaders().get("X-PatchVersion").get(0)); - assertEquals("7.0.0", response.getHeaders().get("X-LatestVersion").get(0)); - assertEquals("requestId", response.getHeaders().get("X-TransactionID").get(0)); - } - @Test public void mapRequestProcessingDataTest() throws JsonParseException, JsonMappingException, IOException { RequestProcessingData entry = new RequestProcessingData(); @@ -423,14 +393,14 @@ public class OrchestrationRequestsTest extends BaseTest { public void setupTestGetOrchestrationRequest() throws Exception { // For testGetOrchestrationRequest - wireMockServer.stubFor(any(urlPathEqualTo("/infraActiveRequests/00032ab7-na18-42e5-965d-8ea592502018")) + wireMockServer.stubFor(any(urlPathEqualTo("/infraActiveRequests/00032ab7-1a18-42e5-965d-8ea592502018")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBody(new String(Files.readAllBytes( Paths.get("src/test/resources/OrchestrationRequest/getOrchestrationRequest.json")))) .withStatus(HttpStatus.SC_OK))); wireMockServer .stubFor(get(urlPathEqualTo("/requestProcessingData/search/findBySoRequestIdOrderByGroupingIdDesc/")) - .withQueryParam("SO_REQUEST_ID", equalTo("00032ab7-na18-42e5-965d-8ea592502018")) + .withQueryParam("SO_REQUEST_ID", equalTo("00032ab7-1a18-42e5-965d-8ea592502018")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBody(new String(Files.readAllBytes(Paths .get("src/test/resources/OrchestrationRequest/getRequestProcessingData.json")))) @@ -439,14 +409,14 @@ public class OrchestrationRequestsTest extends BaseTest { public void setupTestGetOrchestrationRequestInstanceGroup() throws Exception { // For testGetOrchestrationRequest - wireMockServer.stubFor(any(urlPathEqualTo("/infraActiveRequests/00032ab7-na18-42e5-965d-8ea592502018")) + wireMockServer.stubFor(any(urlPathEqualTo("/infraActiveRequests/00032ab7-1a18-42e5-965d-8ea592502018")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBody(new String(Files.readAllBytes(Paths.get( "src/test/resources/OrchestrationRequest/getOrchestrationRequestInstanceGroup.json")))) .withStatus(HttpStatus.SC_OK))); wireMockServer .stubFor(get(urlPathEqualTo("/requestProcessingData/search/findBySoRequestIdOrderByGroupingIdDesc/")) - .withQueryParam("SO_REQUEST_ID", equalTo("00032ab7-na18-42e5-965d-8ea592502018")) + .withQueryParam("SO_REQUEST_ID", equalTo("00032ab7-1a18-42e5-965d-8ea592502018")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBody(new String(Files.readAllBytes(Paths .get("src/test/resources/OrchestrationRequest/getRequestProcessingData.json")))) @@ -461,15 +431,20 @@ public class OrchestrationRequestsTest extends BaseTest { .withStatus(HttpStatus.SC_OK))); } + private void setupTestGetOrchestrationRequestOpenstackDetails(String requestId, String status) throws Exception { + wireMockServer.stubFor(get(urlPathEqualTo(getTestUrl(requestId))).willReturn(aResponse() + .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(new String(Files.readAllBytes(Paths + .get("src/test/resources/OrchestrationRequest/getOrchestrationOpenstackRequestDetails.json")))) + .withStatus(HttpStatus.SC_OK))); + } + private void setupTestUnlockOrchestrationRequest(String requestId, String status) { wireMockServer.stubFor(get(urlPathEqualTo(getTestUrl(requestId))) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBody(String.format(getResponseTemplate, requestId, status)).withStatus(HttpStatus.SC_OK))); - } - - private void setupTestUnlockOrchestrationRequest_invalid_Json() { wireMockServer.stubFor(get(urlPathEqualTo(getTestUrl(INVALID_REQUEST_ID))).willReturn(aResponse() .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON).withStatus(HttpStatus.SC_NOT_FOUND))); diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/OrchestrationRequestsUnitTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/OrchestrationRequestsUnitTest.java new file mode 100644 index 0000000000..19b9d7ea1e --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/OrchestrationRequestsUnitTest.java @@ -0,0 +1,90 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 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.so.apihandlerinfra; + +import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs; +import static org.junit.Assert.assertThat; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Spy; +import org.mockito.junit.MockitoJUnitRunner; +import org.onap.so.apihandlerinfra.exceptions.ApiException; +import org.onap.so.db.request.beans.InfraActiveRequests; +import org.onap.so.serviceinstancebeans.InstanceReferences; +import org.onap.so.serviceinstancebeans.Request; +import org.onap.so.serviceinstancebeans.RequestStatus; + +@RunWith(MockitoJUnitRunner.class) +public class OrchestrationRequestsUnitTest { + + @Spy + private OrchestrationRequests orchestrationRequests; + + private static final String REQUEST_ID = "7cb9aa56-dd31-41e5-828e-d93027d4ebba"; + private static final String SERVICE_INSTANCE_ID = "7cb9aa56-dd31-41e5-828e-d93027d4ebbb"; + private static final String ORIGINAL_REQUEST_ID = "8f2d38a6-7c20-465a-bd7e-075645f1394b"; + private static final String SERVICE = "service"; + private InfraActiveRequests iar; + boolean includeCloudRequest = false; + + @Before + public void setup() { + iar = new InfraActiveRequests(); + iar.setRequestScope(SERVICE); + iar.setRequestId(REQUEST_ID); + iar.setServiceInstanceId(SERVICE_INSTANCE_ID); + } + + @Test + public void mapInfraActiveRequestToRequestWithOriginalRequestIdTest() throws ApiException { + InstanceReferences instanceReferences = new InstanceReferences(); + instanceReferences.setServiceInstanceId(SERVICE_INSTANCE_ID); + RequestStatus requestStatus = new RequestStatus(); + Request expected = new Request(); + expected.setRequestId(REQUEST_ID); + expected.setOriginalRequestId(ORIGINAL_REQUEST_ID); + expected.setInstanceReferences(instanceReferences); + expected.setRequestStatus(requestStatus); + expected.setRequestScope(SERVICE); + + iar.setOriginalRequestId(ORIGINAL_REQUEST_ID); + + Request result = orchestrationRequests.mapInfraActiveRequestToRequest(iar, includeCloudRequest); + assertThat(result, sameBeanAs(expected)); + } + + @Test + public void mapInfraActiveRequestToRequestOriginalRequestIdNullTest() throws ApiException { + InstanceReferences instanceReferences = new InstanceReferences(); + instanceReferences.setServiceInstanceId(SERVICE_INSTANCE_ID); + RequestStatus requestStatus = new RequestStatus(); + Request expected = new Request(); + expected.setRequestId(REQUEST_ID); + expected.setInstanceReferences(instanceReferences); + expected.setRequestStatus(requestStatus); + expected.setRequestScope(SERVICE); + + Request result = orchestrationRequests.mapInfraActiveRequestToRequest(iar, includeCloudRequest); + assertThat(result, sameBeanAs(expected)); + } + +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/RequestHandlerUtilsUnitTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/RequestHandlerUtilsUnitTest.java new file mode 100644 index 0000000000..e92417728c --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/RequestHandlerUtilsUnitTest.java @@ -0,0 +1,399 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 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.so.apihandlerinfra; + +import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThat; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.doReturn; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.sql.Timestamp; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Spy; +import org.mockito.junit.MockitoJUnitRunner; +import org.onap.so.apihandlerinfra.exceptions.ApiException; +import org.onap.so.apihandlerinfra.exceptions.VfModuleNotFoundException; +import org.onap.so.db.catalog.beans.VfModule; +import org.onap.so.db.catalog.client.CatalogDbClient; +import org.onap.so.db.request.beans.InfraActiveRequests; +import org.onap.so.serviceinstancebeans.ModelInfo; +import org.onap.so.serviceinstancebeans.ModelType; + +@RunWith(MockitoJUnitRunner.class) +public class RequestHandlerUtilsUnitTest { + + @Mock + private CatalogDbClient catDbClient; + + @InjectMocks + @Spy + private RequestHandlerUtils requestHandler; + + @Rule + public ExpectedException thrown = ExpectedException.none(); + + private static final String CURRENT_REQUEST_ID = "eca3a1b1-43ab-457e-ab1c-367263d148b4"; + private static final String RESUMED_REQUEST_ID = "59c7247f-839f-4923-90c3-05faa3ab354d"; + private static final String SERVICE_INSTANCE_ID = "00032ab7-na18-42e5-965d-8ea592502018"; + private static final String SERVICE_INSTANCE_NAME = "serviceInstanceName"; + private static final String VNF_ID = "00032ab7-na18-42e5-965d-8ea592502017"; + private static final String VFMODULE_ID = "00032ab7-na18-42e5-965d-8ea592502016"; + private static final String NETWORK_ID = "00032ab7-na18-42e5-965d-8ea592502015"; + private static final String VOLUME_GROUP_ID = "00032ab7-na18-42e5-965d-8ea592502014"; + private static final String VNF_NAME = "vnfName"; + private static final String VFMODULE_NAME = "vfModuleName"; + private static final String NETWORK_NAME = "networkName"; + private static final String VOLUME_GROUP_NAME = "volumeGroupName"; + private static final String MODEL_VERSION_ID = "883f4a7a-b5a5-44e0-8738-361c6413d24c"; + private static final String MODEL_VERSION = "1.0"; + private static final String MODEL_INVARIANT_ID = "d358b828-e7f8-4833-ac96-2782bed1a9a9"; + private static final String MODEL_NAME = "modelName"; + private final Timestamp startTimeStamp = new Timestamp(System.currentTimeMillis()); + private String requestUri = + "http:localhost:6746/onap/so/infra/orchestrationRequests/v7/00032ab7-na18-42e5-965d-8ea592502019/resume"; + private InfraActiveRequests infraActiveRequest = new InfraActiveRequests(); + private InfraActiveRequests currentActiveRequest = new InfraActiveRequests(); + private InfraActiveRequests currentActiveRequestIARNull = new InfraActiveRequests(); + private Action action = Action.createInstance; + private String vnfType = "vnfType"; + private String sdcServiceModelVersion = "7"; + + public String getRequestBody(String request) throws IOException { + request = "src/test/resources/ResumeOrchestrationRequest" + request; + return new String(Files.readAllBytes(Paths.get(request))); + } + + @Before + public void setup() throws IOException { + setInfraActiveRequest(); + setCurrentActiveRequest(); + setCurrentActiveRequestNullInfraActive(); + } + + private void setInfraActiveRequest() throws IOException { + infraActiveRequest.setTenantId("tenant-id"); + infraActiveRequest.setRequestBody(getRequestBody("/RequestBody.json")); + infraActiveRequest.setAicCloudRegion("cloudRegion"); + infraActiveRequest.setRequestScope("service"); + infraActiveRequest.setServiceInstanceId(SERVICE_INSTANCE_ID); + infraActiveRequest.setServiceInstanceName(SERVICE_INSTANCE_NAME); + infraActiveRequest.setRequestStatus(Status.IN_PROGRESS.toString()); + infraActiveRequest.setRequestAction(Action.createInstance.toString()); + infraActiveRequest.setServiceType("serviceType"); + } + + private void setCurrentActiveRequest() throws IOException { + currentActiveRequest.setRequestId(CURRENT_REQUEST_ID); + currentActiveRequest.setSource("VID"); + currentActiveRequest.setStartTime(startTimeStamp); + currentActiveRequest.setTenantId("tenant-id"); + currentActiveRequest.setRequestBody(getRequestBody("/RequestBody.json")); + currentActiveRequest.setAicCloudRegion("cloudRegion"); + currentActiveRequest.setRequestScope("service"); + currentActiveRequest.setRequestStatus(Status.IN_PROGRESS.toString()); + currentActiveRequest.setLastModifiedBy(Constants.MODIFIED_BY_APIHANDLER); + currentActiveRequest.setRequestAction(Action.createInstance.toString()); + currentActiveRequest.setRequestUrl(requestUri); + currentActiveRequest.setRequestorId("xxxxxx"); + currentActiveRequest.setProgress(new Long(5)); + currentActiveRequest.setOriginalRequestId(RESUMED_REQUEST_ID); + } + + private void setCurrentActiveRequestNullInfraActive() throws IOException { + currentActiveRequestIARNull.setRequestId(CURRENT_REQUEST_ID); + currentActiveRequestIARNull.setSource("VID"); + currentActiveRequestIARNull.setStartTime(startTimeStamp); + currentActiveRequestIARNull.setRequestStatus(Status.IN_PROGRESS.toString()); + currentActiveRequestIARNull.setLastModifiedBy(Constants.MODIFIED_BY_APIHANDLER); + currentActiveRequestIARNull.setRequestUrl(requestUri); + currentActiveRequestIARNull.setRequestorId("xxxxxx"); + currentActiveRequestIARNull.setProgress(new Long(5)); + currentActiveRequestIARNull.setOriginalRequestId(RESUMED_REQUEST_ID); + } + + + @Test + public void createNewRecordCopyFromInfraActiveRequestTest() { + doNothing().when(requestHandler).setInstanceIdAndName(infraActiveRequest, currentActiveRequest); + InfraActiveRequests result = requestHandler.createNewRecordCopyFromInfraActiveRequest(infraActiveRequest, + CURRENT_REQUEST_ID, startTimeStamp, "VID", requestUri, "xxxxxx", RESUMED_REQUEST_ID); + assertThat(currentActiveRequest, sameBeanAs(result)); + } + + @Test + public void createNewRecordCopyFromInfraActiveRequestNullIARTest() { + InfraActiveRequests result = requestHandler.createNewRecordCopyFromInfraActiveRequest(null, CURRENT_REQUEST_ID, + startTimeStamp, "VID", requestUri, "xxxxxx", RESUMED_REQUEST_ID); + assertThat(currentActiveRequestIARNull, sameBeanAs(result)); + } + + @Test + public void setInstanceIdAndNameServiceTest() { + InfraActiveRequests serviceRequest = new InfraActiveRequests(); + + InfraActiveRequests expected = new InfraActiveRequests(); + expected.setServiceInstanceId(SERVICE_INSTANCE_ID); + expected.setServiceInstanceName(SERVICE_INSTANCE_NAME); + + requestHandler.setInstanceIdAndName(infraActiveRequest, serviceRequest); + assertThat(serviceRequest, sameBeanAs(expected)); + } + + @Test + public void setInstanceIdAndNameRequestScopeNotValidTest() { + InfraActiveRequests originalServiceRequest = new InfraActiveRequests(); + originalServiceRequest.setRequestScope("test"); + InfraActiveRequests serviceRequest = new InfraActiveRequests(); + + InfraActiveRequests expected = new InfraActiveRequests(); + + requestHandler.setInstanceIdAndName(originalServiceRequest, serviceRequest); + assertThat(serviceRequest, sameBeanAs(expected)); + } + + @Test + public void setInstanceIdAndNameVnfTest() { + InfraActiveRequests vnfRequestOriginal = new InfraActiveRequests(); + vnfRequestOriginal.setRequestScope("vnf"); + vnfRequestOriginal.setVnfId(VNF_ID); + vnfRequestOriginal.setVnfName(VNF_NAME); + InfraActiveRequests vnfRequest = new InfraActiveRequests(); + + InfraActiveRequests expected = new InfraActiveRequests(); + expected.setVnfId(VNF_ID); + expected.setVnfName(VNF_NAME); + + requestHandler.setInstanceIdAndName(vnfRequestOriginal, vnfRequest); + assertThat(vnfRequest, sameBeanAs(expected)); + } + + @Test + public void setInstanceIdAndNameVfModuleTest() { + InfraActiveRequests vfModuleRequestOriginal = new InfraActiveRequests(); + vfModuleRequestOriginal.setRequestScope("vfModule"); + vfModuleRequestOriginal.setVfModuleId(VFMODULE_ID); + vfModuleRequestOriginal.setVfModuleName(VFMODULE_NAME); + InfraActiveRequests vfModuleRequest = new InfraActiveRequests(); + + InfraActiveRequests expected = new InfraActiveRequests(); + expected.setVfModuleId(VFMODULE_ID); + expected.setVfModuleName(VFMODULE_NAME); + + requestHandler.setInstanceIdAndName(vfModuleRequestOriginal, vfModuleRequest); + assertThat(vfModuleRequest, sameBeanAs(expected)); + } + + @Test + public void setInstanceIdAndNameNetworkTest() { + InfraActiveRequests networkRequestOriginal = new InfraActiveRequests(); + networkRequestOriginal.setRequestScope("network"); + networkRequestOriginal.setNetworkId(NETWORK_ID); + networkRequestOriginal.setNetworkName(NETWORK_NAME); + InfraActiveRequests networkRequest = new InfraActiveRequests(); + + InfraActiveRequests expected = new InfraActiveRequests(); + expected.setNetworkId(NETWORK_ID); + expected.setNetworkName(NETWORK_NAME); + + requestHandler.setInstanceIdAndName(networkRequestOriginal, networkRequest); + assertThat(networkRequest, sameBeanAs(expected)); + } + + @Test + public void setInstanceIdAndNameVolumeGroupTest() { + InfraActiveRequests volumeGroupRequestOriginal = new InfraActiveRequests(); + volumeGroupRequestOriginal.setRequestScope("volumeGroup"); + volumeGroupRequestOriginal.setVolumeGroupId(VOLUME_GROUP_ID); + volumeGroupRequestOriginal.setVolumeGroupName(VOLUME_GROUP_NAME); + InfraActiveRequests volumeGroupRequest = new InfraActiveRequests(); + + InfraActiveRequests expected = new InfraActiveRequests(); + expected.setVolumeGroupId(VOLUME_GROUP_ID); + expected.setVolumeGroupName(VOLUME_GROUP_NAME); + + requestHandler.setInstanceIdAndName(volumeGroupRequestOriginal, volumeGroupRequest); + assertThat(volumeGroupRequest, sameBeanAs(expected)); + } + + @Test + public void getIsBaseVfModuleTrueTest() throws ApiException { + VfModule vfModule = new VfModule(); + vfModule.setIsBase(true); + ModelInfo modelInfo = new ModelInfo(); + modelInfo.setModelVersionId(MODEL_VERSION_ID); + + doReturn(vfModule).when(catDbClient).getVfModuleByModelUUID(MODEL_VERSION_ID); + Boolean expected = true; + + Boolean result = requestHandler.getIsBaseVfModule(modelInfo, action, vnfType, sdcServiceModelVersion, + currentActiveRequest); + assertEquals(result, expected); + } + + @Test + public void getIsBaseVfModuleFalseTest() throws ApiException { + VfModule vfModule = new VfModule(); + vfModule.setIsBase(false); + ModelInfo modelInfo = new ModelInfo(); + modelInfo.setModelVersionId(MODEL_VERSION_ID); + + doReturn(vfModule).when(catDbClient).getVfModuleByModelUUID(MODEL_VERSION_ID); + Boolean expected = false; + + Boolean result = requestHandler.getIsBaseVfModule(modelInfo, action, vnfType, sdcServiceModelVersion, + currentActiveRequest); + assertEquals(result, expected); + } + + @Test + public void getIsBaseVfModuleNullTest() throws ApiException { + ModelInfo modelInfo = new ModelInfo(); + modelInfo.setModelVersionId(MODEL_VERSION_ID); + modelInfo.setModelName(MODEL_NAME); + String errorMessage = + "VnfType vnfType and VF Module Model Name modelName with version 7 not found in MSO Catalog DB"; + + doNothing().when(requestHandler).updateStatus(currentActiveRequest, Status.FAILED, errorMessage); + doReturn(null).when(catDbClient).getVfModuleByModelUUID(MODEL_VERSION_ID); + + thrown.expect(VfModuleNotFoundException.class); + thrown.expectMessage(errorMessage); + requestHandler.getIsBaseVfModule(modelInfo, action, vnfType, sdcServiceModelVersion, currentActiveRequest); + } + + @Test + public void getIsBaseVfModuleModelVersionIdNullTest() throws ApiException { + ModelInfo modelInfo = new ModelInfo(); + modelInfo.setModelInvariantId(MODEL_INVARIANT_ID); + modelInfo.setModelVersion(MODEL_VERSION); + modelInfo.setModelName(MODEL_NAME); + Boolean expected = false; + + doReturn(null).when(catDbClient).getVfModuleByModelInvariantUUIDAndModelVersion(MODEL_INVARIANT_ID, + MODEL_VERSION); + + Boolean result = requestHandler.getIsBaseVfModule(modelInfo, Action.deleteInstance, vnfType, + sdcServiceModelVersion, currentActiveRequest); + assertEquals(result, expected); + } + + @Test + public void getIsBaseVfModuleModelInfoNotSetTest() throws ApiException { + ModelInfo modelInfo = new ModelInfo(); + Boolean expected = false; + + Boolean result = requestHandler.getIsBaseVfModule(modelInfo, Action.deleteInstance, vnfType, + sdcServiceModelVersion, currentActiveRequest); + assertEquals(result, expected); + } + + @Test + public void getIsBaseVfModuleModelVersionNullTest() throws ApiException { + ModelInfo modelInfo = new ModelInfo(); + modelInfo.setModelInvariantId(MODEL_INVARIANT_ID); + modelInfo.setModelName(MODEL_NAME); + Boolean expected = false; + + Boolean result = requestHandler.getIsBaseVfModule(modelInfo, Action.deleteInstance, vnfType, + sdcServiceModelVersion, currentActiveRequest); + assertEquals(result, expected); + } + + @Test + public void getIsBaseVfModuleModelVersionNullUpdateTest() throws ApiException { + ModelInfo modelInfo = new ModelInfo(); + modelInfo.setModelInvariantId(MODEL_INVARIANT_ID); + modelInfo.setModelName(MODEL_NAME); + String errorMessage = "VnfType vnfType and VF Module Model Name modelName not found in MSO Catalog DB"; + + doNothing().when(requestHandler).updateStatus(currentActiveRequest, Status.FAILED, errorMessage); + + thrown.expect(VfModuleNotFoundException.class); + thrown.expectMessage(errorMessage); + requestHandler.getIsBaseVfModule(modelInfo, Action.updateInstance, vnfType, null, currentActiveRequest); + } + + @Test + public void getIsBaseVfModulesdcModelVersionEmptyTest() throws ApiException { + ModelInfo modelInfo = new ModelInfo(); + modelInfo.setModelInvariantId(MODEL_INVARIANT_ID); + modelInfo.setModelName(MODEL_NAME); + String errorMessage = "VnfType vnfType and VF Module Model Name modelName not found in MSO Catalog DB"; + + doNothing().when(requestHandler).updateStatus(currentActiveRequest, Status.FAILED, errorMessage); + + thrown.expect(VfModuleNotFoundException.class); + thrown.expectMessage(errorMessage); + requestHandler.getIsBaseVfModule(modelInfo, Action.updateInstance, vnfType, "", currentActiveRequest); + } + + @Test + public void getModelTypeApplyUpdatedConfigTest() { + ModelType modelTypeExpected = ModelType.vnf; + + ModelType modelTypeResult = requestHandler.getModelType(Action.applyUpdatedConfig, null); + assertEquals(modelTypeResult, modelTypeExpected); + } + + @Test + public void getModelTypeInPlaceSoftwareUpdateTest() { + ModelType modelTypeExpected = ModelType.vnf; + + ModelType modelTypeResult = requestHandler.getModelType(Action.inPlaceSoftwareUpdate, null); + assertEquals(modelTypeResult, modelTypeExpected); + } + + @Test + public void getModelTypeAddMembersTest() { + ModelType modelTypeExpected = ModelType.instanceGroup; + + ModelType modelTypeResult = requestHandler.getModelType(Action.addMembers, null); + assertEquals(modelTypeResult, modelTypeExpected); + } + + @Test + public void getModelTypeRemoveMembersTest() { + ModelType modelTypeExpected = ModelType.instanceGroup; + + ModelType modelTypeResult = requestHandler.getModelType(Action.removeMembers, null); + assertEquals(modelTypeResult, modelTypeExpected); + } + + @Test + public void getModelTypeTest() { + ModelType modelTypeExpected = ModelType.service; + ModelInfo modelInfo = new ModelInfo(); + modelInfo.setModelType(ModelType.service); + + ModelType modelTypeResult = requestHandler.getModelType(Action.createInstance, modelInfo); + assertEquals(modelTypeResult, modelTypeExpected); + } + +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ResumeOrchestrationRequestTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ResumeOrchestrationRequestTest.java new file mode 100644 index 0000000000..398966b0b3 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ResumeOrchestrationRequestTest.java @@ -0,0 +1,482 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 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.so.apihandlerinfra; + +import static com.shazam.shazamcrest.MatcherAssert.assertThat; +import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyBoolean; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.nullable; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.junit.Assert.assertEquals; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.sql.Timestamp; +import java.util.HashMap; +import javax.ws.rs.container.ContainerRequestContext; +import javax.ws.rs.core.Response; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Spy; +import org.mockito.junit.MockitoJUnitRunner; +import org.onap.so.apihandler.common.RequestClientParameter; +import org.onap.so.apihandlerinfra.exceptions.ApiException; +import org.onap.so.apihandlerinfra.exceptions.DuplicateRequestException; +import org.onap.so.apihandlerinfra.exceptions.RequestDbFailureException; +import org.onap.so.apihandlerinfra.exceptions.ValidateException; +import org.onap.so.db.request.beans.InfraActiveRequests; +import org.onap.so.db.request.client.RequestsDbClient; +import org.onap.so.serviceinstancebeans.ModelInfo; +import org.onap.so.serviceinstancebeans.ServiceInstancesRequest; +import org.springframework.web.client.HttpClientErrorException; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.onap.so.serviceinstancebeans.ModelType; + +@RunWith(MockitoJUnitRunner.class) +public class ResumeOrchestrationRequestTest { + @Mock + private RequestHandlerUtils requestHandler; + + @Mock + private MsoRequest msoRequest; + + @Mock + private ServiceInstances serviceInstances; + + @Mock + private RequestsDbClient requestDbClient; + + @InjectMocks + @Spy + private ResumeOrchestrationRequest resumeReq; + + @Rule + public ExpectedException thrown = ExpectedException.none(); + + private static final String CURRENT_REQUEST_ID = "eca3a1b1-43ab-457e-ab1c-367263d148b4"; + private static final String REQUEST_ID = "00032ab7-na18-42e5-965d-8ea592502019"; + private static final String SERVICE_INSTANCE_ID = "00032ab7-na18-42e5-965d-8ea592502018"; + private static final String VNF_ID = "00032ab7-na18-42e5-965d-8ea592502017"; + private static final String VFMODULE_ID = "00032ab7-na18-42e5-965d-8ea592502016"; + private static final String NETWORK_ID = "00032ab7-na18-42e5-965d-8ea592502015"; + private static final String VOLUME_GROUP_ID = "00032ab7-na18-42e5-965d-8ea592502014"; + private static final String SERVICE_INSTANCE_NAME = "serviceInstanceName"; + private static final String VNF_NAME = "vnfName"; + private static final String VFMODULE_NAME = "vfModuleName"; + private static final String NETWORK_NAME = "networkName"; + private static final String VOLUME_GROUP_NAME = "volumeGroupName"; + private static final String SERVICE = "service"; + private static final String VNF = "vnf"; + private static final String VFMODULE = "vfModule"; + private static final String NETWORK = "network"; + private static final String VOLUME_GROUP = "volumeGroup"; + private final Timestamp startTimeStamp = new Timestamp(System.currentTimeMillis()); + private final Action action = Action.createInstance; + private final Boolean aLaCarte = false; + private final String version = "7"; + private final String requestUri = + "http:localhost:6746/onap/so/infra/orchestrationRequests/v7/00032ab7-na18-42e5-965d-8ea592502019/resume"; + private final RecipeLookupResult lookupResult = new RecipeLookupResult("/mso/async/services/WorkflowActionBB", 80); + private RequestClientParameter requestClientParameter = null; + private RequestClientParameter requestClientParameterVfModule = null; + private ObjectMapper mapper = new ObjectMapper(); + private InfraActiveRequests infraActiveRequest = new InfraActiveRequests(); + private InfraActiveRequests currentActiveRequest = new InfraActiveRequests(); + private InfraActiveRequests infraActiveRequestVfModule = new InfraActiveRequests(); + private ServiceInstancesRequest sir = new ServiceInstancesRequest(); + private ServiceInstancesRequest sirNullALaCarte = new ServiceInstancesRequest(); + private String requestBody = null; + private String requestBodyNullALaCarte = null; + private ContainerRequestContext requestContext = null; + private HashMap<String, String> instanceIdMap = new HashMap<>(); + ModelInfo modelInfo; + + + @Before + public void setup() throws ValidateException, IOException { + // Setup general requestHandler mocks + when(requestHandler.getRequestUri(any(), anyString())).thenReturn(requestUri); + + // Setup InfraActiveRequests + setInfraActiveRequest(); + setCurrentActiveRequest(); + setInfraActiveRequestVfModule(); + + requestBody = infraActiveRequest.getRequestBody(); + sir = mapper.readValue(requestBody, ServiceInstancesRequest.class); + requestBodyNullALaCarte = getRequestBody("/ALaCarteNull.json"); + sirNullALaCarte = mapper.readValue(requestBodyNullALaCarte, ServiceInstancesRequest.class); + setRequestClientParameter(); + setRequestClientParameterVfModule(); + instanceIdMap.put("serviceInstanceId", SERVICE_INSTANCE_ID); + modelInfo = sir.getRequestDetails().getModelInfo(); + } + + public String getRequestBody(String request) throws IOException { + request = "src/test/resources/ResumeOrchestrationRequest" + request; + return new String(Files.readAllBytes(Paths.get(request))); + } + + private void setInfraActiveRequest() throws IOException { + infraActiveRequest.setTenantId("tenant-id"); + infraActiveRequest.setRequestBody(getRequestBody("/RequestBody.json")); + infraActiveRequest.setAicCloudRegion("cloudRegion"); + infraActiveRequest.setRequestScope(SERVICE); + infraActiveRequest.setServiceInstanceId(SERVICE_INSTANCE_ID); + infraActiveRequest.setServiceInstanceName(SERVICE_INSTANCE_NAME); + infraActiveRequest.setRequestStatus(Status.IN_PROGRESS.toString()); + infraActiveRequest.setRequestAction(Action.createInstance.toString()); + infraActiveRequest.setServiceType("serviceType"); + infraActiveRequest.setVnfId(VNF_ID); + infraActiveRequest.setVfModuleId(VFMODULE_ID); + infraActiveRequest.setNetworkId(NETWORK_ID); + infraActiveRequest.setVolumeGroupId(VOLUME_GROUP_ID); + infraActiveRequest.setVnfName(VNF_NAME); + infraActiveRequest.setVfModuleName(VFMODULE_NAME); + infraActiveRequest.setNetworkName(NETWORK_NAME); + infraActiveRequest.setVolumeGroupName(VOLUME_GROUP_NAME); + infraActiveRequest.setRequestId(REQUEST_ID); + } + + private void setCurrentActiveRequest() throws IOException { + currentActiveRequest.setRequestId(CURRENT_REQUEST_ID); + currentActiveRequest.setSource("VID"); + currentActiveRequest.setStartTime(startTimeStamp); + currentActiveRequest.setTenantId("tenant-id"); + currentActiveRequest.setRequestBody(getRequestBody("/RequestBody.json")); + currentActiveRequest.setAicCloudRegion("cloudRegion"); + currentActiveRequest.setRequestScope(SERVICE); + currentActiveRequest.setServiceInstanceId(SERVICE_INSTANCE_ID); + currentActiveRequest.setServiceInstanceName(SERVICE_INSTANCE_NAME); + currentActiveRequest.setRequestStatus(Status.IN_PROGRESS.toString()); + currentActiveRequest.setLastModifiedBy(Constants.MODIFIED_BY_APIHANDLER); + currentActiveRequest.setRequestAction(Action.createInstance.toString()); + currentActiveRequest.setRequestUrl(requestUri); + currentActiveRequest.setRequestorId("xxxxxx"); + currentActiveRequest.setProgress(new Long(5)); + } + + private void setInfraActiveRequestVfModule() throws IOException { + infraActiveRequestVfModule.setRequestBody(getRequestBody("/RequestBody.json")); + infraActiveRequestVfModule.setRequestScope(VFMODULE); + infraActiveRequestVfModule.setRequestStatus(Status.IN_PROGRESS.toString()); + infraActiveRequestVfModule.setRequestAction(Action.createInstance.toString()); + infraActiveRequestVfModule.setVnfId(VNF_ID); + infraActiveRequestVfModule.setVfModuleId(VFMODULE_ID); + infraActiveRequestVfModule.setVnfName(VNF_NAME); + infraActiveRequestVfModule.setVfModuleName(VFMODULE_NAME); + } + + private void setRequestClientParameter() { + requestClientParameter = + new RequestClientParameter.Builder().setRequestId(CURRENT_REQUEST_ID).setRecipeTimeout(80) + .setRequestAction(Action.createInstance.toString()).setServiceInstanceId(SERVICE_INSTANCE_ID) + .setPnfCorrelationId("pnfCorrelationId").setVnfId(VNF_ID).setVfModuleId(VFMODULE_ID) + .setVolumeGroupId(VOLUME_GROUP_ID).setNetworkId(NETWORK_ID).setServiceType("serviceType") + .setVnfType(null).setNetworkType(null).setRequestDetails(requestBody).setApiVersion(version) + .setALaCarte(aLaCarte).setRequestUri(requestUri).setInstanceGroupId(null).build(); + } + + private void setRequestClientParameterVfModule() { + requestClientParameterVfModule = + new RequestClientParameter.Builder().setRequestId(CURRENT_REQUEST_ID).setRecipeTimeout(80) + .setRequestAction(Action.createInstance.toString()).setPnfCorrelationId("pnfCorrelationId") + .setVnfId(VNF_ID).setVfModuleId(VFMODULE_ID).setRequestDetails(requestBody) + .setApiVersion(version).setALaCarte(aLaCarte).setRequestUri(requestUri).build(); + } + + @Test + public void resumeOrchestationRequestTest() throws Exception { + Response response = null; + when(requestDbClient.getInfraActiveRequestbyRequestId(REQUEST_ID)).thenReturn(infraActiveRequest); + doReturn(currentActiveRequest).when(requestHandler).createNewRecordCopyFromInfraActiveRequest( + any(InfraActiveRequests.class), nullable(String.class), any(Timestamp.class), nullable(String.class), + nullable(String.class), nullable(String.class), anyString()); + doReturn(response).when(resumeReq).resumeRequest(any(InfraActiveRequests.class), any(InfraActiveRequests.class), + anyString(), nullable(String.class)); + + resumeReq.resumeOrchestrationRequest(REQUEST_ID, "v7", requestContext); + + verify(resumeReq).resumeRequest(infraActiveRequest, currentActiveRequest, version, null); + } + + @Test + public void resumeOrchestationRequestDbNullResultTest() throws Exception { + when(requestDbClient.getInfraActiveRequestbyRequestId("00032ab7-na18-42e5-965d-8ea592502018")).thenReturn(null); + + thrown.expect(ValidateException.class); + thrown.expectMessage( + "Null response from requestDB when searching by requestId: 00032ab7-na18-42e5-965d-8ea592502018"); + resumeReq.resumeOrchestrationRequest("00032ab7-na18-42e5-965d-8ea592502018", "v7", requestContext); + } + + @Test + public void resumeOrchestationRequestDbErrorTest() throws Exception { + when(requestDbClient.getInfraActiveRequestbyRequestId("00032ab7-na18-42e5-965d-8ea592502018")) + .thenThrow(HttpClientErrorException.class); + + thrown.expect(ValidateException.class); + thrown.expectMessage("Exception while performing requestDb lookup by requestId"); + resumeReq.resumeOrchestrationRequest("00032ab7-na18-42e5-965d-8ea592502018", "v7", requestContext); + } + + @Test + public void resumeRequestTest() throws ApiException, IOException { + Response response = null; + doReturn(instanceIdMap).when(resumeReq).setInstanceIdMap(infraActiveRequest, ModelType.service.toString()); + doReturn(SERVICE_INSTANCE_NAME).when(resumeReq).getInstanceName(infraActiveRequest, + ModelType.service.toString(), currentActiveRequest); + when(requestHandler.convertJsonToServiceInstanceRequest(anyString(), any(Actions.class), anyString(), + anyString())).thenReturn(sir); + when(serviceInstances.getPnfCorrelationId(any(ServiceInstancesRequest.class))).thenReturn("pnfCorrelationId"); + doReturn(lookupResult).when(serviceInstances).getServiceInstanceOrchestrationURI(sir, action, aLaCarte, + currentActiveRequest); + doReturn(requestClientParameter).when(resumeReq).setRequestClientParameter(lookupResult, version, + infraActiveRequest, currentActiveRequest, "pnfCorrelationId", aLaCarte, sir); + doNothing().when(resumeReq).requestDbSave(currentActiveRequest); + when(requestHandler.postBPELRequest(any(InfraActiveRequests.class), any(RequestClientParameter.class), + anyString(), anyString())).thenReturn(response); + doNothing().when(resumeReq).checkForInProgressRequest(currentActiveRequest, instanceIdMap, SERVICE, + SERVICE_INSTANCE_NAME, action); + + resumeReq.resumeRequest(infraActiveRequest, currentActiveRequest, version, + "/onap/so/infra/orchestrationRequests/v7/requests/00032ab7-na18-42e5-965d-8ea592502018/resume"); + verify(requestHandler).postBPELRequest(currentActiveRequest, requestClientParameter, + lookupResult.getOrchestrationURI(), infraActiveRequest.getRequestScope()); + } + + @Test + public void setRequestClientParameterTest() throws ApiException, IOException { + doReturn(ModelType.service).when(requestHandler).getModelType(action, modelInfo); + when(requestHandler.mapJSONtoMSOStyle(anyString(), any(ServiceInstancesRequest.class), anyBoolean(), + any(Action.class))).thenReturn(requestBody); + RequestClientParameter result = resumeReq.setRequestClientParameter(lookupResult, version, infraActiveRequest, + currentActiveRequest, "pnfCorrelationId", aLaCarte, sir); + assertThat(requestClientParameter, sameBeanAs(result)); + } + + @Test + public void setRequestClientParameterVfModuleTest() throws ApiException, IOException { + when(requestHandler.mapJSONtoMSOStyle(anyString(), any(ServiceInstancesRequest.class), anyBoolean(), + any(Action.class))).thenReturn(requestBody); + doReturn(ModelType.vfModule).when(requestHandler).getModelType(action, modelInfo); + RequestClientParameter result = resumeReq.setRequestClientParameter(lookupResult, version, + infraActiveRequestVfModule, currentActiveRequest, "pnfCorrelationId", aLaCarte, sir); + assertThat(requestClientParameterVfModule, sameBeanAs(result)); + } + + @Test + public void requestDbSaveTest() throws RequestDbFailureException { + doNothing().when(requestDbClient).save(currentActiveRequest); + resumeReq.requestDbSave(currentActiveRequest); + verify(requestDbClient).save(currentActiveRequest); + } + + @Test + public void resumeRequestTestALaCarteNull() throws ApiException, IOException { + Response response = null; + doReturn(instanceIdMap).when(resumeReq).setInstanceIdMap(infraActiveRequest, ModelType.service.toString()); + doReturn(SERVICE_INSTANCE_NAME).when(resumeReq).getInstanceName(infraActiveRequest, + ModelType.service.toString(), currentActiveRequest); + when(requestHandler.convertJsonToServiceInstanceRequest(anyString(), any(Actions.class), anyString(), + anyString())).thenReturn(sirNullALaCarte); + when(serviceInstances.getPnfCorrelationId(any(ServiceInstancesRequest.class))).thenReturn("pnfCorrelationId"); + doReturn(false).when(msoRequest).getAlacarteFlag(sirNullALaCarte); + doReturn(lookupResult).when(serviceInstances).getServiceInstanceOrchestrationURI(sirNullALaCarte, action, false, + currentActiveRequest); + doReturn(requestClientParameter).when(resumeReq).setRequestClientParameter(lookupResult, version, + infraActiveRequest, currentActiveRequest, "pnfCorrelationId", aLaCarte, sirNullALaCarte); + doReturn(false).when(resumeReq).setALaCarteFlagIfNull(SERVICE, action); + doNothing().when(resumeReq).requestDbSave(currentActiveRequest); + when(requestHandler.postBPELRequest(any(InfraActiveRequests.class), any(RequestClientParameter.class), + anyString(), anyString())).thenReturn(response); + doNothing().when(resumeReq).checkForInProgressRequest(currentActiveRequest, instanceIdMap, SERVICE, + SERVICE_INSTANCE_NAME, action); + + resumeReq.resumeRequest(infraActiveRequest, currentActiveRequest, version, + "/onap/so/infra/orchestrationRequests/v7/requests/00032ab7-na18-42e5-965d-8ea592502018/resume"); + verify(requestHandler).postBPELRequest(currentActiveRequest, requestClientParameter, + lookupResult.getOrchestrationURI(), infraActiveRequest.getRequestScope()); + } + + @Test + public void setRequestClientParameterErrorTest() throws ApiException, IOException { + doReturn(ModelType.service).when(requestHandler).getModelType(action, modelInfo); + when(requestHandler.mapJSONtoMSOStyle(anyString(), any(ServiceInstancesRequest.class), anyBoolean(), + any(Action.class))).thenThrow(new IOException("IOException")); + + thrown.expect(ValidateException.class); + thrown.expectMessage("IOException while generating requestClientParameter to send to BPMN: IOException"); + resumeReq.setRequestClientParameter(lookupResult, version, infraActiveRequest, currentActiveRequest, + "pnfCorrelationId", aLaCarte, sir); + } + + @Test + public void checkForInProgressRequest() throws ApiException { + doReturn(infraActiveRequest).when(requestHandler).duplicateCheck(action, instanceIdMap, SERVICE_INSTANCE_NAME, + SERVICE, currentActiveRequest); + doReturn(true).when(requestHandler).camundaHistoryCheck(infraActiveRequest, currentActiveRequest); + doThrow(DuplicateRequestException.class).when(requestHandler).buildErrorOnDuplicateRecord(currentActiveRequest, + action, instanceIdMap, SERVICE_INSTANCE_NAME, SERVICE, infraActiveRequest); + + thrown.expect(DuplicateRequestException.class); + resumeReq.checkForInProgressRequest(currentActiveRequest, instanceIdMap, SERVICE, SERVICE_INSTANCE_NAME, + action); + } + + @Test + public void checkForInProgressRequestNoInProgressRequests() throws ApiException { + doReturn(null).when(requestHandler).duplicateCheck(action, instanceIdMap, SERVICE_INSTANCE_NAME, SERVICE, + currentActiveRequest); + + resumeReq.checkForInProgressRequest(currentActiveRequest, instanceIdMap, SERVICE, SERVICE_INSTANCE_NAME, + action); + verify(requestHandler).duplicateCheck(action, instanceIdMap, SERVICE_INSTANCE_NAME, SERVICE, + currentActiveRequest); + } + + @Test + public void checkForInProgressRequestCamundaHistoryCheckReturnsNoInProgress() throws ApiException { + doReturn(infraActiveRequest).when(requestHandler).duplicateCheck(action, instanceIdMap, SERVICE_INSTANCE_NAME, + SERVICE, currentActiveRequest); + doReturn(false).when(requestHandler).camundaHistoryCheck(infraActiveRequest, currentActiveRequest); + + resumeReq.checkForInProgressRequest(currentActiveRequest, instanceIdMap, SERVICE, SERVICE_INSTANCE_NAME, + action); + verify(requestHandler).duplicateCheck(action, instanceIdMap, SERVICE_INSTANCE_NAME, SERVICE, + currentActiveRequest); + verify(requestHandler).camundaHistoryCheck(infraActiveRequest, currentActiveRequest); + } + + @Test + public void setInstanceIdMapServiceTest() { + HashMap<String, String> expected = new HashMap<>(); + expected.put("serviceInstanceId", SERVICE_INSTANCE_ID); + HashMap<String, String> result = resumeReq.setInstanceIdMap(infraActiveRequest, SERVICE); + assertEquals(result, expected); + } + + @Test + public void setInstanceIdMapRequestScopeNotValidTest() { + HashMap<String, String> expected = new HashMap<>(); + HashMap<String, String> result = resumeReq.setInstanceIdMap(infraActiveRequest, "test"); + assertEquals(result, expected); + } + + @Test + public void setInstanceIdMapVnfTest() { + HashMap<String, String> expected = new HashMap<>(); + expected.put("vnfInstanceId", VNF_ID); + HashMap<String, String> result = resumeReq.setInstanceIdMap(infraActiveRequest, VNF); + assertEquals(result, expected); + } + + @Test + public void setInstanceIdMapVfModuleTest() { + HashMap<String, String> expected = new HashMap<>(); + expected.put("vfModuleInstanceId", VFMODULE_ID); + HashMap<String, String> result = resumeReq.setInstanceIdMap(infraActiveRequest, VFMODULE); + assertEquals(result, expected); + } + + @Test + public void setInstanceIdMapNetworkTest() { + HashMap<String, String> expected = new HashMap<>(); + expected.put("networkInstanceId", NETWORK_ID); + HashMap<String, String> result = resumeReq.setInstanceIdMap(infraActiveRequest, NETWORK); + assertEquals(result, expected); + } + + @Test + public void setInstanceIdMapVolumeGroupTest() { + HashMap<String, String> expected = new HashMap<>(); + expected.put("volumeGroupInstanceId", VOLUME_GROUP_ID); + HashMap<String, String> result = resumeReq.setInstanceIdMap(infraActiveRequest, VOLUME_GROUP); + assertEquals(result, expected); + } + + @Test + public void setInstanceNameServiceTest() throws ValidateException, RequestDbFailureException { + String result = resumeReq.getInstanceName(infraActiveRequest, SERVICE, currentActiveRequest); + assertEquals(result, SERVICE_INSTANCE_NAME); + } + + @Test + public void setInstanceNameRequestScopeNotValidTest() throws ValidateException, RequestDbFailureException { + thrown.expect(ValidateException.class); + thrown.expectMessage( + "requestScope: \"test\" from request: 00032ab7-na18-42e5-965d-8ea592502019 does not match a ModelType enum."); + + resumeReq.getInstanceName(infraActiveRequest, "test", currentActiveRequest); + } + + @Test + public void setInstanceNameVnfTest() throws ValidateException, RequestDbFailureException { + String result = resumeReq.getInstanceName(infraActiveRequest, VNF, currentActiveRequest); + assertEquals(result, VNF_NAME); + } + + @Test + public void setInstanceNameVfModuleTest() throws ValidateException, RequestDbFailureException { + String result = resumeReq.getInstanceName(infraActiveRequest, VFMODULE, currentActiveRequest); + assertEquals(result, VFMODULE_NAME); + } + + @Test + public void setInstanceNameNetworkTest() throws ValidateException, RequestDbFailureException { + String result = resumeReq.getInstanceName(infraActiveRequest, NETWORK, currentActiveRequest); + assertEquals(result, NETWORK_NAME); + } + + @Test + public void setInstanceNameVolumeGroupTest() throws ValidateException, RequestDbFailureException { + String result = resumeReq.getInstanceName(infraActiveRequest, VOLUME_GROUP, currentActiveRequest); + assertEquals(result, VOLUME_GROUP_NAME); + } + + @Test + public void setALaCarteFlagIfNullTest() { + Boolean aLaCarteFlag = resumeReq.setALaCarteFlagIfNull(SERVICE, action); + assertEquals(aLaCarteFlag, false); + } + + @Test + public void setALaCarteFlagIfNullVnfTest() { + Boolean aLaCarteFlag = resumeReq.setALaCarteFlagIfNull(VNF, action); + assertEquals(aLaCarteFlag, true); + } + + @Test + public void setALaCarteFlagIfNullRecreateTest() { + Boolean aLaCarteFlag = resumeReq.setALaCarteFlagIfNull(VNF, Action.recreateInstance); + assertEquals(aLaCarteFlag, false); + } +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ServiceInstancesTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ServiceInstancesTest.java index db6273dc4a..ea43a54e69 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ServiceInstancesTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ServiceInstancesTest.java @@ -28,11 +28,14 @@ import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.onap.so.logger.HttpHeadersConstants.ONAP_REQUEST_ID; import static org.onap.so.logger.HttpHeadersConstants.REQUESTOR_ID; +import static org.onap.so.logger.HttpHeadersConstants.TRANSACTION_ID; import static org.onap.so.logger.MdcConstants.CLIENT_ID; import static org.onap.so.logger.MdcConstants.ENDTIME; import static org.onap.so.logger.MdcConstants.INVOCATION_ID; @@ -41,7 +44,6 @@ import static org.onap.so.logger.MdcConstants.RESPONSECODE; import static org.onap.so.logger.MdcConstants.RESPONSEDESC; import static org.onap.so.logger.MdcConstants.SERVICE_NAME; import static org.onap.so.logger.MdcConstants.STATUSCODE; -import static org.onap.so.logger.HttpHeadersConstants.TRANSACTION_ID; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; @@ -57,12 +59,17 @@ import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; import org.onap.logging.ref.slf4j.ONAPLogConstants; +import org.onap.so.apihandlerinfra.exceptions.ContactCamundaException; +import org.onap.so.apihandlerinfra.exceptions.RequestDbFailureException; import org.onap.so.db.catalog.beans.Service; import org.onap.so.db.catalog.beans.ServiceRecipe; import org.onap.so.db.request.beans.InfraActiveRequests; import org.onap.so.logger.HttpHeadersConstants; import org.onap.so.serviceinstancebeans.CloudConfiguration; +import org.onap.so.serviceinstancebeans.ModelInfo; +import org.onap.so.serviceinstancebeans.RequestDetails; import org.onap.so.serviceinstancebeans.RequestError; +import org.onap.so.serviceinstancebeans.RequestInfo; import org.onap.so.serviceinstancebeans.RequestParameters; import org.onap.so.serviceinstancebeans.RequestReferences; import org.onap.so.serviceinstancebeans.ServiceInstancesRequest; @@ -75,7 +82,6 @@ import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; import org.springframework.util.ResourceUtils; import org.springframework.web.util.UriComponentsBuilder; -import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.DeserializationFeature; @@ -93,6 +99,9 @@ public class ServiceInstancesTest extends BaseTest { @Autowired private ServiceInstances servInstances; + @Autowired + private RequestHandlerUtils requestHandlerUtils; + @Value("${wiremock.server.port}") private String wiremockPort; @@ -2748,5 +2757,194 @@ public class ServiceInstancesTest extends BaseTest { "No valid modelCustomizationId for networkResourceCustomization lookup is specified"); } + @Test + public void setServiceTypeTestALaCarte() throws JsonProcessingException { + String requestScope = ModelType.service.toString(); + Boolean aLaCarteFlag = true; + ServiceInstancesRequest sir = new ServiceInstancesRequest(); + RequestDetails requestDetails = new RequestDetails(); + RequestInfo requestInfo = new RequestInfo(); + requestInfo.setSource("VID"); + requestDetails.setRequestInfo(requestInfo); + sir.setRequestDetails(requestDetails); + Service defaultService = new Service(); + defaultService.setServiceType("testServiceTypeALaCarte"); + + wireMockServer.stubFor(get(urlMatching(".*/service/search/.*")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(mapper.writeValueAsString(defaultService)).withStatus(HttpStatus.SC_OK))); + + String serviceType = requestHandlerUtils.getServiceType(requestScope, sir, aLaCarteFlag); + assertEquals(serviceType, "testServiceTypeALaCarte"); + } + + @Test + public void setServiceTypeTest() throws JsonProcessingException { + String requestScope = ModelType.service.toString(); + Boolean aLaCarteFlag = false; + ServiceInstancesRequest sir = new ServiceInstancesRequest(); + RequestDetails requestDetails = new RequestDetails(); + RequestInfo requestInfo = new RequestInfo(); + ModelInfo modelInfo = new ModelInfo(); + modelInfo.setModelVersionId("0dd91181-49da-446b-b839-cd959a96f04a"); + requestInfo.setSource("VID"); + requestDetails.setModelInfo(modelInfo); + requestDetails.setRequestInfo(requestInfo); + sir.setRequestDetails(requestDetails); + Service defaultService = new Service(); + defaultService.setServiceType("testServiceType"); + + wireMockServer.stubFor(get(urlMatching(".*/service/0dd91181-49da-446b-b839-cd959a96f04a")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(mapper.writeValueAsString(defaultService)).withStatus(HttpStatus.SC_OK))); + + String serviceType = requestHandlerUtils.getServiceType(requestScope, sir, aLaCarteFlag); + assertEquals(serviceType, "testServiceType"); + } + + @Test + public void setServiceTypeTestDefault() throws JsonProcessingException { + String requestScope = ModelType.service.toString(); + Boolean aLaCarteFlag = false; + ServiceInstancesRequest sir = new ServiceInstancesRequest(); + RequestDetails requestDetails = new RequestDetails(); + RequestInfo requestInfo = new RequestInfo(); + ModelInfo modelInfo = new ModelInfo(); + modelInfo.setModelVersionId("0dd91181-49da-446b-b839-cd959a96f04a"); + requestInfo.setSource("VID"); + requestDetails.setModelInfo(modelInfo); + requestDetails.setRequestInfo(requestInfo); + sir.setRequestDetails(requestDetails); + Service defaultService = new Service(); + defaultService.setServiceType("testServiceType"); + + wireMockServer.stubFor(get(urlMatching(".*/service/0dd91181-49da-446b-b839-cd959a96f04a")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withStatus(HttpStatus.SC_NOT_FOUND))); + wireMockServer.stubFor(get(urlMatching(".*/service/search/.*")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(mapper.writeValueAsString(defaultService)).withStatus(HttpStatus.SC_OK))); + + String serviceType = requestHandlerUtils.getServiceType(requestScope, sir, aLaCarteFlag); + assertEquals(serviceType, "testServiceType"); + } + + @Test + public void setServiceTypeTestNetwork() throws JsonProcessingException { + String requestScope = ModelType.network.toString(); + Boolean aLaCarteFlag = null; + ServiceInstancesRequest sir = new ServiceInstancesRequest(); + RequestDetails requestDetails = new RequestDetails(); + RequestInfo requestInfo = new RequestInfo(); + ModelInfo modelInfo = new ModelInfo(); + modelInfo.setModelName("networkModelName"); + requestInfo.setSource("VID"); + requestDetails.setModelInfo(modelInfo); + requestDetails.setRequestInfo(requestInfo); + sir.setRequestDetails(requestDetails); + + String serviceType = requestHandlerUtils.getServiceType(requestScope, sir, aLaCarteFlag); + assertEquals(serviceType, "networkModelName"); + } + + @Test + public void setServiceInstanceIdInstanceGroupTest() throws JsonParseException, JsonMappingException, IOException { + String requestScope = "instanceGroup"; + ServiceInstancesRequest sir = + mapper.readValue(inputStream("/CreateInstanceGroup.json"), ServiceInstancesRequest.class); + assertEquals("ddcbbf3d-f2c1-4ca0-8852-76a807285efc", + requestHandlerUtils.setServiceInstanceId(requestScope, sir)); + } + + @Test + public void setServiceInstanceIdTest() { + String requestScope = "vnf"; + ServiceInstancesRequest sir = new ServiceInstancesRequest(); + sir.setServiceInstanceId("f0a35706-efc4-4e27-80ea-a995d7a2a40f"); + assertEquals("f0a35706-efc4-4e27-80ea-a995d7a2a40f", + requestHandlerUtils.setServiceInstanceId(requestScope, sir)); + } + + @Test + public void setServiceInstanceIdReturnNullTest() { + String requestScope = "vnf"; + ServiceInstancesRequest sir = new ServiceInstancesRequest(); + assertNull(requestHandlerUtils.setServiceInstanceId(requestScope, sir)); + } + + @Test + public void camundaHistoryCheckTest() throws ContactCamundaException, RequestDbFailureException { + wireMockServer.stubFor(get( + ("/sobpmnengine/history/process-instance?variables=mso-request-id_eq_f0a35706-efc4-4e27-80ea-a995d7a2a40f")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBodyFile("Camunda/HistoryCheckResponse.json") + .withStatus(org.apache.http.HttpStatus.SC_OK))); + + InfraActiveRequests duplicateRecord = new InfraActiveRequests(); + duplicateRecord.setRequestId("f0a35706-efc4-4e27-80ea-a995d7a2a40f"); + boolean inProgress = false; + inProgress = requestHandlerUtils.camundaHistoryCheck(duplicateRecord, null); + assertTrue(inProgress); + } + + @Test + public void camundaHistoryCheckNoneFoundTest() throws ContactCamundaException, RequestDbFailureException { + wireMockServer.stubFor(get( + ("/sobpmnengine/history/process-instance?variables=mso-request-id_eq_f0a35706-efc4-4e27-80ea-a995d7a2a40f")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody("[]").withStatus(org.apache.http.HttpStatus.SC_OK))); + InfraActiveRequests duplicateRecord = new InfraActiveRequests(); + duplicateRecord.setRequestId("f0a35706-efc4-4e27-80ea-a995d7a2a40f"); + boolean inProgress = false; + inProgress = requestHandlerUtils.camundaHistoryCheck(duplicateRecord, null); + assertFalse(inProgress); + } + + @Test + public void camundaHistoryCheckNotInProgressTest() throws ContactCamundaException, RequestDbFailureException { + wireMockServer.stubFor(get( + ("/sobpmnengine/history/process-instance?variables=mso-request-id_eq_f0a35706-efc4-4e27-80ea-a995d7a2a40f")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBodyFile("Camunda/HistoryCheckResponseCompleted.json") + .withStatus(org.apache.http.HttpStatus.SC_OK))); + + InfraActiveRequests duplicateRecord = new InfraActiveRequests(); + duplicateRecord.setRequestId("f0a35706-efc4-4e27-80ea-a995d7a2a40f"); + boolean inProgress = false; + inProgress = requestHandlerUtils.camundaHistoryCheck(duplicateRecord, null); + assertFalse(inProgress); + } + + @Test + public void setCamundaHeadersTest() throws ContactCamundaException, RequestDbFailureException { + String encryptedAuth = "015E7ACF706C6BBF85F2079378BDD2896E226E09D13DC2784BA309E27D59AB9FAD3A5E039DF0BB8408"; // user:password + String key = "07a7159d3bf51a0e53be7a8f89699be7"; + HttpHeaders headers = requestHandlerUtils.setCamundaHeaders(encryptedAuth, key); + List<org.springframework.http.MediaType> acceptedType = headers.getAccept(); + String expectedAcceptedType = "application/json"; + assertEquals(expectedAcceptedType, acceptedType.get(0).toString()); + String basicAuth = headers.getFirst(HttpHeaders.AUTHORIZATION); + String expectedBasicAuth = "Basic dXNlcjpwYXNzd29yZA=="; + assertEquals(expectedBasicAuth, basicAuth); + } + + @Test + public void handleReplaceInstance_Test() throws JsonParseException, JsonMappingException, IOException { + String replaceVfModule = inputStream("/ReplaceVfModule.json"); + ObjectMapper mapper = new ObjectMapper(); + ServiceInstancesRequest sir = mapper.readValue(replaceVfModule, ServiceInstancesRequest.class); + Actions action = servInstances.handleReplaceInstance(Action.replaceInstance, sir); + assertEquals(Action.replaceInstance, action); + } + + @Test + public void handleReplaceInstance_retainAssignments_Test() + throws JsonParseException, JsonMappingException, IOException { + String replaceVfModule = inputStream("/ReplaceVfModuleRetainAssignments.json"); + ObjectMapper mapper = new ObjectMapper(); + ServiceInstancesRequest sir = mapper.readValue(replaceVfModule, ServiceInstancesRequest.class); + Actions action = servInstances.handleReplaceInstance(Action.replaceInstance, sir); + assertEquals(Action.replaceInstanceRetainAssignments, action); + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/OrchestrationRequest/OrchestrationList.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/OrchestrationRequest/OrchestrationList.json index 90089c0c7e..baddb21617 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/resources/OrchestrationRequest/OrchestrationList.json +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/OrchestrationRequest/OrchestrationList.json @@ -34,7 +34,7 @@ }, { "request":{ - "requestId":"00032ab7-na18-42e5-965d-8ea592502018", + "requestId":"00032ab7-1a18-42e5-965d-8ea592502018", "requestScope":"vfModule", "requestType":"deleteInstance", "requestDetails":{ @@ -298,7 +298,7 @@ }, { "request":{ - "requestId":"00032ab7-na18-42e5-965d-8ea592502018", + "requestId":"00032ab7-1a18-42e5-965d-8ea592502018", "requestScope":"instanceGroup", "requestType":"addMembers", "requestDetails":{ diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/OrchestrationRequest/getOrchestrationOpenstackRequestDetails.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/OrchestrationRequest/getOrchestrationOpenstackRequestDetails.json new file mode 100644 index 0000000000..41d7e4d706 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/OrchestrationRequest/getOrchestrationOpenstackRequestDetails.json @@ -0,0 +1,62 @@ +{ + "clientRequestId": "00032ab7-3fb3-42e5-965d-8ea592502016", + "action": "deleteInstance", + "requestStatus": "COMPLETE", + "statusMessage": "Vf Module has been deleted successfully.", + "progress": 100, + "startTime": "2016-12-22T13:29:54.000+0000", + "endTime": "2016-12-22T13:30:28.000+0000", + "source": "VID", + "vnfId": "b92f60c8-8de3-46c1-8dc1-e4390ac2b005", + "vnfName": null, + "vnfType": null, + "serviceType": null, + "aicNodeClli": null, + "tenantId": "6accefef3cb442ff9e644d589fb04107", + "provStatus": null, + "vnfParams": null, + "vnfOutputs": null, + "requestBody": "{\"modelInfo\":{\"modelType\":\"vfModule\",\"modelName\":\"test::base::module-0\"},\"requestInfo\":{\"source\":\"VID\"},\"cloudConfiguration\":{\"tenantId\":\"6accefef3cb442ff9e644d589fb04107\",\"lcpCloudRegionId\":\"n6\"}}", + "responseBody": null, + "lastModifiedBy": "BPMN", + "modifyTime": "2016-12-22T13:30:28.000+0000", + "requestType": null, + "volumeGroupId": null, + "volumeGroupName": null, + "vfModuleId": "c7d527b1-7a91-49fd-b97d-1c8c0f4a7992", + "vfModuleName": null, + "vfModuleModelName": "test::base::module-0", + "aaiServiceId": null, + "aicCloudRegion": "n6", + "callBackUrl": null, + "correlator": null, + "serviceInstanceId": "e3b5744d-2ad1-4cdd-8390-c999a38829bc", + "serviceInstanceName": null, + "requestScope": "vfModule", + "requestAction": "deleteInstance", + "networkId": null, + "networkName": null, + "networkType": null, + "requestorId": null, + "configurationId": null, + "configurationName": null, + "operationalEnvId": null, + "operationalEnvName": null, + "cloudApiRequests":[ + { + "id": 1, + "cloudIdentifier": "heatstackName/123123", + "requestBody":"{\r\n \"test\": \"00032ab7-3fb3-42e5-965d-8ea592502016\",\r\n \"test2\": \"deleteInstance\",\r\n \"test3\": \"COMPLETE\",\r\n \"test4\": \"Vf Module has been deleted successfully.\",\r\n \"test5\": 100\r\n}", + "created": "2016-12-22T13:29:54.000+0000" + } + ], + "requestURI": "00032ab7-3fb3-42e5-965d-8ea592502017", + "_links": { + "self": { + "href": "http://localhost:8087/infraActiveRequests/00032ab7-3fb3-42e5-965d-8ea592502017" + }, + "infraActiveRequests": { + "href": "http://localhost:8087/infraActiveRequests/00032ab7-3fb3-42e5-965d-8ea592502017" + } + } +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/ResumeOrchestrationRequest/ALaCarteNull.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/ResumeOrchestrationRequest/ALaCarteNull.json new file mode 100644 index 0000000000..5da139e711 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/ResumeOrchestrationRequest/ALaCarteNull.json @@ -0,0 +1,13 @@ +{ + "requestDetails":{ + "requestInfo":{ + "source":"VID", + "requestorId":"xxxxxx", + "instanceName":"testService", + "productFamilyId":"test" + }, + "requestParameters":{ + "usePreload": "false" + } + } +}
\ No newline at end of file diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/ResumeOrchestrationRequest/RequestBody.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/ResumeOrchestrationRequest/RequestBody.json new file mode 100644 index 0000000000..7e8ed4dee1 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/ResumeOrchestrationRequest/RequestBody.json @@ -0,0 +1,19 @@ +{ + "requestDetails":{ + "requestInfo":{ + "source":"VID", + "requestorId":"xxxxxx", + "instanceName":"testService", + "productFamilyId":"test" + }, + "requestParameters":{ + "aLaCarte":"false" + }, + "modelInfo":{ + "modelInvariantId": "f7ce78bb-423b-11e7-93f8-0050569a7965", + "modelVersion": "1.0", + "modelType":"service", + "modelName":"serviceModel" + } + } +}
\ No newline at end of file diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/ServiceInstanceTest/ReplaceVfModuleRetainAssignments.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/ServiceInstanceTest/ReplaceVfModuleRetainAssignments.json new file mode 100644 index 0000000000..166f7ccce8 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/ServiceInstanceTest/ReplaceVfModuleRetainAssignments.json @@ -0,0 +1,33 @@ +{ + "requestDetails": { + "requestInfo": { + "source": "VID", + "requestorId": "xxxxxx", + "instanceName": "testService60" + }, + "requestParameters": { + "aLaCarte": true, + "autoBuildVfModules": false, + "retainAssignments": true, + "subscriptionServiceType": "test" + }, + "cloudConfiguration": { + "lcpCloudRegionId": "mdt1", + "tenantId": "88a6ca3ee0394ade9403f075db23167e" + }, + "modelInfo":{ + "modelInvariantId": "f7ce78bb-423b-11e7-93f8-0050569a7968", + "modelVersion":"2", + "modelVersionId":"78ca26d0-246d-11e7-93ae-92361f002671", + "modelType":"vfModule", + "modelName":"serviceModel", + "modelCustomizationId": "a7f1d08e-b02d-11e6-80f5-76304dec7eb7" + }, + "subscriberInfo": { + "globalSubscriberId": "MSO_1610_dev", + "subscriberName": "MSO_1610_dev" + } + } +} + +
\ No newline at end of file diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/application-test.yaml b/mso-api-handlers/mso-api-handler-infra/src/test/resources/application-test.yaml index 712fbf54ca..2e1c6a9bdc 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/resources/application-test.yaml +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/application-test.yaml @@ -83,6 +83,8 @@ mso: spring: + jersey: + type: filter datasource: jdbcUrl: jdbc:mariadb://localhost:3307/catalogdb username: root @@ -97,11 +99,10 @@ spring: naming-strategy: org.hibernate.cfg.ImprovedNamingStrategy enable-lazy-load-no-trans: true database-platform: org.hibernate.dialect.MySQL5InnoDBDialect - jersey: - type: filter + security: usercredentials: - - + - username: test password: '$2a$12$Zi3AuYcZoZO/gBQyUtST2.F5N6HqcTtaNci2Et.ufsQhski56srIu' role: InfraPortal-Client diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/schema.sql b/mso-api-handlers/mso-api-handler-infra/src/test/resources/schema.sql index bc9003f5d0..c2eb21b18e 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/resources/schema.sql +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/schema.sql @@ -1108,6 +1108,7 @@ CREATE TABLE `vnf_resource_customization` ( `CREATION_TIMESTAMP` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, `VNF_RESOURCE_MODEL_UUID` varchar(200) NOT NULL, `SERVICE_MODEL_UUID` varchar(200) NOT NULL, + `VNFCINSTANCEGROUP_ORDER` varchar(200) default NULL, PRIMARY KEY (`ID`), UNIQUE KEY `UK_vnf_resource_customization` (`MODEL_CUSTOMIZATION_UUID`,`SERVICE_MODEL_UUID`), KEY `fk_vnf_resource_customization__vnf_resource1_idx` (`VNF_RESOURCE_MODEL_UUID`), @@ -1134,6 +1135,8 @@ CREATE TABLE `vnfc_customization` ( `MODEL_NAME` varchar(200) NOT NULL, `TOSCA_NODE_TYPE` varchar(200) NOT NULL, `DESCRIPTION` varchar(1200) DEFAULT NULL, + `RESOURCE_INPUT` varchar(20000) DEFAULT NULL, + `VNFC_INSTANCE_GROUP_CUSTOMIZATION_ID` integer DEFAULT NULL, `CREATION_TIMESTAMP` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (`MODEL_CUSTOMIZATION_UUID`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; @@ -1460,6 +1463,16 @@ create table if not exists model ( FOREIGN KEY (`RECIPE`) REFERENCES `model_recipe` (`MODEL_ID`) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=latin1; +CREATE TABLE IF NOT EXISTS `requestdb`.`cloud_api_requests` ( +`ID` INT(13) NOT NULL AUTO_INCREMENT, +`REQUEST_BODY` LONGTEXT NOT NULL, +`CLOUD_IDENTIFIER` VARCHAR(200) NULL, +`SO_REQUEST_ID` VARCHAR(45) NOT NULL, +`CREATE_TIME` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, +PRIMARY KEY (`ID`), +INDEX `fk_cloud_api_requests__so_request_id_idx` (`SO_REQUEST_ID` ASC)) +ENGINE = InnoDB DEFAULT CHARSET=latin1; + CREATE TABLE IF NOT EXISTS `workflow` ( `ID` int(11) NOT NULL AUTO_INCREMENT, `ARTIFACT_UUID` varchar(200) NOT NULL, @@ -1477,8 +1490,3 @@ CREATE TABLE IF NOT EXISTS `workflow` ( PRIMARY KEY (`ID`), UNIQUE KEY `UK_workflow` (`ARTIFACT_UUID`,`NAME`,`VERSION`,`SOURCE`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; - - - - - |