diff options
Diffstat (limited to 'bpmn/MSOCommonBPMN/src')
60 files changed, 2095 insertions, 1630 deletions
diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/AaiUtil.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/AaiUtil.groovy index 2f4e70c893..8a262251b1 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/AaiUtil.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/AaiUtil.groovy @@ -26,6 +26,7 @@ import javax.ws.rs.core.UriBuilder import org.camunda.bpm.engine.delegate.BpmnError import org.camunda.bpm.engine.delegate.DelegateExecution +import org.onap.aai.domain.yang.GenericVnf import org.onap.so.bpmn.core.UrnPropertiesReader; import org.onap.so.client.aai.AAIVersion import org.onap.so.client.aai.entities.uri.AAIUri @@ -516,10 +517,10 @@ class AaiUtil { * @return moduleIndex * */ - public int getLowestUnusedVfModuleIndexFromAAIVnfResponse(DelegateExecution execution, String aaiVnfResponse, String key, String value) { + public int getLowestUnusedVfModuleIndexFromAAIVnfResponse(DelegateExecution execution, GenericVnf aaiVnfResponse, String key, String value) { if (aaiVnfResponse != null) { String vfModulesText = taskProcessor.utils.getNodeXml(aaiVnfResponse, "vf-modules") - if (vfModulesText == null || vfModulesText.isEmpty()) { + if (aaiVnfResponse.getVfModules() == null || aaiVnfResponse.getVfModules().getVfModule().isEmpty()) { msoLogger.debug("There are no VF modules in this VNF yet") return 0 } @@ -549,4 +550,3 @@ class AaiUtil { } } } - diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/AllottedResourceUtils.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/AllottedResourceUtils.groovy index e4bc5f8fa2..bb557a8285 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/AllottedResourceUtils.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/AllottedResourceUtils.groovy @@ -20,22 +20,25 @@ package org.onap.so.bpmn.common.scripts -import static org.apache.commons.lang3.StringUtils.*; +import org.onap.so.client.aai.entities.AAIResultWrapper + +import static org.apache.commons.lang3.StringUtils.isBlank; import javax.ws.rs.NotFoundException +import javax.ws.rs.core.UriBuilder -import org.apache.commons.lang3.* +import org.apache.commons.lang.StringUtils import org.camunda.bpm.engine.delegate.BpmnError -import org.camunda.bpm.engine.delegate.DelegateExecution; -import org.onap.so.bpmn.core.UrnPropertiesReader +import org.camunda.bpm.engine.delegate.DelegateExecution +import org.onap.aai.domain.yang.AllottedResource import org.onap.so.bpmn.core.WorkflowException -import org.onap.so.client.aai.AAIObjectType; +import org.onap.so.client.PreconditionFailedException +import org.onap.so.client.aai.AAIObjectType import org.onap.so.client.aai.AAIResourcesClient import org.onap.so.client.aai.entities.uri.AAIResourceUri import org.onap.so.client.aai.entities.uri.AAIUriFactory import org.onap.so.logger.MessageEnum import org.onap.so.logger.MsoLogger -import org.onap.so.rest.APIResponse; @@ -68,7 +71,6 @@ class AllottedResourceUtils { String arType = execution.getVariable("allottedResourceType") String arRole = execution.getVariable("allottedResourceRole") String siXml = execution.getVariable("CSI_service") - String ar = null String orchStatus = null XmlParser xmlParser = new XmlParser() msoLogger.debug("getAROrchStatus siXml:" + siXml) @@ -84,9 +86,8 @@ class AllottedResourceUtils { msoLogger.debug("getARORchStatus AR found") def groovy.util.Node relatedLink = utils.getChildNode(relationship, 'related-link') if (relatedLink != null){ - ar = getARbyLink(execution, relatedLink.text(), arRole) - if (!isBlank(ar)) - { + Optional<AllottedResource> ar = getARbyLink(execution, relatedLink.text(), arRole) + if (ar.isPresent()){ orchStatus = execution.getVariable("aaiAROrchStatus") break } @@ -106,16 +107,21 @@ class AllottedResourceUtils { // get Allotted Resource by AllottedResourceId // used on Delete - called from doDeleteAR // setsVariable aaiARGetResponse - public String getARbyId (DelegateExecution execution, String allottedResourceId) { - msoLogger.trace("getARbyId ") - AAIResourceUri arLink = getARLinkbyId(execution, allottedResourceId) - String ar = null - if (!isBlank(arLink)) - { - ar = getARbyLink(execution, arLink, "") + public boolean ifExistsAR(DelegateExecution execution, String allottedResourceId) { + msoLogger.trace("ifExistsAR ") + try { + AAIResourceUri resourceUri = AAIUriFactory.createResourceUri(AAIObjectType.ALLOTTED_RESOURCE, allottedResourceId) + AAIResultWrapper wrapper = getAAIClient().get(resourceUri) + Optional<AllottedResource> allottedResource = wrapper.asBean(AllottedResource.class) + if(allottedResource.isPresent()) { + setExecutionVariables(execution , allottedResource.get(),resourceUri) + return true + }else { + return false + } + }catch(Exception e){ + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error in ifExistsAR" + e.getMessage()) } - msoLogger.trace(" Exit GetARbyId - AR:" + ar) - return ar; } public String getPSIFmARLink(DelegateExecution execution, String arLink) @@ -128,141 +134,62 @@ class AllottedResourceUtils { msoLogger.trace(" Exit getARLinkbyId - parentServiceInstanceId:" + siId ) return siId } - - // get Allotted Resource Link by AllottedResourceId using Nodes Query - // used on Delete - called from getARbyId - public String getARLinkbyId (DelegateExecution execution, String allottedResourceId) { - msoLogger.trace("getARLinkbyId ") - String arLink = null - try { - AAIResourcesClient client = new AAIResourcesClient() - AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.ALLOTTED_RESOURCE, allottedResourceId) - AaiUtil aaiUtil = new AaiUtil() - arLink = aaiUtil.createAaiUri(uri) - } catch (NotFoundException e) { - msoLogger.debug("GET AR received a Not Found (404) Response") - } catch(Exception e){ - msoLogger.debug(" Error encountered within GetAaiAR" + e.getMessage()) - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error in GetARbyId" + e.getMessage()) - } - msoLogger.debug(" ***** Exit GetARLinkbyId ***** Link:" + arLink) - return arLink - } - + // get Allotted resource using Link // used on Create called from getARORchStatus - // used on Delete called from getARbyId + // used on Delete called from ifExistsAR // setsVariable aaiARPath - used for Patch in create - public String getARbyLink (DelegateExecution execution, String link, String role) { + + public Optional<AllottedResource> getARbyLink (DelegateExecution execution, String link, String role) { msoLogger.trace("getARbyLink ") - String ar = null - String arUrl = null + Optional<AllottedResource> allottedResource = Optional.empty() try { - AaiUtil aaiUriUtil = new AaiUtil(taskProcessor) - String aai_endpoint = UrnPropertiesReader.getVariable("aai.endpoint", execution) - String arEndpoint = "" - - if(!isBlank(link)) { - msoLogger.debug("Incoming AR Resource Link is: " + link) - String[] split = link.split("/aai/") - arEndpoint = "/aai/" + split[1] - } - - arUrl = "${aai_endpoint}" + arEndpoint - - msoLogger.debug("GET AR Aai Path is: \n" + arUrl) - - APIResponse response = aaiUriUtil.executeAAIGetCall(execution, arUrl) - int responseCode = response.getStatusCode() - msoLogger.debug(" GET AR response code is: " + responseCode) - - String aaiResponse = response.getResponseBodyAsString() - msoLogger.debug("GET AR:" + aaiResponse) - if(responseCode == 200 || responseCode == 202){ - msoLogger.debug("GET AR Received a Good Response Code") - if(utils.nodeExists(aaiResponse, "allotted-resource")){ - if (!isBlank(role)) - { - if (utils.nodeExists(aaiResponse, "role") && role.equals(utils.getNodeText(aaiResponse, "role"))) { - ar = aaiResponse - }else{ - msoLogger.debug("AAI AR does not match input role:" + role) - } - } - else - { - ar = aaiResponse + msoLogger.debug("GET AR Aai Path is: \n" + link) + AAIResourceUri uri = AAIUriFactory.createResourceFromExistingURI(AAIObjectType.ALLOTTED_RESOURCE, UriBuilder.fromPath(link).build()) + allottedResource = getAAIClient().get(AllottedResource.class,uri); + if(allottedResource.isPresent()) { + if (!isBlank(role)) { + if (role == allottedResource.get().getRole()) { + setExecutionVariables(execution,allottedResource.get(),uri) + } else { + msoLogger.debug("AAI AR does not match input role:" + role) } + } else { + setExecutionVariables(execution,allottedResource.get(),uri) } - else - { - msoLogger.debug("GET AR Does NOT Contain Data" ) - } - }else if(responseCode == 404){ + }else{ msoLogger.debug("GET AR received a Not Found (404) Response") } - else{ - msoLogger.debug(" GET AR received a Bad Response: \n" + aaiResponse) - buildAAIErrorResponse(execution, aaiResponse, "Error retrieving AR from AAI") - } }catch(Exception e){ msoLogger.debug(" Error encountered within GetAaiAR" + e.getMessage()) exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error in GetAaiAR" + e.getMessage()) } - if (!isBlank(ar)) - { - execution.setVariable("aaiARGetResponse", ar) - execution.setVariable("aaiARPath", arUrl) - - String resourceVersion = null - if (utils.nodeExists(ar, "resource-version")) { - resourceVersion = utils.getNodeText(ar, "resource-version") - execution.setVariable("aaiARResourceVersion", resourceVersion) - } + return allottedResource + } - String orchStatus = null - if (utils.nodeExists(ar, "orchestration-status")) { - orchStatus= utils.getNodeText(ar, "orchestration-status") - } - else - { - orchStatus = " " - } - execution.setVariable("aaiAROrchStatus", orchStatus) + public void setExecutionVariables(DelegateExecution execution, AllottedResource ar, AAIResourceUri arUrl) { + execution.setVariable("aaiARGetResponse", ar) + execution.setVariable("aaiARPath", arUrl.build().toString()) + execution.setVariable("aaiARResourceVersion", ar.getResourceVersion()) + if (StringUtils.isNotEmpty(ar.getOrchestrationStatus())) { + execution.setVariable("aaiAROrchStatus", ar.getOrchestrationStatus()) + } + else + { + execution.setVariable("aaiAROrchStatus", " ") } - msoLogger.trace(" Exit GetARbyLink - AR:" + ar) - return ar } public void updateAROrchStatus(DelegateExecution execution, String status, String aaiARPath){ msoLogger.trace("updaAROrchStatus ") try{ - String updateReq = """ - { - "orchestration-status": "${status}" - } - """ - + AllottedResource allottedResource = new AllottedResource(); + allottedResource.setOrchestrationStatus(status) msoLogger.debug('AAI AR URI: ' + aaiARPath) - AaiUtil aaiUriUtil = new AaiUtil(taskProcessor) - APIResponse apiResponse = aaiUriUtil.executeAAIPatchCall(execution, aaiARPath, updateReq) - def aaiResponse = apiResponse.getResponseBodyAsString() - def responseCode = apiResponse.getStatusCode() - - msoLogger.debug("AAI Response Code: " + responseCode) - msoLogger.debug("AAI Response: " + aaiResponse) - if(responseCode == 200){ - msoLogger.debug("UpdateAR Good REST Response is: " + "\n" + aaiResponse) - }else{ - msoLogger.debug("UpdateAROrchStatus Bad REST Response!") - buildAAIErrorResponse(execution, aaiResponse, "Error updating AR OrchStatus in AAI") - } - - }catch(BpmnError b){ - msoLogger.debug("Rethrowing MSOWorkflowException ") - throw b + AAIResourceUri uri = AAIUriFactory.createResourceFromExistingURI(AAIObjectType.ALLOTTED_RESOURCE, UriBuilder.fromPath(aaiARPath).build()) + getAAIClient().update(uri,allottedResource) }catch(Exception e){ msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception in updateAR.", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, e.getMessage()); exceptionUtil.buildAndThrowWorkflowException(execution, 500, 'Internal Error in updateAROrchStatus.' + e.getMessage()) @@ -274,39 +201,20 @@ class AllottedResourceUtils { public void deleteAR(DelegateExecution execution, String aaiARPath){ msoLogger.trace(" deleteAR - aaiARPath:" + aaiARPath) try { - AaiUtil aaiUriUtil = new AaiUtil(taskProcessor) - APIResponse response = aaiUriUtil.executeAAIDeleteCall(execution, aaiARPath) - int responseCode = response.getStatusCode() - execution.setVariable("deleteARResponseCode", responseCode) - - msoLogger.debug(" Delete AR response code:" + responseCode) - String aaiResponse = response.getResponseBodyAsString() - execution.setVariable("aaiARDeleteResponse", aaiResponse) - - msoLogger.debug("Delete AR Response:" + aaiResponse) - - //Process Response - if(responseCode == 204){ - msoLogger.debug(" Delete AR Received a Good Response") - execution.setVariable("wasDeleted", "true") - }else if(responseCode == 404){ - msoLogger.debug(" Delete AR Received a Not Found (404) Response") - }else if(responseCode == 412){ - msoLogger.debug("Delete AR Received a Resource Version Mismatch Error: \n" + aaiResponse) - exceptionUtil.buildAndThrowWorkflowException(execution, 412, "DeleteAR Received a resource-version Mismatch Error Response from AAI") - }else{ - msoLogger.debug("Delete AR Received a BAD REST Response: \n" + aaiResponse) - buildAAIErrorResponse(execution, aaiResponse, "Error deleting AR in AAI") - exceptionUtil.MapAAIExceptionToWorkflowExceptionGeneric(execution, aaiResponse, responseCode) - } - }catch(BpmnError b){ - msoLogger.debug("Rethrowing MSOWorkflowException") - throw b + AAIResourceUri uri = AAIUriFactory.createResourceFromExistingURI(AAIObjectType.ALLOTTED_RESOURCE, UriBuilder.fromPath(aaiARPath).build()) + getAAIClient().delete(uri); + }catch(NotFoundException ex){ + msoLogger.debug(" Delete AR Received a Not Found (404) Response") + }catch(PreconditionFailedException ex){ + msoLogger.debug("Delete AR Received a Resource Version Mismatch Error: \n") + exceptionUtil.buildAndThrowWorkflowException(execution, 412, "DeleteAR Received a resource-version Mismatch Error Response from AAI") }catch(Exception e){ msoLogger.debug(" Error encountered in deleteAR!" + e) exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured During Delete AR") } + msoLogger.debug(" Delete AR Received a Good Response") + execution.setVariable("wasDeleted", "true") msoLogger.trace("Exit deleteAR ") } @@ -323,5 +231,9 @@ class AllottedResourceUtils { msoLogger.trace("Exit BuildAAIErrorResponse Process") throw new BpmnError("MSOWorkflowException") } + + public AAIResourcesClient getAAIClient(){ + return new AAIResourcesClient() + } } diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/ConfirmVolumeGroupTenant.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/ConfirmVolumeGroupTenant.groovy index 13904c372d..47a4612672 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/ConfirmVolumeGroupTenant.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/ConfirmVolumeGroupTenant.groovy @@ -20,27 +20,17 @@ package org.onap.so.bpmn.common.scripts -import org.onap.so.bpmn.core.UrnPropertiesReader - -import javax.xml.parsers.DocumentBuilder -import javax.xml.parsers.DocumentBuilderFactory - -import org.apache.commons.lang3.* import org.camunda.bpm.engine.delegate.BpmnError import org.camunda.bpm.engine.delegate.DelegateExecution -import org.onap.so.bpmn.core.WorkflowException -import org.onap.so.rest.APIResponse -import org.w3c.dom.Document -import org.w3c.dom.Element -import org.w3c.dom.Node -import org.w3c.dom.NodeList -import org.xml.sax.InputSource -import org.onap.so.logger.MessageEnum -import org.onap.so.logger.MsoLogger +import org.onap.aai.domain.yang.VolumeGroup import org.onap.so.client.aai.AAIObjectType +import org.onap.so.client.aai.entities.AAIResultWrapper +import org.onap.so.client.aai.entities.Relationships import org.onap.so.client.aai.entities.uri.AAIResourceUri import org.onap.so.client.aai.entities.uri.AAIUriFactory import org.onap.so.constants.Defaults +import org.onap.so.logger.MessageEnum +import org.onap.so.logger.MsoLogger /** * Vnf Module Subflow for confirming the volume group belongs @@ -59,60 +49,26 @@ class ConfirmVolumeGroupTenant extends AbstractServiceTaskProcessor{ public void preProcessRequest(DelegateExecution execution){ execution.setVariable("prefix", Prefix) msoLogger.trace("STARTED Confirm Volume Group Tenant Subflow ") - String processKey = getProcessKey(execution); try{ msoLogger.trace("Started QueryAAIForVolumeGroup Process ") String volumeGroupId = execution.getVariable("volumeGroupId") String incomingGroupName = execution.getVariable("volumeGroupName") String incomingTenantId = execution.getVariable("tenantId") - def aicCloudRegion = execution.getVariable("aicCloudRegion") - - AaiUtil aaiUriUtil = new AaiUtil(this) + String aicCloudRegion = execution.getVariable("aicCloudRegion") AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.VOLUME_GROUP, Defaults.CLOUD_OWNER.toString(), aicCloudRegion, volumeGroupId) - String path = aaiUriUtil.createAaiUri(uri) - - APIResponse queryAAIForVolumeGroupResponse = aaiUriUtil.executeAAIGetCall(execution, path) - - def responseCode = queryAAIForVolumeGroupResponse.getStatusCode() - execution.setVariable("queryVolumeGroupResponseCode", responseCode) - String response = queryAAIForVolumeGroupResponse.getResponseBodyAsString() - - msoLogger.debug("ConfirmVolumeGroup Response: " + response) - msoLogger.debug("ConfirmVolumeGroup Response Code: " + responseCode) - - if(responseCode == 200 && response != null){ - execution.setVariable("queryAAIVolumeGroupResponse", response) - msoLogger.debug("QueryAAIForVolumeGroup Received a Good REST Response is: \n" + response) - + AAIResultWrapper wrapper = getAAIClient().get(uri); + Optional<VolumeGroup> volumeGroup = wrapper.asBean(VolumeGroup.class) + Optional<Relationships> relationships = wrapper.getRelationships() + if(volumeGroup.isPresent()){ + execution.setVariable("queryAAIVolumeGroupResponse", volumeGroup.get()) String volumeGroupTenantId = "" - InputSource source = new InputSource(new StringReader(response)); - DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); - docFactory.setNamespaceAware(true) - DocumentBuilder docBuilder = docFactory.newDocumentBuilder() - Document createVCERequestXml = docBuilder.parse(source) - NodeList nodeList = createVCERequestXml.getElementsByTagNameNS("*", "relationship") - for (int x = 0; x < nodeList.getLength(); x++) { - Node node = nodeList.item(x) - if (node.getNodeType() == Node.ELEMENT_NODE) { - Element eElement = (Element) node - String e = eElement.getElementsByTagNameNS("*", "related-to").item(0).getTextContent() - if(e.equals("tenant")){ - NodeList relationDataList = eElement.getElementsByTagNameNS("*", "relationship-data") - for (int d = 0; d < relationDataList.getLength(); d++) { - Node dataNode = relationDataList.item(d) - if (dataNode.getNodeType() == Node.ELEMENT_NODE) { - Element dElement = (Element) dataNode - String key = dElement.getElementsByTagNameNS("*", "relationship-key").item(0).getTextContent() - if(key.equals("tenant.tenant-id")){ - volumeGroupTenantId = dElement.getElementsByTagNameNS("*", "relationship-value").item(0).getTextContent() - } - } - } - } + if(relationships.isPresent()){ + List<AAIResourceUri> tenantUris = relationships.get().getRelatedAAIUris(AAIObjectType.TENANT) + for (AAIResourceUri tenantURI: tenantUris){ + volumeGroupTenantId = tenantURI.getURIKeys().get("tenant-id") } } - //Determine if Tenant Ids match if(incomingTenantId.equals(volumeGroupTenantId)){ msoLogger.debug("Tenant Ids Match") @@ -123,7 +79,7 @@ class ConfirmVolumeGroupTenant extends AbstractServiceTaskProcessor{ } //Determine if Volume Group Names match - String volumeGroupName = utils.getNodeText(response, "volume-group-name") + String volumeGroupName = volumeGroup.get().getVolumeGroupName() if(incomingGroupName == null || incomingGroupName.length() < 1){ msoLogger.debug("Incoming Volume Group Name is NOT Provided.") execution.setVariable("groupNamesMatch", true) @@ -145,7 +101,7 @@ class ConfirmVolumeGroupTenant extends AbstractServiceTaskProcessor{ }catch(BpmnError b){ throw b }catch(Exception e){ - msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception Occured Processing queryAAIForVolumeGroup.", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, e); + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception Occured Processing queryAAIForVolumeGroup.", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, e.getMessage()); exceptionUtil.buildAndThrowWorkflowException(execution, 5000, "Internal Error - Occured in preProcessRequest.") } msoLogger.trace("COMPLETED queryAAIForVolumeGroup Process ") @@ -156,8 +112,8 @@ class ConfirmVolumeGroupTenant extends AbstractServiceTaskProcessor{ try{ msoLogger.trace("Started assignVolumeHeatId Process ") - String response = execution.getVariable("queryAAIVolumeGroupResponse") - String heatStackId = utils.getNodeText(response, "heat-stack-id") + VolumeGroup volumeGroup = execution.getVariable("queryAAIVolumeGroupResponse") + String heatStackId = volumeGroup.getHeatStackId() execution.setVariable("volumeHeatStackId", heatStackId) execution.setVariable("ConfirmVolumeGroupTenantResponse", heatStackId) // TODO: Should deprecate use of processKey+Response variable for the response. Will use "WorkflowResponse" instead diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/CreateAAIVfModule.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/CreateAAIVfModule.groovy index d4777e234c..48268464d8 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/CreateAAIVfModule.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/CreateAAIVfModule.groovy @@ -20,22 +20,24 @@ package org.onap.so.bpmn.common.scripts import org.camunda.bpm.engine.delegate.DelegateExecution +import org.onap.aai.domain.yang.GenericVnf import org.onap.so.bpmn.core.RollbackData +import org.onap.so.client.aai.AAIObjectPlurals import org.onap.so.client.aai.AAIObjectType 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.onap.so.db.catalog.beans.OrchestrationStatus import org.onap.so.logger.MessageEnum import org.onap.so.logger.MsoLogger -import org.onap.so.rest.APIResponse public class CreateAAIVfModule extends AbstractServiceTaskProcessor{ private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, CreateAAIVfModule.class); - def Prefix="CAAIVfMod_" + def prefix="CAAIVfMod_" ExceptionUtil exceptionUtil = new ExceptionUtil() public void initProcessVariables(DelegateExecution execution) { - execution.setVariable("prefix",Prefix) + execution.setVariable("prefix",prefix) execution.setVariable("CAAIVfMod_vnfId",null) execution.setVariable("CAAIVfMod_vnfName",null) execution.setVariable("CAAIVfMod_vnfType",null) @@ -168,38 +170,26 @@ public class CreateAAIVfModule extends AbstractServiceTaskProcessor{ // send a GET request to AA&I to retrieve the Generic VNF/VF Module information based on a Vnf Name // expect a 200 response with the information in the response body or a 404 if the Generic VNF does not exist public void queryAAIForGenericVnf(DelegateExecution execution) { - - AaiUtil aaiUtil = new AaiUtil(this) + AAIResourceUri uri - def vnfId = execution.getVariable("CAAIVfMod_vnfId") def vnfName = execution.getVariable("CAAIVfMod_vnfName") - if (vnfId == null || vnfId.isEmpty()) { - uri = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, "") + uri = AAIUriFactory.createResourceUri(AAIObjectPlurals.GENERIC_VNF) uri.queryParam("vnf-name", vnfName) } else { uri = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId) } - uri.depth(Depth.ONE) - String endPoint = aaiUtil.createAaiUri(uri) - try { - msoLogger.debug("queryAAIForGenericVnf() endpoint-" + endPoint) - msoLogger.debug("invoking GET call to AAI endpoint :"+System.lineSeparator()+endPoint) - msoLogger.debug("CreateAAIVfModule sending GET call to AAI Endpoint: " + endPoint) - - APIResponse response = aaiUtil.executeAAIGetCall(execution, endPoint) - def responseData = response.getResponseBodyAsString() - def statusCode = response.getStatusCode() - execution.setVariable("CAAIVfMod_queryGenericVnfResponseCode", statusCode) - execution.setVariable("CAAIVfMod_queryGenericVnfResponse", responseData) - - msoLogger.debug("CreateAAIVfModule Response Code: " + statusCode) - msoLogger.debug("CreateAAIVfModule Response data: " + responseData) - msoLogger.debug("Response code:" + statusCode) - msoLogger.debug("Response:" + System.lineSeparator()+responseData) + Optional<GenericVnf> genericVnfOp = getAAIClient().get(GenericVnf.class, uri) + if(genericVnfOp.isPresent()){ + execution.setVariable("CAAIVfMod_queryGenericVnfResponseCode", 200) + execution.setVariable("CAAIVfMod_queryGenericVnfResponse", genericVnfOp.get()) + }else{ + execution.setVariable("CAAIVfMod_queryGenericVnfResponseCode", 404) + execution.setVariable("CAAIVfMod_queryGenericVnfResponse", "Generic Vnf not Found!") + } } catch (Exception ex) { msoLogger.debug("Exception occurred while executing AAI GET:" + ex.getMessage()) exceptionUtil.buildAndThrowWorkflowException(execution, 5000, "Internal Error - Occured in queryAAIForGenericVnf.") @@ -238,36 +228,20 @@ public class CreateAAIVfModule extends AbstractServiceTaskProcessor{ def newVnfId = UUID.randomUUID().toString() execution.setVariable("CAAIVfMod_vnfId",newVnfId) - String payload = """<generic-vnf xmlns="${execution.getVariable("CAAIVfMod_aaiNamespace")}"> - <vnf-id>${MsoUtils.xmlEscape(newVnfId)}</vnf-id> - <vnf-name>${MsoUtils.xmlEscape(execution.getVariable("CAAIVfMod_vnfName"))}</vnf-name> - <vnf-type>${MsoUtils.xmlEscape(execution.getVariable("CAAIVfMod_vnfType"))}</vnf-type> - <service-id>${MsoUtils.xmlEscape(execution.getVariable("CAAIVfMod_serviceId"))}</service-id> - <orchestration-status>Active</orchestration-status> - <model-invariant-id>${MsoUtils.xmlEscape(execution.getVariable("CAAIVfMod_vnfPersonaId"))}</model-invariant-id> - <model-version-id>${MsoUtils.xmlEscape(execution.getVariable("CAAIVfMod_vnfPersonaVer"))}</model-version-id> - </generic-vnf>""" as String - execution.setVariable("CAAIVfMod_createGenericVnfPayload", payload) + GenericVnf genericVnf = new GenericVnf() + genericVnf.setVnfId(newVnfId) + genericVnf.setVnfName(execution.getVariable("CAAIVfMod_vnfName")) + genericVnf.setVnfType(execution.getVariable("CAAIVfMod_vnfType")) + genericVnf.setServiceId(execution.getVariable("CAAIVfMod_serviceId")) + genericVnf.setOrchestrationStatus(OrchestrationStatus.ACTIVE.toString()) + genericVnf.setModelInvariantId(execution.getVariable("CAAIVfMod_vnfPersonaId")) + genericVnf.setModelVersionId(execution.getVariable("CAAIVfMod_vnfPersonaVer")) try { - AaiUtil aaiUtil = new AaiUtil(this) AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, newVnfId) - String endPoint = aaiUtil.createAaiUri(uri) - - msoLogger.debug("createGenericVnf() endpoint-" + endPoint) - msoLogger.debug("invoking PUT call to AAI with payload:"+System.lineSeparator()+payload) - msoLogger.debug("Sending PUT call to AAI with Endpoint /n" + endPoint + " with payload /n" + payload) - - APIResponse response = aaiUtil.executeAAIPutCall(execution, endPoint, payload); - def responseData = response.getResponseBodyAsString() - def responseStatusCode = response.getStatusCode() - execution.setVariable("CAAIVfMod_createGenericVnfResponseCode", responseStatusCode) - execution.setVariable("CAAIVfMod_createGenericVnfResponse", responseData) - - msoLogger.debug("Response Code: " + responseStatusCode) - msoLogger.debug("Response Data: " + responseData) - msoLogger.debug("Response code:" + responseStatusCode) - msoLogger.debug("Response:" + System.lineSeparator()+responseData) + getAAIClient().create(uri,genericVnf) + execution.setVariable("CAAIVfMod_createGenericVnfResponseCode", 201) + execution.setVariable("CAAIVfMod_createGenericVnfResponse", "Vnf Created") } catch (Exception ex) { ex.printStackTrace() msoLogger.debug("Exception occurred while executing AAI PUT:" + ex.getMessage()) @@ -289,22 +263,8 @@ public class CreateAAIVfModule extends AbstractServiceTaskProcessor{ int moduleIndex = 0 if (!isBaseModule) { - def aaiVnfResponse = execution.getVariable("CAAIVfMod_queryGenericVnfResponse") - AaiUtil aaiUtil = new AaiUtil(this) - def personaModelId = execution.getVariable("CAAIVfMod_personaId") - - // Check if the response includes model-invariant-id or persona-model-id - // note: getRequiredNodeText() throws an exception if the field is missing - // need to retun a null for the subsequent "either/or" logic to work properly -// def modelInvariantId = getRequiredNodeText(execution, aaiVnfResponse,'model-invariant-id') - def modelInvariantId = getNodeText(aaiVnfResponse,'model-invariant-id', null) - def fieldToCheck = 'model-invariant-id' - if (!modelInvariantId) { - fieldToCheck = 'persona-model-id' - } - - moduleIndex = aaiUtil.getLowestUnusedVfModuleIndexFromAAIVnfResponse(execution, aaiVnfResponse, - fieldToCheck, personaModelId) + GenericVnf aaiVnfResponse = execution.getVariable("CAAIVfMod_queryGenericVnfResponse") + moduleIndex = getLowestUnusedVfModuleIndexFromAAIVnfResponse(aaiVnfResponse,execution) } // if we get to this point, we may be about to create the Vf Module, @@ -318,38 +278,26 @@ public class CreateAAIVfModule extends AbstractServiceTaskProcessor{ rollbackData.put("VFMODULE", "isBaseModule", isBaseModule.toString()) execution.setVariable("RollbackData", rollbackData) msoLogger.debug("RollbackData:" + rollbackData) - String payload = """<vf-module xmlns="${execution.getVariable("CAAIVfMod_aaiNamespace")}"> - <vf-module-id>${MsoUtils.xmlEscape(newModuleId)}</vf-module-id> - <vf-module-name>${MsoUtils.xmlEscape(execution.getVariable("CAAIVfMod_moduleName"))}</vf-module-name> - <model-invariant-id>${MsoUtils.xmlEscape(execution.getVariable("CAAIVfMod_personaId"))}</model-invariant-id> - <model-version-id>${MsoUtils.xmlEscape(execution.getVariable("CAAIVfMod_personaVer"))}</model-version-id> - <model-customization-id>${MsoUtils.xmlEscape(execution.getVariable("CAAIVfMod_modelCustomizationId"))}</model-customization-id> - <is-base-vf-module>${MsoUtils.xmlEscape(isBaseModule)}</is-base-vf-module> - <orchestration-status>PendingCreate</orchestration-status> - <module-index>${MsoUtils.xmlEscape(moduleIndex)}</module-index> - </vf-module>""" as String - execution.setVariable("CAAIVfMod_createVfModulePayload", payload) + + org.onap.aai.domain.yang.VfModule vfModule = new org.onap.aai.domain.yang.VfModule() + vfModule.setVfModuleId(newModuleId) + vfModule.setVfModuleName(execution.getVariable("CAAIVfMod_moduleName")) + vfModule.setModelInvariantId(execution.getVariable("CAAIVfMod_personaId")) + vfModule.setModelVersionId(execution.getVariable("CAAIVfMod_personaVer")) + vfModule.setModelCustomizationId(execution.getVariable("CAAIVfMod_modelCustomizationId")) + vfModule.setIsBaseVfModule(isBaseModule) + vfModule.setOrchestrationStatus(OrchestrationStatus.PENDING_CREATE.toString()) + vfModule.setModuleIndex(moduleIndex) try { - - AaiUtil aaiUtil = new AaiUtil(this) - AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.VF_MODULE, vnfId, newModuleId) - String endPoint = aaiUtil.createAaiUri(uri) - - msoLogger.debug("createVfModule() endpoint-" + endPoint) - msoLogger.debug("invoking PUT call to AAI with payload:"+System.lineSeparator()+payload) - msoLogger.debug("CreateAAIVfModule sending PUT call to AAI with endpoint /n" + endPoint + " with payload /n " + payload) - APIResponse response = aaiUtil.executeAAIPutCall(execution, endPoint, payload) - def responseData = response.getResponseBodyAsString() - def statusCode = response.getStatusCode() + AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.VF_MODULE, vnfId, newModuleId) + getAAIClient().create(uri,vfModule) + def statusCode = 201 execution.setVariable("CAAIVfMod_createVfModuleResponseCode", statusCode) - execution.setVariable("CAAIVfMod_createVfModuleResponse", responseData) - - msoLogger.debug("Response code:" + statusCode) - msoLogger.debug("Response:" + System.lineSeparator()+responseData) - msoLogger.debug("Response Code: " + statusCode) - msoLogger.debug("Response data: " + responseData) + execution.setVariable("CAAIVfMod_createVfModuleResponse", "Vf Module Created") + + // the base or add-on VF Module was successfully created, // add the module name to the rollback data and the response if (isOneOf(statusCode, 200, 201)) { @@ -384,26 +332,55 @@ public class CreateAAIVfModule extends AbstractServiceTaskProcessor{ msoLogger.debug("CreateAAIVfModule Response /n " + responseOut) } } catch (Exception ex) { + execution.setVariable("CAAIVfMod_createVfModuleResponseCode", 500) + execution.setVariable("CAAIVfMod_createVfModuleResponse", ex.getMessage()) msoLogger.debug("Exception occurred while executing AAI PUT:" + ex.getMessage()) exceptionUtil.buildAndThrowWorkflowException(execution, 5000, "Internal Error - Occured in createVfModule.") } } - + + private int getLowestUnusedVfModuleIndexFromAAIVnfResponse(GenericVnf genericVnf,DelegateExecution execution){ + String personaModelId = execution.getVariable("CAAIVfMod_personaId") + if(genericVnf!=null && genericVnf.getVfModules()!= null && + !genericVnf.getVfModules().getVfModule().isEmpty()){ + Set<Integer> moduleIndices = new TreeSet<>() + for(org.onap.aai.domain.yang.VfModule vfModule in genericVnf.getVfModules().getVfModule()){ + if(genericVnf.getModelInvariantId()==null){ + if(vfModule.getPersonaModelVersion().equals(personaModelId) && vfModule.getModuleIndex()!=null) + moduleIndices.add(vfModule.getModuleIndex()) + }else{ + if(vfModule.getModelInvariantId().equals(personaModelId) && vfModule.getModuleIndex()!=null) + moduleIndices.add(vfModule.getModuleIndex()) + } + } + for(i in 0..moduleIndices.size()-1){ + if(moduleIndices.getAt(i) != i){ + return i; + } + } + return moduleIndices.size() + }else{ + return 0 + } + + } + // parses the output from the result from queryAAIForGenericVnf() to determine if the vf-module-name // requested for an Add-on VF Module does not already exist for the specified Generic VNF // also retrieves VNF name from AAI response for existing VNF public void parseForAddOnModule(DelegateExecution execution) { - def xml = execution.getVariable("CAAIVfMod_queryGenericVnfResponse") - def vnfNameFromAAI = utils.getNodeText(xml, "vnf-name") + GenericVnf genericVnf = execution.getVariable("CAAIVfMod_queryGenericVnfResponse") + def vnfNameFromAAI = genericVnf.getVnfName() execution.setVariable("CAAIVfMod_vnfNameFromAAI", vnfNameFromAAI) msoLogger.debug("Obtained vnf-name from AAI for existing VNF: " + vnfNameFromAAI) def newModuleName = execution.getVariable("CAAIVfMod_moduleName") msoLogger.debug("VF Module to be added: " + newModuleName) - def qryModuleNameList = utils.getMultNodes(xml, "vf-module-name") execution.setVariable("CAAIVfMod_moduleExists", false) - if (qryModuleNameList != null) { - msoLogger.debug("Existing VF Module List: " + qryModuleNameList) - for (String qryModuleName : qryModuleNameList) { + if (genericVnf !=null && genericVnf.getVfModules()!=null && !genericVnf.getVfModules().getVfModule().isEmpty()) { + def qryModuleList = genericVnf.getVfModules().getVfModule() + msoLogger.debug("Existing VF Module List: " + qryModuleList) + for (org.onap.aai.domain.yang.VfModule qryModule : qryModuleList) { + def qryModuleName = qryModule.getVfModuleName() if (newModuleName.equals(qryModuleName)) { // a module with the requested name already exists - failure msoLogger.debug("VF Module " + qryModuleName + " already exists for Generic VNF " + vnfNameFromAAI) @@ -425,32 +402,32 @@ public class CreateAAIVfModule extends AbstractServiceTaskProcessor{ // requested for an Add-on VF Module does not already exist for the specified Generic VNF; // also retrieves VNF name from AAI response for existing VNF public void parseForBaseModule(DelegateExecution execution) { - def xml = execution.getVariable("CAAIVfMod_queryGenericVnfResponse") - def vnfNameFromAAI = utils.getNodeText(xml, "vnf-name") + GenericVnf genericVnf = execution.getVariable("CAAIVfMod_queryGenericVnfResponse") + def vnfNameFromAAI = genericVnf.getVnfName() execution.setVariable("CAAIVfMod_vnfNameFromAAI", vnfNameFromAAI) msoLogger.debug("Obtained vnf-name from AAI for existing VNF: " + vnfNameFromAAI) def newModuleName = execution.getVariable("CAAIVfMod_moduleName") msoLogger.debug("VF Module to be added: " + newModuleName) - def qryModuleNameList = utils.getMultNodes(xml, "vf-module-name") + def qryModuleList = genericVnf !=null ? genericVnf.getVfModules():null; execution.setVariable("CAAIVfMod_moduleExists", false) - if (qryModuleNameList != null) { - msoLogger.debug("Existing VF Module List: " + qryModuleNameList) - for (String qryModuleName : qryModuleNameList) { - if (newModuleName.equals(qryModuleName)) { + if (qryModuleList != null && !qryModuleList.getVfModule().isEmpty()) { + def qryModules = qryModuleList.getVfModule() + msoLogger.debug("Existing VF Module List: " + qryModules) + for (org.onap.aai.domain.yang.VfModule qryModule : qryModules) { + if (newModuleName.equals(qryModule.getVfModuleName())) { // a module with the requested name already exists - failure - msoLogger.debug("VF Module " + qryModuleName + " already exists for Generic VNF " + vnfNameFromAAI) + msoLogger.debug("VF Module " + qryModule.getVfModuleName() + " already exists for Generic VNF " + vnfNameFromAAI) execution.setVariable("CAAIVfMod_baseModuleConflict", true) execution.setVariable("CAAIVfMod_parseModuleResponse", - "VF Module " + qryModuleName + " already exists for Generic VNF " + vnfNameFromAAI) + "VF Module " + qryModule.getVfModuleName() + " already exists for Generic VNF " + vnfNameFromAAI) break } } } - def isBaseVfModuleList = utils.getMultNodes(xml, "is-base-vf-module") - if (isBaseVfModuleList != null && !execution.getVariable("CAAIVfMod_baseModuleConflict")) { - - for (String baseValue : isBaseVfModuleList) { - if (baseValue.equals("true")) { + if (qryModuleList != null && !qryModuleList.getVfModule().isEmpty() && !execution.getVariable("CAAIVfMod_baseModuleConflict")) { + def qryModules = qryModuleList.getVfModule() + for (org.onap.aai.domain.yang.VfModule qryModule : qryModules) { + if (qryModule.isBaseVfModule) { // a base module already exists in this VNF - failure msoLogger.debug("Base VF Module already exists for Generic VNF " + vnfNameFromAAI) execution.setVariable("CAAIVfMod_baseModuleConflict", true) diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/CreateAAIVfModuleVolumeGroup.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/CreateAAIVfModuleVolumeGroup.groovy index cc1be47029..075068513a 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/CreateAAIVfModuleVolumeGroup.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/CreateAAIVfModuleVolumeGroup.groovy @@ -22,12 +22,9 @@ package org.onap.so.bpmn.common.scripts import org.camunda.bpm.engine.delegate.BpmnError import org.camunda.bpm.engine.delegate.DelegateExecution -import org.onap.so.bpmn.core.UrnPropertiesReader import org.onap.so.client.aai.AAIObjectType import org.onap.so.client.aai.entities.uri.AAIResourceUri import org.onap.so.client.aai.entities.uri.AAIUriFactory -import org.onap.so.rest.APIResponse -import org.onap.so.logger.MessageEnum import org.onap.so.logger.MsoLogger public class CreateAAIVfModuleVolumeGroup extends AbstractServiceTaskProcessor { @@ -110,24 +107,17 @@ public class CreateAAIVfModuleVolumeGroup extends AbstractServiceTaskProcessor { try { def vnfId = execution.getVariable('CAAIVfModVG_vnfId') def vfModuleId = execution.getVariable('CAAIVfModVG_vfModuleId') - - AaiUtil aaiUtil = new AaiUtil(this) - AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.VF_MODULE, vnfId, vfModuleId) - String endPoint = aaiUtil.createAaiUri(uri) - try { - msoLogger.debug('sending GET to AAI endpoint \'' + endPoint + '\'') - msoLogger.debug("aaiResponse GET TO AAI Endpoint: " + endPoint) - APIResponse response = aaiUtil.executeAAIGetCall(execution, endPoint) - def responseData = response.getResponseBodyAsString() - execution.setVariable('CAAIVfModVG_getVfModuleResponseCode', response.getStatusCode()) - execution.setVariable('CAAIVfModVG_getVfModuleResponse', responseData) - - msoLogger.debug("CreateAAIVfModule Response Code: " + response.getStatusCode()) - msoLogger.debug("CreateAAIVfModule Response: " + response) - msoLogger.debug('Response code:' + response.getStatusCode()) - msoLogger.debug('Response:' + System.lineSeparator() + responseData) - } catch (Exception ex) { + AAIResourceUri resourceUri = AAIUriFactory.createResourceUri(AAIObjectType.VF_MODULE, vnfId, vfModuleId); + Optional<org.onap.aai.domain.yang.VfModule> vfModule = getAAIClient().get(org.onap.aai.domain.yang.VfModule.class, resourceUri) + if(vfModule.isPresent()){ + execution.setVariable('CAAIVfModVG_getVfModuleResponseCode', 200) + execution.setVariable('CAAIVfModVG_getVfModuleResponse', vfModule.get()) + }else{ + execution.setVariable('CAAIVfModVG_getVfModuleResponseCode', 404) + execution.setVariable('CAAIVfModVG_getVfModuleResponse', "VF-Module Not found!!") + } + }catch (Exception ex) { ex.printStackTrace() msoLogger.debug('Exception occurred while executing AAI GET:' + ex.getMessage()) execution.setVariable('CAAIVfModVG_getVfModuleResponseCode', 500) @@ -157,12 +147,10 @@ public class CreateAAIVfModuleVolumeGroup extends AbstractServiceTaskProcessor { try { def vnfId = execution.getVariable('CAAIVfModVG_vnfId') def vfModuleId = execution.getVariable('CAAIVfModVG_vfModuleId') - def vfModule = execution.getVariable('CAAIVfModVG_getVfModuleResponse') - def origRequest = execution.getVariable('CreateAAIVfModuleVolumeGroupRequest') - def Node vfModuleNode = xmlParser.parseText(vfModule) - + org.onap.aai.domain.yang.VfModule vfModule = execution.getVariable('CAAIVfModVG_getVfModuleResponse') + // Confirm resource-version is in retrieved VF Module - if (utils.getChildNode(vfModuleNode, 'resource-version') == null) { + if (vfModule.getResourceVersion() == null) { def msg = 'Can\'t update VF Module ' + vfModuleId + ' since \'resource-version\' is missing' msoLogger.error( msg); throw new Exception(msg) @@ -172,26 +160,16 @@ public class CreateAAIVfModuleVolumeGroup extends AbstractServiceTaskProcessor { def aicCloudRegion = execution.getVariable('CAAIVfModVG_aicCloudRegion') def cloudOwner = execution.getVariable('CAAIVfModVG_cloudOwner') def volumeGroupId = execution.getVariable('CAAIVfModVG_volumeGroupId') - def Node vgRelationshipNode = createVolumeGroupRelationshipNode(cloudOwner, aicCloudRegion, volumeGroupId) - insertVolumeGroupRelationshipNode(vfModuleNode, vgRelationshipNode) - def payload = utils.nodeToString(vfModuleNode) - AaiUtil aaiUtil = new AaiUtil(this) - AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.VF_MODULE, vnfId, vfModuleId) - String endPoint = aaiUtil.createAaiUri(uri) - try { - msoLogger.debug("CreateAAIVfModuleVolume Sendind PUT to AAI Endpoint \n " + endPoint + " with payload \n " + payload) - msoLogger.debug('sending PUT to AAI endpoint \'' + endPoint + '\'' + 'with payload \n' + payload) - APIResponse response = aaiUtil.executeAAIPutCall(execution, endPoint, payload) - def responseData = response.getResponseBodyAsString() - execution.setVariable('CAAIVfModVG_updateVfModuleResponseCode', response.getStatusCode()) - execution.setVariable('CAAIVfModVG_updateVfModuleResponse', responseData) - - msoLogger.debug("CreateAAIVfModule Response code: " + response.getStatusCode()) - msoLogger.debug("CreateAAIVfModule Response: " + responseData) - msoLogger.debug('Response code:' + response.getStatusCode()) - msoLogger.debug('Response:' + System.lineSeparator() + responseData) + AAIResourceUri vfModuleUri = AAIUriFactory.createResourceUri(AAIObjectType.VF_MODULE, vnfId,vfModuleId); + AAIResourceUri volumeGroupUri = AAIUriFactory.createResourceUri(AAIObjectType.VOLUME_GROUP, cloudOwner, aicCloudRegion,volumeGroupId); + msoLogger.debug("Creating relationship between Vf Module: " + vfModuleUri.build().toString() + " and Volume Group: " + volumeGroupUri.build().toString()) + getAAIClient().connect(vfModuleUri,volumeGroupUri) + execution.setVariable('CAAIVfModVG_updateVfModuleResponseCode', 200) + execution.setVariable('CAAIVfModVG_updateVfModuleResponse', "Success") + msoLogger.debug("CreateAAIVfModule Response code: " + 200) + msoLogger.debug("CreateAAIVfModule Response: " + "Success") } catch (Exception ex) { ex.printStackTrace() msoLogger.debug('Exception occurred while executing AAI PUT:' + ex.getMessage()) @@ -206,72 +184,6 @@ public class CreateAAIVfModuleVolumeGroup extends AbstractServiceTaskProcessor { exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in updateVfModule(): ' + e.getMessage()) } } - - /** - * Construct a Volume Group relationship Node with the given AIC Cloud Region and - * Volume Group ID for insertion into a VF Module. - * - * @param aicCloudRegion Cloud Region ID to use in the Volume Group relationship - * @param volumeGroupId Volume Group ID to use in the Volume Group relationship - * @return a Node representing the new Volume Group relationship - */ - private Node createVolumeGroupRelationshipNode(String cloudOwner, String aicCloudRegion, String volumeGroupId) { - - def Node relatedTo = new Node(null, 'related-to', 'volume-group') - - def Node relationshipKeyCO = new Node(null, 'relationship-key', 'cloud-region.cloud-owner') - def Node relationshipValueCO = new Node(null, 'relationship-value', cloudOwner) - def Node relationshipDataCO = new Node(null, 'relationship-data') - relationshipDataCO.append(relationshipKeyCO) - relationshipDataCO.append(relationshipValueCO) - - def Node relationshipKeyCRI = new Node(null, 'relationship-key', 'cloud-region.cloud-region-id') - def Node relationshipValueCRI = new Node(null, 'relationship-value', aicCloudRegion) - def Node relationshipDataCRI = new Node(null, 'relationship-data') - relationshipDataCRI.append(relationshipKeyCRI) - relationshipDataCRI.append(relationshipValueCRI) - - def Node relationshipKeyVGI = new Node(null, 'relationship-key', 'volume-group.volume-group-id') - def Node relationshipValueVGI = new Node(null, 'relationship-value', volumeGroupId) - def Node relationshipDataVGI = new Node(null, 'relationship-data') - relationshipDataVGI.append(relationshipKeyVGI) - relationshipDataVGI.append(relationshipValueVGI) - - def Node volumeGroupRelationship = new Node(null, 'relationship') - volumeGroupRelationship.append(relatedTo) - volumeGroupRelationship.append(relationshipDataCO) - volumeGroupRelationship.append(relationshipDataCRI) - volumeGroupRelationship.append(relationshipDataVGI) - - return volumeGroupRelationship; - } - - /** - * Insert the given Volume Group relationship Node into the given VF Module. - * If the VF Module does NOT contain a relationship list: - * - Create a relationship list containing the Volume Group relationship and insert it into the VF Module - * If the VF Module contains a relationship list but not a Volume Group relationship: - * - Insert the the Volume Group relationship into the relationship lsit - * If the VF Module contains a relationship list and has a Volume Group relationship: - * - Replace the existing Volume Group relationship with the new one - * @param vfModuleNode - * @param volumeGroupRelationshipNode - */ - private void insertVolumeGroupRelationshipNode(Node vfModuleNode, Node volumeGroupRelationshipNode) { - def Node relationshipList = utils.getChildNode(vfModuleNode, 'relationship-list') - if (relationshipList == null) { - relationshipList = new Node(null, 'relationship-list') - relationshipList.append(volumeGroupRelationshipNode) - vfModuleNode.append(relationshipList) - } else { - def Node currVolumeGroupRelationshipNode = getCurrVolumeGroupRelationshipNode(relationshipList) - if (currVolumeGroupRelationshipNode == null) { - relationshipList.append(volumeGroupRelationshipNode) - } else { - currVolumeGroupRelationshipNode.replaceNode(volumeGroupRelationshipNode) - } - } - } /** * Find and return the value of the Volume Group ID for the specified VF Module. If diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/DeleteAAIVfModule.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/DeleteAAIVfModule.groovy index 6da1f6d6ff..b8df241913 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/DeleteAAIVfModule.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/DeleteAAIVfModule.groovy @@ -20,15 +20,11 @@ package org.onap.so.bpmn.common.scripts import org.camunda.bpm.engine.delegate.DelegateExecution -import org.onap.so.bpmn.core.WorkflowException -import org.onap.so.bpmn.core.UrnPropertiesReader +import org.onap.aai.domain.yang.GenericVnf import org.onap.so.client.aai.AAIObjectType 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.onap.so.rest.APIResponse -import org.onap.so.rest.RESTClient; -import org.onap.so.rest.RESTConfig; import org.onap.so.logger.MessageEnum import org.onap.so.logger.MsoLogger @@ -83,15 +79,16 @@ public class DeleteAAIVfModule extends AbstractServiceTaskProcessor{ AaiUtil aaiUriUtil = new AaiUtil(this) AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId) uri.depth(Depth.ONE) - String endPoint = aaiUriUtil.createAaiUri(uri) - - APIResponse response = aaiUriUtil.executeAAIGetCall(execution, endPoint) - - msoLogger.debug('Response code:' + response.getStatusCode()) - msoLogger.debug('Response:' + response.getResponseBodyAsString()) + Optional<GenericVnf> genericVnf = getAAIClient().get(GenericVnf.class, uri) + + if(genericVnf.isPresent()) { + execution.setVariable("DAAIVfMod_queryGenericVnfResponseCode", 200) + execution.setVariable("DAAIVfMod_queryGenericVnfResponse", genericVnf.get()) - execution.setVariable("DAAIVfMod_queryGenericVnfResponseCode", response.getStatusCode()) - execution.setVariable("DAAIVfMod_queryGenericVnfResponse", response.getResponseBodyAsString()) + }else{ + execution.setVariable("DAAIVfMod_queryGenericVnfResponseCode", 404) + execution.setVariable("DAAIVfMod_queryGenericVnfResponse", "Vnf Not Found!") + } } catch (Exception ex) { msoLogger.debug("Exception occurred while executing AAI GET:" + ex.getMessage()) @@ -106,20 +103,10 @@ public class DeleteAAIVfModule extends AbstractServiceTaskProcessor{ try { String vnfId = execution.getVariable("DAAIVfMod_vnfId") - String resourceVersion = execution.getVariable("DAAIVfMod_genVnfRsrcVer") - - AaiUtil aaiUriUtil = new AaiUtil(this) AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId) - uri.resourceVersion(resourceVersion) - String endPoint = aaiUriUtil.createAaiUri(uri) - - APIResponse response = aaiUriUtil.executeAAIDeleteCall(execution, endPoint) - - def responseData = response.getResponseBodyAsString() - execution.setVariable("DAAIVfMod_deleteGenericVnfResponseCode", response.getStatusCode()) - execution.setVariable("DAAIVfMod_deleteGenericVnfResponse", responseData) - msoLogger.debug("Response code:" + response.getStatusCode()) - msoLogger.debug("Response:" + System.lineSeparator() + responseData) + getAAIClient().delete(uri) + execution.setVariable("DAAIVfMod_deleteGenericVnfResponseCode", 200) + execution.setVariable("DAAIVfMod_deleteGenericVnfResponse", "Vnf Deleted") } catch (Exception ex) { ex.printStackTrace() msoLogger.debug("Exception occurred while executing AAI DELETE:" + ex.getMessage()) @@ -133,22 +120,12 @@ public class DeleteAAIVfModule extends AbstractServiceTaskProcessor{ try { String vnfId = execution.getVariable("DAAIVfMod_vnfId") String vfModuleId = execution.getVariable("DAAIVfMod_vfModuleId") - String resourceVersion = execution.getVariable("DAAIVfMod_vfModRsrcVer") - AaiUtil aaiUriUtil = new AaiUtil(this) AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.VF_MODULE, vnfId, vfModuleId) - uri.resourceVersion(resourceVersion) - String endPoint = aaiUriUtil.createAaiUri(uri) - - APIResponse response = aaiUriUtil.executeAAIDeleteCall(execution, endPoint) - - responseData = response.getResponseBodyAsString() - execution.setVariable("DAAIVfMod_deleteVfModuleResponseCode", response.getStatusCode()) - execution.setVariable("DAAIVfMod_deleteVfModuleResponse", responseData) - msoLogger.debug("DeleteAAIVfModule - AAI Response" + responseData) - msoLogger.debug("Response code:" + response.getStatusCode()) - msoLogger.debug("Response:" + System.lineSeparator() + responseData) + getAAIClient().delete(uri) + execution.setVariable("DAAIVfMod_deleteVfModuleResponseCode", 200) + execution.setVariable("DAAIVfMod_deleteVfModuleResponse", "Vf Module Deleted") } catch (Exception ex) { ex.printStackTrace() msoLogger.debug("Exception occurred while executing AAI PUT:" + ex.getMessage()) @@ -160,88 +137,66 @@ public class DeleteAAIVfModule extends AbstractServiceTaskProcessor{ // to be deleted exists for the specified Generic Vnf and if it is the Base Module, // there are no Add-on Modules present public void parseForVfModule(DelegateExecution execution) { - def xml = execution.getVariable("DAAIVfMod_queryGenericVnfResponse") - msoLogger.debug("DeleteAAIVfModule - queryGenericVnfResponse" + xml) + GenericVnf genericVnf = execution.getVariable("DAAIVfMod_queryGenericVnfResponse") def delModuleId = execution.getVariable("DAAIVfMod_vfModuleId") msoLogger.debug("Vf Module to be deleted: " + delModuleId) - List <String> qryModuleIdList = utils.getMultNodes(xml, "vf-module-id") - List <String> qryBaseModuleList = utils.getMultNodes(xml, "is-base-vf-module") - List <String> qryResourceVerList = utils.getMultNodes(xml, "resource-version") - execution.setVariable("DAAIVfMod_moduleExists", false) - execution.setVariable("DAAIVfMod_isBaseModule", false) - execution.setVariable("DAAIVfMod_isLastModule", false) - // - def isBaseVfModule = "false" - // loop through the Vf Module Ids looking for a match - if (qryModuleIdList != null && !qryModuleIdList.empty) { - msoLogger.debug("Existing Vf Module Id List: " + qryModuleIdList) - msoLogger.debug("Existing Vf Module Resource Version List: " + qryResourceVerList) - def moduleCntr = 0 - // the Generic Vnf resource-version in the 1st entry in the query response - execution.setVariable("DAAIVfMod_genVnfRsrcVer", qryResourceVerList[moduleCntr]) - for (String qryModuleId : qryModuleIdList) { - if (delModuleId.equals(qryModuleId)) { - // a Vf Module with the requested Id exists - execution.setVariable("DAAIVfMod_moduleExists", true) - // find the corresponding value for the is-base-vf-module field - isBaseVfModule = qryBaseModuleList[moduleCntr] - // find the corresponding value for the resource-version field - // note: the Generic Vnf entry also has a resource-version field, so - // add 1 to the index to get the corresponding Vf Module value - execution.setVariable("DAAIVfMod_vfModRsrcVer", qryResourceVerList[moduleCntr+1]) - msoLogger.debug("Match found for Vf Module Id " + qryModuleId + " for Generic Vnf Id " + execution.getVariable("DAAIVfMod_vnfId") + ", Base Module is " + isBaseVfModule + ", Resource Version is " + execution.getVariable("vfModRsrcVer")) - break - } - moduleCntr++ - } - } - - // determine if the module to be deleted is a Base Module and/or the Last Module - if (execution.getVariable("DAAIVfMod_moduleExists") == true) { - if (isBaseVfModule.equals("true") && qryModuleIdList.size() != 1) { - execution.setVariable("DAAIVfMod_parseModuleResponse", - "Found Vf Module Id " + delModuleId + " for Generic Vnf Id " + - execution.getVariable("DAAIVfMod_vnfId") + ": is Base Module, not Last Module") - execution.setVariable("DAAIVfMod_isBaseModule", true) - } else { - if (isBaseVfModule.equals("true") && qryModuleIdList.size() == 1) { - execution.setVariable("DAAIVfMod_parseModuleResponse", - "Found Vf Module Id " + delModuleId + " for Generic Vnf Id " + - execution.getVariable("DAAIVfMod_vnfId") + ": is Base Module and Last Module") - execution.setVariable("DAAIVfMod_isBaseModule", true) - execution.setVariable("DAAIVfMod_isLastModule", true) - } else { - if (qryModuleIdList.size() == 1) { - execution.setVariable("DAAIVfMod_parseModuleResponse", - "Found Vf Module Id " + delModuleId + " for Generic Vnf Id " + - execution.getVariable("DAAIVfMod_vnfId") + ": is Not Base Module, is Last Module") - execution.setVariable("DAAIVfMod_isLastModule", true) - } else { - execution.setVariable("DAAIVfMod_parseModuleResponse", - "Found Vf Module Id " + delModuleId + " for Generic Vnf Id " + - execution.getVariable("DAAIVfMod_vnfId") + ": is Not Base Module and Not Last Module") - } - } - } - msoLogger.debug(execution.getVariable("DAAIVfMod_parseModuleResponse")) - } else { // (execution.getVariable("DAAIVfMod_moduleExists") == false) - msoLogger.debug("Vf Module Id " + delModuleId + " does not exist for Generic Vnf Id " + execution.getVariable("DAAIVfMod_vnfId")) - execution.setVariable("DAAIVfMod_parseModuleResponse", - "Vf Module Id " + delModuleId + " does not exist for Generic Vnf Id " + - execution.getVariable("DAAIVfMod_vnfName")) - } + + execution.setVariable("DAAIVfMod_genVnfRsrcVer", genericVnf.getResourceVersion()) + + execution.setVariable("DAAIVfMod_moduleExists", false) + execution.setVariable("DAAIVfMod_isBaseModule", false) + execution.setVariable("DAAIVfMod_isLastModule", false) + if(genericVnf.getVfModules()!= null && !genericVnf.getVfModules().getVfModule().isEmpty()){ + Optional<org.onap.aai.domain.yang.VfModule> vfModule = genericVnf.getVfModules().getVfModule().stream(). + filter{ v -> v.getVfModuleId().equals(delModuleId)}.findFirst() + if(vfModule.isPresent()){ + execution.setVariable("DAAIVfMod_moduleExists", true) + execution.setVariable("DAAIVfMod_vfModRsrcVer", vfModule.get().getResourceVersion()) + + if (vfModule.get().isBaseVfModule && genericVnf.getVfModules().getVfModule().size() != 1) { + execution.setVariable("DAAIVfMod_parseModuleResponse", + "Found Vf Module Id " + delModuleId + " for Generic Vnf Id " + + execution.getVariable("DAAIVfMod_vnfId") + ": is Base Module, not Last Module") + execution.setVariable("DAAIVfMod_isBaseModule", true) + } else { + if (vfModule.get().isBaseVfModule && genericVnf.getVfModules().getVfModule().size() == 1) { + execution.setVariable("DAAIVfMod_parseModuleResponse", + "Found Vf Module Id " + delModuleId + " for Generic Vnf Id " + + execution.getVariable("DAAIVfMod_vnfId") + ": is Base Module and Last Module") + execution.setVariable("DAAIVfMod_isBaseModule", true) + execution.setVariable("DAAIVfMod_isLastModule", true) + } else { + if (genericVnf.getVfModules().getVfModule().size() == 1) { + execution.setVariable("DAAIVfMod_parseModuleResponse", + "Found Vf Module Id " + delModuleId + " for Generic Vnf Id " + + execution.getVariable("DAAIVfMod_vnfId") + ": is Not Base Module, is Last Module") + execution.setVariable("DAAIVfMod_isLastModule", true) + } else { + execution.setVariable("DAAIVfMod_parseModuleResponse", + "Found Vf Module Id " + delModuleId + " for Generic Vnf Id " + + execution.getVariable("DAAIVfMod_vnfId") + ": is Not Base Module and Not Last Module") + } + } + } + msoLogger.debug(execution.getVariable("DAAIVfMod_parseModuleResponse")) + } + } + if (execution.getVariable("DAAIVfMod_moduleExists") == false) { // (execution.getVariable("DAAIVfMod_moduleExists") == false) + msoLogger.debug("Vf Module Id " + delModuleId + " does not exist for Generic Vnf Id " + execution.getVariable("DAAIVfMod_vnfId")) + execution.setVariable("DAAIVfMod_parseModuleResponse", + "Vf Module Id " + delModuleId + " does not exist for Generic Vnf Id " + + execution.getVariable("DAAIVfMod_vnfName")) + } } // parses the output from the result from queryAAIForGenericVnf() to determine if the Vf Module // to be deleted exists for the specified Generic Vnf and if it is the Base Module, // there are no Add-on Modules present public void parseForResourceVersion(DelegateExecution execution) { - def xml = execution.getVariable("DAAIVfMod_queryGenericVnfResponse") - msoLogger.debug("DeleteAAIVfModule - queryGenericVnfResponse" + xml) - String resourceVer = utils.getNodeText(xml, "resource-version") - execution.setVariable("DAAIVfMod_genVnfRsrcVer", resourceVer) - msoLogger.debug("Latest Generic VNF Resource Version: " + resourceVer) + GenericVnf genericVnf = execution.getVariable("DAAIVfMod_queryGenericVnfResponse") + execution.setVariable("DAAIVfMod_genVnfRsrcVer", genericVnf.getResourceVersion()) + msoLogger.debug("Latest Generic VNF Resource Version: " + genericVnf.getResourceVersion()) } @@ -303,4 +258,4 @@ public class DeleteAAIVfModule extends AbstractServiceTaskProcessor{ msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "AAI error occurred deleting the Generic Vnf", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, execution.getVariable("DAAIVfMod_deleteGenericVnfResponse")); exceptionUtil.buildAndThrowWorkflowException(execution, 5000, execution.getVariable("DAAIVfMod_deleteGenericVnfResponse")) } -}
\ No newline at end of file +} diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/NetworkUtils.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/NetworkUtils.groovy index 1e8569c3e7..a1e63dc150 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/NetworkUtils.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/NetworkUtils.groovy @@ -18,31 +18,24 @@ * ============LICENSE_END========================================================= */ -package org.onap.so.bpmn.common.scripts; +package org.onap.so.bpmn.common.scripts -import javax.ws.rs.core.UriBuilder -import javax.xml.parsers.DocumentBuilder -import javax.xml.parsers.DocumentBuilderFactory -import javax.xml.transform.Transformer -import javax.xml.transform.TransformerFactory -import javax.xml.transform.dom.DOMSource -import javax.xml.transform.stream.StreamResult - -import org.apache.commons.lang3.* +import groovy.xml.XmlUtil import org.camunda.bpm.engine.delegate.DelegateExecution import org.onap.so.bpmn.core.UrnPropertiesReader -import org.onap.so.client.aai.AAIObjectType -import org.onap.so.client.aai.entities.uri.AAIResourceUri -import org.onap.so.client.aai.entities.uri.AAIUriFactory import org.onap.so.logger.MsoLogger import org.w3c.dom.Document import org.w3c.dom.Element import org.w3c.dom.Node -import org.w3c.dom.NodeList; +import org.w3c.dom.NodeList import org.xml.sax.InputSource -import groovy.xml.XmlUtil - +import javax.xml.parsers.DocumentBuilder +import javax.xml.parsers.DocumentBuilderFactory +import javax.xml.transform.Transformer +import javax.xml.transform.TransformerFactory +import javax.xml.transform.dom.DOMSource +import javax.xml.transform.stream.StreamResult /** * This groovy class supports the any Network processes that need the methods defined here. @@ -318,46 +311,6 @@ class NetworkUtils { return requestPayload } - - def String createCloudRegionVolumeRequest(groupId, volumeName, vnfType, vnfId, tenantId, cloudOwner, cloudRegion, namespace, modelCustomizationId) { - - String requestPayload = - """<volume-group xmlns="${namespace}"> - <volume-group-id>${MsoUtils.xmlEscape(groupId)}</volume-group-id> - <volume-group-name>${MsoUtils.xmlEscape(volumeName)}</volume-group-name> - <heat-stack-id></heat-stack-id> - <vnf-type>${MsoUtils.xmlEscape(vnfType)}</vnf-type> - <orchestration-status>Pending</orchestration-status> - <vf-module-model-customization-id>${MsoUtils.xmlEscape(modelCustomizationId)}</vf-module-model-customization-id> - <relationship-list> - <relationship> - <related-to>generic-vnf</related-to> - <relationship-data> - <relationship-key>generic-vnf.vnf-id</relationship-key> - <relationship-value>${MsoUtils.xmlEscape(vnfId)}</relationship-value> - </relationship-data> - </relationship> - <relationship> - <related-to>tenant</related-to> - <relationship-data> - <relationship-key>tenant.tenant-id</relationship-key> - <relationship-value>${MsoUtils.xmlEscape(tenantId)}</relationship-value> - </relationship-data> - <relationship-data> - <relationship-key>cloud-region.cloud-owner</relationship-key> - <relationship-value>${cloudOwner}</relationship-value> - </relationship-data> - <relationship-data> - <relationship-key>cloud-region.cloud-region-id</relationship-key> - <relationship-value>${MsoUtils.xmlEscape(cloudRegion)}</relationship-value> - </relationship-data> - </relationship> - </relationship-list> - </volume-group>""" - - return requestPayload - } - /** * This method returns the string for Update Volume Request payload @@ -783,68 +736,7 @@ class NetworkUtils { return rtn } - def isVfRelationshipExist(xmlInput) { - Boolean rtn = false - if (xmlInput!=null) { - def relationshipList = getListWithElements(xmlInput, 'relationship') - def relationshipListSize = relationshipList.size() - if (relationshipListSize > 0) { - for (i in 0..relationshipListSize-1) { - def relationshipXml = XmlUtil.serialize(relationshipList[i]) - if (utils.getNodeText(relationshipXml, 'related-to') == "vf-module") { - rtn = true - } - } - } - } - return rtn - - } - - def getCloudRegion(xmlInput) { - String lcpCloudRegion = "" - if (xmlInput!=null) { - def relationshipList = getListWithElements(xmlInput, 'relationship') - def relationshipListSize = relationshipList.size() - if (relationshipListSize > 0) { - for (i in 0..relationshipListSize-1) { - def relationshipXml = XmlUtil.serialize(relationshipList[i]) - if (utils.getNodeText(relationshipXml, 'related-to') == "cloud-region") { - def relatedLink = utils.getNodeText(relationshipXml, 'related-link') - if (relatedLink != null || relatedLink != "") { - AAIResourceUri aaiUri = AAIUriFactory.createResourceFromExistingURI(AAIObjectType.CLOUD_REGION, UriBuilder.fromUri(relatedLink).build()) - lcpCloudRegion = aaiUri.getURIKeys().getOrDefault("cloud-region", "") - } - } - } - } - } - return lcpCloudRegion - } - - def getTenantId(xmlInput) { - String tenantId = "" - if (xmlInput!=null) { - def relationshipList = getListWithElements(xmlInput, 'relationship') - def relationshipListSize = relationshipList.size() - if (relationshipListSize > 0) { - for (i in 0..relationshipListSize-1) { - def relationshipXml = XmlUtil.serialize(relationshipList[i]) - if (utils.getNodeText(relationshipXml, 'related-to') == "tenant") { - def relatedLink = utils.getNodeText(relationshipXml, 'related-link') - if (relatedLink != null || relatedLink != "") { - tenantId = relatedLink.substring(relatedLink.indexOf("/tenant/")+8, relatedLink.length()) - if (tenantId.contains('/')) { - tenantId = relatedLink.substring(relatedLink.indexOf("/tenant/")+8, relatedLink.length()-1) - } - } - } - } - } - } - return tenantId - } - + def isInstanceValueMatch(linkResource, globalSubscriberId, serviceType) { Boolean rtn = false try { diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/SDNCAdapterUtils.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/SDNCAdapterUtils.groovy index 58c8f27de9..32d1ee74bf 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/SDNCAdapterUtils.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/SDNCAdapterUtils.groovy @@ -20,9 +20,9 @@ package org.onap.so.bpmn.common.scripts; -import org.apache.commons.lang3.* import org.camunda.bpm.engine.delegate.BpmnError import org.camunda.bpm.engine.delegate.DelegateExecution +import org.onap.aai.domain.yang.L3Network import org.onap.so.bpmn.core.WorkflowException import org.onap.so.bpmn.core.json.JsonUtils; import org.springframework.web.util.UriUtils @@ -495,7 +495,7 @@ class SDNCAdapterUtils { * @param additionalData additional XML content to be inserted into the * RequestData element (may be null) */ - public String sdncTopologyRequestV2 (DelegateExecution execution, String requestXML, String serviceInstanceId, String callbackUrl, String action, String requestAction, String cloudRegionId, networkId, String queryAAIResponse, String additionalData) { + public String sdncTopologyRequestV2 (DelegateExecution execution, String requestXML, String serviceInstanceId, String callbackUrl, String action, String requestAction, String cloudRegionId, networkId, L3Network queryAAIResponse, String additionalData) { def utils=new MsoUtils() // SNDC is expecting request Id for header as unique each call. @@ -526,7 +526,7 @@ class SDNCAdapterUtils { // Replace/Use the value of network-type from aai query (vs input) during Delete Network flows. if (queryAAIResponse != null) { - networkType = utils.getNodeText(queryAAIResponse, "network-type") + networkType = queryAAIResponse.getNetworkType() } String serviceId = "" @@ -536,7 +536,7 @@ class SDNCAdapterUtils { String networkName = "" // Replace/Use the value of network-name from aai query (vs input) if it was already set in AAI if (queryAAIResponse != null) { - networkName = utils.getNodeText(queryAAIResponse, "network-name") + networkName = queryAAIResponse.getNetworkName() } if (networkName.isEmpty() && utils.nodeExists(requestXML, "network-name")) { networkName = utils.getNodeText(requestXML, "network-name") diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/UpdateAAIGenericVnf.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/UpdateAAIGenericVnf.groovy index 3e7c4f2d49..5eb72bb2f2 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/UpdateAAIGenericVnf.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/UpdateAAIGenericVnf.groovy @@ -22,14 +22,12 @@ package org.onap.so.bpmn.common.scripts import org.camunda.bpm.engine.delegate.BpmnError import org.camunda.bpm.engine.delegate.DelegateExecution +import org.onap.aai.domain.yang.GenericVnf import org.onap.so.bpmn.core.WorkflowException -import org.onap.so.bpmn.core.UrnPropertiesReader import org.onap.so.client.aai.AAIObjectType 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.onap.so.rest.APIResponse -import org.springframework.web.util.UriUtils import org.onap.so.logger.MessageEnum import org.onap.so.logger.MsoLogger @@ -37,7 +35,7 @@ import org.onap.so.logger.MsoLogger public class UpdateAAIGenericVnf extends AbstractServiceTaskProcessor { - private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, UpdateAAIGenericVnf.class); + private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, UpdateAAIGenericVnf.class) private XmlParser xmlParser = new XmlParser() @@ -109,9 +107,9 @@ public class UpdateAAIGenericVnf extends AbstractServiceTaskProcessor { msoLogger.trace('Exited ' + method) } catch (BpmnError e) { - throw e; + throw e } catch (Exception e) { - msoLogger.error(e); + msoLogger.error(e) exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in preProcessRequest(): ' + e.getMessage()) } } @@ -131,34 +129,26 @@ public class UpdateAAIGenericVnf extends AbstractServiceTaskProcessor { try { def vnfId = execution.getVariable('UAAIGenVnf_vnfId') - // Construct endpoint - AaiUtil aaiUriUtil = new AaiUtil(this) AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId) uri.depth(Depth.ONE) - String endPoint = aaiUriUtil.createAaiUri(uri) - try { - msoLogger.debug('sending GET to AAI endpoint \'' + endPoint + '\'') - msoLogger.debug("Sending GET to AAI endpoint: " + endPoint) - - APIResponse response = aaiUriUtil.executeAAIGetCall(execution, endPoint) - def responseData = response.getResponseBodyAsString() - execution.setVariable('UAAIGenVnf_getGenericVnfResponseCode', response.getStatusCode()) - execution.setVariable('UAAIGenVnf_getGenericVnfResponse', responseData) - msoLogger.debug("UpdateAAIGenericVnf Response data: " + responseData) - msoLogger.debug('Response code:' + response.getStatusCode()) - msoLogger.debug('Response:' + System.lineSeparator() + responseData) - } catch (Exception ex) { - msoLogger.error(e); + Optional<GenericVnf> genericVnf = getAAIClient().get(GenericVnf.class,uri) + if(genericVnf.isPresent()){ + execution.setVariable('UAAIGenVnf_getGenericVnfResponseCode', 200) + execution.setVariable('UAAIGenVnf_getGenericVnfResponse', genericVnf.get()) + }else{ + execution.setVariable('UAAIGenVnf_getGenericVnfResponseCode', 404) + execution.setVariable('UAAIGenVnf_getGenericVnfResponse', "Generic VNF not found for VNF ID: "+vnfId) + } + }catch (Exception ex) { + msoLogger.error(ex.getMessage()) msoLogger.debug('Exception occurred while executing AAI GET:' + ex.getMessage()) execution.setVariable('UAAIGenVnf_getGenericVnfResponseCode', 500) execution.setVariable('UAAIGenVnf_getGenericVnfResponse', 'AAI GET Failed:' + ex.getMessage()) } msoLogger.trace('Exited ' + method) - } catch (BpmnError e) { - throw e; } catch (Exception e) { - msoLogger.error(e); + msoLogger.error(e) exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in getGenericVnf(): ' + e.getMessage()) } } @@ -176,38 +166,19 @@ public class UpdateAAIGenericVnf extends AbstractServiceTaskProcessor { try { def vnfId = execution.getVariable('UAAIGenVnf_vnfId') - def genericVnf = execution.getVariable('UAAIGenVnf_getGenericVnfResponse') + GenericVnf genericVnf = execution.getVariable('UAAIGenVnf_getGenericVnfResponse') def origRequest = execution.getVariable('UpdateAAIGenericVnfRequest') msoLogger.debug("UpdateGenericVnf Request: " + origRequest) - // Confirm resource-version is in retrieved Generic VNF - def Node genericVnfNode = xmlParser.parseText(genericVnf) - if (utils.getChildNode(genericVnfNode, 'resource-version') == null) { - def msg = 'Can\'t update Generic VNF ' + vnfId + ' since \'resource-version\' is missing' - msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, msg, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, ""); - throw new Exception(msg) - } - // Handle persona-model-id/persona-model-version - def String newPersonaModelId = execution.getVariable('UAAIGenVnf_personaModelId') - def String newPersonaModelVersion = execution.getVariable('UAAIGenVnf_personaModelVersion') - def String personaModelVersionEntry = "" + String newPersonaModelId = execution.getVariable('UAAIGenVnf_personaModelId') + String newPersonaModelVersion = execution.getVariable('UAAIGenVnf_personaModelVersion') + String personaModelVersionEntry = "" if (newPersonaModelId != null || newPersonaModelVersion != null) { - - // Confirm "new" persona-model-id is same as "current" persona-model-id - def Node currPersonaModelIdNode = utils.getChildNode(genericVnfNode, 'model-invariant-id') - if (currPersonaModelIdNode == null) { - // check the old attribute name - currPersonaModelIdNode = utils.getChildNode(genericVnfNode, 'persona-model-id') - } - def String currPersonaModelId = '' - if (currPersonaModelIdNode != null) { - currPersonaModelId = currPersonaModelIdNode.text() - } - if (!newPersonaModelId.equals(currPersonaModelId)) { + if (newPersonaModelId != genericVnf.getModelInvariantId()) { def msg = 'Can\'t update Generic VNF ' + vnfId + ' since there is \'persona-model-id\' mismatch between the current and new values' - msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, msg, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, ""); + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, msg, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "") throw new Exception(msg) } @@ -216,24 +187,24 @@ public class UpdateAAIGenericVnf extends AbstractServiceTaskProcessor { } // Handle ipv4-oam-address - def String ipv4OamAddress = execution.getVariable('UAAIGenVnf_ipv4OamAddress') - def String ipv4OamAddressEntry = "" + String ipv4OamAddress = execution.getVariable('UAAIGenVnf_ipv4OamAddress') + String ipv4OamAddressEntry = "" if (ipv4OamAddress != null) { // Construct payload ipv4OamAddressEntry = updateGenericVnfNode(origRequest, genericVnfNode, 'ipv4-oam-address') } // Handle management-v6-address - def String managementV6Address = execution.getVariable('UAAIGenVnf_managementV6Address') - def String managementV6AddressEntry = "" + String managementV6Address = execution.getVariable('UAAIGenVnf_managementV6Address') + String managementV6AddressEntry = "" if (managementV6Address != null) { // Construct payload managementV6AddressEntry = updateGenericVnfNode(origRequest, genericVnfNode, 'management-v6-address') } // Handle orchestration-status - def String orchestrationStatus = execution.getVariable('UAAIGenVnf_orchestrationStatus') - def String orchestrationStatusEntry = "" + String orchestrationStatus = execution.getVariable('UAAIGenVnf_orchestrationStatus') + String orchestrationStatusEntry = "" if (orchestrationStatus != null) { // Construct payload orchestrationStatusEntry = updateGenericVnfNode(origRequest, genericVnfNode, 'orchestration-status') @@ -248,22 +219,10 @@ public class UpdateAAIGenericVnf extends AbstractServiceTaskProcessor { } """ - // Construct endpoint - AaiUtil aaiUriUtil = new AaiUtil(this) AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId) - String endPoint = aaiUriUtil.createAaiUri(uri) try { - msoLogger.debug('sending PATCH to AAI endpoint \'' + endPoint + '\'' + 'with payload \n' + payload) - msoLogger.debug("Sending PATCH to AAI endpoint: " + endPoint) - - APIResponse response = aaiUriUtil.executeAAIPatchCall(execution, endPoint, payload) - def responseData = response.getResponseBodyAsString() - execution.setVariable('UAAIGenVnf_updateGenericVnfResponseCode', response.getStatusCode()) - execution.setVariable('UAAIGenVnf_updateGenericVnfResponse', responseData) - msoLogger.debug("UpdateAAIGenericVnf Response Data: " + responseData) - msoLogger.debug('Response code:' + response.getStatusCode()) - msoLogger.debug('Response:' + System.lineSeparator() + responseData) + getAAIClient().update(uri,payload) } catch (Exception ex) { ex.printStackTrace() msoLogger.debug('Exception occurred while executing AAI PATCH:' + ex.getMessage()) @@ -271,10 +230,8 @@ public class UpdateAAIGenericVnf extends AbstractServiceTaskProcessor { execution.setVariable('UAAIGenVnf_updateGenericVnfResponse', 'AAI PATCH Failed:' + ex.getMessage()) } msoLogger.trace('Exited ' + method) - } catch (BpmnError e) { - throw e; } catch (Exception e) { - msoLogger.error(e); + msoLogger.error(e) exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in updateGenericVnf(): ' + e.getMessage()) } } @@ -293,7 +250,7 @@ public class UpdateAAIGenericVnf extends AbstractServiceTaskProcessor { } def elementValue = utils.getNodeText(origRequest, elementName) - if (elementValue.equals('DELETE')) { + if (elementValue == 'DELETE') { // Set the element being deleted to null return """"${elementName}": null,""" } @@ -314,8 +271,8 @@ public class UpdateAAIGenericVnf extends AbstractServiceTaskProcessor { ')' msoLogger.trace('Entered ' + method) - msoLogger.error( 'Error occurred attempting to query AAI, Response Code ' + execution.getVariable('UAAIGenVnf_getGenericVnfResponseCode')); - String processKey = getProcessKey(execution); + msoLogger.error( 'Error occurred attempting to query AAI, Response Code ' + execution.getVariable('UAAIGenVnf_getGenericVnfResponseCode')) + String processKey = getProcessKey(execution) WorkflowException exception = new WorkflowException(processKey, 5000, execution.getVariable('UAAIGenVnf_getGenericVnfResponse')) execution.setVariable('WorkflowException', exception) @@ -335,9 +292,9 @@ public class UpdateAAIGenericVnf extends AbstractServiceTaskProcessor { ')' msoLogger.trace('Entered ' + method) - msoLogger.error('Error occurred attempting to update Generic VNF in AAI, Response Code ' + execution.getVariable('UAAIGenVnf_updateGenericVnfResponseCode')); + msoLogger.error('Error occurred attempting to update Generic VNF in AAI, Response Code ' + execution.getVariable('UAAIGenVnf_updateGenericVnfResponseCode')) - String processKey = getProcessKey(execution); + String processKey = getProcessKey(execution) WorkflowException exception = new WorkflowException(processKey, 5000, execution.getVariable('UAAIGenVnf_updateGenericVnfResponse')) execution.setVariable('WorkflowException', exception) @@ -345,4 +302,4 @@ public class UpdateAAIGenericVnf extends AbstractServiceTaskProcessor { msoLogger.debug("Workflow Exception occurred when Updating GenericVnf: " + exception.getErrorMessage()) msoLogger.trace('Exited ' + method) } -}
\ No newline at end of file +} diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/UpdateAAIVfModule.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/UpdateAAIVfModule.groovy index c455ae90ce..6691a82352 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/UpdateAAIVfModule.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/UpdateAAIVfModule.groovy @@ -20,21 +20,17 @@ package org.onap.so.bpmn.common.scripts +import javax.ws.rs.NotFoundException + import org.camunda.bpm.engine.delegate.BpmnError import org.camunda.bpm.engine.delegate.DelegateExecution import org.onap.so.bpmn.core.WorkflowException -import org.onap.so.bpmn.core.UrnPropertiesReader import org.onap.so.client.aai.AAIObjectType import org.onap.so.client.aai.entities.uri.AAIResourceUri import org.onap.so.client.aai.entities.uri.AAIUriFactory -import org.onap.so.rest.APIResponse -import org.springframework.web.util.UriUtils -import org.onap.so.logger.MessageEnum import org.onap.so.logger.MsoLogger - - public class UpdateAAIVfModule extends AbstractServiceTaskProcessor { private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, UpdateAAIVfModule.class); @@ -106,29 +102,21 @@ public class UpdateAAIVfModule extends AbstractServiceTaskProcessor { try { def vnfId = execution.getVariable('UAAIVfMod_vnfId') def vfModuleId = execution.getVariable('UAAIVfMod_vfModuleId') - - AaiUtil aaiUriUtil = new AaiUtil(this) - AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.VF_MODULE, vnfId, vfModuleId) - String endPoint = aaiUriUtil.createAaiUri(uri) - try { - msoLogger.debug('sending GET to AAI endpoint \'' + endPoint + '\'') - msoLogger.debug("UpdateAAIVfModule sending GET to AAI endpoint: " + endPoint) - - APIResponse response = aaiUriUtil.executeAAIGetCall(execution, endPoint) - def responseData = response.getResponseBodyAsString() - execution.setVariable('UAAIVfMod_getVfModuleResponseCode', response.getStatusCode()) - execution.setVariable('UAAIVfMod_getVfModuleResponse', responseData) - msoLogger.debug('Response code:' + response.getStatusCode()) - msoLogger.debug('Response:' + System.lineSeparator() + responseData) - msoLogger.debug("UpdateAAIVfModule response data: " + responseData) + AAIResourceUri resourceUri = AAIUriFactory.createResourceUri(AAIObjectType.VF_MODULE, vnfId, vfModuleId); + Optional<org.onap.aai.domain.yang.VfModule> vfModule = getAAIClient().get(org.onap.aai.domain.yang.VfModule.class, resourceUri) + if (vfModule.isPresent()) { + execution.setVariable('UAAIVfMod_getVfModuleResponseCode', 200) + execution.setVariable('UAAIVfMod_getVfModuleResponse', vfModule.get()) + } else { + execution.setVariable('UAAIVfMod_getVfModuleResponseCode', 404) + execution.setVariable('UAAIVfMod_getVfModuleResponse', "VF Module not found in AAI") + } } catch (Exception ex) { - ex.printStackTrace() msoLogger.debug('Exception occurred while executing AAI GET:' + ex.getMessage()) execution.setVariable('UAAIVfMod_getVfModuleResponseCode', 500) execution.setVariable('UAAIVfMod_getVfModuleResponse', 'AAI GET Failed:' + ex.getMessage()) } - msoLogger.trace('Exited ' + method) } catch (BpmnError e) { throw e; } catch (Exception e) { @@ -151,18 +139,10 @@ public class UpdateAAIVfModule extends AbstractServiceTaskProcessor { try { def vnfId = execution.getVariable('UAAIVfMod_vnfId') def vfModuleId = execution.getVariable('UAAIVfMod_vfModuleId') - def vfModule = execution.getVariable('UAAIVfMod_getVfModuleResponse') + org.onap.aai.domain.yang.VfModule vfModule = execution.getVariable('UAAIVfMod_getVfModuleResponse') def origRequest = execution.getVariable('UpdateAAIVfModuleRequest') - def Node vfModuleNode = xmlParser.parseText(vfModule) - + msoLogger.debug("UpdateAAIVfModule request: " + origRequest) - // Confirm resource-version is in retrieved VF Module - if (utils.getChildNode(vfModuleNode, 'resource-version') == null) { - def msg = 'Can\'t update VF Module ' + vfModuleId + ' since \'resource-version\' is missing' - msoLogger.error(msg); - throw new Exception(msg) - } - // Handle persona-model-id/persona-model-version def boolean doPersonaModelVersion = true def String newPersonaModelId = utils.getNodeText(origRequest, 'persona-model-id') @@ -171,10 +151,10 @@ public class UpdateAAIVfModule extends AbstractServiceTaskProcessor { doPersonaModelVersion = false } else { // Confirm "new" persona-model-id is same as "current" persona-model-id - def String currPersonaModelId = utils.getChildNodeText(vfModuleNode, 'model-invariant-id') + def String currPersonaModelId = vfModule.getModelInvariantId() if (currPersonaModelId == null) { // check the old attribute name - currPersonaModelId = utils.getChildNodeText(vfModuleNode, 'model-version-id') + currPersonaModelId = vfModule.getModelVersionId() } if (currPersonaModelId == null) { currPersonaModelId = '' @@ -187,13 +167,13 @@ public class UpdateAAIVfModule extends AbstractServiceTaskProcessor { } // Construct payload - String orchestrationStatusEntry = updateVfModuleNode(origRequest, vfModuleNode, 'orchestration-status') - String heatStackIdEntry = updateVfModuleNode(origRequest, vfModuleNode, 'heat-stack-id') + String orchestrationStatusEntry = updateVfModuleNode(origRequest , 'orchestration-status') + String heatStackIdEntry = updateVfModuleNode(origRequest, 'heat-stack-id') String personaModelVersionEntry = "" if (doPersonaModelVersion) { - personaModelVersionEntry = updateVfModuleNode(origRequest, vfModuleNode, 'persona-model-version') + personaModelVersionEntry = updateVfModuleNode(origRequest, 'persona-model-version') } - String contrailServiceInstanceFqdnEntry = updateVfModuleNode(origRequest, vfModuleNode, 'contrail-service-instance-fqdn') + String contrailServiceInstanceFqdnEntry = updateVfModuleNode(origRequest, 'contrail-service-instance-fqdn') def payload = """ { ${orchestrationStatusEntry} ${heatStackIdEntry} @@ -203,28 +183,16 @@ public class UpdateAAIVfModule extends AbstractServiceTaskProcessor { } """ - AaiUtil aaiUriUtil = new AaiUtil(this) - AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.VF_MODULE, vnfId, vfModuleId) - String endPoint = aaiUriUtil.createAaiUri(uri) - - try { - msoLogger.debug('sending PATCH to AAI endpoint \'' + endPoint + '\'' + 'with payload \n' + payload) - msoLogger.debug("Sending PATCH to AAI endpoint: " + endPoint) - - APIResponse response = aaiUriUtil.executeAAIPatchCall(execution, endPoint, payload) - def responseData = response.getResponseBodyAsString() - execution.setVariable('UAAIVfMod_updateVfModuleResponseCode', response.getStatusCode()) - execution.setVariable('UAAIVfMod_updateVfModuleResponse', responseData) - msoLogger.debug("UpdateAAIVfModule Response data: " + responseData) - msoLogger.debug('Response code:' + response.getStatusCode()) - msoLogger.debug('Response:' + System.lineSeparator() + responseData) - } catch (Exception ex) { - ex.printStackTrace() - msoLogger.debug('Exception occurred while executing AAI PATCH:' + ex.getMessage()) - execution.setVariable('UAAIVfMod_updateVfModuleResponseCode', 500) - execution.setVariable('UAAIVfMod_updateVfModuleResponse', 'AAI PATCH Failed:' + ex.getMessage()) - } - msoLogger.trace('Exited ' + method) + try { + AAIResourceUri resourceUri = AAIUriFactory.createResourceUri(AAIObjectType.VF_MODULE, vnfId, vfModuleId) + getAAIClient().update(resourceUri, payload) + }catch(NotFoundException ignored){ + msoLogger.debug("VF-Module not found!!") + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "vf-module " + vfModuleId + " not found for under vnf " + vnfId + " in A&AI!") + } + catch(Exception ex){ + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, 'Exception occurred while executing AAI PATCH:' + ex.getMessage()) + } } catch (BpmnError e) { throw e; } catch (Exception e) { @@ -237,10 +205,9 @@ public class UpdateAAIVfModule extends AbstractServiceTaskProcessor { * Sets up json attributes for PATCH request for Update * * @param origRequest Incoming update request with VF Module elements to be updated. - * @param vfModule Current VF Module retrieved from AAI. * @param element Name of element to be inserted. */ - private String updateVfModuleNode(String origRequest, Node vfModuleNode, String elementName) { + private String updateVfModuleNode(String origRequest, String elementName) { if (!utils.nodeExists(origRequest, elementName)) { return "" @@ -343,25 +310,4 @@ public class UpdateAAIVfModule extends AbstractServiceTaskProcessor { msoLogger.debug("UpdateAAIVfModule query failure: " + exception.getErrorMessage()) msoLogger.trace('Exited ' + method) } - - /** - * Generates a WorkflowException if updating a VF Module in AAI returns a response code other than 200. - * - * @param execution The flow's execution instance. - */ - public void handleUpdateVfModuleFailure(DelegateExecution execution) { - def method = getClass().getSimpleName() + '.handleUpdateVfModuleFailure(' + - 'execution=' + execution.getId() + - ')' - msoLogger.trace('Entered ' + method) - - msoLogger.error('Error occurred attempting to update VF Module in AAI, Response Code ' + execution.getVariable('UAAIVfMod_updateVfModuleResponseCode')); - String processKey = getProcessKey(execution); - WorkflowException exception = new WorkflowException(processKey, 5000, - execution.getVariable('UAAIVfMod_updateVfModuleResponse')) - execution.setVariable('WorkflowException', exception) - - msoLogger.debug("UpdateAAIVfModule failure: " + exception.getErrorMessage()) - msoLogger.trace('Exited ' + method) - } } diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/recipe/BpmnRestClient.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/recipe/BpmnRestClient.java index bbaebb64dc..1157750312 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/recipe/BpmnRestClient.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/recipe/BpmnRestClient.java @@ -37,6 +37,7 @@ import org.onap.so.logger.MessageEnum; import org.onap.so.logger.MsoLogger; import org.onap.so.utils.CryptoUtils; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; /** @@ -54,11 +55,11 @@ public class BpmnRestClient { public static final String DEFAULT_BPEL_AUTH = "admin:admin"; - public static final String ENCRYPTION_KEY = "aa3871669d893c7fb8abbcda31b88b4f"; + public static final String ENCRYPTION_KEY_PROP = "org.onap.so.adapters.network.encryptionKey"; public static final String CONTENT_TYPE_JSON = "application/json"; - public static final String CAMUNDA_AUTH = "camundaAuth"; + public static final String CAMUNDA_AUTH = "mso.camundaAuth"; private static final String MSO_PROP_APIHANDLER_INFRA = "MSO_PROP_APIHANDLER_INFRA"; @Autowired @@ -108,7 +109,7 @@ public class BpmnRestClient { String encryptedCredentials; encryptedCredentials = urnPropertiesReader.getVariable(CAMUNDA_AUTH); if(encryptedCredentials != null) { - String userCredentials = getEncryptedPropValue(encryptedCredentials, DEFAULT_BPEL_AUTH, ENCRYPTION_KEY); + String userCredentials = getEncryptedPropValue(encryptedCredentials, DEFAULT_BPEL_AUTH, ENCRYPTION_KEY_PROP); if(userCredentials != null) { post.addHeader("Authorization", "Basic " + DatatypeConverter.printBase64Binary(userCredentials.getBytes())); } @@ -195,7 +196,7 @@ public class BpmnRestClient { */ protected String getEncryptedPropValue(String prop, String defaultValue, String encryptionKey) { try { - return CryptoUtils.decrypt(prop, encryptionKey); + return CryptoUtils.decrypt(prop, urnPropertiesReader.getVariable(encryptionKey)); } catch(GeneralSecurityException e) { msoLogger.debug("Security exception", e); } diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/validation/BuildingBlockValidator.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/validation/BuildingBlockValidator.java new file mode 100644 index 0000000000..d4467b8270 --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/validation/BuildingBlockValidator.java @@ -0,0 +1,44 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2018 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.bpmn.common.validation; + +import java.util.Set; + +import org.onap.so.bpmn.common.BuildingBlockExecution; + +public interface BuildingBlockValidator { + + + /** + * Name of the building block to be validated + * @return + */ + public Set<String> forBuildingBlock(); + + /** + * Determines whether or not the building block should be executed + * + * @param execution + * @return + */ + public boolean validate(BuildingBlockExecution execution); + +} diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/validation/BuildingBlockValidatorRunner.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/validation/BuildingBlockValidatorRunner.java new file mode 100644 index 0000000000..d26ae7b92b --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/validation/BuildingBlockValidatorRunner.java @@ -0,0 +1,150 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2018 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.bpmn.common.validation; + +import java.lang.annotation.Annotation; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HashMap; +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; + +import javax.annotation.PostConstruct; +import javax.annotation.Priority; + +import org.camunda.bpm.engine.delegate.BpmnError; +import org.javatuples.Pair; +import org.onap.so.bpmn.common.BuildingBlockExecution; +import org.onap.so.client.exception.ExceptionBuilder; +import org.reflections.Reflections; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationContext; +import org.springframework.stereotype.Component; + + +/** + * Controls running all pre and post validation for building blocks. + * + * To define a validation you must make it a spring bean and implement either {@link org.onap.so.bpmn.common.validation.PreBuildingBlockValidator} or + * {@link org.onap.so.bpmn.common.validation.PostBuildingBlockValidator} your validation will automatically be + * run by this class. + * + */ +@Component +public class BuildingBlockValidatorRunner { + + private static Logger logger = LoggerFactory.getLogger(BuildingBlockValidatorRunner.class); + @Autowired + private ApplicationContext context; + + @Autowired + private ExceptionBuilder exceptionBuilder; + + private List<PreBuildingBlockValidator> preBuildingBlockValidators; + private List<PostBuildingBlockValidator> postBuildingBlockValidators; + + + @PostConstruct + protected void init() { + + preBuildingBlockValidators = new ArrayList<>( + Optional.ofNullable(context.getBeansOfType(PreBuildingBlockValidator.class)).orElse(new HashMap<>()).values()); + postBuildingBlockValidators = new ArrayList<>( + Optional.ofNullable(context.getBeansOfType(PostBuildingBlockValidator.class)).orElse(new HashMap<>()).values()); + } + + public boolean preValidate(String bbName, BuildingBlockExecution execution) { + return validate(preBuildingBlockValidators, bbName, execution); + } + + + public boolean postValidate(String bbName, BuildingBlockExecution execution) { + return validate(postBuildingBlockValidators, bbName, execution); + } + + + protected boolean validate(List<? extends BuildingBlockValidator> validators, String bbName, BuildingBlockExecution execution) { + List<Pair<String, Boolean>> results = runValidations(validators, bbName, execution); + + if (!results.isEmpty()) { + exceptionBuilder.buildAndThrowWorkflowException(execution, 7000, + "Failed Validations:\n" + results.stream().map(item -> item.getValue0()).collect(Collectors.joining("\n"))); + } + + return true; + + } + protected List<Pair<String, Boolean>> runValidations(List<? extends BuildingBlockValidator> validators, String bbName, BuildingBlockExecution execution) { + + List<BuildingBlockValidator> filtered = filterValidators(validators, bbName); + + List<Pair<String,Boolean>> results = new ArrayList<>(); + filtered.forEach(item -> results.add(new Pair<>(item.getClass().getName(), item.validate(execution)))); + + return results.stream().filter(item -> item.getValue1().equals(false)).collect(Collectors.toList()); + } + + protected List<BuildingBlockValidator> filterValidators(List<? extends BuildingBlockValidator> validators, String bbName) { + return validators.stream() + .filter(item -> { + return item.forBuildingBlock().contains(bbName); + }) + .sorted(Comparator.comparing(item -> { + Priority p = Optional.ofNullable(item.getClass().getAnnotation(Priority.class)).orElse(new Priority() { + public int value() { + return 1000; + } + + @Override + public Class<? extends Annotation> annotationType() { + return Priority.class; + } + }); + return p.value(); + })).collect(Collectors.toList()); + } + + protected <T> List<T> buildalidatorList(Reflections reflections, Class<T> clazz) { + List<T> result = new ArrayList<>(); + try { + for (Class<? extends T> klass : reflections.getSubTypesOf(clazz)) { + result.add(klass.newInstance()); + } + } catch (InstantiationException | IllegalAccessException e) { + logger.error("failed to build validator list for " + clazz.getName(), e); + throw new RuntimeException(e); + } + + return result; + } + + protected List<PreBuildingBlockValidator> getPreBuildingBlockValidators() { + return this.preBuildingBlockValidators; + } + + protected List<PostBuildingBlockValidator> getPostBuildingBlockValidators() { + return this.postBuildingBlockValidators; + } + +} diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/validation/PostBuildingBlockValidator.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/validation/PostBuildingBlockValidator.java new file mode 100644 index 0000000000..0b1ef5c6e1 --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/validation/PostBuildingBlockValidator.java @@ -0,0 +1,26 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2018 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.bpmn.common.validation; + + +public interface PostBuildingBlockValidator extends BuildingBlockValidator { + +} diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/validation/PreBuildingBlockValidator.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/validation/PreBuildingBlockValidator.java new file mode 100644 index 0000000000..489ac483d0 --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/validation/PreBuildingBlockValidator.java @@ -0,0 +1,25 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2018 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.bpmn.common.validation; + +public interface PreBuildingBlockValidator extends BuildingBlockValidator { + +} diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/BBInputSetup.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/BBInputSetup.java index 8cc25a2c52..5296d5995f 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/BBInputSetup.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/BBInputSetup.java @@ -336,14 +336,16 @@ public class BBInputSetup implements JavaDelegate { protected VnfVfmoduleCvnfcConfigurationCustomization findVnfVfmoduleCvnfcConfigurationCustomization(String vfModuleCustomizationUUID, String vnfResourceCustomizationUUID, String cvnfcCustomizationUUID, ConfigurationResourceCustomization configurationResourceCustomization) { - for(VnfVfmoduleCvnfcConfigurationCustomization vnfVfmoduleCvnfcConfigurationCustomization : - configurationResourceCustomization.getConfigurationResource().getVnfVfmoduleCvnfcConfigurationCustomization()) { - if(vnfVfmoduleCvnfcConfigurationCustomization.getVfModuleCustomization().getModelCustomizationUUID().equalsIgnoreCase(vfModuleCustomizationUUID) - && vnfVfmoduleCvnfcConfigurationCustomization.getVnfResourceCustomization().getModelCustomizationUUID().equalsIgnoreCase(vnfResourceCustomizationUUID) - && vnfVfmoduleCvnfcConfigurationCustomization.getCvnfcCustomization().getModelCustomizationUUID().equalsIgnoreCase(cvnfcCustomizationUUID)) { - return vnfVfmoduleCvnfcConfigurationCustomization; + + if(configurationResourceCustomization.getConfigurationResource() != null) + for(VnfVfmoduleCvnfcConfigurationCustomization vnfVfmoduleCvnfcConfigurationCustomization : + configurationResourceCustomization.getConfigurationResource().getVnfVfmoduleCvnfcConfigurationCustomization()) { + if(vnfVfmoduleCvnfcConfigurationCustomization.getVfModuleCustomization().getModelCustomizationUUID().equalsIgnoreCase(vfModuleCustomizationUUID) + && vnfVfmoduleCvnfcConfigurationCustomization.getVnfResourceCustomization().getModelCustomizationUUID().equalsIgnoreCase(vnfResourceCustomizationUUID) + && vnfVfmoduleCvnfcConfigurationCustomization.getCvnfcCustomization().getModelCustomizationUUID().equalsIgnoreCase(cvnfcCustomizationUUID)) { + return vnfVfmoduleCvnfcConfigurationCustomization; + } } - } return null; } diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/ExecuteBuildingBlockRainyDay.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/ExecuteBuildingBlockRainyDay.java index d8f9a66568..e815051eaa 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/ExecuteBuildingBlockRainyDay.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/ExecuteBuildingBlockRainyDay.java @@ -57,7 +57,7 @@ public class ExecuteBuildingBlockRainyDay { } } - public void queryRainyDayTable(DelegateExecution execution) { + public void queryRainyDayTable(DelegateExecution execution, boolean primaryPolicy) { try { ExecuteBuildingBlock ebb = (ExecuteBuildingBlock) execution.getVariable("buildingBlock"); String bbName = ebb.getBuildingBlock().getBpmnFlowName(); @@ -102,10 +102,18 @@ public class ExecuteBuildingBlockRainyDay { if(rainyDayHandlerStatus==null){ handlingCode = "Abort"; }else{ - handlingCode = rainyDayHandlerStatus.getPolicy(); + if(primaryPolicy){ + handlingCode = rainyDayHandlerStatus.getPolicy(); + }else{ + handlingCode = rainyDayHandlerStatus.getSecondaryPolicy(); + } } }else{ - handlingCode = rainyDayHandlerStatus.getPolicy(); + if(primaryPolicy){ + handlingCode = rainyDayHandlerStatus.getPolicy(); + }else{ + handlingCode = rainyDayHandlerStatus.getSecondaryPolicy(); + } } msoLogger.debug("RainyDayHandler Status Code is: " + handlingCode); execution.setVariable(HANDLING_CODE, handlingCode); diff --git a/bpmn/MSOCommonBPMN/src/main/resources/subprocess/UpdateAAIVfModule.bpmn b/bpmn/MSOCommonBPMN/src/main/resources/subprocess/UpdateAAIVfModule.bpmn index f0b1d8d027..7ad101f33f 100644 --- a/bpmn/MSOCommonBPMN/src/main/resources/subprocess/UpdateAAIVfModule.bpmn +++ b/bpmn/MSOCommonBPMN/src/main/resources/subprocess/UpdateAAIVfModule.bpmn @@ -1,7 +1,7 @@ <?xml version="1.0" encoding="UTF-8"?> -<bpmn2:definitions xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:bpmn2="http://www.omg.org/spec/BPMN/20100524/MODEL" xmlns:bpmndi="http://www.omg.org/spec/BPMN/20100524/DI" xmlns:camunda="http://camunda.org/schema/1.0/bpmn" xmlns:dc="http://www.omg.org/spec/DD/20100524/DC" xmlns:di="http://www.omg.org/spec/DD/20100524/DI" xsi:schemaLocation="http://www.omg.org/spec/BPMN/20100524/MODEL BPMN20.xsd" id="_Wblj8GyfEeWUWLTvug7ZOg" exporter="camunda modeler" exporterVersion="2.7.0" targetNamespace="http://camunda.org/schema/1.0/bpmn"> +<bpmn2:definitions xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:bpmn2="http://www.omg.org/spec/BPMN/20100524/MODEL" xmlns:bpmndi="http://www.omg.org/spec/BPMN/20100524/DI" xmlns:camunda="http://camunda.org/schema/1.0/bpmn" xmlns:dc="http://www.omg.org/spec/DD/20100524/DC" xmlns:di="http://www.omg.org/spec/DD/20100524/DI" id="_Wblj8GyfEeWUWLTvug7ZOg" targetNamespace="http://camunda.org/schema/1.0/bpmn" exporter="Camunda Modeler" exporterVersion="1.7.2" xsi:schemaLocation="http://www.omg.org/spec/BPMN/20100524/MODEL BPMN20.xsd"> <bpmn2:process id="UpdateAAIVfModule" name="UpdateAAIVfModule" isExecutable="true"> - <bpmn2:documentation>This flow expects its incoming request to be in the variable 'UpdateAAIVfModuleRequest'. This flow produces no output.</bpmn2:documentation> + <bpmn2:documentation><![CDATA[This flow expects its incoming request to be in the variable 'UpdateAAIVfModuleRequest'. This flow produces no output.]]></bpmn2:documentation> <bpmn2:scriptTask id="QueryAAIForVfModule" name="Query AAI for VF Module" scriptFormat="groovy"> <bpmn2:incoming>SequenceFlow_38</bpmn2:incoming> <bpmn2:outgoing>SequenceFlow_39</bpmn2:outgoing> @@ -9,10 +9,10 @@ def uvm = new UpdateAAIVfModule() uvm.getVfModule(execution)]]></bpmn2:script> </bpmn2:scriptTask> - <bpmn2:sequenceFlow id="SequenceFlow_39" name="" sourceRef="QueryAAIForVfModule" targetRef="ExclusiveGateway_3"/> + <bpmn2:sequenceFlow id="SequenceFlow_39" name="" sourceRef="QueryAAIForVfModule" targetRef="ExclusiveGateway_3" /> <bpmn2:endEvent id="EndEvent_7"> <bpmn2:incoming>SequenceFlow_18</bpmn2:incoming> - <bpmn2:errorEventDefinition id="_ErrorEventDefinition_68" errorRef="Error_1"/> + <bpmn2:errorEventDefinition id="_ErrorEventDefinition_68" errorRef="Error_1" /> </bpmn2:endEvent> <bpmn2:scriptTask id="AAIQueryFailure" name="Handle AAI Query Failure" scriptFormat="groovy"> <bpmn2:incoming>SequenceFlow_23</bpmn2:incoming> @@ -21,11 +21,7 @@ uvm.getVfModule(execution)]]></bpmn2:script> def uvm= new UpdateAAIVfModule() uvm.handleAAIQueryFailure(execution)]]></bpmn2:script> </bpmn2:scriptTask> - <bpmn2:sequenceFlow id="SequenceFlow_18" name="" sourceRef="AAIQueryFailure" targetRef="EndEvent_7"/> - <bpmn2:endEvent id="EndEvent_2"> - <bpmn2:incoming>SequenceFlow_8</bpmn2:incoming> - <bpmn2:errorEventDefinition id="_ErrorEventDefinition_50" errorRef="Error_1"/> - </bpmn2:endEvent> + <bpmn2:sequenceFlow id="SequenceFlow_18" name="" sourceRef="AAIQueryFailure" targetRef="EndEvent_7" /> <bpmn2:endEvent id="EndEvent_4" name="TheEnd"> <bpmn2:extensionElements> <camunda:connector> @@ -36,7 +32,7 @@ uvm.handleAAIQueryFailure(execution)]]></bpmn2:script> </camunda:inputOutput> </camunda:connector> </bpmn2:extensionElements> - <bpmn2:incoming>SequenceFlow_13</bpmn2:incoming> + <bpmn2:incoming>SequenceFlow_1x7tivg</bpmn2:incoming> </bpmn2:endEvent> <bpmn2:exclusiveGateway id="ExclusiveGateway_3" default="SequenceFlow_23"> <bpmn2:incoming>SequenceFlow_39</bpmn2:incoming> @@ -44,38 +40,20 @@ uvm.handleAAIQueryFailure(execution)]]></bpmn2:script> <bpmn2:outgoing>SequenceFlow_23</bpmn2:outgoing> </bpmn2:exclusiveGateway> <bpmn2:sequenceFlow id="SequenceFlow_22" name="" sourceRef="ExclusiveGateway_3" targetRef="UpdateVfModule"> - <bpmn2:conditionExpression xsi:type="bpmn2:tFormalExpression">#{execution.getVariable('UAAIVfMod_getVfModuleResponseCode') == 200}</bpmn2:conditionExpression> - </bpmn2:sequenceFlow> - <bpmn2:sequenceFlow id="SequenceFlow_23" name="AAI Query failure or
VF Module not found" sourceRef="ExclusiveGateway_3" targetRef="AAIQueryFailure"/> - <bpmn2:scriptTask id="HandleUpdateVfModuleFailure" name="Handle Update VF Module Failure" scriptFormat="groovy"> - <bpmn2:incoming>SequenceFlow_4</bpmn2:incoming> - <bpmn2:outgoing>SequenceFlow_8</bpmn2:outgoing> - <bpmn2:script><![CDATA[import org.onap.so.bpmn.common.scripts.* -def uvm= new UpdateAAIVfModule() -uvm.handleUpdateVfModuleFailure(execution)]]></bpmn2:script> - </bpmn2:scriptTask> - <bpmn2:sequenceFlow id="SequenceFlow_8" name="" sourceRef="HandleUpdateVfModuleFailure" targetRef="EndEvent_2"/> - <bpmn2:exclusiveGateway id="ExclusiveGateway_1" default="SequenceFlow_4"> - <bpmn2:incoming>SequenceFlow_14</bpmn2:incoming> - <bpmn2:outgoing>SequenceFlow_13</bpmn2:outgoing> - <bpmn2:outgoing>SequenceFlow_4</bpmn2:outgoing> - </bpmn2:exclusiveGateway> - <bpmn2:sequenceFlow id="SequenceFlow_13" sourceRef="ExclusiveGateway_1" targetRef="EndEvent_4"> - <bpmn2:conditionExpression xsi:type="bpmn2:tFormalExpression">#{execution.getVariable('UAAIVfMod_updateVfModuleResponseCode') == 200}</bpmn2:conditionExpression> + <bpmn2:conditionExpression xsi:type="bpmn2:tFormalExpression"><![CDATA[#{execution.getVariable('UAAIVfMod_getVfModuleResponseCode') == 200}]]></bpmn2:conditionExpression> </bpmn2:sequenceFlow> - <bpmn2:sequenceFlow id="SequenceFlow_4" name="Update VF Module Failure" sourceRef="ExclusiveGateway_1" targetRef="HandleUpdateVfModuleFailure"/> + <bpmn2:sequenceFlow id="SequenceFlow_23" name="AAI Query failure or
VF Module not found" sourceRef="ExclusiveGateway_3" targetRef="AAIQueryFailure" /> <bpmn2:scriptTask id="UpdateVfModule" name="Update VF Module" scriptFormat="groovy"> <bpmn2:incoming>SequenceFlow_22</bpmn2:incoming> - <bpmn2:outgoing>SequenceFlow_14</bpmn2:outgoing> + <bpmn2:outgoing>SequenceFlow_1x7tivg</bpmn2:outgoing> <bpmn2:script><![CDATA[import org.onap.so.bpmn.common.scripts.* def uvm= new UpdateAAIVfModule() uvm.updateVfModule(execution)]]></bpmn2:script> </bpmn2:scriptTask> - <bpmn2:sequenceFlow id="SequenceFlow_14" name="" sourceRef="UpdateVfModule" targetRef="ExclusiveGateway_1"/> <bpmn2:startEvent id="StartEvent_1" name="Start"> <bpmn2:outgoing>SequenceFlow_1</bpmn2:outgoing> </bpmn2:startEvent> - <bpmn2:sequenceFlow id="SequenceFlow_1" name="" sourceRef="StartEvent_1" targetRef="ProcessReceivedRequest"/> + <bpmn2:sequenceFlow id="SequenceFlow_1" name="" sourceRef="StartEvent_1" targetRef="ProcessReceivedRequest" /> <bpmn2:scriptTask id="ProcessReceivedRequest" name="Process Received Request" scriptFormat="groovy"> <bpmn2:incoming>SequenceFlow_1</bpmn2:incoming> <bpmn2:outgoing>SequenceFlow_38</bpmn2:outgoing> @@ -83,142 +61,101 @@ uvm.updateVfModule(execution)]]></bpmn2:script> def uvm= new UpdateAAIVfModule() uvm.preProcessRequest(execution)]]></bpmn2:script> </bpmn2:scriptTask> - <bpmn2:sequenceFlow id="SequenceFlow_38" name="" sourceRef="ProcessReceivedRequest" targetRef="QueryAAIForVfModule"/> + <bpmn2:sequenceFlow id="SequenceFlow_38" name="" sourceRef="ProcessReceivedRequest" targetRef="QueryAAIForVfModule" /> + <bpmn2:sequenceFlow id="SequenceFlow_1x7tivg" sourceRef="UpdateVfModule" targetRef="EndEvent_4" /> </bpmn2:process> - <bpmn2:error id="Error_1" errorCode="MSOWorkflowException" name="MSO Workflow Exception"/> + <bpmn2:error id="Error_1" name="MSO Workflow Exception" errorCode="MSOWorkflowException" /> <bpmndi:BPMNDiagram id="BPMNDiagram_1"> <bpmndi:BPMNPlane id="BPMNPlane_1" bpmnElement="UpdateAAIVfModule"> <bpmndi:BPMNShape id="_BPMNShape_StartEvent_37" bpmnElement="StartEvent_1"> - <dc:Bounds height="36.0" width="36.0" x="69.0" y="212.0"/> + <dc:Bounds x="69" y="212" width="36" height="36" /> <bpmndi:BPMNLabel> - <dc:Bounds height="22.0" width="34.0" x="70.0" y="253.0"/> + <dc:Bounds x="70" y="253" width="34" height="22" /> </bpmndi:BPMNLabel> </bpmndi:BPMNShape> <bpmndi:BPMNShape id="_BPMNShape_ScriptTask_22" bpmnElement="ProcessReceivedRequest"> - <dc:Bounds height="80.0" width="100.0" x="180.0" y="190.0"/> + <dc:Bounds x="180" y="190" width="100" height="80" /> </bpmndi:BPMNShape> <bpmndi:BPMNEdge id="BPMNEdge_SequenceFlow_1" bpmnElement="SequenceFlow_1" sourceElement="_BPMNShape_StartEvent_37" targetElement="_BPMNShape_ScriptTask_22"> - <di:waypoint xsi:type="dc:Point" x="105.0" y="230.0"/> - <di:waypoint xsi:type="dc:Point" x="180.0" y="230.0"/> + <di:waypoint xsi:type="dc:Point" x="105" y="230" /> + <di:waypoint xsi:type="dc:Point" x="180" y="230" /> <bpmndi:BPMNLabel> - <dc:Bounds height="6.0" width="6.0" x="127.0" y="230.0"/> + <dc:Bounds x="127" y="230" width="6" height="6" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> <bpmndi:BPMNShape id="_BPMNShape_Task_2" bpmnElement="UpdateVfModule"> - <dc:Bounds height="80.0" width="100.0" x="672.0" y="190.0"/> + <dc:Bounds x="672" y="190" width="100" height="80" /> </bpmndi:BPMNShape> <bpmndi:BPMNShape id="_BPMNShape_EndEvent_92" bpmnElement="EndEvent_4"> - <dc:Bounds height="36.0" width="36.0" x="1016.0" y="212.0"/> - <bpmndi:BPMNLabel> - <dc:Bounds height="22.0" width="50.0" x="1009.0" y="253.0"/> - </bpmndi:BPMNLabel> - </bpmndi:BPMNShape> - <bpmndi:BPMNShape id="_BPMNShape_ExclusiveGateway_54" bpmnElement="ExclusiveGateway_1" isMarkerVisible="true"> - <dc:Bounds height="50.0" width="50.0" x="840.0" y="206.0"/> - <bpmndi:BPMNLabel> - <dc:Bounds height="0.0" width="0.0" x="865.0" y="261.0"/> - </bpmndi:BPMNLabel> - </bpmndi:BPMNShape> - <bpmndi:BPMNEdge id="BPMNEdge_SequenceFlow_14" bpmnElement="SequenceFlow_13" sourceElement="_BPMNShape_ExclusiveGateway_54" targetElement="_BPMNShape_EndEvent_92"> - <di:waypoint xsi:type="dc:Point" x="890.0" y="231.0"/> - <di:waypoint xsi:type="dc:Point" x="993.0" y="231.0"/> - <di:waypoint xsi:type="dc:Point" x="993.0" y="230.0"/> - <di:waypoint xsi:type="dc:Point" x="1016.0" y="230.0"/> - <bpmndi:BPMNLabel> - <dc:Bounds height="0.0" width="0.0" x="928.0" y="231.0"/> - </bpmndi:BPMNLabel> - </bpmndi:BPMNEdge> - <bpmndi:BPMNShape id="_BPMNShape_EndEvent_120" bpmnElement="EndEvent_2"> - <dc:Bounds height="36.0" width="36.0" x="848.0" y="0.0"/> + <dc:Bounds x="1016" y="212" width="36" height="36" /> <bpmndi:BPMNLabel> - <dc:Bounds height="0.0" width="0.0" x="866.0" y="41.0"/> + <dc:Bounds x="1009" y="253" width="50" height="22" /> </bpmndi:BPMNLabel> </bpmndi:BPMNShape> <bpmndi:BPMNShape id="_BPMNShape_ExclusiveGateway_86" bpmnElement="ExclusiveGateway_3" isMarkerVisible="true"> - <dc:Bounds height="50.0" width="50.0" x="493.0" y="204.0"/> + <dc:Bounds x="493" y="204" width="50" height="50" /> <bpmndi:BPMNLabel> - <dc:Bounds height="0.0" width="0.0" x="518.0" y="259.0"/> + <dc:Bounds x="518" y="259" width="0" height="0" /> </bpmndi:BPMNLabel> </bpmndi:BPMNShape> <bpmndi:BPMNEdge id="BPMNEdge_SequenceFlow_23" bpmnElement="SequenceFlow_22" sourceElement="_BPMNShape_ExclusiveGateway_86" targetElement="_BPMNShape_Task_2"> - <di:waypoint xsi:type="dc:Point" x="543.0" y="229.0"/> - <di:waypoint xsi:type="dc:Point" x="607.0" y="229.0"/> - <di:waypoint xsi:type="dc:Point" x="607.0" y="230.0"/> - <di:waypoint xsi:type="dc:Point" x="672.0" y="230.0"/> + <di:waypoint xsi:type="dc:Point" x="543" y="229" /> + <di:waypoint xsi:type="dc:Point" x="607" y="229" /> + <di:waypoint xsi:type="dc:Point" x="607" y="230" /> + <di:waypoint xsi:type="dc:Point" x="672" y="230" /> <bpmndi:BPMNLabel> - <dc:Bounds height="6.0" width="6.0" x="558.0" y="229.0"/> + <dc:Bounds x="558" y="229" width="6" height="6" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> <bpmndi:BPMNShape id="_BPMNShape_ScriptTask_155" bpmnElement="AAIQueryFailure"> - <dc:Bounds height="80.0" width="100.0" x="468.0" y="60.0"/> + <dc:Bounds x="468" y="60" width="100" height="80" /> </bpmndi:BPMNShape> <bpmndi:BPMNEdge id="BPMNEdge_SequenceFlow_24" bpmnElement="SequenceFlow_23" sourceElement="_BPMNShape_ExclusiveGateway_86" targetElement="_BPMNShape_ScriptTask_155"> - <di:waypoint xsi:type="dc:Point" x="518.0" y="204.0"/> - <di:waypoint xsi:type="dc:Point" x="518.0" y="140.0"/> + <di:waypoint xsi:type="dc:Point" x="518" y="204" /> + <di:waypoint xsi:type="dc:Point" x="518" y="140" /> <bpmndi:BPMNLabel> - <dc:Bounds height="38.0" width="130.0" x="528.0" y="152.0"/> + <dc:Bounds x="528" y="152" width="130" height="38" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> <bpmndi:BPMNShape id="_BPMNShape_EndEvent_160" bpmnElement="EndEvent_7"> - <dc:Bounds height="36.0" width="36.0" x="500.0" y="0.0"/> + <dc:Bounds x="500" y="0" width="36" height="36" /> <bpmndi:BPMNLabel> - <dc:Bounds height="0.0" width="0.0" x="518.0" y="41.0"/> + <dc:Bounds x="518" y="41" width="0" height="0" /> </bpmndi:BPMNLabel> </bpmndi:BPMNShape> <bpmndi:BPMNEdge id="BPMNEdge_SequenceFlow_18" bpmnElement="SequenceFlow_18" sourceElement="_BPMNShape_ScriptTask_155" targetElement="_BPMNShape_EndEvent_160"> - <di:waypoint xsi:type="dc:Point" x="518.0" y="60.0"/> - <di:waypoint xsi:type="dc:Point" x="518.0" y="36.0"/> + <di:waypoint xsi:type="dc:Point" x="518" y="60" /> + <di:waypoint xsi:type="dc:Point" x="518" y="36" /> <bpmndi:BPMNLabel> - <dc:Bounds height="6.0" width="6.0" x="515.0" y="49.0"/> + <dc:Bounds x="515" y="49" width="6" height="6" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> <bpmndi:BPMNShape id="_BPMNShape_ScriptTask_160" bpmnElement="QueryAAIForVfModule"> - <dc:Bounds height="80.0" width="100.0" x="336.0" y="190.0"/> + <dc:Bounds x="336" y="190" width="100" height="80" /> </bpmndi:BPMNShape> <bpmndi:BPMNEdge id="BPMNEdge_SequenceFlow_38" bpmnElement="SequenceFlow_38" sourceElement="_BPMNShape_ScriptTask_22" targetElement="_BPMNShape_ScriptTask_160"> - <di:waypoint xsi:type="dc:Point" x="280.0" y="230.0"/> - <di:waypoint xsi:type="dc:Point" x="336.0" y="230.0"/> + <di:waypoint xsi:type="dc:Point" x="280" y="230" /> + <di:waypoint xsi:type="dc:Point" x="336" y="230" /> <bpmndi:BPMNLabel> - <dc:Bounds height="6.0" width="6.0" x="300.0" y="230.0"/> + <dc:Bounds x="300" y="230" width="6" height="6" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> <bpmndi:BPMNEdge id="BPMNEdge_SequenceFlow_39" bpmnElement="SequenceFlow_39" sourceElement="_BPMNShape_ScriptTask_160" targetElement="_BPMNShape_ExclusiveGateway_86"> - <di:waypoint xsi:type="dc:Point" x="436.0" y="230.0"/> - <di:waypoint xsi:type="dc:Point" x="452.0" y="230.0"/> - <di:waypoint xsi:type="dc:Point" x="452.0" y="229.0"/> - <di:waypoint xsi:type="dc:Point" x="493.0" y="229.0"/> - <bpmndi:BPMNLabel> - <dc:Bounds height="6.0" width="6.0" x="449.0" y="229.0"/> - </bpmndi:BPMNLabel> - </bpmndi:BPMNEdge> - <bpmndi:BPMNShape id="_BPMNShape_ScriptTask_161" bpmnElement="HandleUpdateVfModuleFailure"> - <dc:Bounds height="80.0" width="100.0" x="816.0" y="60.0"/> - </bpmndi:BPMNShape> - <bpmndi:BPMNEdge id="BPMNEdge_SequenceFlow_6" bpmnElement="SequenceFlow_8" sourceElement="_BPMNShape_ScriptTask_161" targetElement="_BPMNShape_EndEvent_120"> - <di:waypoint xsi:type="dc:Point" x="866.0" y="60.0"/> - <di:waypoint xsi:type="dc:Point" x="866.0" y="36.0"/> - <bpmndi:BPMNLabel> - <dc:Bounds height="6.0" width="6.0" x="863.0" y="51.0"/> - </bpmndi:BPMNLabel> - </bpmndi:BPMNEdge> - <bpmndi:BPMNEdge id="BPMNEdge_SequenceFlow_13" bpmnElement="SequenceFlow_14" sourceElement="_BPMNShape_Task_2" targetElement="_BPMNShape_ExclusiveGateway_54"> - <di:waypoint xsi:type="dc:Point" x="772.0" y="230.0"/> - <di:waypoint xsi:type="dc:Point" x="797.0" y="230.0"/> - <di:waypoint xsi:type="dc:Point" x="797.0" y="231.0"/> - <di:waypoint xsi:type="dc:Point" x="840.0" y="231.0"/> + <di:waypoint xsi:type="dc:Point" x="436" y="230" /> + <di:waypoint xsi:type="dc:Point" x="452" y="230" /> + <di:waypoint xsi:type="dc:Point" x="452" y="229" /> + <di:waypoint xsi:type="dc:Point" x="493" y="229" /> <bpmndi:BPMNLabel> - <dc:Bounds height="6.0" width="6.0" x="801.0" y="231.0"/> + <dc:Bounds x="449" y="229" width="6" height="6" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> - <bpmndi:BPMNEdge id="BPMNEdge_SequenceFlow_3" bpmnElement="SequenceFlow_4" sourceElement="_BPMNShape_ExclusiveGateway_54" targetElement="_BPMNShape_ScriptTask_161"> - <di:waypoint xsi:type="dc:Point" x="865.0" y="206.0"/> - <di:waypoint xsi:type="dc:Point" x="865.0" y="172.0"/> - <di:waypoint xsi:type="dc:Point" x="867.0" y="172.0"/> - <di:waypoint xsi:type="dc:Point" x="867.0" y="140.0"/> + <bpmndi:BPMNEdge id="SequenceFlow_1x7tivg_di" bpmnElement="SequenceFlow_1x7tivg"> + <di:waypoint xsi:type="dc:Point" x="772" y="230" /> + <di:waypoint xsi:type="dc:Point" x="1016" y="230" /> <bpmndi:BPMNLabel> - <dc:Bounds height="22.0" width="157.0" x="883.0" y="160.0"/> + <dc:Bounds x="894" y="208" width="0" height="13" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> </bpmndi:BPMNPlane> </bpmndi:BPMNDiagram> -</bpmn2:definitions>
\ No newline at end of file +</bpmn2:definitions> diff --git a/bpmn/MSOCommonBPMN/src/test/groovy/org/onap/so/bpmn/common/scripts/AaiUtilTest.groovy b/bpmn/MSOCommonBPMN/src/test/groovy/org/onap/so/bpmn/common/scripts/AaiUtilTest.groovy index 05b1c5e6ed..1165bbbc71 100644 --- a/bpmn/MSOCommonBPMN/src/test/groovy/org/onap/so/bpmn/common/scripts/AaiUtilTest.groovy +++ b/bpmn/MSOCommonBPMN/src/test/groovy/org/onap/so/bpmn/common/scripts/AaiUtilTest.groovy @@ -44,8 +44,6 @@ import org.camunda.bpm.engine.impl.persistence.entity.ExecutionEntity import org.camunda.bpm.engine.impl.pvm.process.ProcessDefinitionImpl import org.camunda.bpm.engine.repository.ProcessDefinition -@RunWith(MockitoJUnitRunner.class) -@Ignore class AaiUtilTest extends MsoGroovyTest { @@ -53,7 +51,7 @@ class AaiUtilTest extends MsoGroovyTest { public WireMockRule wireMockRule = new WireMockRule(8090); @Rule - public ExpectedException thrown = ExpectedException.none + public ExpectedException thrown = ExpectedException.none() def aaiPaylod = "<allotted-resource xmlns=\"http://org.openecomp.aai.inventory/v9\">\n" + @@ -128,6 +126,7 @@ class AaiUtilTest extends MsoGroovyTest { } @Test + @Ignore public void testExecuteAAIGetCall() { ExecutionEntity mockExecution = setupMock('CreateAAIVfModule') when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn('true') @@ -140,6 +139,7 @@ class AaiUtilTest extends MsoGroovyTest { @Test + @Ignore public void testExecuteAAIPutCall() { ExecutionEntity mockExecution = setupMock('CreateAAIVfModule') when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn('true') diff --git a/bpmn/MSOCommonBPMN/src/test/groovy/org/onap/so/bpmn/common/scripts/AbstractServiceTaskProcessorTest.groovy b/bpmn/MSOCommonBPMN/src/test/groovy/org/onap/so/bpmn/common/scripts/AbstractServiceTaskProcessorTest.groovy index 86a175d811..459b18b7f1 100644 --- a/bpmn/MSOCommonBPMN/src/test/groovy/org/onap/so/bpmn/common/scripts/AbstractServiceTaskProcessorTest.groovy +++ b/bpmn/MSOCommonBPMN/src/test/groovy/org/onap/so/bpmn/common/scripts/AbstractServiceTaskProcessorTest.groovy @@ -32,7 +32,7 @@ import static org.mockito.Mockito.* import org.onap.so.rest.HttpHeader import org.mockito.MockitoAnnotations -import org.mockito.runners.MockitoJUnitRunner +import org.mockito.junit.MockitoJUnitRunner; import org.mockito.internal.debugging.MockitoDebuggerImpl import org.junit.Before import org.onap.so.bpmn.common.scripts.AaiUtil; @@ -58,7 +58,8 @@ class AbstractServiceTaskProcessorImpl extends AbstractServiceTaskProcessor{ } } -@RunWith(MockitoJUnitRunner.class) + +@RunWith(MockitoJUnitRunner.Silent.class) public class AbstractServiceTaskProcessorTest extends MsoGroovyTest { @Captor @@ -171,12 +172,12 @@ public class AbstractServiceTaskProcessorTest extends MsoGroovyTest { @Test public void testSetBasicDBAuthHeader_Success() { ExecutionEntity mockExecution = setupMock() - when(mockExecution.getVariable("mso.adapters.db.auth")).thenReturn('9B2278E8B8E95F256A560719055F4DF3') - when(mockExecution.getVariable("mso.msoKey")).thenReturn('aa3871669d893c7fb8abbcda31b88b4f') + when(mockExecution.getVariable("mso.adapters.db.auth")).thenReturn('5E12ACACBD552A415E081E29F2C4772F9835792A51C766CCFDD7433DB5220B59969CB2798C') + when(mockExecution.getVariable("mso.msoKey")).thenReturn('07a7159d3bf51a0e53be7a8f89699be7') AbstractServiceTaskProcessorImpl serviceTaskProcessor = new AbstractServiceTaskProcessorImpl(); serviceTaskProcessor.setBasicDBAuthHeader(mockExecution, "true") - verify(mockExecution).setVariable("BasicAuthHeaderValueDB",'Basic dXAyMTE4OnVwMjExOA==') + verify(mockExecution).setVariable("BasicAuthHeaderValueDB",'Basic dGVzdDp0ZXN0') } } diff --git a/bpmn/MSOCommonBPMN/src/test/groovy/org/onap/so/bpmn/common/scripts/AllottedResourceUtilsTest.groovy b/bpmn/MSOCommonBPMN/src/test/groovy/org/onap/so/bpmn/common/scripts/AllottedResourceUtilsTest.groovy new file mode 100644 index 0000000000..3da126f7a9 --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/test/groovy/org/onap/so/bpmn/common/scripts/AllottedResourceUtilsTest.groovy @@ -0,0 +1,99 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2018 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.bpmn.common.scripts + +import org.camunda.bpm.engine.delegate.DelegateExecution +import org.junit.Before +import org.junit.Ignore +import org.junit.Test +import org.mockito.Mockito +import org.mockito.internal.stubbing.answers.DoesNothing +import org.onap.aai.domain.yang.AllottedResource +import org.onap.so.client.aai.AAIObjectType +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 javax.ws.rs.core.UriBuilder +import static org.junit.Assert.assertEquals +import static org.junit.Assert.assertTrue +import static org.mockito.Matchers.any +import static org.mockito.Matchers.anyObject +import static org.mockito.Matchers.isA +import static org.mockito.Mockito.atLeastOnce +import static org.mockito.Mockito.doNothing +import static org.mockito.Mockito.doThrow +import static org.mockito.Mockito.mock +import static org.mockito.Mockito.spy +import static org.mockito.Mockito.verify +import static org.mockito.Mockito.when + + +class AllottedResourceUtilsTest extends MsoGroovyTest{ + + private static final String ALLOTTED_RESOURSE_URI = "/aai/v11/business/customers/customer/MSO-MUX-User/service-subscriptions/service-subscription/MSO-vCB/service-instances/service-instance/a1f53c6a-81a3-4e44-a900-d64f3b131d35/allotted-resources/allotted-resource/ID" + + AllottedResourceUtils allottedResourceUtils + + @Before + void init(){ + super.init("AllottedResourceUtils") + allottedResourceUtils = spy(new AllottedResourceUtils(mock(AbstractServiceTaskProcessor.class))) + when(allottedResourceUtils.getAAIClient()).thenReturn(client) + } + + @Test + @Ignore + void getARbyId() { + String allottedResourceId = "allottedResourceId" + AllottedResource expectedAllottedResource = new AllottedResource() + expectedAllottedResource.setId("ID") + expectedAllottedResource.setResourceVersion("1.2") + when(client.get(any(AAIResourceUri.class))).thenReturn(new AAIResultWrapper(expectedAllottedResource)) + AAIResourceUri resourceUri = AAIUriFactory.createResourceUri(AAIObjectType.ALLOTTED_RESOURCE, allottedResourceId) + when(allottedResourceUtils.setExecutionVariables(mockExecution,expectedAllottedResource,resourceUri)).thenAnswer(new DoesNothing()) + boolean allottedResource = allottedResourceUtils.ifExistsAR(mockExecution,allottedResourceId) + assertTrue(allottedResource) + } + + @Test + void getARbyLink() { + println "************ testGetARbyLink ************* " + + AllottedResource expectedAllottedResource = new AllottedResource() + expectedAllottedResource.setId("ID") + AAIResourceUri uri = AAIUriFactory.createResourceFromExistingURI(AAIObjectType.ALLOTTED_RESOURCE, UriBuilder.fromPath(ALLOTTED_RESOURSE_URI).build()) + when(client.get(AllottedResource.class, uri)).thenReturn(Optional.of(expectedAllottedResource)) + Optional<AllottedResource> allottedResource = allottedResourceUtils.getARbyLink(mockExecution, ALLOTTED_RESOURSE_URI,"") + assertEquals(expectedAllottedResource.getId(),allottedResource.get().getId()) + } + + @Test + void updateAROrchStatus() { + allottedResourceUtils.updateAROrchStatus(mockExecution,"PENDING",ALLOTTED_RESOURSE_URI) + } + + @Test + void deleteAR() { + allottedResourceUtils.deleteAR(mockExecution,ALLOTTED_RESOURSE_URI) + verify(mockExecution,atLeastOnce()).setVariable("wasDeleted","true") + } + +} diff --git a/bpmn/MSOCommonBPMN/src/test/groovy/org/onap/so/bpmn/common/scripts/CatalogDbUtilsTest.groovy b/bpmn/MSOCommonBPMN/src/test/groovy/org/onap/so/bpmn/common/scripts/CatalogDbUtilsTest.groovy deleted file mode 100644 index 39064caa28..0000000000 --- a/bpmn/MSOCommonBPMN/src/test/groovy/org/onap/so/bpmn/common/scripts/CatalogDbUtilsTest.groovy +++ /dev/null @@ -1,98 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 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.bpmn.common.scripts - -import com.github.tomakehurst.wiremock.junit.WireMockRule -import org.camunda.bpm.engine.ProcessEngineServices -import org.camunda.bpm.engine.RepositoryService -import org.camunda.bpm.engine.impl.persistence.entity.ExecutionEntity -import org.camunda.bpm.engine.repository.ProcessDefinition -import org.junit.Assert -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.runner.RunWith -import org.mockito.Mockito -import org.mockito.runners.MockitoJUnitRunner -import org.onap.so.bpmn.mock.FileUtil - -import static com.github.tomakehurst.wiremock.client.WireMock.aResponse -import static com.github.tomakehurst.wiremock.client.WireMock.get -import static com.github.tomakehurst.wiremock.client.WireMock.stubFor -import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching -import static org.mockito.Mockito.mock -import static org.mockito.Mockito.mock -import static org.mockito.Mockito.mock -import static org.mockito.Mockito.mock -import static org.mockito.Mockito.when -import static org.mockito.Mockito.when -import static org.mockito.Mockito.when -import static org.mockito.Mockito.when -import static org.mockito.Mockito.when -import static org.mockito.Mockito.when -import static org.mockito.Mockito.when - -@RunWith(MockitoJUnitRunner.class) -class CatalogDbUtilsTest { - - - @Rule - public WireMockRule wireMockRule = new WireMockRule(8090) - - @Test - public void testGetResponseFromCatalogDb() { - ExecutionEntity mockExecution = setupMock() - when(mockExecution.getVariable("mso.catalog.db.endpoint")).thenReturn('http://localhost:8090') - when(mockExecution.getVariable("mso.adapters.db.auth")).thenReturn('757A94191D685FD2092AC1490730A4FC') - when(mockExecution.getVariable("mso.msoKey")).thenReturn('07a7159d3bf51a0e53be7a8f89699be7') - - stubFor(get(urlMatching(".*/serviceNetworks[?]serviceModelUuid=12345")) - .willReturn(aResponse() - .withStatus(200) - .withBodyFile("catalogDbFiles/DoCreateServiceInstance_request.json"))) - - CatalogDbUtils obj = new CatalogDbUtils() - String str = obj.getResponseFromCatalogDb(mockExecution, "/serviceNetworks?serviceModelUuid=12345") - String expectedValue = - FileUtil.readResourceFile("__files/catalogDbFiles/DoCreateServiceInstance_request.json"); - Assert.assertEquals(expectedValue, str) - - } - - private ExecutionEntity setupMock() { - - ProcessDefinition mockProcessDefinition = mock(ProcessDefinition.class) - when(mockProcessDefinition.getKey()).thenReturn("GenericGetService") - RepositoryService mockRepositoryService = mock(RepositoryService.class) - when(mockRepositoryService.getProcessDefinition()).thenReturn(mockProcessDefinition) - when(mockRepositoryService.getProcessDefinition().getKey()).thenReturn("GenericGetService") - when(mockRepositoryService.getProcessDefinition().getId()).thenReturn("100") - ProcessEngineServices mockProcessEngineServices = mock(ProcessEngineServices.class) - when(mockProcessEngineServices.getRepositoryService()).thenReturn(mockRepositoryService) - ExecutionEntity mockExecution = mock(ExecutionEntity.class) - when(mockExecution.getId()).thenReturn("100") - when(mockExecution.getProcessDefinitionId()).thenReturn("GenericGetService") - when(mockExecution.getProcessInstanceId()).thenReturn("GenericGetService") - when(mockExecution.getProcessEngineServices()).thenReturn(mockProcessEngineServices) - when(mockExecution.getProcessEngineServices().getRepositoryService().getProcessDefinition(mockExecution.getProcessDefinitionId())).thenReturn(mockProcessDefinition) - return mockExecution - } -} diff --git a/bpmn/MSOCommonBPMN/src/test/groovy/org/onap/so/bpmn/common/scripts/CompleteMsoProcessTest.groovy b/bpmn/MSOCommonBPMN/src/test/groovy/org/onap/so/bpmn/common/scripts/CompleteMsoProcessTest.groovy index 4b0c33ab99..70068c849b 100644 --- a/bpmn/MSOCommonBPMN/src/test/groovy/org/onap/so/bpmn/common/scripts/CompleteMsoProcessTest.groovy +++ b/bpmn/MSOCommonBPMN/src/test/groovy/org/onap/so/bpmn/common/scripts/CompleteMsoProcessTest.groovy @@ -76,7 +76,7 @@ class CompleteMsoProcessTest { ExecutionEntity mockExecution = mock(ExecutionEntity.class) when(mockExecution.getVariable("CompleteMsoProcessRequest")).thenReturn(completeMsoProcessRequest) - when(mockExecution.getVariable("mso.adapters.db.auth")).thenReturn("757A94191D685FD2092AC1490730A4FC"); + when(mockExecution.getVariable("mso.adapters.db.auth")).thenReturn("5E12ACACBD552A415E081E29F2C4772F9835792A51C766CCFDD7433DB5220B59969CB2798C"); when(mockExecution.getVariable("mso.msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7"); CompleteMsoProcess completeMsoProcess = new CompleteMsoProcess() @@ -155,28 +155,6 @@ class CompleteMsoProcessTest { <sdncadapterworkflow:out>BPEL BPEL-NAME FAILED</sdncadapterworkflow:out> </sdncadapterworkflow:MsoCompletionResponse>""" - @Test - void testBuildDataError() { - // given - def message = "Some-Message" - - def mockExecution = mock ExecutionEntity.class - when mockExecution.getVariable("CMSO_mso-bpel-name") thenReturn "BPEL-NAME" - when mockExecution.getVariable("testProcessKey") thenReturn "CompleteMsoProcess" - - def completeMsoProcess = new CompleteMsoProcess() - // when - assertThatThrownBy { completeMsoProcess.buildDataError(mockExecution, message) } isInstanceOf BpmnError - // then - verify mockExecution setVariable("CompleteMsoProcessResponse", msoCompletionResponse) - def argumentCaptor = ArgumentCaptor.forClass WorkflowException.class - verify mockExecution setVariable(eq("WorkflowException"), argumentCaptor.capture()) - def capturedException = argumentCaptor.value - - assertThat capturedException.processKey isEqualTo "CompleteMsoProcess" - assertThat capturedException.errorCode isEqualTo 500 - assertThat capturedException.errorMessage isEqualTo message - } @Test void postProcessResponse_successful() { diff --git a/bpmn/MSOCommonBPMN/src/test/groovy/org/onap/so/bpmn/common/scripts/ConfirmVolumeGroupTenantTest.groovy b/bpmn/MSOCommonBPMN/src/test/groovy/org/onap/so/bpmn/common/scripts/ConfirmVolumeGroupTenantTest.groovy index 5a01c83a80..e40b877177 100644 --- a/bpmn/MSOCommonBPMN/src/test/groovy/org/onap/so/bpmn/common/scripts/ConfirmVolumeGroupTenantTest.groovy +++ b/bpmn/MSOCommonBPMN/src/test/groovy/org/onap/so/bpmn/common/scripts/ConfirmVolumeGroupTenantTest.groovy @@ -20,106 +20,72 @@ package org.onap.so.bpmn.common.scripts -import com.github.tomakehurst.wiremock.junit.WireMockRule +import static com.shazam.shazamcrest.MatcherAssert.assertThat +import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs +import static org.mockito.Mockito.spy +import static org.mockito.Mockito.times +import static org.mockito.Mockito.when -import static org.junit.Assert.*; -import static org.mockito.Mockito.* - -import org.onap.so.rest.HttpHeader -import org.mockito.MockitoAnnotations -import org.mockito.runners.MockitoJUnitRunner -import org.mockito.internal.debugging.MockitoDebuggerImpl -import org.junit.Before -import org.onap.so.bpmn.common.scripts.AaiUtil; -import org.junit.Rule; -import org.junit.Test -import org.junit.Ignore -import org.junit.runner.RunWith -import org.junit.Before; -import org.junit.Test; -import org.camunda.bpm.engine.ProcessEngineServices -import org.camunda.bpm.engine.RepositoryService import org.camunda.bpm.engine.impl.persistence.entity.ExecutionEntity -import org.camunda.bpm.engine.impl.pvm.process.ProcessDefinitionImpl -import org.camunda.bpm.engine.repository.ProcessDefinition -import org.junit.Assert import org.junit.Before -import org.junit.Rule import org.junit.Test -import org.junit.runner.RunWith import org.mockito.ArgumentCaptor import org.mockito.Captor import org.mockito.Mockito -import org.mockito.runners.MockitoJUnitRunner -import org.onap.so.bpmn.common.scripts.ConfirmVolumeGroupTenant -import org.onap.so.bpmn.core.WorkflowException +import org.onap.aai.domain.yang.Relationship +import org.onap.aai.domain.yang.RelationshipData +import org.onap.aai.domain.yang.RelationshipList +import org.onap.aai.domain.yang.VolumeGroup +import org.onap.so.client.aai.AAIObjectType +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.constants.Defaults -import static com.github.tomakehurst.wiremock.client.WireMock.* -import static org.mockito.Mockito.* - -@RunWith(MockitoJUnitRunner.class) -@Ignore class ConfirmVolumeGroupTenantTest extends MsoGroovyTest { @Captor - ArgumentCaptor<ExecutionEntity> captor = ArgumentCaptor.forClass(ExecutionEntity.class); - - @Rule - public WireMockRule wireMockRule = new WireMockRule(8090); + static ArgumentCaptor<ExecutionEntity> captor = ArgumentCaptor.forClass(ExecutionEntity.class) + @Before + public void init(){ + super.init("ConfirmVolumeGroupTenant") + } @Test - public void testpreProcessRequest() { - ExecutionEntity mockExecution = setupMock() + void testpreProcessRequest() { + VolumeGroup expectedVolumeGroup = new VolumeGroup(); + expectedVolumeGroup.setVolumeGroupId("VolumeGroupId") + RelationshipList relationshipList = new RelationshipList(); + Relationship relationship = new Relationship(); + relationship.setRelatedTo("tenant") + RelationshipData data = new RelationshipData(); + data.setRelationshipKey("tenant.tenant-id") + data.setRelationshipValue("tenantId") + relationship.setRelatedLink("/cloud-infrastructure/cloud-regions/cloud-region/" + Defaults.CLOUD_OWNER.toString() + "/cloudRegionId/tenants/tenant/tenantId") + relationship.getRelationshipData().add(data) + relationshipList.getRelationship().add(relationship) + expectedVolumeGroup.setRelationshipList(relationshipList) + + + expectedVolumeGroup.setRelationshipList(relationshipList) + ConfirmVolumeGroupTenant confirmVolumeGroupTenant = spy(ConfirmVolumeGroupTenant.class) + when(confirmVolumeGroupTenant.getAAIClient()).thenReturn(client) + when(mockExecution.getVariable("aicCloudRegion")).thenReturn("aicCloudRegionId"); + when(mockExecution.getVariable("volumeGroupId")).thenReturn("volumeGroupId"); when(mockExecution.getVariable("aai.endpoint")).thenReturn('http://localhost:8090') - when(mockExecution.getVariable("volumeGroupId")).thenReturn('testVolumeGroupId') when(mockExecution.getVariable("volumeGroupName")).thenReturn('testVolumeGroupName') when(mockExecution.getVariable("tenantId")).thenReturn('tenantId') - when(mockExecution.getVariable("aicCloudRegion")).thenReturn('aicCloudRegion') when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn('true') when(mockExecution.getVariable("mso.workflow.global.default.aai.version")).thenReturn('8') when(mockExecution.getVariable("mso.workflow.default.aai.v8.cloud-region.uri")).thenReturn('/aai/v8/cloud-infrastructure/cloud-regions/cloud-region/CloudOwner') when(mockExecution.getVariable("mso.workflow.global.default.aai.namespace")).thenReturn('http://org.openecomp.aai.inventory/') - - - mockData() - - - ConfirmVolumeGroupTenant confirmVolumeGroupTenant = new ConfirmVolumeGroupTenant() + AAIResourceUri arURI = AAIUriFactory. createResourceUri(AAIObjectType.VOLUME_GROUP, Defaults.CLOUD_OWNER.toString(), "aicCloudRegionId","volumeGroupId") + AAIResultWrapper wrapper = new AAIResultWrapper(expectedVolumeGroup) + when(client.get(arURI)).thenReturn(wrapper) confirmVolumeGroupTenant.preProcessRequest(mockExecution) - /* Mockito.verify(mockExecution, times(5)).setVariable(captor.capture(), captor.capture())*/ - verify(mockExecution).setVariable("prefix", "CVGT_") - verify(mockExecution).setVariable("queryVolumeGroupResponseCode", 200) - verify(mockExecution).setVariable("queryAAIVolumeGroupResponse", "<volume-group xmlns=\"http://org.openecomp.aai.inventory/v10\"><volume-group-id>17ef4658-bd1f-4ef0-9ca0-ea76e2bf122c</volume-group-id><volume-group-name>MSOTESTVOL103a-vSAMP12_base_module-0_vol</volume-group-name><heat-stack-id>9d1f53e3-3158-44f8-8032-a6bf40bbc9db</heat-stack-id><vnf-type>pcrf-capacity</vnf-type><orchestration-status>Active</orchestration-status><resource-version>0000020</resource-version><relationship-list><relationship><related-to>tenant</related-to><relationship-data><relationship-key>cloud-region.cloud-owner</relationship-key><relationship-value>CloudOwner</relationship-value></relationship-data><relationship-data><relationship-key>cloud-region.cloud-region-id</relationship-key><relationship-value>RegionOne</relationship-value></relationship-data><relationship-data><relationship-key>tenant.tenant-id</relationship-key><relationship-value>22eb191dd41a4f3c9be370fc638322f4</relationship-value></relationship-data></relationship></relationship-list></volume-group>") - verify(mockExecution).setVariable("tenantIdsMatch", false) - verify(mockExecution).setVariable("groupNamesMatch", false) - } - - - private void mockData() { - stubFor(get(urlMatching("/aai/v8/cloud-infrastructure/cloud-regions/cloud-region/CloudOwner/aicCloudRegion/volume-groups/volume-group/testVolumeGroupId")) - .willReturn(aResponse() - .withStatus(200) - .withBody("<volume-group xmlns=\"http://org.openecomp.aai.inventory/v10\"><volume-group-id>17ef4658-bd1f-4ef0-9ca0-ea76e2bf122c</volume-group-id><volume-group-name>MSOTESTVOL103a-vSAMP12_base_module-0_vol</volume-group-name><heat-stack-id>9d1f53e3-3158-44f8-8032-a6bf40bbc9db</heat-stack-id><vnf-type>pcrf-capacity</vnf-type><orchestration-status>Active</orchestration-status><resource-version>0000020</resource-version><relationship-list><relationship><related-to>tenant</related-to><relationship-data><relationship-key>cloud-region.cloud-owner</relationship-key><relationship-value>CloudOwner</relationship-value></relationship-data><relationship-data><relationship-key>cloud-region.cloud-region-id</relationship-key><relationship-value>RegionOne</relationship-value></relationship-data><relationship-data><relationship-key>tenant.tenant-id</relationship-key><relationship-value>22eb191dd41a4f3c9be370fc638322f4</relationship-value></relationship-data></relationship></relationship-list></volume-group>"))) - } - - private ExecutionEntity setupMock() { - - ProcessDefinition mockProcessDefinition = mock(ProcessDefinition.class) - when(mockProcessDefinition.getKey()).thenReturn("ConfirmVolumeGroupTenant") - RepositoryService mockRepositoryService = mock(RepositoryService.class) - when(mockRepositoryService.getProcessDefinition()).thenReturn(mockProcessDefinition) - when(mockRepositoryService.getProcessDefinition().getKey()).thenReturn("ConfirmVolumeGroupTenant") - when(mockRepositoryService.getProcessDefinition().getId()).thenReturn("100") - ProcessEngineServices mockProcessEngineServices = mock(ProcessEngineServices.class) - when(mockProcessEngineServices.getRepositoryService()).thenReturn(mockRepositoryService) - - ExecutionEntity mockExecution = mock(ExecutionEntity.class) - when(mockExecution.getId()).thenReturn("100") - when(mockExecution.getProcessDefinitionId()).thenReturn("ConfirmVolumeGroupTenant") - when(mockExecution.getProcessInstanceId()).thenReturn("ConfirmVolumeGroupTenant") - when(mockExecution.getProcessEngineServices()).thenReturn(mockProcessEngineServices) - when(mockExecution.getProcessEngineServices().getRepositoryService().getProcessDefinition(mockExecution.getProcessDefinitionId())).thenReturn(mockProcessDefinition) + Mockito.verify(mockExecution, times(4)).setVariable(captor.capture(), captor.capture()) + List<ExecutionEntity> executionEntities = captor.getAllValues() - return mockExecution + assertThat(executionEntities.get(3), sameBeanAs(expectedVolumeGroup)) } } diff --git a/bpmn/MSOCommonBPMN/src/test/groovy/org/onap/so/bpmn/common/scripts/CreateAAIVfModuleTest.groovy b/bpmn/MSOCommonBPMN/src/test/groovy/org/onap/so/bpmn/common/scripts/CreateAAIVfModuleTest.groovy index 999a12c869..886e92bd45 100644 --- a/bpmn/MSOCommonBPMN/src/test/groovy/org/onap/so/bpmn/common/scripts/CreateAAIVfModuleTest.groovy +++ b/bpmn/MSOCommonBPMN/src/test/groovy/org/onap/so/bpmn/common/scripts/CreateAAIVfModuleTest.groovy @@ -2,16 +2,17 @@ * ============LICENSE_START======================================================= * ONAP - SO * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017 - 2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Copyright (C) 2018 Nokia. * ================================================================================ + * * 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. @@ -22,43 +23,160 @@ package org.onap.so.bpmn.common.scripts -import joptsimple.internal.Strings +import static org.assertj.core.api.Assertions.assertThat +import static org.mockito.ArgumentMatchers.any +import static org.mockito.ArgumentMatchers.anyObject +import static org.mockito.Mockito.mock +import static org.mockito.Mockito.when + import org.camunda.bpm.extension.mockito.delegate.DelegateExecutionFake import org.junit.Before import org.junit.Test +import org.mockito.Mockito +import org.mockito.MockitoAnnotations +import org.mockito.Spy +import org.onap.aai.domain.yang.GenericVnf +import org.onap.aai.domain.yang.VfModule +import org.onap.aai.domain.yang.VfModules import org.onap.so.bpmn.core.UrnPropertiesReader +import org.onap.so.client.aai.entities.uri.AAIResourceUri import org.springframework.core.env.Environment -import static org.assertj.core.api.Assertions.assertThat -import static org.mockito.Mockito.mock -import static org.mockito.Mockito.when +class CreateAAIVfModuleTest extends MsoGroovyTest{ -class CreateAAIVfModuleTest { - - private static final String VNF_ID = "vnfIdTest" - private static final String VNF_TYPE = "vnfTypeTest" - private static final String VNF_NAME = "testVnf" - private static final String SERVICE_ID = "123" - private static final String PERSONAL_MODEL_ID = "modelTest" - private static final String PERSONAL_MODEL_VERSION = "12" - private static final String MODEL_CUST_ID = "modelCustIdTest" - private static final String VNF_PERSONAL_MODEL_ID = "perModIdTest" - private static final String VNF_PERSONAL_MODEL_VER = "14" - private static final String VF_MODULE_NAME = "modTestName" - private static final String VF_MODULE_MODEL_NAME = "modModelNameTest" - private static final String DEFAULT_AAI_VERSION = "9" - private static final String DEFAULT_AAI_NAMESPACE = "defaultTestNamespace" - - private CreateAAIVfModule testedObject - private DelegateExecutionFake executionFake + private static final String VNF_ID = "vnfIdTest" + private static final String VNF_TYPE = "vnfTypeTest" + private static final String VNF_NAME = "testVnf" + private static final String SERVICE_ID = "123" + private static final String PERSONAL_MODEL_ID = "modelTest" + private static final String PERSONAL_MODEL_VERSION = "12" + private static final String MODEL_CUST_ID = "modelCustIdTest" + private static final String VNF_PERSONAL_MODEL_ID = "perModIdTest" + private static final String VNF_PERSONAL_MODEL_VER = "14" + private static final String VF_MODULE_NAME = "modTestName" + private static final String VF_MODULE_MODEL_NAME = "modModelNameTest" + private static final String DEFAULT_AAI_VERSION = "9" + private static final String DEFAULT_AAI_NAMESPACE = "defaultTestNamespace" + + @Spy + CreateAAIVfModule createAAIVfModule ; + private DelegateExecutionFake executionFake; + @Before - void setupTest() { - testedObject = new CreateAAIVfModule() + public void init() throws IOException { + super.init("CreateAAIVfModule") + MockitoAnnotations.initMocks(this); executionFake = new DelegateExecutionFake() + when(createAAIVfModule.getAAIClient()).thenReturn(client) + } + + @Test + void testQueryAAIForGenericVnf(){ + when(mockExecution.getVariable("CAAIVfMod_vnfId")).thenReturn("vnfId1") + when(mockExecution.getVariable("CAAIVfMod_vnfName")).thenReturn("vnfName") + Optional<GenericVnf> expectedResponse = mockAAIGenericVnf("vnfId1") + createAAIVfModule.queryAAIForGenericVnf(mockExecution) + Mockito.verify(mockExecution).setVariable("CAAIVfMod_queryGenericVnfResponseCode", 200) + Mockito.verify(mockExecution).setVariable("CAAIVfMod_queryGenericVnfResponse", expectedResponse.get()) + } + + @Test + void testQueryAAIForGenericVnfNotFound(){ + when(mockExecution.getVariable("CAAIVfMod_vnfId")).thenReturn("vnfIdNotFound") + when(mockExecution.getVariable("CAAIVfMod_vnfName")).thenReturn("vnfName") + mockAAIGenericVnfNotFound("vnfIdNotFound") + createAAIVfModule.queryAAIForGenericVnf(mockExecution) + Mockito.verify(mockExecution).setVariable("CAAIVfMod_queryGenericVnfResponseCode", 404) + Mockito.verify(mockExecution).setVariable("CAAIVfMod_queryGenericVnfResponse", "Generic Vnf not Found!") } + + @Test + void testCreateGenericVnf(){ + when(mockExecution.getVariable("CAAIVfMod_vnfName")).thenReturn("vnfName") + Mockito.doNothing().when(client).create(any(AAIResourceUri.class),anyObject()) + createAAIVfModule.createGenericVnf(mockExecution) + Mockito.verify(mockExecution).setVariable("CAAIVfMod_createGenericVnfResponseCode", 201) + Mockito.verify(mockExecution).setVariable("CAAIVfMod_createGenericVnfResponse","Vnf Created") + } + + + @Test + void testCreateVfModule(){ + Optional<GenericVnf> genericVnf = getAAIObjectFromJson(GenericVnf.class,"__files/aai/GenericVnfVfModule.json"); + when(mockExecution.getVariable("CAAIVfMod_queryGenericVnfResponse")).thenReturn(genericVnf.get()) + + when(mockExecution.getVariable("CAAIVfMod_personaId")).thenReturn("model1") + when(mockExecution.getVariable("CAAIVfMod_moduleName")).thenReturn("vfModuleName") + Mockito.doNothing().when(client).create(any(AAIResourceUri.class),anyObject()) + createAAIVfModule.createVfModule(mockExecution,false) + Mockito.verify(mockExecution).setVariable("CAAIVfMod_createVfModuleResponseCode", 201) + Mockito.verify(mockExecution).setVariable("CAAIVfMod_createVfModuleResponse","Vf Module Created") + } + + @Test + void testParseForAddOnModule(){ + Optional<GenericVnf> genericVnf = getAAIObjectFromJson(GenericVnf.class,"__files/aai/GenericVnfVfModule.json"); + when(mockExecution.getVariable("CAAIVfMod_queryGenericVnfResponse")).thenReturn(genericVnf.get()) + when(mockExecution.getVariable("CAAIVfMod_moduleName")).thenReturn("newVfModule") + createAAIVfModule.parseForAddOnModule(mockExecution) + Mockito.verify(mockExecution).setVariable("CAAIVfMod_moduleExists", false) + } + + @Test + void testParseForAddOnModuleTrue(){ + Optional<GenericVnf> genericVnf = getAAIObjectFromJson(GenericVnf.class,"__files/aai/GenericVnfVfModule.json"); + when(mockExecution.getVariable("CAAIVfMod_queryGenericVnfResponse")).thenReturn(genericVnf.get()) + when(mockExecution.getVariable("CAAIVfMod_moduleName")).thenReturn("testVfModuleNameGWPrim") + createAAIVfModule.parseForAddOnModule(mockExecution) + Mockito.verify(mockExecution).setVariable("CAAIVfMod_moduleExists", true) + } + + @Test + void testParseForBaseModule(){ + Optional<GenericVnf> genericVnfOps = getAAIObjectFromJson(GenericVnf.class,"__files/aai/GenericVnfVfModule.json") + GenericVnf genericVnf = genericVnfOps.get() + genericVnf.getVfModules().getVfModule().remove(0) + when(mockExecution.getVariable("CAAIVfMod_queryGenericVnfResponse")).thenReturn(genericVnf) + when(mockExecution.getVariable("CAAIVfMod_moduleName")).thenReturn("newVfModule") + createAAIVfModule.parseForBaseModule(mockExecution) + Mockito.verify(mockExecution).setVariable("CAAIVfMod_moduleExists", false) + } + + @Test + void testParseForBaseModuleConflict(){ + Optional<GenericVnf> genericVnf = getAAIObjectFromJson(GenericVnf.class,"__files/aai/GenericVnfVfModule.json"); + when(mockExecution.getVariable("CAAIVfMod_queryGenericVnfResponse")).thenReturn(genericVnf.get()) + when(mockExecution.getVariable("CAAIVfMod_moduleName")).thenReturn("testVfModuleNameGWPrim") + when(mockExecution.getVariable("CAAIVfMod_baseModuleConflict")).thenReturn(true) + createAAIVfModule.parseForBaseModule(mockExecution) + Mockito.verify(mockExecution).setVariable("CAAIVfMod_baseModuleConflict", true) + } + + @Test + void testParseForBaseModuleExists(){ + Optional<GenericVnf> genericVnf = getAAIObjectFromJson(GenericVnf.class,"__files/aai/GenericVnfVfModule.json"); + when(mockExecution.getVariable("CAAIVfMod_queryGenericVnfResponse")).thenReturn(genericVnf.get()) + when(mockExecution.getVariable("CAAIVfMod_moduleName")).thenReturn("newVfModule") + when(mockExecution.getVariable("CAAIVfMod_baseModuleConflict")).thenReturn(false) + createAAIVfModule.parseForBaseModule(mockExecution) + Mockito.verify(mockExecution).setVariable("CAAIVfMod_moduleExists", false) + Mockito.verify(mockExecution).setVariable("CAAIVfMod_baseModuleConflict", true) + } + + @Test + void testCreateVfModuleBase(){ + Optional<GenericVnf> genericVnf = getAAIObjectFromJson(GenericVnf.class,"__files/aai/GenericVnfVfModule.json"); + when(mockExecution.getVariable("CAAIVfMod_queryGenericVnfResponse")).thenReturn(genericVnf.get()) + when(mockExecution.getVariable("CAAIVfMod_moduleName")).thenReturn("vfModuleName") + Mockito.doNothing().when(client).create(any(AAIResourceUri.class),anyObject()) + createAAIVfModule.createVfModule(mockExecution,true) + Mockito.verify(mockExecution).setVariable("CAAIVfMod_createVfModuleResponseCode", 201) + Mockito.verify(mockExecution).setVariable("CAAIVfMod_createVfModuleResponse","Vf Module Created") + } + @Test void preProcessRequest_successful() { //given prepareUrnPropertiesReader() @@ -75,7 +193,7 @@ class CreateAAIVfModuleTest { executionFake.setVariable("vfModuleName", VF_MODULE_NAME) executionFake.setVariable("vfModuleModelName", VF_MODULE_MODEL_NAME) //when - testedObject.preProcessRequest(executionFake) + createAAIVfModule.preProcessRequest(executionFake) //then assertThat(executionFake.getVariable("CAAIVfMod_vnfId")).isEqualTo(VNF_ID) assertThat(executionFake.getVariable("CAAIVfMod_vnfName")).isEqualTo(VNF_NAME) @@ -96,10 +214,10 @@ class CreateAAIVfModuleTest { @Test void processAAIGenericVnfQuery_setVnfResponse() { executionFake.setVariable("CAAIVfMod_queryGenericVnfResponseCode", 200) - executionFake.setVariable("CAAIVfMod_vnfId", Strings.EMPTY) + executionFake.setVariable("CAAIVfMod_vnfId", "") executionFake.setVariable("CAAIVfMod_vnfName", VNF_NAME) - testedObject.processAAIGenericVnfQuery(executionFake) + createAAIVfModule.processAAIGenericVnfQuery(executionFake) assertThat(executionFake.getVariable("CAAIVfMod_queryGenericVnfResponse")) .isEqualTo("Invalid request for new Generic VNF which already exists, Vnf Name=" + VNF_NAME) @@ -110,7 +228,7 @@ class CreateAAIVfModuleTest { executionFake.setVariable("CAAIVfMod_queryGenericVnfResponseCode", 500) executionFake.setVariable("CAAIVfMod_vnfId", VNF_ID) - testedObject.processAAIGenericVnfQuery(executionFake) + createAAIVfModule.processAAIGenericVnfQuery(executionFake) assertThat(executionFake.getVariable("CAAIVfMod_createVfModuleResponse")) .isEqualTo("Invalid request for Add-on Module requested for non-existant Generic VNF, VNF Id=" + VNF_ID) @@ -118,12 +236,18 @@ class CreateAAIVfModuleTest { @Test void parseForAddOnModule_moduleNameFound() { - String xml = "<CAAIVfMod_queryGenericVnfResponse><vnf-name>" + VNF_NAME + "</vnf-name>" + - "<vf-module-name>" + VF_MODULE_NAME + "</vf-module-name></CAAIVfMod_queryGenericVnfResponse>" - executionFake.setVariable("CAAIVfMod_queryGenericVnfResponse", xml) + + GenericVnf vnf = new GenericVnf(); + VfModule module = new VfModule(); + VfModules modules = new VfModules(); + vnf.setVnfName(VNF_NAME) + vnf.setVfModules(modules) + modules.getVfModule().add(module) + module.setVfModuleName(VF_MODULE_NAME) + executionFake.setVariable("CAAIVfMod_queryGenericVnfResponse", vnf) executionFake.setVariable("CAAIVfMod_moduleName", VF_MODULE_NAME) - testedObject.parseForAddOnModule(executionFake) + createAAIVfModule.parseForAddOnModule(executionFake) assertThat(executionFake.getVariable("CAAIVfMod_vnfNameFromAAI")).isEqualTo(VNF_NAME) assertThat(executionFake.getVariable("CAAIVfMod_moduleExists")).isEqualTo(true) @@ -133,13 +257,13 @@ class CreateAAIVfModuleTest { @Test void parseForAddOnModule_moduleNameNotFound() { - String xml = "<CAAIVfMod_queryGenericVnfResponse><vnf-name>" + VNF_NAME + "</vnf-name>" + - "</CAAIVfMod_queryGenericVnfResponse>" - executionFake.setVariable("CAAIVfMod_queryGenericVnfResponse", xml) + GenericVnf vnf = new GenericVnf(); + vnf.setVnfName(VNF_NAME) + executionFake.setVariable("CAAIVfMod_queryGenericVnfResponse", vnf) executionFake.setVariable("CAAIVfMod_moduleName", VF_MODULE_NAME) executionFake.setVariable("CAAIVfMod_moduleExists", false) - testedObject.parseForAddOnModule(executionFake) + createAAIVfModule.parseForAddOnModule(executionFake) assertThat(executionFake.getVariable("CAAIVfMod_vnfNameFromAAI")).isEqualTo(VNF_NAME) assertThat(executionFake.getVariable("CAAIVfMod_moduleExists")).isEqualTo(false) @@ -149,12 +273,17 @@ class CreateAAIVfModuleTest { @Test void parseForBaseModule_moduleNameFound() { - String xml = "<CAAIVfMod_queryGenericVnfResponse><vnf-name>" + VNF_NAME + "</vnf-name>" + - "<vf-module-name>" + VF_MODULE_NAME + "</vf-module-name></CAAIVfMod_queryGenericVnfResponse>" - executionFake.setVariable("CAAIVfMod_queryGenericVnfResponse", xml) + GenericVnf vnf = new GenericVnf(); + VfModule module = new VfModule(); + VfModules modules = new VfModules(); + vnf.setVnfName(VNF_NAME) + vnf.setVfModules(modules) + modules.getVfModule().add(module) + module.setVfModuleName(VF_MODULE_NAME) + executionFake.setVariable("CAAIVfMod_queryGenericVnfResponse", vnf) executionFake.setVariable("CAAIVfMod_moduleName", VF_MODULE_NAME) - testedObject.parseForBaseModule(executionFake) + createAAIVfModule.parseForBaseModule(executionFake) assertThat(executionFake.getVariable("CAAIVfMod_vnfNameFromAAI")).isEqualTo(VNF_NAME) assertThat(executionFake.getVariable("CAAIVfMod_moduleExists")).isEqualTo(false) @@ -165,12 +294,19 @@ class CreateAAIVfModuleTest { @Test void parseForBaseModule_isBaseVfModule() { - String xml = "<CAAIVfMod_queryGenericVnfResponse><vnf-name>" + VNF_NAME + "</vnf-name>" + - "<is-base-vf-module>true</is-base-vf-module></CAAIVfMod_queryGenericVnfResponse>" - executionFake.setVariable("CAAIVfMod_queryGenericVnfResponse", xml) + GenericVnf vnf = new GenericVnf(); + VfModule module = new VfModule(); + VfModules modules = new VfModules(); + vnf.setVfModules(modules) + vnf.setVnfName(VNF_NAME) + modules.getVfModule().add(module) + module.setVfModuleName(VF_MODULE_NAME) + module.setIsBaseVfModule(true) + + executionFake.setVariable("CAAIVfMod_queryGenericVnfResponse", vnf) executionFake.setVariable("CAAIVfMod_baseModuleConflict", false) - testedObject.parseForBaseModule(executionFake) + createAAIVfModule.parseForBaseModule(executionFake) assertThat(executionFake.getVariable("CAAIVfMod_vnfNameFromAAI")).isEqualTo(VNF_NAME) assertThat(executionFake.getVariable("CAAIVfMod_moduleExists")).isEqualTo(false) @@ -181,12 +317,13 @@ class CreateAAIVfModuleTest { @Test void parseForBaseModule_baseModuleConflictIsFalse() { - String xml = "<CAAIVfMod_queryGenericVnfResponse><vnf-name>" + VNF_NAME + "</vnf-name></CAAIVfMod_queryGenericVnfResponse>" - executionFake.setVariable("CAAIVfMod_queryGenericVnfResponse", xml) + GenericVnf vnf = new GenericVnf(); + vnf.setVnfName(VNF_NAME) + executionFake.setVariable("CAAIVfMod_queryGenericVnfResponse", vnf) executionFake.setVariable("CAAIVfMod_baseModuleConflict", false) executionFake.setVariable("CAAIVfMod_moduleName", VF_MODULE_NAME) - testedObject.parseForBaseModule(executionFake) + createAAIVfModule.parseForBaseModule(executionFake) assertThat(executionFake.getVariable("CAAIVfMod_vnfNameFromAAI")).isEqualTo(VNF_NAME) assertThat(executionFake.getVariable("CAAIVfMod_moduleExists")).isEqualTo(false) @@ -201,5 +338,4 @@ class CreateAAIVfModuleTest { UrnPropertiesReader urnPropertiesReader = new UrnPropertiesReader() urnPropertiesReader.setEnvironment(mockEnvironment) } - } diff --git a/bpmn/MSOCommonBPMN/src/test/groovy/org/onap/so/bpmn/common/scripts/CreateAAIVfModuleVolumeGroupTest.groovy b/bpmn/MSOCommonBPMN/src/test/groovy/org/onap/so/bpmn/common/scripts/CreateAAIVfModuleVolumeGroupTest.groovy new file mode 100644 index 0000000000..ea38ed8c83 --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/test/groovy/org/onap/so/bpmn/common/scripts/CreateAAIVfModuleVolumeGroupTest.groovy @@ -0,0 +1,119 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2018 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.bpmn.common.scripts + +import static org.mockito.Mockito.doNothing +import static org.mockito.Mockito.doThrow +import static org.mockito.Mockito.when + +import org.junit.Before +import org.junit.Test +import org.mockito.Mockito +import org.mockito.Spy +import org.onap.so.client.aai.AAIObjectType +import org.onap.so.client.aai.entities.uri.AAIResourceUri +import org.onap.so.client.aai.entities.uri.AAIUriFactory +import org.onap.so.constants.Defaults + +class CreateAAIVfModuleVolumeGroupTest extends MsoGroovyTest{ + + @Spy + CreateAAIVfModuleVolumeGroup createAAIVfModuleVolumeGroup; + + @Before + void init(){ + super.init("CreateAAIVfModuleVolumeGroup") + when(createAAIVfModuleVolumeGroup.getAAIClient()).thenReturn(client) + } + + @Test + void testGetVfModule (){ + when(mockExecution.getVariable("CAAIVfModVG_vnfId")).thenReturn("Vnf123") + when(mockExecution.getVariable("CAAIVfModVG_vfModuleId")).thenReturn("VfModule123") + org.onap.aai.domain.yang.VfModule vfModuleExpected = new org.onap.aai.domain.yang.VfModule() + vfModuleExpected.setVfModuleId("VfModule123") + AAIResourceUri resourceUri = AAIUriFactory.createResourceUri(AAIObjectType.VF_MODULE, "Vnf123", "VfModule123"); + when(client.get(org.onap.aai.domain.yang.VfModule.class,resourceUri)).thenReturn(Optional.of(vfModuleExpected)) + createAAIVfModuleVolumeGroup.getVfModule(mockExecution) + Mockito.verify(mockExecution).setVariable("CAAIVfModVG_getVfModuleResponseCode", 200) + Mockito.verify(mockExecution).setVariable("CAAIVfModVG_getVfModuleResponse", vfModuleExpected) + } + + @Test + void testGetVfModuleNotFound (){ + when(mockExecution.getVariable("CAAIVfModVG_vnfId")).thenReturn("Vnf123") + when(mockExecution.getVariable("CAAIVfModVG_vfModuleId")).thenReturn("VfModule123") + AAIResourceUri resourceUri = AAIUriFactory.createResourceUri(AAIObjectType.VF_MODULE, "Vnf123", "VfModule123"); + when(client.get(org.onap.aai.domain.yang.VfModule.class,resourceUri)).thenReturn(Optional.empty()) + createAAIVfModuleVolumeGroup.getVfModule(mockExecution) + Mockito.verify(mockExecution).setVariable("CAAIVfModVG_getVfModuleResponseCode", 404) + Mockito.verify(mockExecution).setVariable("CAAIVfModVG_getVfModuleResponse", "VF-Module Not found!!") + } + + @Test + void testGetVfModuleException (){ + when(mockExecution.getVariable("CAAIVfModVG_vnfId")).thenReturn("Vnf123") + when(mockExecution.getVariable("CAAIVfModVG_vfModuleId")).thenReturn("VfModule123") + AAIResourceUri resourceUri = AAIUriFactory.createResourceUri(AAIObjectType.VF_MODULE, "Vnf123", "VfModule123"); + when(client.get(org.onap.aai.domain.yang.VfModule.class,resourceUri)).thenThrow(new NullPointerException("Error in AAI client")) + createAAIVfModuleVolumeGroup.getVfModule(mockExecution) + Mockito.verify(mockExecution).setVariable("CAAIVfModVG_getVfModuleResponseCode", 500) + Mockito.verify(mockExecution).setVariable("CAAIVfModVG_getVfModuleResponse", "AAI GET Failed:Error in AAI client") + } + + @Test + void testUpdateVfModule (){ + when(mockExecution.getVariable("CAAIVfModVG_vnfId")).thenReturn("Vnf123") + when(mockExecution.getVariable("CAAIVfModVG_vfModuleId")).thenReturn("VfModule123") + when(mockExecution.getVariable("CAAIVfModVG_aicCloudRegion")).thenReturn("CloudRegion1") + when(mockExecution.getVariable("CAAIVfModVG_volumeGroupId")).thenReturn("VolumeGroup1") + when(mockExecution.getVariable("CAAIVfModVG_cloudOwner")).thenReturn("cloudOwner") + org.onap.aai.domain.yang.VfModule vfModuleExpected = new org.onap.aai.domain.yang.VfModule() + vfModuleExpected.setVfModuleId("VfModule123") + vfModuleExpected.setResourceVersion("12345") + when(mockExecution.getVariable("CAAIVfModVG_getVfModuleResponse")).thenReturn(vfModuleExpected) + AAIResourceUri resourceUri = AAIUriFactory.createResourceUri(AAIObjectType.VF_MODULE, "Vnf123", "VfModule123"); + AAIResourceUri resourceUri1 = AAIUriFactory.createResourceUri(AAIObjectType.VOLUME_GROUP, Defaults.CLOUD_OWNER.toString(),"CloudRegion1", "VolumeGroup1") + doNothing().when(client).connect(resourceUri ,resourceUri1 ) + createAAIVfModuleVolumeGroup.updateVfModule(mockExecution) + Mockito.verify(mockExecution).setVariable("CAAIVfModVG_updateVfModuleResponseCode", 200) + Mockito.verify(mockExecution).setVariable("CAAIVfModVG_updateVfModuleResponse", "Success") + } + + @Test + void testUpdateVfModuleAAIException (){ + when(mockExecution.getVariable("CAAIVfModVG_vnfId")).thenReturn("Vnf123") + when(mockExecution.getVariable("CAAIVfModVG_vfModuleId")).thenReturn("VfModule123") + when(mockExecution.getVariable("CAAIVfModVG_aicCloudRegion")).thenReturn("CloudRegion1") + when(mockExecution.getVariable("CAAIVfModVG_volumeGroupId")).thenReturn("VolumeGroup1") + org.onap.aai.domain.yang.VfModule vfModuleExpected = new org.onap.aai.domain.yang.VfModule() + vfModuleExpected.setVfModuleId("VfModule123") + vfModuleExpected.setResourceVersion("12345") + when(mockExecution.getVariable("CAAIVfModVG_cloudOwner")).thenReturn("cloudOwner") + when(mockExecution.getVariable("CAAIVfModVG_getVfModuleResponse")).thenReturn(vfModuleExpected) + AAIResourceUri resourceUri = AAIUriFactory.createResourceUri(AAIObjectType.VF_MODULE, "Vnf123", "VfModule123"); + AAIResourceUri resourceUri1 = AAIUriFactory.createResourceUri(AAIObjectType.VOLUME_GROUP, 'cloudOwner',"CloudRegion1", "VolumeGroup1") + doThrow(new NullPointerException("Error in AAI client")).when(client).connect(resourceUri ,resourceUri1 ) + createAAIVfModuleVolumeGroup.updateVfModule(mockExecution) + Mockito.verify(mockExecution).setVariable("CAAIVfModVG_updateVfModuleResponseCode", 500) + Mockito.verify(mockExecution).setVariable("CAAIVfModVG_updateVfModuleResponse", 'AAI PUT Failed:'+ "Error in AAI client") + } +} diff --git a/bpmn/MSOCommonBPMN/src/test/groovy/org/onap/so/bpmn/common/scripts/DeleteAAIVfModuleTest.groovy b/bpmn/MSOCommonBPMN/src/test/groovy/org/onap/so/bpmn/common/scripts/DeleteAAIVfModuleTest.groovy index 025bea5325..4b6f8aa918 100644 --- a/bpmn/MSOCommonBPMN/src/test/groovy/org/onap/so/bpmn/common/scripts/DeleteAAIVfModuleTest.groovy +++ b/bpmn/MSOCommonBPMN/src/test/groovy/org/onap/so/bpmn/common/scripts/DeleteAAIVfModuleTest.groovy @@ -20,125 +20,157 @@ package org.onap.so.bpmn.common.scripts -import com.github.tomakehurst.wiremock.junit.WireMockRule +import static org.mockito.Mockito.* + +import javax.ws.rs.NotFoundException + import org.camunda.bpm.engine.ProcessEngineServices import org.camunda.bpm.engine.RepositoryService +import org.camunda.bpm.engine.delegate.DelegateExecution import org.camunda.bpm.engine.impl.persistence.entity.ExecutionEntity import org.camunda.bpm.engine.repository.ProcessDefinition +import org.camunda.bpm.extension.mockito.delegate.DelegateExecutionFake import org.junit.Assert import org.junit.Before -import org.junit.Ignore -import org.junit.Rule import org.junit.Test -import org.junit.runner.RunWith import org.mockito.ArgumentCaptor import org.mockito.Captor -import org.mockito.Mock import org.mockito.Mockito -import org.mockito.MockitoAnnotations -import org.mockito.runners.MockitoJUnitRunner +import org.mockito.Spy +import org.onap.aai.domain.yang.GenericVnf import org.onap.so.bpmn.core.WorkflowException -import org.onap.so.bpmn.mock.StubResponseAAI - -import static com.github.tomakehurst.wiremock.client.WireMock.* -import static org.mockito.Mockito.* +import org.onap.so.client.aai.entities.uri.AAIResourceUri -@RunWith(MockitoJUnitRunner.class) -@Ignore -class DeleteAAIVfModuleTest { +class DeleteAAIVfModuleTest extends MsoGroovyTest{ def prefix = "DAAIVfMod_" - @Rule - public WireMockRule wireMockRule = new WireMockRule(28090) + @Spy + DeleteAAIVfModule deleteAAIVfModule ; @Captor static ArgumentCaptor<ExecutionEntity> captor = ArgumentCaptor.forClass(ExecutionEntity.class) @Before void init() throws IOException { - MockitoAnnotations.initMocks(this); + super.init("DeleteAAIVfModule") + when(deleteAAIVfModule.getAAIClient()).thenReturn(client) } @Test void testQueryAAIForGenericVnf() { ExecutionEntity mockExecution = setupMock() - when(mockExecution.getVariable("prefix")).thenReturn(prefix) - when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") - when(mockExecution.getVariable(prefix + "genericVnfEndpoint")).thenReturn("/aai/v8/network/generic-vnfs/generic-vnf/skask") - when(mockExecution.getVariable(prefix + "vfModuleId")).thenReturn("supercool") - when(mockExecution.getVariable("aai.endpoint")).thenReturn("http://localhost:28090") - when(mockExecution.getVariable("aai.auth")).thenReturn("9B2278E8B8E95F256A560719055F4DF3") - when(mockExecution.getVariable("mso.msoKey")).thenReturn("aa3871669d893c7fb8abbcda31b88b4f") - - StubResponseAAI.MockAAIVfModule() - DeleteAAIVfModule obj = new DeleteAAIVfModule() - obj.queryAAIForGenericVnf(mockExecution) - + when(mockExecution.getVariable("DAAIVfMod_vnfId")).thenReturn("vnfId1") + mockAAIGenericVnf("vnfId1") + deleteAAIVfModule.queryAAIForGenericVnf(mockExecution) Mockito.verify(mockExecution).setVariable(prefix + "queryGenericVnfResponseCode", 200) } @Test - void testQueryAAIForGenericVnfEndpointNull() { + void testQueryAAIForGenericVnfNotFound() { ExecutionEntity mockExecution = setupMock() - when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") - when(mockExecution.getVariable(prefix + "genericVnfEndpoint")).thenReturn("/aai/v8/network/generic-vnfs/generic-vnf/skask") - when(mockExecution.getVariable(prefix + "vfModuleId")).thenReturn("supercool") - when(mockExecution.getVariable("aai.endpoint")).thenReturn(null) - when(mockExecution.getVariable("aai.auth")).thenReturn("9B2278E8B8E95F256A560719055F4DF3") - when(mockExecution.getVariable("mso.msoKey")).thenReturn("aa3871669d893c7fb8abbcda31b88b4f") - - StubResponseAAI.MockAAIVfModule() + when(mockExecution.getVariable("DAAIVfMod_vnfId")).thenReturn("vnfId1") + mockAAIGenericVnfNotFound("vnfId1") + deleteAAIVfModule.queryAAIForGenericVnf(mockExecution) + Mockito.verify(mockExecution).setVariable(prefix + "queryGenericVnfResponseCode", 404) + } + @Test + void testQueryAAIForGenericVnfEndpointNull() { + DelegateExecution execution = new DelegateExecutionFake(); + execution.setVariable("DAAIVfMod_vnfId", "vnfId1") try { - DeleteAAIVfModule obj = new DeleteAAIVfModule() - obj.queryAAIForGenericVnf(mockExecution) + deleteAAIVfModule.queryAAIForGenericVnf(execution) } catch (Exception ex) { println " Test End - Handle catch-throw BpmnError()! " } - Mockito.verify(mockExecution, times(2)).setVariable(captor.capture(), captor.capture()) - WorkflowException workflowException = captor.getValue() - Assert.assertEquals(5000, workflowException.getErrorCode()) - Assert.assertEquals("Internal Error - Occured during queryAAIForGenericVnf", workflowException.getErrorMessage()) + Assert.assertEquals(404, execution.getVariable("DAAIVfMod_queryGenericVnfResponseCode")) + Assert.assertEquals("Vnf Not Found!", execution.getVariable("DAAIVfMod_queryGenericVnfResponse")) } @Test void testDeleteGenericVnf() { ExecutionEntity mockExecution = setupMock() - when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") - when(mockExecution.getVariable(prefix + "genericVnfEndpoint")).thenReturn("/aai/v9/cloud-infrastructure/volume-groups/volume-group/78987") - when(mockExecution.getVariable(prefix + "genVnfRsrcVer")).thenReturn("0000020") - when(mockExecution.getVariable("aai.endpoint")).thenReturn("http://localhost:28090") - when(mockExecution.getVariable("aai.auth")).thenReturn("9B2278E8B8E95F256A560719055F4DF3") - when(mockExecution.getVariable("mso.msoKey")).thenReturn("aa3871669d893c7fb8abbcda31b88b4f") - - stubFor(delete(urlMatching("/aai/v[0-9]+/cloud-infrastructure/volume-groups/volume-group/78987/[?]resource-version=0000020")) - .willReturn(aResponse() - .withStatus(200) - .withHeader("Content-Type", "text/xml") - .withBodyFile(""))) - - StubResponseAAI.MockAAIVfModule() - DeleteAAIVfModule obj = new DeleteAAIVfModule() - obj.deleteGenericVnf(mockExecution) - + when(mockExecution.getVariable("DAAIVfMod_vnfId")).thenReturn("vnfId1") + doNothing().when(client).delete(isA(AAIResourceUri.class)) + deleteAAIVfModule.deleteGenericVnf(mockExecution) Mockito.verify(mockExecution).setVariable(prefix + "deleteGenericVnfResponseCode", 200) } @Test + void testParseForVfModule() { + ExecutionEntity mockExecution = setupMock() + when(mockExecution.getVariable("DAAIVfMod_vfModuleId")).thenReturn("testVfModuleIdGWSec") + Optional<GenericVnf> genericVnf = getAAIObjectFromJson(GenericVnf.class,"__files/aai/GenericVnfVfModule.json"); + when(mockExecution.getVariable("DAAIVfMod_queryGenericVnfResponse")).thenReturn(genericVnf.get()) + deleteAAIVfModule.parseForVfModule(mockExecution) + Mockito.verify(mockExecution).setVariable("DAAIVfMod_moduleExists", true) + Mockito.verify(mockExecution).setVariable("DAAIVfMod_isBaseModule", false) + Mockito.verify(mockExecution).setVariable("DAAIVfMod_isLastModule", false) + } + + @Test + void testParseForVfModuleNotFound() { + ExecutionEntity mockExecution = setupMock() + when(mockExecution.getVariable("DAAIVfMod_vfModuleId")).thenReturn("notFound") + when(mockExecution.getVariable("DAAIVfMod_moduleExists")).thenReturn(false) + Optional<GenericVnf> genericVnf = getAAIObjectFromJson(GenericVnf.class,"__files/aai/GenericVnfVfModule.json"); + when(mockExecution.getVariable("DAAIVfMod_queryGenericVnfResponse")).thenReturn(genericVnf.get()) + deleteAAIVfModule.parseForVfModule(mockExecution) + Mockito.verify(mockExecution).setVariable("DAAIVfMod_moduleExists", false) + Mockito.verify(mockExecution).setVariable("DAAIVfMod_isBaseModule", false) + Mockito.verify(mockExecution).setVariable("DAAIVfMod_isLastModule", false) + } + + @Test + void testParseForVfModuleBase() { + ExecutionEntity mockExecution = setupMock() + when(mockExecution.getVariable("DAAIVfMod_vfModuleId")).thenReturn("lukewarm") + Optional<GenericVnf> genericVnf = getAAIObjectFromJson(GenericVnf.class,"__files/aai/GenericVnfVfModule.json"); + when(mockExecution.getVariable("DAAIVfMod_queryGenericVnfResponse")).thenReturn(genericVnf.get()) + deleteAAIVfModule.parseForVfModule(mockExecution) + Mockito.verify(mockExecution).setVariable("DAAIVfMod_moduleExists", true) + Mockito.verify(mockExecution).setVariable("DAAIVfMod_isBaseModule", true) + Mockito.verify(mockExecution).setVariable("DAAIVfMod_isLastModule", false) + } + + @Test + void testParseForVfModuleLast() { + ExecutionEntity mockExecution = setupMock() + when(mockExecution.getVariable("DAAIVfMod_vfModuleId")).thenReturn("testVfModuleIdGWSec") + Optional<GenericVnf> genericVnfOps = getAAIObjectFromJson(GenericVnf.class,"__files/aai/GenericVnfVfModule.json"); + GenericVnf genericVnf = genericVnfOps.get(); + genericVnf.getVfModules().getVfModule().remove(0) + when(mockExecution.getVariable("DAAIVfMod_queryGenericVnfResponse")).thenReturn(genericVnf) + deleteAAIVfModule.parseForVfModule(mockExecution) + Mockito.verify(mockExecution).setVariable("DAAIVfMod_moduleExists", true) + Mockito.verify(mockExecution).setVariable("DAAIVfMod_isBaseModule", false) + Mockito.verify(mockExecution).setVariable("DAAIVfMod_isLastModule", true) + } + + @Test + void testParseForVfModuleBaseLast() { + ExecutionEntity mockExecution = setupMock() + when(mockExecution.getVariable("DAAIVfMod_vfModuleId")).thenReturn("lukewarm") + Optional<GenericVnf> genericVnfOps = getAAIObjectFromJson(GenericVnf.class,"__files/aai/GenericVnfVfModule.json"); + GenericVnf genericVnf = genericVnfOps.get(); + genericVnf.getVfModules().getVfModule().remove(1) + when(mockExecution.getVariable("DAAIVfMod_queryGenericVnfResponse")).thenReturn(genericVnf) + deleteAAIVfModule.parseForVfModule(mockExecution) + Mockito.verify(mockExecution).setVariable("DAAIVfMod_moduleExists", true) + Mockito.verify(mockExecution).setVariable("DAAIVfMod_isBaseModule", true) + Mockito.verify(mockExecution).setVariable("DAAIVfMod_isLastModule", true) + } + + + + @Test void testDeleteGenericVnfEndpointNull() { ExecutionEntity mockExecution = setupMock() - when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") - when(mockExecution.getVariable(prefix + "genericVnfEndpoint")).thenReturn("/aai/v9/cloud-infrastructure/volume-groups/volume-group/78987") - when(mockExecution.getVariable(prefix + "genVnfRsrcVer")).thenReturn("0000020") - when(mockExecution.getVariable("aai.endpoint")).thenReturn(null) - when(mockExecution.getVariable("aai.auth")).thenReturn("9B2278E8B8E95F256A560719055F4DF3") - when(mockExecution.getVariable("mso.msoKey")).thenReturn("aa3871669d893c7fb8abbcda31b88b4f") - - StubResponseAAI.MockAAIVfModule() + when(mockExecution.getVariable("DAAIVfMod_vnfId")).thenReturn("vnfId1") try { - DeleteAAIVfModule obj = new DeleteAAIVfModule() - obj.deleteGenericVnf(mockExecution) + doThrow(new NotFoundException("Vnf Not Found")).when(client).delete(isA(AAIResourceUri.class)) + deleteAAIVfModule.deleteGenericVnf(mockExecution) } catch (Exception ex) { println " Test End - Handle catch-throw BpmnError()! " } @@ -152,39 +184,21 @@ class DeleteAAIVfModuleTest { @Test void testDeleteVfModule() { ExecutionEntity mockExecution = setupMock() - when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") - when(mockExecution.getVariable(prefix + "vfModuleEndpoint")).thenReturn("/aai/v9/cloud-infrastructure/volume-groups/volume-group/78987") - when(mockExecution.getVariable(prefix + "vfModRsrcVer")).thenReturn("0000020") - when(mockExecution.getVariable("aai.endpoint")).thenReturn("http://localhost:28090") - when(mockExecution.getVariable("aai.auth")).thenReturn("9B2278E8B8E95F256A560719055F4DF3") - when(mockExecution.getVariable("mso.msoKey")).thenReturn("aa3871669d893c7fb8abbcda31b88b4f") - - stubFor(delete(urlMatching("/aai/v[0-9]+/cloud-infrastructure/volume-groups/volume-group/78987/[?]resource-version=0000020")) - .willReturn(aResponse() - .withStatus(200) - .withHeader("Content-Type", "text/xml") - .withBodyFile(""))) - - DeleteAAIVfModule obj = new DeleteAAIVfModule() - obj.deleteVfModule(mockExecution) - + when(mockExecution.getVariable("DAAIVfMod_vnfId")).thenReturn("vnfId1") + when(mockExecution.getVariable("DAAIVfMod_vfModuleId")).thenReturn("vfModuleId1") + doNothing().when(client).delete(isA(AAIResourceUri.class)) + deleteAAIVfModule.deleteVfModule(mockExecution) Mockito.verify(mockExecution).setVariable(prefix + "deleteVfModuleResponseCode", 200) } @Test void testDeleteVfModuleEndpointNull() { ExecutionEntity mockExecution = setupMock() - when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") - when(mockExecution.getVariable(prefix + "vfModuleEndpoint")).thenReturn("/aai/v9/cloud-infrastructure/volume-groups/volume-group/78987") - when(mockExecution.getVariable(prefix + "vfModRsrcVer")).thenReturn("0000020") - when(mockExecution.getVariable("aai.endpoint")).thenReturn(null) - when(mockExecution.getVariable("aai.auth")).thenReturn("9B2278E8B8E95F256A560719055F4DF3") - when(mockExecution.getVariable("mso.msoKey")).thenReturn("aa3871669d893c7fb8abbcda31b88b4f") - - StubResponseAAI.MockAAIVfModule() + when(mockExecution.getVariable("DAAIVfMod_vnfId")).thenReturn("vnfId1") + when(mockExecution.getVariable("DAAIVfMod_vfModuleId")).thenReturn("vfModuleId1") try { - DeleteAAIVfModule obj = new DeleteAAIVfModule() - obj.deleteVfModule(mockExecution) + doThrow(new NotFoundException("Vnf Not Found")).when(client).delete(isA(AAIResourceUri.class)) + deleteAAIVfModule.deleteVfModule(mockExecution) } catch (Exception ex) { println " Test End - Handle catch-throw BpmnError()! " } diff --git a/bpmn/MSOCommonBPMN/src/test/groovy/org/onap/so/bpmn/common/scripts/FalloutHandlerTest.groovy b/bpmn/MSOCommonBPMN/src/test/groovy/org/onap/so/bpmn/common/scripts/FalloutHandlerTest.groovy index 016d968a12..25f62a6555 100644 --- a/bpmn/MSOCommonBPMN/src/test/groovy/org/onap/so/bpmn/common/scripts/FalloutHandlerTest.groovy +++ b/bpmn/MSOCommonBPMN/src/test/groovy/org/onap/so/bpmn/common/scripts/FalloutHandlerTest.groovy @@ -72,7 +72,7 @@ class FalloutHandlerTest { ExecutionEntity mockExecution = mock(ExecutionEntity.class) when(mockExecution.getVariable("FalloutHandlerRequest")).thenReturn(falloutHandlerRequest) - when(mockExecution.getVariable("mso.adapters.db.auth")).thenReturn("757A94191D685FD2092AC1490730A4FC"); + when(mockExecution.getVariable("mso.adapters.db.auth")).thenReturn("5E12ACACBD552A415E081E29F2C4772F9835792A51C766CCFDD7433DB5220B59969CB2798C"); when(mockExecution.getVariable("mso.msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7"); FalloutHandler falloutHandler = new FalloutHandler() diff --git a/bpmn/MSOCommonBPMN/src/test/groovy/org/onap/so/bpmn/common/scripts/MsoGroovyTest.groovy b/bpmn/MSOCommonBPMN/src/test/groovy/org/onap/so/bpmn/common/scripts/MsoGroovyTest.groovy index 19638f42da..de44caa120 100644 --- a/bpmn/MSOCommonBPMN/src/test/groovy/org/onap/so/bpmn/common/scripts/MsoGroovyTest.groovy +++ b/bpmn/MSOCommonBPMN/src/test/groovy/org/onap/so/bpmn/common/scripts/MsoGroovyTest.groovy @@ -16,7 +16,7 @@ * See the License for the specific language governing permissions and * limitations under the License. * ============LICENSE_END========================================================= - */ + */ package org.onap.so.bpmn.common.scripts @@ -29,16 +29,30 @@ import org.camunda.bpm.engine.repository.ProcessDefinition import org.junit.Rule import org.junit.rules.ExpectedException import org.junit.runner.RunWith -import org.mockito.runners.MockitoJUnitRunner +import org.mockito.junit.MockitoJUnitRunner +import org.onap.aai.domain.yang.GenericVnf +import org.onap.so.bpmn.mock.FileUtil +import org.onap.so.client.aai.AAIObjectPlurals +import org.onap.so.client.aai.AAIObjectType import org.onap.so.client.aai.AAIResourcesClient +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.onap.so.constants.Defaults -@RunWith(MockitoJUnitRunner.class) +@RunWith(MockitoJUnitRunner.Silent.class) abstract class MsoGroovyTest { @Rule public ExpectedException thrown = ExpectedException.none() + protected ExecutionEntity mockExecution protected AAIResourcesClient client + protected AllottedResourceUtils allottedResourceUtils_MOCK + protected final String SEARCH_RESULT_AAI_WITH_RESULTDATA = + FileUtil.readResourceFile("__files/aai/searchResults.json") + protected static final String CLOUD_OWNER = Defaults.CLOUD_OWNER.toString(); protected void init(String procName){ mockExecution = setupMock(procName) @@ -49,14 +63,91 @@ abstract class MsoGroovyTest { protected ExecutionEntity setupMock(String procName) { ProcessDefinition mockProcessDefinition = mock(ProcessDefinition.class) when(mockProcessDefinition.getKey()).thenReturn(procName) + RepositoryService mockRepositoryService = mock(RepositoryService.class) when(mockRepositoryService.getProcessDefinition()).thenReturn(mockProcessDefinition) when(mockRepositoryService.getProcessDefinition().getKey()).thenReturn(procName) when(mockRepositoryService.getProcessDefinition().getId()).thenReturn("100") + ProcessEngineServices mockProcessEngineServices = mock(ProcessEngineServices.class) when(mockProcessEngineServices.getRepositoryService()).thenReturn(mockRepositoryService) + ExecutionEntity mockExecution = mock(ExecutionEntity.class) when(mockExecution.getProcessEngineServices()).thenReturn(mockProcessEngineServices) + + return mockExecution + } + + protected ExecutionEntity setupMockWithPrefix(String procName, String prefix) { + ExecutionEntity mockExecution = mock(ExecutionEntity.class) + + when(mockExecution.getVariable("prefix")).thenReturn(prefix) + + ProcessEngineServices processEngineServices = mock(ProcessEngineServices.class) + RepositoryService repositoryService = mock(RepositoryService.class) + ProcessDefinition processDefinition = mock(ProcessDefinition.class) + + when(mockExecution.getProcessEngineServices()).thenReturn(processEngineServices) + when(processEngineServices.getRepositoryService()).thenReturn(repositoryService) + when(repositoryService.getProcessDefinition(mockExecution.getProcessDefinitionId())).thenReturn(processDefinition) + when(processDefinition.getKey()).thenReturn(procName) + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") return mockExecution } + + protected <T> Optional<T> getAAIObjectFromJson(Class<T> clazz , String file){ + String json = FileUtil.readResourceFile(file) + AAIResultWrapper resultWrapper = new AAIResultWrapper(json) + return resultWrapper.asBean(clazz) + } + + protected Optional<GenericVnf> mockAAIGenericVnf(String vnfId){ + return mockAAIGenericVnf(vnfId,"__files/aai/GenericVnf.json") + } + + protected Optional<GenericVnf> mockAAIGenericVnf(String vnfId,String file){ + AAIResourceUri resourceUri = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId) + AAIResourceUri resourceUriDepthOne = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId).depth(Depth.ONE) + Optional<GenericVnf> genericVnf = getAAIObjectFromJson(GenericVnf.class,file); + when(client.get(GenericVnf.class, resourceUri)).thenReturn(genericVnf) + when(client.get(GenericVnf.class, resourceUriDepthOne)).thenReturn(genericVnf) + return genericVnf + } + + protected Optional<GenericVnf> mockAAIGenericVnfByName(String vnfName){ + AAIResourceUri resourceUri = AAIUriFactory.createResourceUri(AAIObjectPlurals.GENERIC_VNF).queryParam("vnf-name", vnfName) + AAIResourceUri resourceUriDepthOne = AAIUriFactory.createResourceUri(AAIObjectPlurals.GENERIC_VNF).queryParam("vnf-name", vnfName).depth(Depth.ONE) + Optional<GenericVnf> genericVnf = getAAIObjectFromJson(GenericVnf.class,"__files/aai/GenericVnf.json"); + when(client.get(GenericVnf.class, resourceUri)).thenReturn(genericVnf) + when(client.get(GenericVnf.class, resourceUriDepthOne)).thenReturn(genericVnf) + return genericVnf + } + + protected void mockAAIGenericVnfNotFound(String vnfId){ + AAIResourceUri resourceUri = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId).depth(Depth.ONE) + AAIResourceUri resourceUriDepthOne = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId).depth(Depth.ONE) + when(client.get(GenericVnf.class, resourceUri)).thenReturn(Optional.empty()) + when(client.get(GenericVnf.class, resourceUriDepthOne)).thenReturn(Optional.empty()) + } + + protected void mockAAIGenericVnfByNameNotFound(String vnfName){ + AAIResourceUri resourceUri = AAIUriFactory.createResourceUri(AAIObjectPlurals.GENERIC_VNF).queryParam("vnf-name", vnfName) + AAIResourceUri resourceUriDepthOne = AAIUriFactory.createResourceUri(AAIObjectPlurals.GENERIC_VNF).queryParam("vnf-name", vnfName).depth(Depth.ONE) + when(client.get(GenericVnf.class, resourceUri)).thenReturn(Optional.empty()) + when(client.get(GenericVnf.class, resourceUriDepthOne)).thenReturn(Optional.empty()) + } + + protected AAIResultWrapper mockVolumeGroupWrapper(String region, String volumeGroupId, String file){ + AAIResourceUri resourceUri = AAIUriFactory.createResourceUri(AAIObjectType.VOLUME_GROUP,CLOUD_OWNER, region,volumeGroupId) + String json = FileUtil.readResourceFile(file) + AAIResultWrapper resultWrapper = new AAIResultWrapper(json) + when(client.get(resourceUri)).thenReturn(resultWrapper) + return resultWrapper + } + + void initAR(String procName){ + init(procName) + allottedResourceUtils_MOCK = spy(new AllottedResourceUtils(mock(AbstractServiceTaskProcessor.class))) + when(allottedResourceUtils_MOCK.getAAIClient()).thenReturn(client) + } } diff --git a/bpmn/MSOCommonBPMN/src/test/groovy/org/onap/so/bpmn/common/scripts/MsoUtilsTest.groovy b/bpmn/MSOCommonBPMN/src/test/groovy/org/onap/so/bpmn/common/scripts/MsoUtilsTest.groovy index dfcf69a931..dfaf5d2140 100644 --- a/bpmn/MSOCommonBPMN/src/test/groovy/org/onap/so/bpmn/common/scripts/MsoUtilsTest.groovy +++ b/bpmn/MSOCommonBPMN/src/test/groovy/org/onap/so/bpmn/common/scripts/MsoUtilsTest.groovy @@ -20,23 +20,15 @@ package org.onap.so.bpmn.common.scripts -// JUnit 4 -import org.junit.Test -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Rule; - -import static groovy.test.GroovyAssert.shouldFail - import groovy.util.slurpersupport.NodeChild +import org.junit.Before +import org.junit.Ignore +import org.junit.Test +import org.onap.so.bpmn.common.scripts.MsoUtils -import static groovy.test.GroovyAssert.assertTrue import static groovy.test.GroovyAssert.assertEquals -import static groovy.test.GroovyAssert.assertNotNull; - -import org.onap.so.bpmn.common.scripts.MsoUtils; -import org.apache.commons.lang3.* +// JUnit 4 class MsoUtilsTest { @@ -198,22 +190,20 @@ class MsoUtilsTest { @Test public void testGetBasicAuth(){ - def encodedAuth = utils.getBasicAuth("3E3CFA7BE2F6107AAD4AAA65F8976690","07a7159d3bf51a0e53be7a8f89699be7") + def encodedAuth = utils.getBasicAuth(utils.encrypt("myString","07a7159d3bf51a0e53be7a8f89699be7"),"07a7159d3bf51a0e53be7a8f89699be7") assertEquals("Basic bXlTdHJpbmc=", encodedAuth) } @Test public void testEncrypt(){ def encrypted = utils.encrypt("myString","07a7159d3bf51a0e53be7a8f89699be7") - assertEquals("3E3CFA7BE2F6107AAD4AAA65F8976690", encrypted) + assertEquals("myString", utils.decrypt(encrypted,"07a7159d3bf51a0e53be7a8f89699be7")) - //use to get value for urn properties - //println(utils.encrypt("password")) } @Test public void testDecrypt(){ - def decrypted = utils.decrypt("3E3CFA7BE2F6107AAD4AAA65F8976690", "07a7159d3bf51a0e53be7a8f89699be7") + def decrypted = utils.decrypt(utils.encrypt("myString","07a7159d3bf51a0e53be7a8f89699be7"), "07a7159d3bf51a0e53be7a8f89699be7") assertEquals("myString", decrypted) } diff --git a/bpmn/MSOCommonBPMN/src/test/groovy/org/onap/so/bpmn/common/scripts/SDNCAdapterRestV1Test.groovy b/bpmn/MSOCommonBPMN/src/test/groovy/org/onap/so/bpmn/common/scripts/SDNCAdapterRestV1Test.groovy index 1079bb48b3..e79075a1a1 100644 --- a/bpmn/MSOCommonBPMN/src/test/groovy/org/onap/so/bpmn/common/scripts/SDNCAdapterRestV1Test.groovy +++ b/bpmn/MSOCommonBPMN/src/test/groovy/org/onap/so/bpmn/common/scripts/SDNCAdapterRestV1Test.groovy @@ -51,7 +51,7 @@ public class SDNCAdapterRestV1Test { when(mockExecution.getVariable("prefix")).thenReturn("SDNCREST_") when(mockExecution.getVariable("mso-request-id")).thenReturn("testMsoRequestId") when(mockExecution.getVariable("SDNCREST_Request")).thenReturn(sdncAdapterWorkflowRequest) - when(mockExecution.getVariable("mso.adapters.po.auth")).thenReturn("3141634BF7E070AA289CF2892C986C0B") + when(mockExecution.getVariable("mso.adapters.po.auth")).thenReturn("5E12ACACBD552A415E081E29F2C4772F9835792A51C766CCFDD7433DB5220B59969CB2798C") when(mockExecution.getVariable("mso.msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7") when(mockExecution.getVariable("mso.adapters.sdnc.rest.endpoint")).thenReturn("http://localhost:18080/adapters/rest/v1/sdnc/") @@ -88,7 +88,7 @@ public class SDNCAdapterRestV1Test { when(mockExecution.getVariable("prefix")).thenReturn("SDNCREST_") when(mockExecution.getVariable("mso-request-id")).thenReturn("testMsoRequestId") when(mockExecution.getVariable("SDNCREST_Request")).thenReturn(sdncAdapterWorkflowRequest) - when(mockExecution.getVariable("mso.adapters.po.auth")).thenReturn("3141634BF7E070AA289CF2892C986C0B") + when(mockExecution.getVariable("mso.adapters.po.auth")).thenReturn("5E12ACACBD552A415E081E29F2C4772F9835792A51C766CCFDD7433DB5220B59969CB2798C") when(mockExecution.getVariable("mso.msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7") when(mockExecution.getVariable("mso.adapters.sdnc.rest.endpoint")).thenReturn("http://localhost:18080/adapters/rest/v1/sdnc/") diff --git a/bpmn/MSOCommonBPMN/src/test/groovy/org/onap/so/bpmn/common/scripts/SDNCAdapterRestV2Test.groovy b/bpmn/MSOCommonBPMN/src/test/groovy/org/onap/so/bpmn/common/scripts/SDNCAdapterRestV2Test.groovy index d7fe0ee208..c9e3fead67 100644 --- a/bpmn/MSOCommonBPMN/src/test/groovy/org/onap/so/bpmn/common/scripts/SDNCAdapterRestV2Test.groovy +++ b/bpmn/MSOCommonBPMN/src/test/groovy/org/onap/so/bpmn/common/scripts/SDNCAdapterRestV2Test.groovy @@ -51,7 +51,7 @@ public class SDNCAdapterRestV2Test { when(mockExecution.getVariable("prefix")).thenReturn("SDNCREST_") when(mockExecution.getVariable("mso-request-id")).thenReturn("testMsoRequestId") when(mockExecution.getVariable("SDNCREST_Request")).thenReturn(sdncAdapterWorkflowRequest) - when(mockExecution.getVariable("mso.adapters.po.auth")).thenReturn("3141634BF7E070AA289CF2892C986C0B") + when(mockExecution.getVariable("mso.adapters.po.auth")).thenReturn("5E12ACACBD552A415E081E29F2C4772F9835792A51C766CCFDD7433DB5220B59969CB2798C") when(mockExecution.getVariable("mso.msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7") when(mockExecution.getVariable("mso.adapters.sdnc.rest.endpoint")).thenReturn("http://localhost:18080/adapters/rest/v1/sdnc/") @@ -88,7 +88,7 @@ public class SDNCAdapterRestV2Test { when(mockExecution.getVariable("prefix")).thenReturn("SDNCREST_") when(mockExecution.getVariable("mso-request-id")).thenReturn("testMsoRequestId") when(mockExecution.getVariable("SDNCREST_Request")).thenReturn(sdncAdapterWorkflowRequest) - when(mockExecution.getVariable("mso.adapters.po.auth")).thenReturn("3141634BF7E070AA289CF2892C986C0B") + when(mockExecution.getVariable("mso.adapters.po.auth")).thenReturn("5E12ACACBD552A415E081E29F2C4772F9835792A51C766CCFDD7433DB5220B59969CB2798C") when(mockExecution.getVariable("mso.msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7") when(mockExecution.getVariable("mso.adapters.sdnc.rest.endpoint")).thenReturn("http://localhost:18080/adapters/rest/v1/sdnc/") diff --git a/bpmn/MSOCommonBPMN/src/test/groovy/org/onap/so/bpmn/common/scripts/SDNCAdapterTest.groovy b/bpmn/MSOCommonBPMN/src/test/groovy/org/onap/so/bpmn/common/scripts/SDNCAdapterTest.groovy index 18d65d00d8..bf0f2d20c0 100644 --- a/bpmn/MSOCommonBPMN/src/test/groovy/org/onap/so/bpmn/common/scripts/SDNCAdapterTest.groovy +++ b/bpmn/MSOCommonBPMN/src/test/groovy/org/onap/so/bpmn/common/scripts/SDNCAdapterTest.groovy @@ -31,13 +31,13 @@ import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.mockito.MockitoAnnotations -import org.mockito.runners.MockitoJUnitRunner +import org.mockito.junit.MockitoJUnitRunner; import org.mockito.internal.debugging.MockitoDebuggerImpl import org.onap.so.bpmn.common.scripts.SDNCAdapter; import org.onap.so.bpmn.mock.FileUtil -@RunWith(MockitoJUnitRunner.class) +@RunWith(MockitoJUnitRunner.Silent.class) public class SDNCAdapterTest { @Before @@ -821,7 +821,7 @@ def sdncAdapterResponseError = String sdncAdapterWorkflowRequest = FileUtil.readResourceFile("__files/SDN-ETHERNET-INTERNET/SDNCAdapterV1/sdncadapterworkflowrequest.xml"); ExecutionEntity mockExecution = mock(ExecutionEntity.class) - when(mockExecution.getVariable("mso.adapters.po.auth")).thenReturn("3141634BF7E070AA289CF2892C986C0B") + when(mockExecution.getVariable("mso.adapters.po.auth")).thenReturn("5E12ACACBD552A415E081E29F2C4772F9835792A51C766CCFDD7433DB5220B59969CB2798C") when(mockExecution.getVariable("mso.msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7") when(mockExecution.getVariable("sdncAdapterWorkflowRequest")).thenReturn(sdncAdapterWorkflowRequest) when(mockExecution.getVariable("mso.workflow.sdncadapter.callback")).thenReturn("http://someurl.someting.com:28080/mso/sdncAdapterCallbackServiceImpl") @@ -842,12 +842,12 @@ def sdncAdapterResponseError = verify(mockExecution).setVariable("sdncAdapterResponse","") verify(mockExecution).setVariable("asynchronousResponseTimeout",false) verify(mockExecution).setVariable("continueListening",false) - verify(mockExecution).setVariable("BasicAuthHeaderValue","Basic cGFzc3dvcmQ=") verify(mockExecution).setVariable("serviceConfigActivate",false) verify(mockExecution).setVariable("SDNCA_requestId", "745b1b50-e39e-4685-9cc8-c71f0bde8bf0") verify(mockExecution).setVariable("SDNCA_SuccessIndicator",false) - verify(mockExecution).setVariable("source","") verify(mockExecution).setVariable("SDNCA_InterimNotify",false) + verify(mockExecution).setVariable("BasicAuthHeaderValue","Basic dGVzdDp0ZXN0") + verify(mockExecution).setVariable("source","") verify(mockExecution).setVariable("sdncAdapterRequest", sdncAdapterRequest) } diff --git a/bpmn/MSOCommonBPMN/src/test/groovy/org/onap/so/bpmn/common/scripts/SDNCAdapterUtilsTest.groovy b/bpmn/MSOCommonBPMN/src/test/groovy/org/onap/so/bpmn/common/scripts/SDNCAdapterUtilsTest.groovy index 803e2b03a3..ef71e9073b 100644 --- a/bpmn/MSOCommonBPMN/src/test/groovy/org/onap/so/bpmn/common/scripts/SDNCAdapterUtilsTest.groovy +++ b/bpmn/MSOCommonBPMN/src/test/groovy/org/onap/so/bpmn/common/scripts/SDNCAdapterUtilsTest.groovy @@ -26,6 +26,7 @@ import static org.mockito.Mockito.* import org.junit.Before import org.junit.Ignore import org.junit.Test +import org.junit.runner.RunWith import org.camunda.bpm.engine.delegate.BpmnError import org.camunda.bpm.engine.impl.persistence.entity.ExecutionEntity import org.camunda.bpm.engine.delegate.DelegateExecution @@ -34,6 +35,9 @@ import org.onap.so.bpmn.common.scripts.SDNCAdapterUtils import org.onap.so.bpmn.mock.FileUtil +import org.mockito.junit.MockitoJUnitRunner; + +@RunWith(MockitoJUnitRunner.Silent.class) public class SDNCAdapterUtilsTest { private def map @@ -59,14 +63,14 @@ public class SDNCAdapterUtilsTest { // svcex gets its variables from "map" when(svcex.getVariable(any())).thenAnswer( { invocation -> - return map.get(invocation.getArgumentAt(0, String.class)) }) + return map.get(invocation.getArgument(0)) }) // svcex puts its variables into "map" when(svcex.setVariable(any(), any())).thenAnswer( { invocation -> return map.put( - invocation.getArgumentAt(0, String.class), - invocation.getArgumentAt(1, String.class)) }) + invocation.getArgument(0), + invocation.getArgument(1)) }) map.put("isDebugLogEnabled", "true") map.put("prefix", "mypfx-") diff --git a/bpmn/MSOCommonBPMN/src/test/groovy/org/onap/so/bpmn/common/scripts/UpdateAAIVfModuleTest.groovy b/bpmn/MSOCommonBPMN/src/test/groovy/org/onap/so/bpmn/common/scripts/UpdateAAIVfModuleTest.groovy index 407ffa2915..cb9bb5c541 100644 --- a/bpmn/MSOCommonBPMN/src/test/groovy/org/onap/so/bpmn/common/scripts/UpdateAAIVfModuleTest.groovy +++ b/bpmn/MSOCommonBPMN/src/test/groovy/org/onap/so/bpmn/common/scripts/UpdateAAIVfModuleTest.groovy @@ -20,34 +20,37 @@ package org.onap.so.bpmn.common.scripts -import com.github.tomakehurst.wiremock.junit.WireMockRule -import org.camunda.bpm.engine.ProcessEngineServices -import org.camunda.bpm.engine.RepositoryService +import org.junit.rules.ExpectedException + +import static org.mockito.Mockito.* + +import javax.ws.rs.NotFoundException + +import org.camunda.bpm.engine.delegate.BpmnError import org.camunda.bpm.engine.impl.persistence.entity.ExecutionEntity -import org.camunda.bpm.engine.repository.ProcessDefinition -import org.junit.Assert import org.junit.Before -import org.junit.Ignore import org.junit.Rule import org.junit.Test -import org.junit.runner.RunWith import org.mockito.ArgumentCaptor import org.mockito.Captor -import org.mockito.Mockito import org.mockito.MockitoAnnotations -import org.mockito.runners.MockitoJUnitRunner -import org.onap.so.bpmn.core.WorkflowException -import org.onap.so.bpmn.mock.FileUtil -import org.onap.so.bpmn.mock.StubResponseAAI +import org.mockito.Spy +import org.onap.so.client.aai.AAIObjectType +import org.onap.so.client.aai.entities.uri.AAIResourceUri +import org.onap.so.client.aai.entities.uri.AAIUriFactory +import org.onap.aai.domain.yang.VfModule -import static org.mockito.Mockito.* +import com.github.tomakehurst.wiremock.junit.WireMockRule -@RunWith(MockitoJUnitRunner.class) -@Ignore -class UpdateAAIVfModuleTest { +class UpdateAAIVfModuleTest extends MsoGroovyTest { def prefix = "UAAIVfMod_" @Rule + public ExpectedException thrown = ExpectedException.none(); + @Spy + UpdateAAIVfModule updateAAIVfModule; + + @Rule public WireMockRule wireMockRule = new WireMockRule(28090) @Captor @@ -55,121 +58,92 @@ class UpdateAAIVfModuleTest { @Before void init() throws IOException { - MockitoAnnotations.initMocks(this); + super.init("UpdateAAIVfModule") + when(updateAAIVfModule.getAAIClient()).thenReturn(client) } @Test void testGetVfModule() { - ExecutionEntity mockExecution = setupMock() when(mockExecution.getVariable("prefix")).thenReturn(prefix) - when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") when(mockExecution.getVariable(prefix + "vnfId")).thenReturn("skask") when(mockExecution.getVariable(prefix + "vfModuleId")).thenReturn("supercool") - - when(mockExecution.getVariable("aai.endpoint")).thenReturn("http://localhost:28090") - when(mockExecution.getVariable("mso.workflow.global.default.aai.namespace")).thenReturn("http://org.openecomp.aai.inventory/") - when(mockExecution.getVariable("mso.workflow.custom.UpdateAAIVfModule.aai.version")).thenReturn('8') - - StubResponseAAI.MockAAIVfModule() - UpdateAAIVfModule obj = new UpdateAAIVfModule() - obj.getVfModule(mockExecution) - + VfModule vfModule = new VfModule() + vfModule.setVfModuleId("supercool") + AAIResourceUri resourceUri = AAIUriFactory.createResourceUri(AAIObjectType.VF_MODULE, "skask", "supercool"); + when(client.get(VfModule.class,resourceUri)).thenReturn(Optional.of(vfModule)) + updateAAIVfModule.getVfModule(mockExecution) verify(mockExecution).setVariable(prefix + "getVfModuleResponseCode", 200) + verify(mockExecution).setVariable(prefix + "getVfModuleResponse", vfModule) } @Test - void testGetVfModuleEndpointNull() { - ExecutionEntity mockExecution = setupMock() + void testGetVfModuleNotFound() { when(mockExecution.getVariable("prefix")).thenReturn(prefix) - when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") when(mockExecution.getVariable(prefix + "vnfId")).thenReturn("skask") when(mockExecution.getVariable(prefix + "vfModuleId")).thenReturn("supercool") + AAIResourceUri resourceUri = AAIUriFactory.createResourceUri(AAIObjectType.VF_MODULE, "skask", "supercool"); + when(client.get(VfModule.class,resourceUri)).thenReturn(Optional.empty()) + updateAAIVfModule.getVfModule(mockExecution) + verify(mockExecution).setVariable(prefix + "getVfModuleResponseCode", 404) + verify(mockExecution).setVariable(prefix + "getVfModuleResponse", "VF Module not found in AAI") + } - when(mockExecution.getVariable("aai.endpoint")).thenReturn(null) - when(mockExecution.getVariable("mso.workflow.global.default.aai.namespace")).thenReturn("http://org.openecomp.aai.inventory/") - when(mockExecution.getVariable("mso.workflow.custom.UpdateAAIVfModule.aai.version")).thenReturn('8') - - StubResponseAAI.MockAAIVfModule() - try { - UpdateAAIVfModule obj = new UpdateAAIVfModule() - obj.getVfModule(mockExecution) - } catch (Exception ex) { - println " Test End - Handle catch-throw BpmnError()! " - } - - Mockito.verify(mockExecution, times(3)).setVariable(captor.capture(), captor.capture()) - WorkflowException workflowException = captor.getAllValues().get(1) - Assert.assertEquals(9999, workflowException.getErrorCode()) - Assert.assertEquals("org.apache.http.client.ClientProtocolException", workflowException.getErrorMessage()) + @Test + void testGetVfModuleException() { + when(mockExecution.getVariable("prefix")).thenReturn(prefix) + when(mockExecution.getVariable(prefix + "vnfId")).thenReturn("skask") + when(mockExecution.getVariable(prefix + "vfModuleId")).thenReturn("supercool") + AAIResourceUri resourceUri = AAIUriFactory.createResourceUri(AAIObjectType.VF_MODULE, "skask", "supercool"); + when(client.get(VfModule.class,resourceUri)).thenThrow(new NullPointerException("Error from AAI client")) + updateAAIVfModule.getVfModule(mockExecution) + verify(mockExecution).setVariable(prefix + "getVfModuleResponseCode", 500) + verify(mockExecution).setVariable(prefix + "getVfModuleResponse", "AAI GET Failed:"+"Error from AAI client") } + @Test void testUpdateVfModule() { - ExecutionEntity mockExecution = setupMock() when(mockExecution.getVariable("prefix")).thenReturn(prefix) when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") when(mockExecution.getVariable(prefix + "vnfId")).thenReturn("skask") when(mockExecution.getVariable(prefix + "vfModuleId")).thenReturn("supercool") - - when(mockExecution.getVariable("aai.endpoint")).thenReturn("http://localhost:28090") - when(mockExecution.getVariable("mso.workflow.global.default.aai.namespace")).thenReturn("http://org.openecomp.aai.inventory/") - when(mockExecution.getVariable("mso.workflow.custom.UpdateAAIVfModule.aai.version")).thenReturn('8') - - String getVfModuleResponse = FileUtil.readResourceFile("__files/VfModularity/GenericVnf.xml") - when(mockExecution.getVariable(prefix + "getVfModuleResponse")).thenReturn(getVfModuleResponse) - StubResponseAAI.MockAAIVfModule() - UpdateAAIVfModule obj = new UpdateAAIVfModule() - obj.updateVfModule(mockExecution) - - verify(mockExecution).setVariable(prefix + "updateVfModuleResponseCode", 200) + VfModule vfModule = new VfModule() + vfModule.setVfModuleId("supercool") + vfModule.setResourceVersion("12345") + when(mockExecution.getVariable(prefix + "getVfModuleResponse")).thenReturn(vfModule) + doNothing().when(client).update(isA(AAIResourceUri.class), anyObject()) + updateAAIVfModule.updateVfModule(mockExecution) } @Test - void testUpdateVfModuleEndpointNull() { - ExecutionEntity mockExecution = setupMock() + void testUpdateVfModuleNotFound() throws BpmnError { when(mockExecution.getVariable("prefix")).thenReturn(prefix) when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") when(mockExecution.getVariable(prefix + "vnfId")).thenReturn("skask") when(mockExecution.getVariable(prefix + "vfModuleId")).thenReturn("supercool") - - when(mockExecution.getVariable("aai.endpoint")).thenReturn(null) - when(mockExecution.getVariable("mso.workflow.global.default.aai.namespace")).thenReturn("http://org.openecomp.aai.inventory/") - when(mockExecution.getVariable("mso.workflow.custom.UpdateAAIVfModule.aai.version")).thenReturn('8') - - String getVfModuleResponse = FileUtil.readResourceFile("__files/VfModularity/GenericVnf.xml") - when(mockExecution.getVariable(prefix + "getVfModuleResponse")).thenReturn(getVfModuleResponse) - StubResponseAAI.MockAAIVfModule() - try { - UpdateAAIVfModule obj = new UpdateAAIVfModule() - obj.updateVfModule(mockExecution) - } catch (Exception ex) { - println " Test End - Handle catch-throw BpmnError()! " - } - - Mockito.verify(mockExecution, times(3)).setVariable(captor.capture(), captor.capture()) - WorkflowException workflowException = captor.getAllValues().get(1) - Assert.assertEquals(9999, workflowException.getErrorCode()) - Assert.assertEquals("org.apache.http.client.ClientProtocolException", workflowException.getErrorMessage()) + VfModule vfModule = new VfModule() + vfModule.setVfModuleId("supercool") + vfModule.setResourceVersion("12345") + when(mockExecution.getVariable(prefix + "getVfModuleResponse")).thenReturn(vfModule) + doThrow(new NotFoundException("Vf Module not found")).when(client).update(isA(AAIResourceUri.class), anyObject()) + thrown.expect(BpmnError.class) + updateAAIVfModule.updateVfModule(mockExecution) } - private static ExecutionEntity setupMock() { - ProcessDefinition mockProcessDefinition = mock(ProcessDefinition.class) - when(mockProcessDefinition.getKey()).thenReturn("UpdateAAIVfModule") - RepositoryService mockRepositoryService = mock(RepositoryService.class) - when(mockRepositoryService.getProcessDefinition()).thenReturn(mockProcessDefinition) - when(mockRepositoryService.getProcessDefinition().getKey()).thenReturn("UpdateAAIVfModule") - when(mockRepositoryService.getProcessDefinition().getId()).thenReturn("100") - ProcessEngineServices mockProcessEngineServices = mock(ProcessEngineServices.class) - when(mockProcessEngineServices.getRepositoryService()).thenReturn(mockRepositoryService) - - ExecutionEntity mockExecution = mock(ExecutionEntity.class) - // Initialize prerequisite variables - when(mockExecution.getId()).thenReturn("100") - when(mockExecution.getProcessDefinitionId()).thenReturn("UpdateAAIVfModule") - when(mockExecution.getProcessInstanceId()).thenReturn("UpdateAAIVfModule") - when(mockExecution.getProcessEngineServices()).thenReturn(mockProcessEngineServices) - when(mockExecution.getProcessEngineServices().getRepositoryService().getProcessDefinition(mockExecution.getProcessDefinitionId())).thenReturn(mockProcessDefinition) - - return mockExecution + + @Test + void testUpdateVfModuleException() { + when(mockExecution.getVariable("prefix")).thenReturn(prefix) + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable(prefix + "vnfId")).thenReturn("skask") + when(mockExecution.getVariable(prefix + "vfModuleId")).thenReturn("supercool") + VfModule vfModule = new VfModule() + vfModule.setVfModuleId("supercool") + vfModule.setResourceVersion("12345") + when(mockExecution.getVariable(prefix + "getVfModuleResponse")).thenReturn(vfModule) + doThrow(new IllegalStateException("Error in AAI client")).when(client).update(isA(AAIResourceUri.class), anyObject()) + thrown.expect(BpmnError.class) + updateAAIVfModule.updateVfModule(mockExecution) + } } diff --git a/bpmn/MSOCommonBPMN/src/test/groovy/org/onap/so/bpmn/common/scripts/VnfAdapterRestV1Test.groovy b/bpmn/MSOCommonBPMN/src/test/groovy/org/onap/so/bpmn/common/scripts/VnfAdapterRestV1Test.groovy index 22c8e297ca..77edd2dc6d 100644 --- a/bpmn/MSOCommonBPMN/src/test/groovy/org/onap/so/bpmn/common/scripts/VnfAdapterRestV1Test.groovy +++ b/bpmn/MSOCommonBPMN/src/test/groovy/org/onap/so/bpmn/common/scripts/VnfAdapterRestV1Test.groovy @@ -50,7 +50,7 @@ public class VnfAdapterRestV1Test { when(mockExecution.getVariable("prefix")).thenReturn("VNFREST_") when(mockExecution.getVariable("mso-request-id")).thenReturn("testMsoRequestId") when(mockExecution.getVariable("VNFREST_Request")).thenReturn(sdncAdapterWorkflowRequest) - when(mockExecution.getVariable("mso.adapters.po.auth")).thenReturn("3141634BF7E070AA289CF2892C986C0B") + when(mockExecution.getVariable("mso.adapters.po.auth")).thenReturn("5E12ACACBD552A415E081E29F2C4772F9835792A51C766CCFDD7433DB5220B59969CB2798C") when(mockExecution.getVariable("mso.msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7") when(mockExecution.getVariable("mso.adapters.vnf.rest.endpoint")).thenReturn("http://localhost:18080/vnfs/rest/v1/vnfs") diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/BaseTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/BaseTest.java index 119d3b1e2d..5d6f98c907 100644 --- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/BaseTest.java +++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/BaseTest.java @@ -29,13 +29,10 @@ import java.util.Map; import org.camunda.bpm.engine.RepositoryService; import org.camunda.bpm.engine.RuntimeService; -import org.camunda.bpm.model.bpmn.Bpmn; -import org.camunda.bpm.model.bpmn.BpmnModelInstance; import org.junit.Before; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.onap.so.bpmn.common.InjectionHelper; -import org.onap.so.bpmn.common.MockLoggerDelegate; import org.onap.so.bpmn.servicedecomposition.tasks.BBInputSetup; import org.onap.so.bpmn.servicedecomposition.tasks.BBInputSetupMapperLayer; import org.onap.so.bpmn.servicedecomposition.tasks.BBInputSetupUtils; @@ -44,7 +41,7 @@ import org.onap.so.db.catalog.client.CatalogDbClient; import org.onap.so.test.categories.SpringAware; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; -import org.springframework.boot.context.embedded.LocalServerPort; +import org.springframework.boot.web.server.LocalServerPort; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.boot.test.mock.mockito.SpyBean; @@ -146,21 +143,5 @@ public abstract class BaseTest extends BuildingBlockTestDataSetup { protected String createURLWithPort(String uri) { return "http://localhost:" + port + uri; } - /** - * Create and deploy a process model with one logger delegate as service task. - * - * @param origProcessKey - * key to call - * @param mockProcessName - * process name - * @param fileName - * file name without extension - */ - protected void mockSubprocess(String origProcessKey, String mockProcessName, String fileName) { - BpmnModelInstance modelInstance = Bpmn.createExecutableProcess(origProcessKey).name(mockProcessName) - .startEvent().name("Start Point").serviceTask().name("Log Something for Test") - .camundaClass(MockLoggerDelegate.class.getName()).endEvent().name("End Point").done(); - repositoryService.createDeployment().addModelInstance(fileName + ".bpmn", modelInstance).deploy(); - } } diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/BuildingBlockTestDataSetup.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/BuildingBlockTestDataSetup.java index 5be879560f..0398c87d69 100644 --- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/BuildingBlockTestDataSetup.java +++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/BuildingBlockTestDataSetup.java @@ -168,7 +168,11 @@ public class BuildingBlockTestDataSetup{ dataMap.put("vpnRegion","testVpnRegion"); dataMap.put("vpnRt","testVpnRt"); dataMap.put("vpnName","vpnName"); - dataMap.put("vpnRegion", Arrays.asList(new String[] {"USA", "EMEA", "APAC"})); + ArrayList<String> vpnRegions = new ArrayList<String>(); + vpnRegions.add("USA"); + vpnRegions.add("EMEA"); + vpnRegions.add("APAC"); + dataMap.put("vpnRegion", vpnRegions); HashMap<String,Object> userParams = new HashMap<>(); userParams.put("vpnData",dataMap); diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/EmbeddedMariaDbConfig.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/EmbeddedMariaDbConfig.java index a29df9cbcf..fb08e5e830 100644 --- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/EmbeddedMariaDbConfig.java +++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/EmbeddedMariaDbConfig.java @@ -23,7 +23,7 @@ import ch.vorburger.exec.ManagedProcessException; import ch.vorburger.mariadb4j.DBConfigurationBuilder; import ch.vorburger.mariadb4j.springframework.MariaDB4jSpringService; import org.springframework.beans.factory.annotation.Value; -import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder; +import org.springframework.boot.jdbc.DataSourceBuilder; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/recipe/BpmnRestClientTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/recipe/BpmnRestClientTest.java new file mode 100644 index 0000000000..85507afd3f --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/recipe/BpmnRestClientTest.java @@ -0,0 +1,57 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2018 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.bpmn.common.recipe; + +import org.apache.http.HttpResponse; +import org.apache.http.HttpStatus; +import org.junit.Test; +import org.onap.so.BaseTest; +import org.springframework.beans.factory.annotation.Autowired; +import java.io.IOException; + +import static com.github.tomakehurst.wiremock.client.WireMock.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +public class BpmnRestClientTest extends BaseTest{ + + @Autowired + private BpmnRestClient bpmnRestClient; + + @Test + public void postTest() throws IOException, Exception{ + stubFor(post(urlPathMatching("/testRecipeUri")) + .willReturn(aResponse().withHeader("Content-Type", "application/json").withStatus(org.springframework.http.HttpStatus.OK.value()).withBody("{}"))); + + HttpResponse httpResponse = bpmnRestClient.post( + "http://localhost:" + wireMockPort +"/testRecipeUri", + "test-req-id", + 1000, + "testRequestAction", + "1234", + "testServiceType", + "testRequestDetails", + "testRecipeparamXsd"); + + assertNotNull(httpResponse); + assertEquals(HttpStatus.SC_OK,httpResponse.getStatusLine().getStatusCode()); + } +} diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/util/CryptoHandlerTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/util/CryptoHandlerTest.java index cbde63e933..76bc830d26 100644 --- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/util/CryptoHandlerTest.java +++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/util/CryptoHandlerTest.java @@ -20,21 +20,22 @@ package org.onap.so.bpmn.common.util; -import static org.junit.Assert.assertEquals; - import org.junit.Before; import org.junit.Ignore; import org.junit.Test; -import org.onap.so.BaseTest; + +import static org.junit.Assert.assertEquals; public class CryptoHandlerTest { private static final String plainPswd = "mso0206"; - private static final String encryptPwd = "C1FC4A39E16419DD41DFC1212843F440"; private CryptoHandler cryptoHandler; - + private static String encryptPwd; + + @Before public void setup() { cryptoHandler = new CryptoHandler(); + encryptPwd = cryptoHandler.encryptMsoPassword(plainPswd); } @Test @@ -45,7 +46,7 @@ public class CryptoHandlerTest { @Test public void encryptMsoPasswordTest() { - assertEquals(encryptPwd, cryptoHandler.encryptMsoPassword(plainPswd)); + assertEquals(plainPswd,cryptoHandler.decryptMsoPassword(cryptoHandler.encryptMsoPassword(plainPswd))); } @Test diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/validation/BuildingBlockValidatorRunnerTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/validation/BuildingBlockValidatorRunnerTest.java new file mode 100644 index 0000000000..9478b8f1f6 --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/validation/BuildingBlockValidatorRunnerTest.java @@ -0,0 +1,90 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2018 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.bpmn.common.validation; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.mockito.Mockito.mock; + +import java.util.Arrays; +import java.util.List; + +import org.camunda.bpm.engine.delegate.BpmnError; +import org.camunda.bpm.extension.mockito.delegate.DelegateExecutionFake; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.junit.runner.RunWith; +import org.onap.so.bpmn.common.BuildingBlockExecution; +import org.onap.so.bpmn.common.DelegateExecutionImpl; +import org.onap.so.bpmn.core.WorkflowException; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = {ValidationConfig.class}) +public class BuildingBlockValidatorRunnerTest { + + @Rule + public ExpectedException thrown= ExpectedException.none(); + + @Autowired + private BuildingBlockValidatorRunner runner; + + @Test + public void filterValidatorTest() { + + MyPreValidatorOne one = new MyPreValidatorOne(); + MyPreValidatorTwo two = new MyPreValidatorTwo(); + MyPreValidatorThree three = new MyPreValidatorThree(); + List<BuildingBlockValidator> validators = Arrays.asList(one, two, three); + + List<BuildingBlockValidator> result = runner.filterValidators(validators, "test"); + + List<BuildingBlockValidator> expected = Arrays.asList(two, one); + + assertEquals(expected, result); + } + + @Test + public void testValidate() { + + BuildingBlockExecution execution = new DelegateExecutionImpl(new DelegateExecutionFake()); + execution.setVariable("testProcessKey", "1234"); + try { + runner.preValidate("test", execution); + fail("exception not thrown"); + } catch (BpmnError e) { + WorkflowException workflowException = execution.getVariable("WorkflowException"); + assertEquals("Failed Validations:\norg.onap.so.bpmn.common.validation.MyPreValidatorTwo\norg.onap.so.bpmn.common.validation.MyPreValidatorOne", workflowException.getErrorMessage()); + } + runner.preValidate("test2", mock(BuildingBlockExecution.class)); + } + + @Test + public void testEmptyList() { + boolean result = runner.preValidate("test3", mock(BuildingBlockExecution.class)); + + assertTrue(result); + } +} diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/MockLoggerDelegate.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/validation/MyPreValidatorFour.java index 6a9ff2a4a8..1b52f049b3 100644 --- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/MockLoggerDelegate.java +++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/validation/MyPreValidatorFour.java @@ -18,18 +18,25 @@ * ============LICENSE_END========================================================= */ -package org.onap.so.bpmn.common; +package org.onap.so.bpmn.common.validation; -import org.camunda.bpm.engine.delegate.DelegateExecution; -import org.camunda.bpm.engine.delegate.JavaDelegate; +import java.util.Collections; +import java.util.Set; + +import org.onap.so.bpmn.common.BuildingBlockExecution; +import org.springframework.stereotype.Component; + +@Component +public class MyPreValidatorFour implements PreBuildingBlockValidator { + + @Override + public Set<String> forBuildingBlock() { + return Collections.singleton("test2"); + } -public class MockLoggerDelegate implements JavaDelegate { @Override - public void execute(DelegateExecution execution) throws Exception { - System.out.println("\n\n ..." + MockLoggerDelegate.class.getName() + " invoked by " + "processDefinitionId=" - + execution.getProcessDefinitionId() + ", activtyId=" + execution.getCurrentActivityId() - + ", activtyName='" + execution.getCurrentActivityName() + "'" + ", processInstanceId=" - + execution.getProcessInstanceId() + ", businessKey=" + execution.getProcessBusinessKey() - + ", executionId=" + execution.getId() + " \n\n"); + public boolean validate(BuildingBlockExecution exeuction) { + return true; } + } diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/validation/MyPreValidatorOne.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/validation/MyPreValidatorOne.java new file mode 100644 index 0000000000..d6afea9b19 --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/validation/MyPreValidatorOne.java @@ -0,0 +1,43 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2018 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.bpmn.common.validation; + +import java.util.Collections; +import java.util.Set; + +import org.onap.so.bpmn.common.BuildingBlockExecution; +import org.springframework.stereotype.Component; + +@Component +public class MyPreValidatorOne implements PreBuildingBlockValidator { + + @Override + public Set<String> forBuildingBlock() { + + return Collections.singleton("test"); + } + + @Override + public boolean validate(BuildingBlockExecution exeuction) { + return false; + } + +} diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/validation/MyPreValidatorThree.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/validation/MyPreValidatorThree.java new file mode 100644 index 0000000000..f7e93d5bd2 --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/validation/MyPreValidatorThree.java @@ -0,0 +1,42 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2018 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.bpmn.common.validation; + +import java.util.Collections; +import java.util.Set; + +import org.onap.so.bpmn.common.BuildingBlockExecution; +import org.springframework.stereotype.Component; + +@Component +public class MyPreValidatorThree implements PreBuildingBlockValidator { + + @Override + public Set<String> forBuildingBlock() { + return Collections.singleton("test2"); + } + + @Override + public boolean validate(BuildingBlockExecution exeuction) { + return true; + } + +} diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/validation/MyPreValidatorTwo.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/validation/MyPreValidatorTwo.java new file mode 100644 index 0000000000..0c15fd8589 --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/validation/MyPreValidatorTwo.java @@ -0,0 +1,45 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2018 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.bpmn.common.validation; + +import java.util.Collections; +import java.util.Set; + +import javax.annotation.Priority; + +import org.onap.so.bpmn.common.BuildingBlockExecution; +import org.springframework.stereotype.Component; + +@Priority(1) +@Component +public class MyPreValidatorTwo implements PreBuildingBlockValidator { + + @Override + public Set<String> forBuildingBlock() { + return Collections.singleton("test"); + } + + @Override + public boolean validate(BuildingBlockExecution exeuction) { + return false; + } + +} diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/validation/ValidationConfig.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/validation/ValidationConfig.java new file mode 100644 index 0000000000..7570e4c915 --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/validation/ValidationConfig.java @@ -0,0 +1,33 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2018 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.bpmn.common.validation; + +import org.onap.so.bpmn.common.DefaultToShortClassNameBeanNameGenerator; +import org.onap.so.client.exception.ExceptionBuilder; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Profile; + +@Configuration +@ComponentScan(basePackages = {"org.onap.so.bpmn.common.validation"}, basePackageClasses = {ExceptionBuilder.class}, nameGenerator = DefaultToShortClassNameBeanNameGenerator.class) +public class ValidationConfig { + +} diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/tasks/BBInputSetupTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/tasks/BBInputSetupTest.java index 0db2f9fc12..23524f4e7d 100644 --- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/tasks/BBInputSetupTest.java +++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/tasks/BBInputSetupTest.java @@ -25,9 +25,9 @@ import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; -import static org.mockito.Matchers.any; +import static org.mockito.ArgumentMatchers.any; import static org.mockito.Matchers.eq; -import static org.mockito.Matchers.isA; +import static org.mockito.ArgumentMatchers.isA; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.times; @@ -45,10 +45,12 @@ import org.camunda.bpm.engine.delegate.DelegateExecution; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; +import org.mockito.ArgumentMatchers; +import org.mockito.Matchers; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.Spy; -import org.mockito.runners.MockitoJUnitRunner; +import org.mockito.junit.MockitoJUnitRunner; import org.onap.so.bpmn.servicedecomposition.bbobjects.CloudRegion; import org.onap.so.bpmn.servicedecomposition.bbobjects.Collection; import org.onap.so.bpmn.servicedecomposition.bbobjects.Configuration; @@ -232,9 +234,6 @@ public class BBInputSetupTest { requestDetails.setSubscriberInfo(null); - doReturn(null).when(this.SPY_bbInputSetup).getServiceSubscription(requestDetails, expected); - doReturn(expected).when(this.SPY_bbInputSetup).getCustomerFromURI(resourceId); - doReturn(serviceSubscription).when(this.SPY_bbInputSetup).getServiceSubscriptionFromURI(resourceId, expected); assertThat(actual, sameBeanAs(expected)); @@ -295,7 +294,7 @@ public class BBInputSetupTest { String requestAction = "createInstance"; doReturn(expected).when(SPY_bbInputSetup).getGBBALaCarteService(executeBB, requestDetails, lookupKeyMap, requestAction, resourceId); - doNothing().when(SPY_bbInputSetup).populateLookupKeyMapWithIds(any(WorkflowResourceIds.class), any()); + doNothing().when(SPY_bbInputSetup).populateLookupKeyMapWithIds(executeBB.getWorkflowResourceIds(),lookupKeyMap); boolean aLaCarte = true; GeneralBuildingBlock actual = SPY_bbInputSetup.getGBB(executeBB, lookupKeyMap, requestAction, aLaCarte, resourceId, null); @@ -321,14 +320,11 @@ public class BBInputSetupTest { CloudConfiguration cloudConfiguration = new CloudConfiguration(); cloudConfiguration.setLcpCloudRegionId("myRegionId"); requestDetails.setCloudConfiguration(cloudConfiguration); - doReturn(requestDetails).when(SPY_bbInputSetupUtils).getRequestDetails(executeBB.getRequestId()); Map<ResourceKey, String> lookupKeyMap = new HashMap<>(); String resourceId = "123"; String requestAction = "createInstance"; - doReturn(expected).when(SPY_bbInputSetup).getGBBALaCarteService(executeBB, requestDetails, lookupKeyMap, - requestAction, resourceId); - doNothing().when(SPY_bbInputSetup).populateLookupKeyMapWithIds(any(WorkflowResourceIds.class), any()); - doReturn(null).when(bbInputSetupMapperLayer).mapAAIGenericVnfIntoGenericVnf(any(org.onap.aai.domain.yang.GenericVnf.class)); + + doReturn(null).when(bbInputSetupMapperLayer).mapAAIGenericVnfIntoGenericVnf(ArgumentMatchers.isNull()); GeneralBuildingBlock actual = SPY_bbInputSetup.getGBBCM(executeBB, requestDetails, lookupKeyMap, requestAction, resourceId); @@ -355,7 +351,6 @@ public class BBInputSetupTest { lookupKeyMap.put(ResourceKey.SERVICE_INSTANCE_ID, "instanceId"); doReturn(service).when(SPY_bbInputSetupUtils).getCatalogServiceByModelUUID(aaiServiceInstance.getModelVersionId()); doReturn(aaiServiceInstance).when(SPY_bbInputSetupUtils).getAAIServiceInstanceById("instanceId"); - doReturn(aaiCloudRegion).when(SPY_bbInputSetupUtils).getCloudRegion(requestDetails.getCloudConfiguration()); doNothing().when(SPY_bbInputSetup).populateObjectsOnAssignAndCreateFlows(requestDetails, service, "bbName", serviceInstance, lookupKeyMap, resourceId, vnfType); @@ -381,9 +376,7 @@ public class BBInputSetupTest { aaiServiceInstance.setModelVersionId("modelVersionId"); String resourceId = "123"; String vnfType = "vnfType"; - doReturn(null).when(SPY_bbInputSetupUtils).getCatalogServiceByModelUUID(aaiServiceInstance.getModelVersionId()); - doReturn(aaiServiceInstance).when(SPY_bbInputSetupUtils).getAAIServiceInstanceById("instanceId"); - + SPY_bbInputSetup.getGBBALaCarteNonService(executeBB, requestDetails, lookupKeyMap, requestAction, resourceId, vnfType); } @@ -408,7 +401,6 @@ public class BBInputSetupTest { lookupKeyMap.put(ResourceKey.SERVICE_INSTANCE_ID, "instanceId"); doReturn(service).when(SPY_bbInputSetupUtils).getCatalogServiceByModelUUID(aaiServiceInstance.getModelVersionId()); doReturn(aaiServiceInstance).when(SPY_bbInputSetupUtils).getAAIServiceInstanceById("instanceId"); - doReturn(aaiCloudRegion).when(SPY_bbInputSetupUtils).getCloudRegion(requestDetails.getCloudConfiguration()); doNothing().when(SPY_bbInputSetup).populateObjectsOnAssignAndCreateFlows(requestDetails, service, "bbName", serviceInstance, lookupKeyMap, resourceId, vnfType); @@ -452,7 +444,6 @@ public class BBInputSetupTest { doReturn(service).when(SPY_bbInputSetupUtils) .getCatalogServiceByModelUUID(requestDetails.getModelInfo().getModelVersionId()); - doReturn(aaiCloudRegion).when(SPY_bbInputSetupUtils).getCloudRegion(requestDetails.getCloudConfiguration()); doReturn(project).when(bbInputSetupMapperLayer).mapRequestProject(requestDetails.getProject()); doReturn(owningEntity).when(bbInputSetupMapperLayer) .mapRequestOwningEntity(requestDetails.getOwningEntity()); @@ -501,13 +492,11 @@ public class BBInputSetupTest { .getCatalogServiceByModelUUID(requestDetails.getModelInfo().getModelVersionId()); doReturn(service).when(SPY_bbInputSetupUtils).getCatalogServiceByModelVersionAndModelInvariantUUID( requestDetails.getModelInfo().getModelVersion(), requestDetails.getModelInfo().getModelInvariantId()); - doReturn(aaiCloudRegion).when(SPY_bbInputSetupUtils).getCloudRegion(requestDetails.getCloudConfiguration()); doReturn(project).when(bbInputSetupMapperLayer).mapRequestProject(requestDetails.getProject()); doReturn(owningEntity).when(bbInputSetupMapperLayer) .mapRequestOwningEntity(requestDetails.getOwningEntity()); doReturn(customer).when(SPY_bbInputSetup).getCustomerAndServiceSubscription(requestDetails, resourceId); - doReturn(serviceSubscription).when(SPY_bbInputSetup).getServiceSubscription(requestDetails, customer); doReturn(serviceInstance).when(SPY_bbInputSetup).getALaCarteServiceInstance(service, requestDetails, customer, project, owningEntity, lookupKeyMap, resourceId, Boolean.TRUE.equals(executeBB.isaLaCarte()), executeBB.getBuildingBlock().getBpmnFlowName()); @@ -543,14 +532,12 @@ public class BBInputSetupTest { Map<String, String> uriKeys = new HashMap<>(); uriKeys.put("global-customer-id", "globalCustomerId"); uriKeys.put("service-type", "serviceType"); - doReturn(uriKeys).when(SPY_bbInputSetupUtils) - .getURIKeysFromServiceInstance(resourceId); + doReturn(service).when(SPY_bbInputSetupUtils) .getCatalogServiceByModelUUID(requestDetails.getModelInfo().getModelVersionId()); - doReturn(aaiCloudRegion).when(SPY_bbInputSetupUtils).getCloudRegion(requestDetails.getCloudConfiguration()); doReturn(customer).when(SPY_bbInputSetup).getCustomerAndServiceSubscription(requestDetails, resourceId); - doReturn(serviceSubscription).when(SPY_bbInputSetup).getServiceSubscription(requestDetails, customer); + doReturn(serviceInstance).when(SPY_bbInputSetup).getALaCarteServiceInstance(service, requestDetails, customer, null, null, lookupKeyMap, resourceId, Boolean.TRUE.equals(executeBB.isaLaCarte()), executeBB.getBuildingBlock().getBpmnFlowName()); @@ -660,9 +647,7 @@ public class BBInputSetupTest { differentService.setModelUUID("modelUUIDDifferent"); doReturn(serviceInstanceAAI).when(SPY_bbInputSetupUtils).getAAIServiceInstanceById(serviceInstanceId); - doReturn(differentService).when(SPY_bbInputSetupUtils) - .getCatalogServiceByModelUUID(serviceInstanceAAI.getModelVersionId()); - doReturn(expected).when(SPY_bbInputSetup).getExistingServiceInstance(serviceInstanceAAI); + ServiceInstance actual = SPY_bbInputSetup.getServiceInstanceHelper(requestDetails, customer, null, null, lookupKeyMap, serviceInstanceId, aLaCarte, service, bbName); @@ -888,7 +873,6 @@ public class BBInputSetupTest { doReturn(expected).when(bbInputSetupMapperLayer) .mapAAIServiceInstanceIntoServiceInstance(serviceInstanceAAI); - doNothing().when(SPY_bbInputSetup).addRelationshipsToSI(serviceInstanceAAI, expected); ServiceInstance actual = SPY_bbInputSetup.getExistingServiceInstance(serviceInstanceAAI); assertThat(actual, sameBeanAs(expected)); @@ -909,8 +893,7 @@ public class BBInputSetupTest { doReturn(collection).when(SPY_bbInputSetup).createCollection(resourceId); doReturn(instanceGroup).when(SPY_bbInputSetup).createInstanceGroup(); doNothing().when(SPY_bbInputSetup).mapCatalogCollection(service, collection, key); - doNothing().when(SPY_bbInputSetup).mapCatalogNetworkCollectionInstanceGroup(service, - collection.getInstanceGroup(), key); + NetworkCollectionResourceCustomization networkCollection = new NetworkCollectionResourceCustomization(); networkCollection.setModelCustomizationUUID(key); networkCollection.setCollectionResource(new CollectionResource()); @@ -1059,7 +1042,6 @@ public class BBInputSetupTest { instanceName = "networkName2"; L3Network network2 = SPY_bbInputSetup.createNetwork(lookupKeyMap, instanceName, resourceId, null); - doReturn(network2).when(SPY_bbInputSetup).createNetwork(lookupKeyMap, instanceName, resourceId, null); SPY_bbInputSetup.populateL3Network(instanceName, modelInfo, service, bbName, serviceInstance, lookupKeyMap, resourceId, null); verify(SPY_bbInputSetup, times(2)).mapCatalogNetwork(network2, modelInfo, service); @@ -1269,8 +1251,7 @@ public class BBInputSetupTest { instanceName = "vnfName2"; GenericVnf vnf2 = SPY_bbInputSetup.createGenericVnf(lookupKeyMap, instanceName, platform, lineOfBusiness, resourceId, vnfType, null); - doReturn(vnf2).when(SPY_bbInputSetup).createGenericVnf(lookupKeyMap, instanceName, platform, lineOfBusiness, - resourceId, vnfType, null); + org.onap.aai.domain.yang.GenericVnf vnf2AAI = new org.onap.aai.domain.yang.GenericVnf(); vnfAAI.setModelCustomizationId("modelCustId2"); doReturn(vnf2AAI).when(SPY_bbInputSetupUtils).getAAIGenericVnf(vnf2.getVnfId()); @@ -1348,8 +1329,7 @@ public class BBInputSetupTest { doReturn(modelInfoCollection).when(bbInputSetupMapperLayer).mapCatalogCollectionToCollection(collectionCust, collectionResource); - doReturn(instanceGroupCustList).when(SPY_bbInputSetupUtils) - .getCollectionResourceInstanceGroupCustomization(collectionCust.getModelCustomizationUUID()); + doReturn(modelInfoInstanceGroup).when(bbInputSetupMapperLayer).mapCatalogInstanceGroupToInstanceGroup(collectionCust, catalogInstanceGroup); @@ -1376,8 +1356,7 @@ public class BBInputSetupTest { uriKeys.put("global-customer-id", "globalCustomerId"); uriKeys.put("service-type", "serviceType"); - doReturn(uriKeys).when(SPY_bbInputSetupUtils) - .getURIKeysFromServiceInstance(serviceInstanceAAI.getServiceInstanceId()); + doNothing().when(SPY_bbInputSetup).mapProject(any(), eq(serviceInstance)); doNothing().when(SPY_bbInputSetup).mapOwningEntity(any(), eq(serviceInstance)); doNothing().when(SPY_bbInputSetup).mapL3Networks(any(), eq(serviceInstance.getNetworks())); @@ -1524,7 +1503,6 @@ public class BBInputSetupTest { CollectionResource collectionResource = new CollectionResource(); doReturn(collection).when(bbInputSetupMapperLayer) .mapAAICollectionIntoCollection(isA(org.onap.aai.domain.yang.Collection.class)); - doReturn(instanceGroup).when(SPY_bbInputSetup).mapInstanceGroup(isA(AAIResultWrapper.class)); doReturn(instanceGroupsList).when(SPY_bbInputSetup).mapInstanceGroups(any()); doReturn(networkCollectionCust).when(SPY_bbInputSetupUtils).getCatalogNetworkCollectionResourceCustByID(aaiCollection.getCollectionCustomizationId()); doReturn(collectionResource).when(networkCollectionCust).getCollectionResource(); @@ -1745,7 +1723,7 @@ public class BBInputSetupTest { executeBB.getBuildingBlock().setKey("72d9d1cd-f46d-447a-abdb-451d6fb05fa8"); SPY_bbInputSetup.getGBBMacro(executeBB, requestDetails, lookupKeyMap, requestAction, resourceId, vnfType); verify(SPY_bbInputSetup, times(1)).populateVolumeGroup(isA(ModelInfo.class), isA(Service.class), - any(String.class), isA(ServiceInstance.class), any(), any(String.class), any(), any(String.class), + any(String.class), isA(ServiceInstance.class), any(), any(String.class),ArgumentMatchers.isNull(),ArgumentMatchers.isNull(), any(String.class), any()); Configuration configuration = new Configuration(); @@ -1757,13 +1735,13 @@ public class BBInputSetupTest { doReturn(configurationCustList).when(service).getConfigurationCustomizations(); configurationCustList.add(configurationCust); doNothing().when(SPY_bbInputSetup).populateConfiguration(isA(ModelInfo.class), isA(Service.class), - any(String.class), isA(ServiceInstance.class), any(), any(String.class), any(String.class), isA(ConfigurationResourceKeys.class)); + any(String.class), isA(ServiceInstance.class), any(), any(String.class), ArgumentMatchers.isNull(), isA(ConfigurationResourceKeys.class)); executeBB.getBuildingBlock().setBpmnFlowName("AssignFabricConfigurationBB"); executeBB.getBuildingBlock().setKey("72d9d1cd-f46d-447a-abdb-451d6fb05fa9"); SPY_bbInputSetup.getGBBMacro(executeBB, requestDetails, lookupKeyMap, requestAction, resourceId, vnfType); verify(SPY_bbInputSetup, times(1)).populateConfiguration(isA(ModelInfo.class), isA(Service.class), - any(String.class), isA(ServiceInstance.class), any(), any(String.class), any(String.class), isA(ConfigurationResourceKeys.class)); + any(String.class), isA(ServiceInstance.class), any(), any(String.class),ArgumentMatchers.isNull(), isA(ConfigurationResourceKeys.class)); } @Test @@ -1831,10 +1809,7 @@ public class BBInputSetupTest { requestAction, resourceId); doReturn(service).when(SPY_bbInputSetupUtils) .getCatalogServiceByModelUUID(gBB.getServiceInstance().getModelInfoServiceInstance().getModelUuid()); - doNothing().when(SPY_bbInputSetupUtils).updateInfraActiveRequestVnfId(request, - lookupKeyMap.get(ResourceKey.GENERIC_VNF_ID)); - doReturn("vnfId").when(SPY_bbInputSetup).getVnfId(executeBB, lookupKeyMap); - doReturn(aaiVnf).when(SPY_bbInputSetupUtils).getAAIGenericVnf(any(String.class)); + executeBB.getBuildingBlock().setBpmnFlowName(AssignFlows.NETWORK_MACRO.toString()); executeBB.getBuildingBlock().setKey("ab153b6e-c364-44c0-bef6-1f2982117f04"); executeBB.getBuildingBlock().setIsVirtualLink(Boolean.FALSE); @@ -1858,9 +1833,7 @@ public class BBInputSetupTest { String requestAction = "createInstance"; doReturn(null).when(SPY_bbInputSetup).getGBBALaCarteService(executeBB, requestDetails, lookupKeyMap, requestAction, resourceId); - doReturn(service).when(SPY_bbInputSetupUtils) - .getCatalogServiceByModelUUID(gBB.getServiceInstance().getModelInfoServiceInstance().getModelUuid()); - + executeBB.getBuildingBlock().setBpmnFlowName("Network"); executeBB.getBuildingBlock().setKey("ab153b6e-c364-44c0-bef6-1f2982117f04"); SPY_bbInputSetup.getGBBMacro(executeBB, requestDetails, lookupKeyMap, requestAction, resourceId, vnfType); @@ -1909,7 +1882,7 @@ public class BBInputSetupTest { verify(SPY_bbInputSetup, times(1)).populateGenericVnf(isA(ModelInfo.class), any(String.class), isA(org.onap.so.serviceinstancebeans.Platform.class), isA(org.onap.so.serviceinstancebeans.LineOfBusiness.class), isA(Service.class), any(String.class), - isA(ServiceInstance.class), any(), any(), any(String.class), any(String.class), any()); + isA(ServiceInstance.class), any(),ArgumentMatchers.isNull(), any(String.class), ArgumentMatchers.isNull(), any()); lookupKeyMap.put(ResourceKey.GENERIC_VNF_ID, null); executeBB.getBuildingBlock().setBpmnFlowName(AssignFlows.VF_MODULE.toString()); @@ -1923,8 +1896,8 @@ public class BBInputSetupTest { executeBB.getBuildingBlock().setKey("72d9d1cd-f46d-447a-abdb-451d6fb05fa8"); SPY_bbInputSetup.getGBBMacro(executeBB, requestDetails, lookupKeyMap, requestAction, resourceId, vnfType); verify(SPY_bbInputSetup, times(1)).populateVolumeGroup(isA(ModelInfo.class), isA(Service.class), - any(String.class), isA(ServiceInstance.class), any(), any(String.class), any(), any(String.class), - any(String.class), any()); + any(String.class), isA(ServiceInstance.class), any(), any(String.class), ArgumentMatchers.isNull(), ArgumentMatchers.isNull(), + ArgumentMatchers.isNull(), any()); } @Test @@ -1984,7 +1957,7 @@ public class BBInputSetupTest { executeBB.getBuildingBlock().setKey("72d9d1cd-f46d-447a-abdb-451d6fb05fa8"); SPY_bbInputSetup.getGBBMacro(executeBB, requestDetails, lookupKeyMap, requestAction, resourceId, vnfType); verify(SPY_bbInputSetup, times(1)).populateVolumeGroup(isA(ModelInfo.class), isA(Service.class), - any(String.class), isA(ServiceInstance.class), any(), any(String.class), any(), any(String.class), + any(String.class), isA(ServiceInstance.class), any(), any(String.class), ArgumentMatchers.isNull(), ArgumentMatchers.isNull(), any(String.class), any()); } @@ -2014,8 +1987,6 @@ public class BBInputSetupTest { doReturn(service).when(SPY_bbInputSetupUtils) .getCatalogServiceByModelUUID(gBB.getServiceInstance().getModelInfoServiceInstance().getModelUuid()); String generatedId = "12131"; - doReturn(generatedId).when(SPY_bbInputSetup).generateRandomUUID(); - doReturn(aaiVnf).when(SPY_bbInputSetupUtils).getAAIGenericVnf(any(String.class)); executeBB.getBuildingBlock().setBpmnFlowName("DeactivateServiceInstanceBB"); executeBB.getBuildingBlock().setKey("3c40d244-808e-42ca-b09a-256d83d19d0a"); @@ -2056,8 +2027,7 @@ public class BBInputSetupTest { String requestAction = "createInstance"; doReturn(gBB).when(SPY_bbInputSetup).getGBBALaCarteService(executeBB, requestDetails, lookupKeyMap, requestAction, resourceId); - doReturn(null).when(SPY_bbInputSetupUtils) - .getCatalogServiceByModelUUID(requestDetails.getModelInfo().getModelVersionId()); + doReturn(service).when(SPY_bbInputSetupUtils) .getCatalogServiceByModelUUID(gBB.getServiceInstance().getModelInfoServiceInstance().getModelUuid()); List<NetworkResourceCustomization> networkCustList = new ArrayList<>(); @@ -2122,7 +2092,7 @@ public class BBInputSetupTest { requestAction, resourceId); doReturn(service).when(SPY_bbInputSetupUtils) .getCatalogServiceByModelUUID(gBB.getServiceInstance().getModelInfoServiceInstance().getModelUuid()); - doReturn(aaiVnf).when(SPY_bbInputSetupUtils).getAAIGenericVnf(any(String.class)); + //doReturn(aaiVnf).when(SPY_bbInputSetupUtils).getAAIGenericVnf(any(String.class)); CloudConfiguration cloudConfig = new CloudConfiguration(); cloudConfig.setLcpCloudRegionId("lcpCloudRegionId"); @@ -2193,10 +2163,7 @@ public class BBInputSetupTest { doReturn(service).when(SPY_bbInputSetupUtils) .getCatalogServiceByModelUUID(gBB.getServiceInstance().getModelInfoServiceInstance().getModelUuid()); String generatedId = "12131"; - doReturn(generatedId).when(SPY_bbInputSetup).generateRandomUUID(); - doReturn(aaiVnf).when(SPY_bbInputSetupUtils).getAAIGenericVnf(any(String.class)); - executeBB.getBuildingBlock().setBpmnFlowName(AssignFlows.SERVICE_INSTANCE.toString()); executeBB.getBuildingBlock().setKey("3c40d244-808e-42ca-b09a-256d83d19d0a"); SPY_bbInputSetup.getGBBMacro(executeBB, requestDetails, lookupKeyMap, requestAction, resourceId, vnfType); } @@ -2276,7 +2243,6 @@ public class BBInputSetupTest { any(Service.class), any(String.class)); org.onap.aai.domain.yang.CloudRegion aaiCloudRegion = Mockito.mock(org.onap.aai.domain.yang.CloudRegion.class); - doReturn(aaiCloudRegion).when(SPY_bbInputSetupUtils).getCloudRegion(requestDetails.getCloudConfiguration()); VolumeGroup volumeGroup = new VolumeGroup(); volumeGroup.setVolumeGroupId("volumeGroupId"); gBB.getServiceInstance().getVnfs().get(0).getVolumeGroups().add(volumeGroup); diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/tasks/BBInputSetupUtilsTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/tasks/BBInputSetupUtilsTest.java index e1efe1c9c5..f70912f725 100644 --- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/tasks/BBInputSetupUtilsTest.java +++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/tasks/BBInputSetupUtilsTest.java @@ -24,9 +24,9 @@ import static com.shazam.shazamcrest.MatcherAssert.assertThat; import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; -import static org.mockito.Matchers.any; +import static org.mockito.ArgumentMatchers.any; import static org.mockito.Matchers.eq; -import static org.mockito.Matchers.isA; +import static org.mockito.ArgumentMatchers.isA; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; @@ -44,7 +44,7 @@ import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; -import org.mockito.runners.MockitoJUnitRunner; +import org.mockito.junit.MockitoJUnitRunner; import org.onap.aai.domain.yang.CloudRegion; import org.onap.aai.domain.yang.Configuration; import org.onap.aai.domain.yang.GenericVnf; diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/tasks/ExecuteBuildlingBlockRainyDayTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/tasks/ExecuteBuildlingBlockRainyDayTest.java index 0c2a95f5d1..8fe20de5f0 100644 --- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/tasks/ExecuteBuildlingBlockRainyDayTest.java +++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/tasks/ExecuteBuildlingBlockRainyDayTest.java @@ -22,9 +22,9 @@ package org.onap.so.bpmn.servicedecomposition.tasks; import static org.hamcrest.CoreMatchers.any; import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; +import static org.mockito.ArgumentMatchers.any; import static org.mockito.Matchers.eq; -import static org.mockito.Matchers.isA; +import static org.mockito.ArgumentMatchers.isA; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; @@ -84,7 +84,7 @@ public class ExecuteBuildlingBlockRainyDayTest extends BaseTest { public void setRetryTimerExceptionTest() { expectedException.expect(BpmnError.class); DelegateExecution execution = mock(DelegateExecution.class); - when(execution.getVariable(eq("retryCount"))).thenThrow(Exception.class); + when(execution.getVariable(eq("retryCount"))).thenThrow(BpmnError.class); executeBuildingBlockRainyDay.setRetryTimer(execution); } @@ -104,7 +104,7 @@ public class ExecuteBuildlingBlockRainyDayTest extends BaseTest { doReturn(rainyDayHandlerStatus).when(MOCK_catalogDbClient).getRainyDayHandlerStatusByFlowNameAndServiceTypeAndVnfTypeAndErrorCodeAndWorkStep("AssignServiceInstanceBB", "st1", "vnft1", "7000", "*"); - executeBuildingBlockRainyDay.queryRainyDayTable(delegateExecution); + executeBuildingBlockRainyDay.queryRainyDayTable(delegateExecution,true); assertEquals("Rollback", delegateExecution.getVariable("handlingCode")); } @@ -126,7 +126,7 @@ public class ExecuteBuildlingBlockRainyDayTest extends BaseTest { doReturn(null).when(MOCK_catalogDbClient).getRainyDayHandlerStatusByFlowNameAndServiceTypeAndVnfTypeAndErrorCodeAndWorkStep("AssignServiceInstanceBB", "st1", "vnft1", "7000", ASTERISK); doReturn(rainyDayHandlerStatus).when(MOCK_catalogDbClient).getRainyDayHandlerStatusByFlowNameAndServiceTypeAndVnfTypeAndErrorCodeAndWorkStep("AssignServiceInstanceBB", ASTERISK, ASTERISK, ASTERISK, ASTERISK); - executeBuildingBlockRainyDay.queryRainyDayTable(delegateExecution); + executeBuildingBlockRainyDay.queryRainyDayTable(delegateExecution,true); assertEquals("Rollback", delegateExecution.getVariable("handlingCode")); } @@ -139,17 +139,40 @@ public class ExecuteBuildlingBlockRainyDayTest extends BaseTest { doReturn(null).when(MOCK_catalogDbClient).getRainyDayHandlerStatusByFlowNameAndServiceTypeAndVnfTypeAndErrorCodeAndWorkStep(isA(String.class), isA(String.class), isA(String.class), isA(String.class), isA(String.class)); - executeBuildingBlockRainyDay.queryRainyDayTable(delegateExecution); + executeBuildingBlockRainyDay.queryRainyDayTable(delegateExecution,true); assertEquals("Abort", delegateExecution.getVariable("handlingCode")); } @Test public void queryRainyDayTableExceptionTest() { - doThrow(Exception.class).when(MOCK_catalogDbClient).getRainyDayHandlerStatusByFlowNameAndServiceTypeAndVnfTypeAndErrorCodeAndWorkStep(isA(String.class), isA(String.class), isA(String.class), isA(String.class), isA(String.class)); + doThrow(RuntimeException.class).when(MOCK_catalogDbClient).getRainyDayHandlerStatusByFlowNameAndServiceTypeAndVnfTypeAndErrorCodeAndWorkStep(isA(String.class), isA(String.class), isA(String.class), isA(String.class), isA(String.class)); - executeBuildingBlockRainyDay.queryRainyDayTable(delegateExecution); + executeBuildingBlockRainyDay.queryRainyDayTable(delegateExecution,true); assertEquals("Abort", delegateExecution.getVariable("handlingCode")); } + + @Test + public void queryRainyDayTableSecondaryPolicyExists() throws Exception{ + customer.getServiceSubscription().getServiceInstances().add(serviceInstance); + serviceInstance.getModelInfoServiceInstance().setServiceType("st1"); + vnf.setVnfType("vnft1"); + + RainyDayHandlerStatus rainyDayHandlerStatus = new RainyDayHandlerStatus(); + rainyDayHandlerStatus.setErrorCode("7000"); + rainyDayHandlerStatus.setFlowName("AssignServiceInstanceBB"); + rainyDayHandlerStatus.setServiceType("st1"); + rainyDayHandlerStatus.setVnfType("vnft1"); + rainyDayHandlerStatus.setPolicy("Retry"); + rainyDayHandlerStatus.setWorkStep(ASTERISK); + rainyDayHandlerStatus.setSecondaryPolicy("Abort"); + + doReturn(rainyDayHandlerStatus).when(MOCK_catalogDbClient).getRainyDayHandlerStatusByFlowNameAndServiceTypeAndVnfTypeAndErrorCodeAndWorkStep("AssignServiceInstanceBB", "st1", "vnft1", "7000", "*"); + + executeBuildingBlockRainyDay.queryRainyDayTable(delegateExecution,false); + + assertEquals("Abort", delegateExecution.getVariable("handlingCode")); + } + } diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/ResponseExceptionMapperImplTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/ResponseExceptionMapperImplTest.java index c8e1266b90..2df4b0bfdb 100644 --- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/ResponseExceptionMapperImplTest.java +++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/ResponseExceptionMapperImplTest.java @@ -20,8 +20,6 @@ package org.onap.so.client; -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -41,59 +39,67 @@ import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; +import org.junit.Rule; import org.junit.Test; +import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; -import org.onap.so.BaseTest; + import junitparams.JUnitParamsRunner; import junitparams.Parameters; @RunWith(JUnitParamsRunner.class) public class ResponseExceptionMapperImplTest{ - private static final ResponseExceptionMapperImpl mapper = new ResponseExceptionMapperImpl(); + private static final ResponseExceptionMapperImpl mapper = new ResponseExceptionMapperImpl(); - public static Object[][] statusesAndCorrespondingExceptions() { - return new Object[][]{ - {Status.BAD_REQUEST, BadRequestException.class}, - {Status.UNAUTHORIZED, NotAuthorizedException.class}, - {Status.FORBIDDEN, ForbiddenException.class}, - {Status.NOT_FOUND, NotFoundException.class}, - {Status.METHOD_NOT_ALLOWED, NotAllowedException.class}, - {Status.NOT_ACCEPTABLE, NotAcceptableException.class}, - {Status.PRECONDITION_FAILED, PreconditionFailedException.class}, - {Status.UNSUPPORTED_MEDIA_TYPE, NotSupportedException.class}, - {Status.INTERNAL_SERVER_ERROR, InternalServerErrorException.class}, - {Status.SERVICE_UNAVAILABLE, WebApplicationException.class}, - {Status.BAD_GATEWAY, WebApplicationException.class}, - }; - } + public static Object[][] statusesAndCorrespondingExceptions() { + return new Object[][]{ + {Status.BAD_REQUEST, BadRequestException.class}, + {Status.UNAUTHORIZED, NotAuthorizedException.class}, + {Status.FORBIDDEN, ForbiddenException.class}, + {Status.NOT_FOUND, NotFoundException.class}, + {Status.METHOD_NOT_ALLOWED, NotAllowedException.class}, + {Status.NOT_ACCEPTABLE, NotAcceptableException.class}, + {Status.PRECONDITION_FAILED, PreconditionFailedException.class}, + {Status.UNSUPPORTED_MEDIA_TYPE, NotSupportedException.class}, + {Status.INTERNAL_SERVER_ERROR, InternalServerErrorException.class}, + {Status.SERVICE_UNAVAILABLE, WebApplicationException.class}, + {Status.BAD_GATEWAY, WebApplicationException.class}, + }; + } - @Test - @Parameters(method = "statusesAndCorrespondingExceptions") - public void shouldThrowExceptionWhenStatusIsNotOk(Status status, Class<Exception> expectedException) { - // given - Response response = createMockResponse(status); - // when, then - assertThatThrownBy(() -> mapper.map(response)).isInstanceOf(expectedException); - } + @Rule + public ExpectedException expectedExceptionTest = ExpectedException.none(); - @Test - public void shouldNotThrowExceptionWhenStatusIsOk() { - // given - Response response = createMockResponse(Status.OK); - // when, then - assertThatCode(() -> mapper.map(response)).doesNotThrowAnyException(); - } + @Test + @Parameters(method = "statusesAndCorrespondingExceptions") + public void shouldThrowExceptionWhenStatusIsNotOk(Status status, Class<Exception> expectedException) { + // given + Response response = createMockResponse(status); + // when, then + expectedExceptionTest.expect(expectedException); + mapper.map(response); + } + @Test + public void shouldNotThrowExceptionWhenStatusIsOk() { + // given + Response response = createMockResponse(Status.OK); + // when, then + expectedExceptionTest.none(); + mapper.map(response); + } + @Test public void shouldThrowExceptionWithCustomMessageWhenResponseHasEntity() throws UnsupportedEncodingException { // given Response response = createMockResponse(Status.BAD_REQUEST); when(response.hasEntity()).thenReturn(true); when(response.getEntity()).thenReturn(new ByteArrayInputStream("test message".getBytes(StandardCharsets.UTF_8))); - // when, then - assertThatThrownBy(() -> mapper.map(response)).isInstanceOf(BadRequestException.class) - .hasMessage("test message"); + + expectedExceptionTest.expect(BadRequestException.class); + expectedExceptionTest.expectMessage("test message"); + mapper.map(response); } @Test @@ -102,14 +108,15 @@ public class ResponseExceptionMapperImplTest{ Response response = createMockResponse(Status.BAD_REQUEST); when(response.hasEntity()).thenReturn(false); // when, then - assertThatThrownBy(() -> mapper.map(response)).isInstanceOf(BadRequestException.class) - .hasMessage("empty message"); - } - - private static Response createMockResponse(Status status) { - Response responseContext = mock(Response.class); - when(responseContext.getStatusInfo()).thenReturn(status); - when(responseContext.getStatus()).thenReturn(status.getStatusCode()); - return responseContext; + expectedExceptionTest.expect(BadRequestException.class); + expectedExceptionTest.expectMessage(""); + mapper.map(response); } + + private static Response createMockResponse(Status status) { + Response responseContext = mock(Response.class); + when(responseContext.getStatusInfo()).thenReturn(status); + when(responseContext.getStatus()).thenReturn(status.getStatusCode()); + return responseContext; + } }
\ No newline at end of file diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/appc/ApplicationControllerActionTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/appc/ApplicationControllerActionTest.java index 6fad47d8bb..2f65f9ce66 100644 --- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/appc/ApplicationControllerActionTest.java +++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/appc/ApplicationControllerActionTest.java @@ -21,7 +21,7 @@ package org.onap.so.client.appc; import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; +import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.times; diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/appc/ApplicationControllerClientV2Test.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/appc/ApplicationControllerClientV2Test.java index 0aeb3a2a04..77daee6050 100644 --- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/appc/ApplicationControllerClientV2Test.java +++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/appc/ApplicationControllerClientV2Test.java @@ -27,7 +27,7 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; -import org.mockito.runners.MockitoJUnitRunner; +import org.mockito.junit.MockitoJUnitRunner; import org.onap.appc.client.lcm.model.Action; import org.onap.appc.client.lcm.model.ActionIdentifiers; import org.onap.appc.client.lcm.model.CheckLockInput; diff --git a/bpmn/MSOCommonBPMN/src/test/resources/__files/aai/GenericVnf.json b/bpmn/MSOCommonBPMN/src/test/resources/__files/aai/GenericVnf.json new file mode 100644 index 0000000000..e997db3f69 --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/test/resources/__files/aai/GenericVnf.json @@ -0,0 +1,57 @@ +{ + "closedLoopDisabled":false, + "vnf-id":"vnfId1", + "vnf-name":"vnfName", + "vnf-type":"vnfType", + "orchestration-status":"PRECREATED", + "vf-modules": { + "vf-module": [{ + "vf-module-id": "lukewarm", + "vf-module-name": "testVfModuleNameGWPrim", + "heat-stack-id": "fastburn", + "is-base-vf-module": true, + "orchestration-status": "Created" + }, + { + "vf-module-id": "testVfModuleIdGWSec", + "vf-module-name": "testVfModuleNameGWSec", + "heat-stack-id": "testHeatStackIdGWSec", + "orchestration-status": "Created" + }] + }, + "volume-groups":[], + "line-of-business":null, + "platform":null, + "cascaded":false, + "cloud-params":{}, + "cloud-context":null, + "solution":null, + "vnf-name-2":null, + "service-id":null, + "regional-resource-zone":null, + "prov-status":null, + "operational-status":null, + "equipment-role":null, + "management-option":null, + "ipv4-oam-address":null, + "ipv4-loopback0-address":null, + "nm-lan-v6-address":null, + "management-v6-address":null, + "vcpu":null, + "vcpu-units":null, + "vmemory":null, + "vmemory-units":null, + "vdisk":null, + "vdisk-units":null, + "in-maint":false, + "is-closed-loop-disabled":false, + "summary-status":null, + "encrypted-access-flag":null, + "as-number":null, + "regional-resource-subzone":null, + "self-link":null, + "ipv4-oam-gateway-address":null, + "ipv4-oam-gateway-address-prefix-length":null, + "vlan-id-outer":null,"nm-profile-name":null, + "model-info-generic-vnf":null +}
\ No newline at end of file diff --git a/bpmn/MSOCommonBPMN/src/test/resources/__files/aai/GenericVnfVfModule.json b/bpmn/MSOCommonBPMN/src/test/resources/__files/aai/GenericVnfVfModule.json new file mode 100644 index 0000000000..488865c326 --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/test/resources/__files/aai/GenericVnfVfModule.json @@ -0,0 +1,62 @@ +{ + "closedLoopDisabled":false, + "vnf-id":"vnfId1", + "vnf-name":"vnfName", + "vnf-type":"vnfType", + "orchestration-status":"PRECREATED", + "model-invariant-id":"model1", + "vf-modules": { + "vf-module": [{ + "vf-module-id": "lukewarm", + "vf-module-name": "testVfModuleNameGWPrim", + "heat-stack-id": "fastburn", + "is-base-vf-module": true, + "orchestration-status": "Created", + "module-index":0, + "model-invariant-id":"model1" + }, + { + "vf-module-id": "testVfModuleIdGWSec", + "vf-module-name": "testVfModuleNameGWSec", + "heat-stack-id": "testHeatStackIdGWSec", + "orchestration-status": "Created", + "module-index":2, + "model-invariant-id":"model1" + }] + }, + "volume-groups":[], + "line-of-business":null, + "platform":null, + "cascaded":false, + "cloud-params":{}, + "cloud-context":null, + "solution":null, + "vnf-name-2":null, + "service-id":null, + "regional-resource-zone":null, + "prov-status":null, + "operational-status":null, + "equipment-role":null, + "management-option":null, + "ipv4-oam-address":null, + "ipv4-loopback0-address":null, + "nm-lan-v6-address":null, + "management-v6-address":null, + "vcpu":null, + "vcpu-units":null, + "vmemory":null, + "vmemory-units":null, + "vdisk":null, + "vdisk-units":null, + "in-maint":false, + "is-closed-loop-disabled":false, + "summary-status":null, + "encrypted-access-flag":null, + "as-number":null, + "regional-resource-subzone":null, + "self-link":null, + "ipv4-oam-gateway-address":null, + "ipv4-oam-gateway-address-prefix-length":null, + "vlan-id-outer":null,"nm-profile-name":null, + "model-info-generic-vnf":null +}
\ No newline at end of file diff --git a/bpmn/MSOCommonBPMN/src/test/resources/__files/aai/VolumeGroup.json b/bpmn/MSOCommonBPMN/src/test/resources/__files/aai/VolumeGroup.json new file mode 100644 index 0000000000..7902bae83a --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/test/resources/__files/aai/VolumeGroup.json @@ -0,0 +1,10 @@ +{ + "volume-group-id":"VolumeGroup123", + "volume-group-name":"volumeGroupName", + "vnf-type":"vnfType", + "orchestration-status":"PRECREATED", + "cloud-params":{}, + "cascaded":false, + "heat-stack-id":"heatStackId", + "resource-version":"12345" +} diff --git a/bpmn/MSOCommonBPMN/src/test/resources/__files/aai/VolumeGroupWithTenant.json b/bpmn/MSOCommonBPMN/src/test/resources/__files/aai/VolumeGroupWithTenant.json new file mode 100644 index 0000000000..c43b2c8ed3 --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/test/resources/__files/aai/VolumeGroupWithTenant.json @@ -0,0 +1,20 @@ +{ + "volume-group-id":"volumeGroupId", + "volume-group-name":"volumeGroupName", + "vnf-type":"vnfType", + "orchestration-status":"PRECREATED", + "cloud-params":{}, + "cascaded":false, + "heat-stack-id":"heatStackId", + "relationship-list": { + "relationship": [ + { + "related-to": "tenant", + "related-link": "/aai/v11/network/Test", + "relationship-data": [{ + "relationship-key": "tenant.tenant-id", + "relationship-value": "Tenant123" + }] + }] + } +} diff --git a/bpmn/MSOCommonBPMN/src/test/resources/__files/aai/VolumeGroupWithVfModule.json b/bpmn/MSOCommonBPMN/src/test/resources/__files/aai/VolumeGroupWithVfModule.json new file mode 100644 index 0000000000..9a47c44751 --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/test/resources/__files/aai/VolumeGroupWithVfModule.json @@ -0,0 +1,26 @@ +{ + "volume-group-id":"volumeGroupId", + "volume-group-name":"volumeGroupName", + "vnf-type":"vnfType", + "orchestration-status":"PRECREATED", + "cloud-params":{}, + "cascaded":false, + "heat-stack-id":"heatStackId", + "relationship-list": { + "relationship": [ + { + "related-to": "vf-module", + "related-link": "/aai/v11/network/generic-vnfs/generic-vnf/GENERIC-VNFSAT-vig30001vm001vig001/vf-modules/vf-module/a62d14f0-421e-4e64-980a-a368722819db", + "relationship-data": [ + { + "relationship-key": "generic-vnf.vnf-id", + "relationship-value": "GENERIC-VNFSAT-vig30001vm001vig001" + }, + { + "relationship-key": "vf-module.vf-module-id", + "relationship-value": "a62d14f0-421e-4e64-980a-a368722819db" + } + ] + }] + } +} diff --git a/bpmn/MSOCommonBPMN/src/test/resources/__files/aai/searchResults.json b/bpmn/MSOCommonBPMN/src/test/resources/__files/aai/searchResults.json new file mode 100644 index 0000000000..0e8719bea8 --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/test/resources/__files/aai/searchResults.json @@ -0,0 +1,8 @@ +{ + "result-data": [ + { + "resource-type": "service-instance", + "resource-link": "/aai/v11/business/customers/customer/MSO-MUX-User/service-subscriptions/service-subscription/MSO-vCB/service-instances/service-instance/a1f53c6a-81a3-4e44-a900-d64f3b131d35" + } + ] +}
\ No newline at end of file diff --git a/bpmn/MSOCommonBPMN/src/test/resources/application-test.yaml b/bpmn/MSOCommonBPMN/src/test/resources/application-test.yaml index dea3f17f8e..2985505b46 100644 --- a/bpmn/MSOCommonBPMN/src/test/resources/application-test.yaml +++ b/bpmn/MSOCommonBPMN/src/test/resources/application-test.yaml @@ -1,5 +1,5 @@ aai: - auth: 26AFB797A6A57960D5D718491925C50F77CDC22AC394B3DBA09950D8FD1C0764 + auth: 5A1272FE739BECA4D4374A86B25C021DFE6745E3BB7BE6836BF64A6059B8220E586C21FD7567AF41DB42571EB7 endpoint: http://localhost:${wiremock.server.port} appc: client: @@ -37,7 +37,7 @@ mso: completemsoprocess: endpoint: http://localhost:${wiremock.server.port}/CompleteMsoProcess db: - auth: 757A94191D685FD2092AC1490730A4FC + auth: 5E12ACACBD552A415E081E29F2C4772F9835792A51C766CCFDD7433DB5220B59969CB2798C endpoint: http://localhost:${wiremock.server.port}/dbadapters/RequestsDbAdapter att-endpoint: http://localhost:${wiremock.server.port}/dbadapters/AttRequestsDbAdapter spring: @@ -50,7 +50,7 @@ mso: db: endpoint: http://localhost:${wiremock.server.port}/dbadapters/RequestsDbAdapter po: - auth: 757A94191D685FD2092AC1490730A4FC + auth: 5E12ACACBD552A415E081E29F2C4772F9835792A51C766CCFDD7433DB5220B59969CB2798C password: 3141634BF7E070AA289CF2892C986C0B sdnc: endpoint: http://localhost:${wiremock.server.port}/SDNCAdapter @@ -71,6 +71,7 @@ mso: workflow: message: endpoint: http://localhost:${wiremock.server.port}/workflows/messages/message + camundaAuth: E8E19DD16CC90D2E458E8FF9A884CC0452F8F3EB8E321F96038DE38D5C1B0B02DFAE00B88E2CF6E2A4101AB2C011FC161212EE async: core-pool-size: 50 @@ -177,7 +178,7 @@ sniro: spring: datasource: - url: jdbc:mariadb://localhost:3307/camundabpmn + jdbc-url: jdbc:mariadb://localhost:3307/camundabpmn username: root password: password driver-class-name: org.mariadb.jdbc.Driver @@ -195,8 +196,16 @@ mariaDB4j: dataDir: port: 3307 databaseName: camundabpmn + camunda: bpm: metrics: enabled: false db-reporter-activate: false + +org: + onap: + so: + adapters: + network: + encryptionKey: aa3871669d893c7fb8abbcda31b88b4f |