diff options
Diffstat (limited to 'bpmn/so-bpmn-infrastructure-common')
104 files changed, 4165 insertions, 4519 deletions
diff --git a/bpmn/so-bpmn-infrastructure-common/pom.xml b/bpmn/so-bpmn-infrastructure-common/pom.xml index 55d5d9244e..9ba278a119 100644 --- a/bpmn/so-bpmn-infrastructure-common/pom.xml +++ b/bpmn/so-bpmn-infrastructure-common/pom.xml @@ -3,14 +3,11 @@ <parent> <groupId>org.onap.so</groupId> <artifactId>bpmn</artifactId> - <version>1.3.0-SNAPSHOT</version> + <version>1.4.0-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>so-bpmn-infrastructure-common</artifactId> <packaging>jar</packaging> - <properties> - <camunda.version>7.8.0</camunda.version> - </properties> <build> <plugins> <plugin> @@ -82,7 +79,7 @@ </plugins> <pluginManagement> <plugins> - <!--This plugin's configuration is used to store Eclipse m2e settings + <!--This plugin's configuration is used to store Eclipse m2e settings only. It has no influence on the Maven build itself. --> <plugin> <groupId>org.eclipse.m2e</groupId> @@ -123,10 +120,10 @@ <goals> <goal>test</goal> </goals> - <configuration> + <configuration> <includes> - <include>**/AllTestsTestSuite.java</include> - </includes> + <include>**/AllTestsTestSuite.java</include> + </includes> </configuration> </execution> <execution> @@ -134,10 +131,10 @@ <goals> <goal>test</goal> </goals> - <configuration> + <configuration> <includes> - <include>**/AllTasksTestsTestSuite.java</include> - </includes> + <include>**/AllTasksTestsTestSuite.java</include> + </includes> </configuration> </execution> </executions> @@ -163,18 +160,14 @@ <dependency> <groupId>org.camunda.bpm.springboot</groupId> <artifactId>camunda-bpm-spring-boot-starter</artifactId> - <version>2.3.0</version> + <version>${camunda.springboot.version}</version> <scope>test</scope> </dependency> <dependency> - <groupId>org.springframework.boot</groupId> - <artifactId>spring-boot-starter-web</artifactId> + <groupId>org.camunda.bpm.springboot</groupId> + <artifactId>camunda-bpm-spring-boot-starter-webapp</artifactId> + <version>${camunda.springboot.version}</version> <scope>test</scope> - </dependency> - <dependency> - <groupId>org.springframework.boot</groupId> - <artifactId>spring-boot-starter-data-jpa</artifactId> - <optional>true</optional> </dependency> <dependency> <groupId>org.apache.cxf</groupId> @@ -190,13 +183,17 @@ <groupId>org.apache.cxf</groupId> <artifactId>cxf-rt-rs-service-description-swagger</artifactId> <version>${cxf.version}</version> - </dependency> + </dependency> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <scope>test</scope> </dependency> <dependency> + <groupId>com.google.guava</groupId> + <artifactId>guava</artifactId> + </dependency> + <dependency> <groupId>com.fasterxml.uuid</groupId> <artifactId>java-uuid-generator</artifactId> </dependency> @@ -207,7 +204,6 @@ <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> - <version>3.4</version> </dependency> <dependency> <groupId>org.onap.so</groupId> @@ -232,11 +228,6 @@ <version>${jax.ws.rs}</version> </dependency> <dependency> - <groupId>org.onap.so</groupId> - <artifactId>MSORESTClient</artifactId> - <version>${project.version}</version> - </dependency> - <dependency> <groupId>org.camunda.spin</groupId> <artifactId>camunda-spin-core</artifactId> <scope>test</scope> @@ -264,7 +255,6 @@ <dependency> <groupId>javax.annotation</groupId> <artifactId>javax.annotation-api</artifactId> - <version>1.3</version> </dependency> <dependency> <groupId>org.onap.msb.java-sdk</groupId> @@ -294,7 +284,7 @@ <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> - </dependency> + </dependency> <dependency> <groupId>org.mariadb.jdbc</groupId> <artifactId>mariadb-java-client</artifactId> @@ -315,8 +305,17 @@ <dependency> <groupId>org.camunda.bpm.springboot</groupId> <artifactId>camunda-bpm-spring-boot-starter-test</artifactId> - <version>2.3.0</version> + <version>${camunda.springboot.version}</version> <scope>test</scope> </dependency> + <dependency> + <groupId>org.assertj</groupId> + <artifactId>assertj-core</artifactId> + <scope>test</scope> + </dependency> + <dependency> + <groupId>org.camunda.bpm.extension.mockito</groupId> + <artifactId>camunda-bpm-mockito</artifactId> + </dependency> </dependencies> </project> diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/Create3rdONAPE2EServiceInstance.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/Create3rdONAPE2EServiceInstance.groovy index 2ae7686703..05fd517e47 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/Create3rdONAPE2EServiceInstance.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/Create3rdONAPE2EServiceInstance.groovy @@ -23,6 +23,7 @@ package org.onap.so.bpmn.infrastructure.scripts import org.json.JSONArray import org.json.JSONObject import org.json.XML +import org.onap.so.bpmn.common.scripts.ExternalAPIUtilFactory import static org.apache.commons.lang3.StringUtils.* import groovy.xml.XmlUtil @@ -381,7 +382,7 @@ public class Create3rdONAPE2EServiceInstance extends AbstractServiceTaskProcesso valueMap.put("serviceName", '"' + serviceName + '"') valueMap.put("serviceUuId", '"' + serviceUuId + '"') - ExternalAPIUtil externalAPIUtil = new ExternalAPIUtil() + ExternalAPIUtil externalAPIUtil = new ExternalAPIUtilFactory().create() // insert CallSource='ExternalAPI' to uuiRequest Map<String, String> requestInputsMap = new HashMap<>() @@ -426,7 +427,7 @@ public class Create3rdONAPE2EServiceInstance extends AbstractServiceTaskProcesso msoLogger.debug("doCreateE2ESIin3rdONAP externalAPIURL is: " + extAPIPath) msoLogger.debug("doCreateE2ESIin3rdONAP payload is: " + payload) - ExternalAPIUtil externalAPIUtil = new ExternalAPIUtil() + ExternalAPIUtil externalAPIUtil = new ExternalAPIUtilFactory().create() execution.setVariable("ServiceOrderId", "") Response response = externalAPIUtil.executeExternalAPIPostCall(execution, extAPIPath, payload) @@ -471,7 +472,7 @@ public class Create3rdONAPE2EServiceInstance extends AbstractServiceTaskProcesso extAPIPath += "/" + execution.getVariable("ServiceOrderId") msoLogger.debug("getE2ESIProgressin3rdONAP create externalAPIURL is: " + extAPIPath) - ExternalAPIUtil externalAPIUtil = new ExternalAPIUtil() + ExternalAPIUtil externalAPIUtil = new ExternalAPIUtilFactory().create() Response response = externalAPIUtil.executeExternalAPIGetCall(execution, extAPIPath) diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateVFCNSResource.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateVFCNSResource.groovy index 94df0a977a..6222214108 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateVFCNSResource.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateVFCNSResource.groovy @@ -20,6 +20,7 @@ package org.onap.so.bpmn.infrastructure.scripts +import org.onap.so.client.HttpClientFactory 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; @@ -28,18 +29,12 @@ import org.camunda.bpm.engine.delegate.DelegateExecution import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor import org.onap.so.bpmn.common.scripts.ExceptionUtil import org.onap.so.bpmn.core.json.JsonUtils -//import org.onap.so.client.HttpClient -//import org.onap.so.client.RestRequest -import org.onap.so.logger.MessageEnum +import org.onap.so.client.HttpClient import org.onap.so.logger.MsoLogger -import org.onap.so.rest.APIResponse -import org.onap.so.rest.RESTClient -import org.onap.so.rest.RESTConfig import org.onap.so.bpmn.core.UrnPropertiesReader -import groovy.json.* -//import javax.ws.rs.core.Response -//import org.onap.so.utils.TargetEntity +import javax.ws.rs.core.Response +import org.onap.so.utils.TargetEntity /** * This groovy class supports the <class>DoCreateVFCNetworkServiceInstance.bpmn</class> process. @@ -48,10 +43,6 @@ import groovy.json.* public class CreateVFCNSResource extends AbstractServiceTaskProcessor { private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, CreateVFCNSResource.class); -// String vfcUrl = "/vfc/rest/v1/vfcadapter" - -// String host = "http://mso.mso.testlab.openecomp.org:8080" - ExceptionUtil exceptionUtil = new ExceptionUtil() JsonUtils jsonUtil = new JsonUtils() @@ -166,9 +157,9 @@ public class CreateVFCNSResource extends AbstractServiceTaskProcessor { "additionalParamForNs":${requestInputs} } }""" - APIResponse apiResponse = postRequest(execution, vfcAdapterUrl + "/ns", reqBody) - String returnCode = apiResponse.getStatusCode() - String aaiResponseAsString = apiResponse.getResponseBodyAsString() + Response apiResponse = postRequest(execution, vfcAdapterUrl + "/ns", reqBody) + String returnCode = apiResponse.getStatus () + String aaiResponseAsString = apiResponse.readEntity(String.class) String nsInstanceId = ""; if(returnCode== "200" || returnCode == "201"){ nsInstanceId = jsonUtil.getJsonValue(aaiResponseAsString, "nsInstanceId") @@ -195,9 +186,9 @@ public class CreateVFCNSResource extends AbstractServiceTaskProcessor { }""" String nsInstanceId = execution.getVariable("nsInstanceId") String url = vfcAdapterUrl + "/ns/" +nsInstanceId + "/instantiate" - APIResponse apiResponse = postRequest(execution, url, reqBody) - String returnCode = apiResponse.getStatusCode() - String aaiResponseAsString = apiResponse.getResponseBodyAsString() + Response apiResponse = postRequest(execution, url, reqBody) + String returnCode = apiResponse.getStatus() + String aaiResponseAsString = apiResponse.readEntity(String.class) String jobId = ""; if(returnCode== "200"|| returnCode == "201"){ jobId = jsonUtil.getJsonValue(aaiResponseAsString, "jobId") @@ -215,9 +206,9 @@ public class CreateVFCNSResource extends AbstractServiceTaskProcessor { String jobId = execution.getVariable("jobId") String nsOperationKey = execution.getVariable("nsOperationKey"); String url = vfcAdapterUrl + "/jobs/" + jobId - APIResponse apiResponse = postRequest(execution, url, nsOperationKey) - String returnCode = apiResponse.getStatusCode() - String aaiResponseAsString = apiResponse.getResponseBodyAsString() + Response apiResponse = postRequest(execution, url, nsOperationKey) + String returnCode = apiResponse.getStatus() + String aaiResponseAsString = apiResponse.readEntity(String.class) String operationStatus = "error" if(returnCode== "200"|| returnCode == "201"){ operationStatus = jsonUtil.getJsonValue(aaiResponseAsString, "responseDescriptor.status") @@ -268,36 +259,31 @@ public class CreateVFCNSResource extends AbstractServiceTaskProcessor { * url: the url of the request * requestBody: the body of the request */ - private APIResponse postRequest(DelegateExecution execution, String urlString, String requestBody){ + private Response postRequest(DelegateExecution execution, String urlString, String requestBody){ msoLogger.trace("Started Execute VFC adapter Post Process ") msoLogger.info("url:" + urlString +"\nrequestBody:"+ requestBody) - APIResponse apiResponse = null - try{ - // Get the Basic Auth credentials for the VFCAdapter, username is 'bpel', auth is '07a7159d3bf51a0e53be7a8f89699be7' - def basicAuthHeaderValue = "" - RESTConfig config = new RESTConfig(urlString) - RESTClient client = null; - int statusCode = 0; - - // user 'bepl' authHeader is the same with mso.db.auth - String basicAuthValuedb = UrnPropertiesReader.getVariable("mso.db.auth", execution) - - client = new RESTClient(config) - client.addHeader("Accept", "application/json") - client.addAuthorizationHeader(basicAuthValuedb) - client.addHeader("Content-Type", "application/json") - - apiResponse = client.httpPost(requestBody) - statusCode = apiResponse.getStatusCode() - - msoLogger.debug("response code:"+ apiResponse.getStatusCode() +"\nresponse body:"+ apiResponse.getResponseBodyAsString()) - - }catch(Exception e){ - msoLogger.error("Exception occured while executing VF-C Post Call. Exception is: \n" + e.getMessage()); - throw new BpmnError("MSOWorkflowException") - } + Response apiResponse = null + try{ + + URL url = new URL(urlString); + + // Get the Basic Auth credentials for the VFCAdapter, username is 'bpel', auth is '07a7159d3bf51a0e53be7a8f89699be7' + // user 'bepl' authHeader is the same with mso.db.auth + String basicAuthValuedb = UrnPropertiesReader.getVariable("mso.db.auth", execution) + HttpClient httpClient = new HttpClientFactory().newJsonClient(url, TargetEntity.VNF_ADAPTER) + httpClient.addAdditionalHeader("Accept", "application/json") + httpClient.addAdditionalHeader("Authorization", basicAuthValuedb) + + apiResponse = httpClient.post(requestBody) + + msoLogger.debug("response code:"+ apiResponse.getStatus() +"\nresponse body:"+ apiResponse.readEntity(String.class)) + + }catch(Exception e){ + msoLogger.error("VFC Aatpter Post Call Exception:" + e.getMessage()); + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, "VFC Aatpter Post Call Exception") + } - msoLogger.trace("Completed Execute VF-C adapter Post Process ") + msoLogger.trace("Completed Execute VF-C adapter Post Process ") return apiResponse } diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateVfModuleVolumeInfraV1.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateVfModuleVolumeInfraV1.groovy index 965d178cce..05c8246311 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateVfModuleVolumeInfraV1.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateVfModuleVolumeInfraV1.groovy @@ -20,21 +20,26 @@ package org.onap.so.bpmn.infrastructure.scripts -import org.apache.commons.lang3.* +import org.apache.commons.collections.CollectionUtils import org.camunda.bpm.engine.delegate.BpmnError -import org.camunda.bpm.engine.delegate.DelegateExecution; -import org.onap.so.bpmn.common.scripts.AaiUtil; +import org.camunda.bpm.engine.delegate.DelegateExecution +import org.onap.aai.domain.yang.SearchResults import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor; import org.onap.so.bpmn.common.scripts.ExceptionUtil; import org.onap.so.bpmn.common.scripts.MsoUtils import org.onap.so.bpmn.core.WorkflowException +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.logger.MessageEnum import org.onap.so.logger.MsoLogger -import org.onap.so.rest.APIResponse import groovy.json.JsonOutput import groovy.json.JsonSlurper + class CreateVfModuleVolumeInfraV1 extends AbstractServiceTaskProcessor { private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, CreateVfModuleVolumeInfraV1.class); @@ -314,34 +319,21 @@ class CreateVfModuleVolumeInfraV1 extends AbstractServiceTaskProcessor { def request = execution.getVariable(prefix+"Request") def serviceInstanceId = utils.getNodeText(request, "service-instance-id") - - AaiUtil aaiUtil = new AaiUtil(this) - String aaiEndpoint = aaiUtil.getSearchNodesQueryEndpoint(execution) - - def String queryAAIRequest = aaiEndpoint + "?search-node-type=service-instance&filter=service-instance-id:EQUALS:" + serviceInstanceId - msoLogger.debug("AAI query service instance request: " + queryAAIRequest) - - APIResponse response = aaiUtil.executeAAIGetCall(execution, queryAAIRequest) - - String returnCode = response.getStatusCode() - String aaiResponseAsString = response.getResponseBodyAsString() - - msoLogger.debug("AAI query service instance return code: " + returnCode) - msoLogger.debug("AAI query service instance response: " + aaiResponseAsString) - ExceptionUtil exceptionUtil = new ExceptionUtil() + try { - if (returnCode=='200') { - msoLogger.debug('Service instance ' + serviceInstanceId + ' found in AAI.') - } else { - if (returnCode=='404') { + AAIResourceUri uri = AAIUriFactory.createNodesUri(AAIObjectType.SERVICE_INSTANCE,serviceInstanceId) + if(getAAIClient().exists(uri)){ + msoLogger.debug('Service instance ' + serviceInstanceId + ' found in AAI.') + }else{ def message = 'Service instance ' + serviceInstanceId + ' was not found in AAI. Return code: 404.' msoLogger.debug(message) exceptionUtil.buildAndThrowWorkflowException(execution, 2500, message) - } else { - WorkflowException aWorkflowException = exceptionUtil.MapAAIExceptionToWorkflowException(aaiResponseAsString, execution) - throw new BpmnError("MSOWorkflowException") } + }catch(BpmnError bpmnError){ + throw bpmnError + }catch(Exception ex){ + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, ex.getMessage()) } } diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateVnfInfra.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateVnfInfra.groovy index 9c25a57adc..af46bf65b8 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateVnfInfra.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateVnfInfra.groovy @@ -20,6 +20,8 @@ package org.onap.so.bpmn.infrastructure.scripts +import org.onap.so.bpmn.common.scripts.CatalogDbUtilsFactory + import static org.apache.commons.lang3.StringUtils.*; import org.camunda.bpm.engine.delegate.BpmnError @@ -55,8 +57,7 @@ class CreateVnfInfra extends AbstractServiceTaskProcessor { ExceptionUtil exceptionUtil = new ExceptionUtil() JsonUtils jsonUtil = new JsonUtils() VidUtils vidUtils = new VidUtils(this) - CatalogDbUtils cutils = new CatalogDbUtils() - AAICreateResources aaiCR = new AAICreateResources() + CatalogDbUtils catalogDbUtils = new CatalogDbUtilsFactory().create() /** * This method gets and validates the incoming @@ -448,7 +449,7 @@ class CreateVnfInfra extends AbstractServiceTaskProcessor { String vnfModelCustomizationUuid = jsonUtil.getJsonValueForKey(vnfModelInfo, "modelCustomizationUuid") msoLogger.debug("querying Catalog DB by vnfModelCustomizationUuid: " + vnfModelCustomizationUuid) - JSONArray vnfs = cutils.getAllVnfsByVnfModelCustomizationUuid(execution, + JSONArray vnfs = catalogDbUtils.getAllVnfsByVnfModelCustomizationUuid(execution, vnfModelCustomizationUuid, "v2") msoLogger.debug("obtained VNF list: " + vnfs) diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/Delete3rdONAPE2EServiceInstance.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/Delete3rdONAPE2EServiceInstance.groovy index 078d68bd75..b718e4a2e0 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/Delete3rdONAPE2EServiceInstance.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/Delete3rdONAPE2EServiceInstance.groovy @@ -20,6 +20,8 @@ package org.onap.so.bpmn.infrastructure.scripts +import org.onap.so.bpmn.common.scripts.ExternalAPIUtilFactory + import javax.ws.rs.NotFoundException import javax.ws.rs.core.Response @@ -249,7 +251,7 @@ public class Delete3rdONAPE2EServiceInstance extends AbstractServiceTaskProcesso valueMap.put("serviceName", "null") valueMap.put("serviceUuId", '"' + serviceSpecificationId + '"') - ExternalAPIUtil externalAPIUtil = new ExternalAPIUtil() + ExternalAPIUtil externalAPIUtil = new ExternalAPIUtilFactory().create() valueMap.put("_requestInputs_", "") @@ -271,7 +273,7 @@ public class Delete3rdONAPE2EServiceInstance extends AbstractServiceTaskProcesso String extAPIPath = sppartnerUrl + "/service?relatedParty.id=" + globalSubscriberId msoLogger.debug("queryServicefrom3rdONAP externalAPIURL is: " + extAPIPath) - ExternalAPIUtil externalAPIUtil = new ExternalAPIUtil() + ExternalAPIUtil externalAPIUtil = new ExternalAPIUtilFactory().create() Response response = externalAPIUtil.executeExternalAPIGetCall(execution, extAPIPath) @@ -317,7 +319,7 @@ public class Delete3rdONAPE2EServiceInstance extends AbstractServiceTaskProcesso msoLogger.debug("doDeleteE2ESIin3rdONAP externalAPIURL is: " + extAPIPath) msoLogger.debug("doDeleteE2ESIin3rdONAP payload is: " + payload) - ExternalAPIUtil externalAPIUtil = new ExternalAPIUtil() + ExternalAPIUtil externalAPIUtil = new ExternalAPIUtilFactory().create() execution.setVariable("ServiceOrderId", "") Response response = externalAPIUtil.executeExternalAPIPostCall(execution, extAPIPath, payload) @@ -361,7 +363,7 @@ public class Delete3rdONAPE2EServiceInstance extends AbstractServiceTaskProcesso extAPIPath += "/" + execution.getVariable("ServiceOrderId") msoLogger.debug("getE2ESIProgressin3rdONAP delete externalAPIURL is: " + extAPIPath) - ExternalAPIUtil externalAPIUtil = new ExternalAPIUtil() + ExternalAPIUtil externalAPIUtil = new ExternalAPIUtilFactory().create() Response response = externalAPIUtil.executeExternalAPIGetCall(execution, extAPIPath) diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteVfModuleVolumeInfraV1.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteVfModuleVolumeInfraV1.groovy index 83f2fe04db..8c9ab3fe45 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteVfModuleVolumeInfraV1.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteVfModuleVolumeInfraV1.groovy @@ -23,6 +23,7 @@ package org.onap.so.bpmn.infrastructure.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.VolumeGroup import org.onap.so.bpmn.common.scripts.AaiUtil; import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor; import org.onap.so.bpmn.common.scripts.ExceptionUtil; @@ -30,18 +31,21 @@ import org.onap.so.bpmn.common.scripts.MsoUtils import org.onap.so.bpmn.common.scripts.VidUtils; import org.onap.so.bpmn.core.UrnPropertiesReader import org.onap.so.bpmn.core.WorkflowException +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.client.aai.AAIObjectType import org.onap.so.constants.Defaults import org.onap.so.logger.MessageEnum import org.onap.so.logger.MsoLogger -import org.onap.so.rest.APIResponse import org.springframework.web.util.UriUtils import groovy.json.JsonSlurper +import javax.ws.rs.NotFoundException + /** * This groovy class supports the <class>DeleteVfModuleVolume.bpmn</class> process. */ @@ -233,52 +237,39 @@ public class DeleteVfModuleVolumeInfraV1 extends AbstractServiceTaskProcessor { } String cloudRegion = execution.getVariable('DELVfModVol_aicCloudRegion') - AaiUtil aaiUtil = new AaiUtil(this) - - AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.VOLUME_GROUP, Defaults.CLOUD_OWNER.toString(), cloudRegion, volumeGroupId) - def queryAAIVolumeGroupRequest = aaiUtil.createAaiUri(uri) - - msoLogger.debug('Query AAI volume group by ID: ' + queryAAIVolumeGroupRequest) - - APIResponse response = aaiUtil.executeAAIGetCall(execution, queryAAIVolumeGroupRequest) - - String returnCode = response.getStatusCode() - String aaiResponseAsString = response.getResponseBodyAsString() - - msoLogger.debug("AAI query volume group by id return code: " + returnCode) - msoLogger.debug("AAI query volume group by id response: " + aaiResponseAsString) - - execution.setVariable("DELVfModVol_queryAAIVolGrpResponse", aaiResponseAsString) - - if (returnCode=='200' || returnCode == '204') { - - def heatStackId = getNodeTextForce(aaiResponseAsString, 'heat-stack-id') - execution.setVariable('DELVfModVol_volumeGroupHeatStackId', heatStackId) - - if(hasVfModuleRelationship(aaiResponseAsString)){ - msoLogger.debug('Volume Group ' + volumeGroupId + ' currently in use') - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Volume Group ${volumeGroupId} currently in use - found vf-module relationship.") - } - - def volumeGroupTenantId = getTenantIdFromVolumeGroup(aaiResponseAsString) - if (volumeGroupTenantId == null) { - msoLogger.debug("Could not find Tenant Id element in Volume Group with Volume Group Id ${volumeGroupId}") - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Could not find Tenant Id element in Volume Group with Volume Group Id ${volumeGroupId}") - } - - execution.setVariable('DELVfModVol_volumeGroupTenantId', volumeGroupTenantId) - msoLogger.debug('Received Tenant Id ' + volumeGroupTenantId + ' from AAI for Volume Group with Volume Group Id ' + volumeGroupId ) - } - else { - if (returnCode=='404') { - msoLogger.debug("Volume Group ${volumeGroupId} not found in AAI") - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Volume Group ${volumeGroupId} not found in AAI. Response code: 404") - } - else { - WorkflowException aWorkflowException = exceptionUtil.MapAAIExceptionToWorkflowException(aaiResponseAsString, execution) - throw new BpmnError("MSOWorkflowException") - } - } + try { + AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.VOLUME_GROUP, Defaults.CLOUD_OWNER.toString(), cloudRegion, volumeGroupId) + AAIResultWrapper volumeGroupWrapper = getAAIClient().get(uri) + + if (!volumeGroupWrapper.isEmpty()) { + Optional<VolumeGroup> volumeGroupOp = volumeGroupWrapper.asBean(VolumeGroup.class) + execution.setVariable("DELVfModVol_queryAAIVolGrpResponse", volumeGroupOp.get()) + def heatStackId = volumeGroupOp.get().getHeatStackId() ?: "" + execution.setVariable('DELVfModVol_volumeGroupHeatStackId', heatStackId) + + if ( volumeGroupWrapper.getRelationships().isPresent() && !volumeGroupWrapper.getRelationships().get().getRelatedAAIUris(AAIObjectType.VF_MODULE).isEmpty()) { + msoLogger.debug('Volume Group ' + volumeGroupId + ' currently in use') + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Volume Group ${volumeGroupId} currently in use - found vf-module relationship.") + } + + def volumeGroupTenantId = getTenantIdFromVolumeGroup(volumeGroupWrapper) + if (volumeGroupTenantId == null) { + msoLogger.debug("Could not find Tenant Id element in Volume Group with Volume Group Id ${volumeGroupId}") + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Could not find Tenant Id element in Volume Group with Volume Group Id ${volumeGroupId}") + } + + execution.setVariable('DELVfModVol_volumeGroupTenantId', volumeGroupTenantId) + msoLogger.debug('Received Tenant Id ' + volumeGroupTenantId + ' from AAI for Volume Group with Volume Group Id ' + volumeGroupId) + } else { + msoLogger.debug("Volume Group ${volumeGroupId} not found in AAI") + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Volume Group ${volumeGroupId} not found in AAI. Response code: 404") + } + }catch (BpmnError e){ + throw e + }catch (Exception e){ + WorkflowException aWorkflowException = exceptionUtil.MapAAIExceptionToWorkflowException(e.getMessage(), execution) + throw new BpmnError("MSOWorkflowException") + } } /** @@ -288,27 +279,13 @@ public class DeleteVfModuleVolumeInfraV1 extends AbstractServiceTaskProcessor { * @return the Tenant Id extracted from the Volume Group information. 'null' is returned if * the Tenant Id is missing or could not otherwise be extracted. */ - private String getTenantIdFromVolumeGroup(String volumeGroupXml) { - def Node volumeGroupNode = xmlParser.parseText(volumeGroupXml) - def Node relationshipList = utils.getChildNode(volumeGroupNode, 'relationship-list') - if (relationshipList != null) { - def NodeList relationships = utils.getIdenticalChildren(relationshipList, 'relationship') - for (Node relationship in relationships) { - def Node relatedTo = utils.getChildNode(relationship, 'related-to') - if ((relatedTo != null) && (relatedTo.text().equals('tenant'))) { - def NodeList relationshipDataList = utils.getIdenticalChildren(relationship, 'relationship-data') - for (Node relationshipData in relationshipDataList) { - def Node relationshipKey = utils.getChildNode(relationshipData, 'relationship-key') - if ((relationshipKey != null) && (relationshipKey.text().equals('tenant.tenant-id'))) { - def Node relationshipValue = utils.getChildNode(relationshipData, 'relationship-value') - if (relationshipValue != null) { - return relationshipValue.text() - } - } - } - } - } - } + private String getTenantIdFromVolumeGroup(AAIResultWrapper wrapper) { + if(wrapper.getRelationships().isPresent()) { + List<AAIResourceUri> tenantURIList = wrapper.getRelationships().get().getRelatedAAIUris(AAIObjectType.TENANT) + if(!tenantURIList.isEmpty()){ + return tenantURIList.get(0).getURIKeys().get("tenant-id") + } + } return null } @@ -330,24 +307,6 @@ public class DeleteVfModuleVolumeInfraV1 extends AbstractServiceTaskProcessor { return false } - private boolean hasVfModuleRelationship(String volumeGroupXml) { - def Node volumeGroupNode = xmlParser.parseText(volumeGroupXml) - def Node relationshipList = utils.getChildNode(volumeGroupNode, 'relationship-list') - if (relationshipList != null) { - def NodeList relationships = utils.getIdenticalChildren(relationshipList, 'relationship') - for (Node relationship in relationships) { - def Node relatedTo = utils.getChildNode(relationship, 'related-to') - if ((relatedTo != null) && (relatedTo.text().equals('vf-module'))) { - def Node relatedLink = utils.getChildNode(relationship, 'related-link') - if (relatedLink !=null && relatedLink.text() != null){ - return true - } - } - } - } - return false - } - public void prepareVnfAdapterDeleteRequest(DelegateExecution execution, isDebugLogEnabled) { def cloudRegion = execution.getVariable('DELVfModVol_cloudRegion') def tenantId = execution.getVariable('DELVfModVol_tenantId') @@ -387,38 +346,21 @@ public class DeleteVfModuleVolumeInfraV1 extends AbstractServiceTaskProcessor { public void deleteVolGrpId(DelegateExecution execution, isDebugEnabled) { // get variables - String queryAAIVolGrpIdResponse = execution.getVariable("DELVfModVol_queryAAIVolGrpResponse") - String groupId = utils.getNodeText(queryAAIVolGrpIdResponse, "volume-group-id") - String resourceVersion = utils.getNodeText(queryAAIVolGrpIdResponse, "resource-version") - String messageId = execution.getVariable('DELVfModVol_messageId') + VolumeGroup volumeGroup = execution.getVariable("DELVfModVol_queryAAIVolGrpResponse") + String groupId = volumeGroup.getVolumeGroupId() String cloudRegion = execution.getVariable('DELVfModVol_aicCloudRegion') - AaiUtil aaiUtil = new AaiUtil(this) - - AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.VOLUME_GROUP, Defaults.CLOUD_OWNER.toString(), cloudRegion, groupId).resourceVersion(resourceVersion) - def deleteAAIVolumeGrpIdRequest = aaiUtil.createAaiUri(uri) - - msoLogger.debug("Delete AAI volume group : " + deleteAAIVolumeGrpIdRequest) - - APIResponse response = aaiUtil.executeAAIDeleteCall(execution, deleteAAIVolumeGrpIdRequest) - - String returnCode = response.getStatusCode() - String aaiResponseAsString = response.getResponseBodyAsString() - - msoLogger.debug("AAI delete volume group return code: " + returnCode) - msoLogger.debug("AAI delete volume group response: " + aaiResponseAsString) - - ExceptionUtil exceptionUtil = new ExceptionUtil() - if (returnCode=='200' || (returnCode == '204')) { - msoLogger.debug("Volume group $groupId deleted.") - } else { - if (returnCode=='404') { - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Volume group $groupId not found for delete in AAI Response code: 404") - } else { - WorkflowException aWorkflowException = exceptionUtil.MapAAIExceptionToWorkflowException(aaiResponseAsString, execution) - throw new BpmnError("MSOWorkflowException") - } - } + ExceptionUtil exceptionUtil = new ExceptionUtil() + try { + AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.VOLUME_GROUP, Defaults.CLOUD_OWNER.toString(), cloudRegion, groupId) + getAAIClient().delete(uri) + msoLogger.debug("Volume group $groupId deleted.") + }catch(NotFoundException e){ + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Volume group $groupId not found for delete in AAI Response code: 404") + }catch(Exception e1){ + WorkflowException aWorkflowException = exceptionUtil.MapAAIExceptionToWorkflowException(e1.getMessage(), execution) + throw new BpmnError("MSOWorkflowException") + } } diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCompareModelVersions.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCompareModelVersions.groovy index 75db5db0dc..24071d38f6 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCompareModelVersions.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCompareModelVersions.groovy @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP - SO * ================================================================================ - * Copyright (C) 2018 Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (C) 2018 Huawei Technologies Co., Ltd. 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. @@ -20,42 +20,14 @@ package org.onap.so.bpmn.infrastructure.scripts; import static org.apache.commons.lang3.StringUtils.*; -import groovy.xml.XmlUtil -import groovy.json.* import org.onap.so.bpmn.core.domain.ServiceDecomposition -import org.onap.so.bpmn.core.domain.ServiceInstance -import org.onap.so.bpmn.core.domain.ModelInfo import org.onap.so.bpmn.core.domain.Resource -import org.onap.so.bpmn.core.domain.AllottedResource -import org.onap.so.bpmn.core.domain.NetworkResource -import org.onap.so.bpmn.core.domain.VnfResource -import org.onap.so.bpmn.common.recipe.ResourceInput -import org.onap.so.bpmn.common.recipe.BpmnRestClient import org.onap.so.bpmn.core.json.JsonUtils -import org.onap.so.bpmn.common.scripts.AaiUtil import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor import org.onap.so.bpmn.common.scripts.ExceptionUtil -import org.onap.so.bpmn.common.scripts.SDNCAdapterUtils -import org.onap.so.bpmn.common.scripts.CatalogDbUtils; -import org.onap.so.bpmn.core.RollbackData -import org.onap.so.bpmn.core.WorkflowException -import java.util.List; -import java.util.UUID; - -import org.camunda.bpm.engine.delegate.BpmnError -import org.camunda.bpm.engine.runtime.Execution import org.camunda.bpm.engine.delegate.DelegateExecution -import org.json.JSONObject; -import org.json.JSONArray; -import org.apache.commons.lang3.* -import org.apache.commons.codec.binary.Base64; -import org.springframework.web.util.UriUtils; -import org.onap.so.logger.MessageEnum -import org.onap.so.logger.MsoLogger - - /** * This groovy class supports the <class>DoCompareModelVersions.bpmn</class> process. @@ -76,7 +48,6 @@ public class DoCompareModelVersions extends AbstractServiceTaskProcessor { String Prefix="DCMPMDV_" ExceptionUtil exceptionUtil = new ExceptionUtil() JsonUtils jsonUtil = new JsonUtils() - CatalogDbUtils cutils = new CatalogDbUtils() public void preProcessRequest (DelegateExecution execution) { def isDebugEnabled = execution.getVariable("isDebugLogEnabled") @@ -85,48 +56,48 @@ public class DoCompareModelVersions extends AbstractServiceTaskProcessor { try { execution.setVariable("prefix", Prefix) - + //Inputs String modelInvariantUuid_target = execution.getVariable("model-invariant-id-target") if (isBlank(modelInvariantUuid_target)) { msg = "Input model-invariant-id-target is null" utils.log("INFO", msg, isDebugEnabled) exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) - } - + } + String modelUuid_target = execution.getVariable("model-version-id-target") if (isBlank(modelUuid_target)) { msg = "Input model-version-id-target is null" utils.log("INFO", msg, isDebugEnabled) exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) } - + String modelInvariantUuid_original = execution.getVariable("model-invariant-id-original") if (isBlank(modelInvariantUuid_original)) { msg = "Input model-invariant-id-original is null" utils.log("INFO", msg, isDebugEnabled) exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) } - + String modelUuid_original = execution.getVariable("model-version-id-original") if (isBlank(modelUuid_original)) { msg = "Input model-version-id-original is null" utils.log("INFO", msg, isDebugEnabled) exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) - } - + } + // Target and original modelInvariantUuid must to be the same if(modelInvariantUuid_target != modelInvariantUuid_original){ msg = "Input model-invariant-id-target and model-invariant-id-original must to be the same" utils.log("INFO", msg, isDebugEnabled) - exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) } - + // Target and original modelUuid must not to be the same if(modelUuid_target == modelUuid_original){ msg = "Input model-version-id-target and model-version-id-original must not to be the same" utils.log("INFO", msg, isDebugEnabled) - exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) } } catch (Exception ex){ @@ -136,7 +107,7 @@ public class DoCompareModelVersions extends AbstractServiceTaskProcessor { } utils.log("INFO"," ***** Exit preProcessRequest *****", isDebugEnabled) } - + public void prepareDecomposeService_Target(DelegateExecution execution) { def isDebugEnabled=execution.getVariable("isDebugLogEnabled") @@ -150,7 +121,7 @@ public class DoCompareModelVersions extends AbstractServiceTaskProcessor { "modelUuid":"${modelUuid}", "modelVersion":"" }""" - + execution.setVariable("serviceModelInfo_Target", serviceModelInfo) utils.log("DEBUG", " ***** Completed prepareDecomposeService_Target of update generic e2e service ***** ", isDebugEnabled) @@ -163,8 +134,8 @@ public class DoCompareModelVersions extends AbstractServiceTaskProcessor { public void processDecomposition_Target(DelegateExecution execution) { def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - - utils.log("DEBUG", " ***** Inside processDecomposition_Target() of update generic e2e service flow ***** ", isDebugEnabled) + + utils.log("DEBUG", " ***** Inside processDecomposition_Target() of update generic e2e service flow ***** ", isDebugEnabled) try { ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition") execution.setVariable("serviceDecomposition_Target", serviceDecomposition) @@ -174,7 +145,7 @@ public class DoCompareModelVersions extends AbstractServiceTaskProcessor { exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) } } - + public void prepareDecomposeService_Original(DelegateExecution execution) { def isDebugEnabled=execution.getVariable("isDebugLogEnabled") @@ -188,7 +159,7 @@ public class DoCompareModelVersions extends AbstractServiceTaskProcessor { "modelUuid":"${modelUuid}", "modelVersion":"" }""" - + execution.setVariable("serviceModelInfo_Original", serviceModelInfo) utils.log("DEBUG", " ***** Completed prepareDecomposeService_Original of update generic e2e service ***** ", isDebugEnabled) @@ -201,8 +172,8 @@ public class DoCompareModelVersions extends AbstractServiceTaskProcessor { public void processDecomposition_Original(DelegateExecution execution) { def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - - utils.log("DEBUG", " ***** Inside processDecomposition_Original() of update generic e2e service flow ***** ", isDebugEnabled) + + utils.log("DEBUG", " ***** Inside processDecomposition_Original() of update generic e2e service flow ***** ", isDebugEnabled) try { ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition") execution.setVariable("serviceDecomposition_Original", serviceDecomposition) @@ -211,45 +182,45 @@ public class DoCompareModelVersions extends AbstractServiceTaskProcessor { utils.log("DEBUG", exceptionMessage, isDebugEnabled) exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) } - } + } public void doCompareModelVersions(DelegateExecution execution){ def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - utils.log("INFO", "======== Start doCompareModelVersions Process ======== ", isDebugEnabled) + utils.log("INFO", "======== Start doCompareModelVersions Process ======== ", isDebugEnabled) ServiceDecomposition serviceDecomposition_Target = execution.getVariable("serviceDecomposition_Target") ServiceDecomposition serviceDecomposition_Original = execution.getVariable("serviceDecomposition_Original") - + List<Resource> allSR_target = serviceDecomposition_Target.getServiceResources(); List<Resource> allSR_original = serviceDecomposition_Original.getServiceResources(); - + List<Resource> addResourceList = new ArrayList<String>() List<Resource> delResourceList = new ArrayList<String>() - + addResourceList.addAll(allSR_target) delResourceList.addAll(allSR_original) - + //Compare for (Resource rc_t : allSR_target){ String muuid = rc_t.getModelInfo().getModelUuid() String mIuuid = rc_t.getModelInfo().getModelInvariantUuid() String mCuuid = rc_t.getModelInfo().getModelCustomizationUuid() for (Resource rc_o : allSR_original){ - if(rc_o.getModelInfo().getModelUuid() == muuid - && rc_o.getModelInfo().getModelInvariantUuid() == mIuuid + if(rc_o.getModelInfo().getModelUuid() == muuid + && rc_o.getModelInfo().getModelInvariantUuid() == mIuuid && rc_o.getModelInfo().getModelCustomizationUuid() == mCuuid) { addResourceList.remove(rc_t); delResourceList.remove(rc_o); } - } + } } execution.setVariable("addResourceList", addResourceList) execution.setVariable("delResourceList", delResourceList) - utils.log("INFO", "addResourceList: " + addResourceList, isDebugEnabled) + utils.log("INFO", "addResourceList: " + addResourceList, isDebugEnabled) utils.log("INFO", "delResourceList: " + delResourceList, isDebugEnabled) - - utils.log("INFO", "======== COMPLETED doCompareModelVersions Process ======== ", isDebugEnabled) + + utils.log("INFO", "======== COMPLETED doCompareModelVersions Process ======== ", isDebugEnabled) } } diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateE2EServiceInstance.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateE2EServiceInstance.groovy index c987b062ae..2168dab736 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateE2EServiceInstance.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateE2EServiceInstance.groovy @@ -24,12 +24,10 @@ import static org.apache.commons.lang3.StringUtils.*; import javax.ws.rs.NotFoundException -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.ServiceInstance import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor -import org.onap.so.bpmn.common.scripts.CatalogDbUtils; import org.onap.so.bpmn.common.scripts.ExceptionUtil import org.onap.so.bpmn.common.scripts.MsoUtils import org.onap.so.bpmn.core.RollbackData @@ -49,10 +47,6 @@ import org.onap.so.logger.MsoLogger import org.springframework.web.util.UriUtils import org.onap.so.bpmn.core.UrnPropertiesReader -import groovy.json.* - - - /** * This groovy class supports the <class>DoCreateServiceInstance.bpmn</class> process. * @@ -85,7 +79,6 @@ public class DoCreateE2EServiceInstance extends AbstractServiceTaskProcessor { String Prefix="DCRESI_" ExceptionUtil exceptionUtil = new ExceptionUtil() JsonUtils jsonUtil = new JsonUtils() - CatalogDbUtils cutils = new CatalogDbUtils() public void preProcessRequest (DelegateExecution execution) { String msg = "" diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateNetworkInstance.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateNetworkInstance.groovy index 51574f63f8..1b64671163 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateNetworkInstance.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateNetworkInstance.groovy @@ -21,7 +21,8 @@ package org.onap.so.bpmn.infrastructure.scripts; import javax.ws.rs.core.UriBuilder - +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 @@ -41,14 +42,24 @@ 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.client.aai.entities.AAIResultWrapper +import org.onap.so.client.aai.entities.Relationships import org.onap.so.client.graphinventory.entities.uri.Depth import org.onap.so.constants.Defaults import org.onap.so.logger.MsoLogger -import org.onap.so.rest.APIResponse; import org.springframework.web.util.UriUtils +import org.w3c.dom.Document +import org.w3c.dom.Element +import org.w3c.dom.NamedNodeMap +import org.w3c.dom.Node +import org.w3c.dom.NodeList; +import org.xml.sax.InputSource import org.onap.aai.domain.yang.VpnBinding +import org.onap.aai.domain.yang.L3Network +import org.onap.aai.domain.yang.L3Networks +import org.onap.aai.domain.yang.NetworkPolicy +import org.onap.aai.domain.yang.RouteTableReference import org.onap.aai.domain.yang.RouteTarget - +import org.onap.aai.domain.yang.Subnet import com.fasterxml.jackson.jaxrs.util.EndpointAsBeanProperty import javax.ws.rs.NotFoundException @@ -359,66 +370,26 @@ public class DoCreateNetworkInstance extends AbstractServiceTaskProcessor { msoLogger.debug(" ***** Inside callRESTQueryAAINetworkName() of DoCreateNetworkInstance ***** " ) - // get variables - String networkInputs = execution.getVariable(Prefix + "networkInputs") - String networkName = utils.getNodeText(networkInputs, "network-name") - networkName = UriUtils.encode(networkName,"UTF-8") - - // Prepare AA&I url with network-name - String aai_endpoint = UrnPropertiesReader.getVariable("aai.endpoint", execution) - AaiUtil aaiUriUtil = new AaiUtil(this) - - AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectPlurals.L3_NETWORK) - uri.queryParam("network-name", networkName) - String queryAAINameRequest = aaiUriUtil.createAaiUri(uri) - - execution.setVariable(Prefix + "queryNameAAIRequest", queryAAINameRequest) - msoLogger.debug(Prefix + "queryNameAAIRequest - " + "\n" + queryAAINameRequest) - - try { - APIResponse response = aaiUriUtil.executeAAIGetCall(execution, queryAAINameRequest) - String returnCode = response.getStatusCode() - execution.setVariable(Prefix + "aaiNameReturnCode", returnCode) - msoLogger.debug(" ***** AAI Query Name Response Code : " + returnCode) - - String aaiResponseAsString = response.getResponseBodyAsString() - msoLogger.debug(" ***** AAI Query Name Response : " +'\n'+ aaiResponseAsString) - - if (returnCode=='200') { - execution.setVariable(Prefix + "queryNameAAIResponse", aaiResponseAsString) - execution.setVariable(Prefix + "isAAIqueryNameGood", true) - String orchestrationStatus = "" - try { - // response is NOT empty - orchestrationStatus = utils.getNodeText(aaiResponseAsString, "orchestration-status") - execution.setVariable(Prefix + "orchestrationStatus", orchestrationStatus.toUpperCase()) - msoLogger.debug(Prefix + "orchestrationStatus - " + orchestrationStatus.toUpperCase()) - execution.setVariable("orchestrationStatus", orchestrationStatus) - - } catch (Exception ex) { - // response is empty - execution.setVariable(Prefix + "orchestrationStatus", orchestrationStatus) - msoLogger.debug(Prefix + "orchestrationStatus - " + orchestrationStatus) - } - - } else { - if (returnCode=='404') { - msoLogger.debug(" QueryAAINetworkName return code = '404' (Not Found). Proceed with the Create !!! ") - - } else { - // aai all errors - String dataErrorMessage = "Unexpected Error Response from QueryAAINetworkName - " + returnCode - msoLogger.debug(dataErrorMessage) - exceptionUtil.buildWorkflowException(execution, 2500, dataErrorMessage) + try{ + // get variables + String networkInputs = execution.getVariable(Prefix + "networkInputs") + String networkName = utils.getNodeText(networkInputs, "network-name") - } + AAIResourcesClient client = new AAIResourcesClient() + AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectPlurals.L3_NETWORK).queryParam("network-name", networkName) + L3Networks networks = client.get(uri, NotFoundException.class).asBean(L3Networks.class).get() + L3Network network = networks.getL3Network().get(0) - } + execution.setVariable(Prefix + "isAAIqueryNameGood", true) + String orchestrationStatus = network.getOrchestrationStatus() + execution.setVariable(Prefix + "orchestrationStatus", orchestrationStatus.toUpperCase()) + msoLogger.debug(Prefix + "orchestrationStatus - " + orchestrationStatus.toUpperCase()) + execution.setVariable("orchestrationStatus", orchestrationStatus) msoLogger.debug(Prefix + "isAAIqueryNameGood? : " + execution.getVariable(Prefix + "isAAIqueryNameGood")) - } catch (BpmnError e) { - throw e; + } catch (NotFoundException e) { + msoLogger.debug(" QueryAAINetworkName return code = '404' (Not Found). Proceed with the Create !!! ") } catch (Exception ex) { // try error @@ -515,57 +486,21 @@ public class DoCreateNetworkInstance extends AbstractServiceTaskProcessor { String networkName = utils.getNodeText(assignSDNCResponse, "network-name") execution.setVariable(Prefix + "networkName", networkName) - networkId = UriUtils.encode(networkId,"UTF-8") - - AaiUtil aaiUriUtil = new AaiUtil(this) - AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.L3_NETWORK, networkId) - uri.depth(Depth.ALL) - String queryIdAAIRequest = aaiUriUtil.createAaiUri(uri) - - execution.setVariable(Prefix + "queryIdAAIRequest", queryIdAAIRequest) - msoLogger.debug(Prefix + "queryIdAAIRequest - " + "\n" + queryIdAAIRequest) - - APIResponse response = aaiUriUtil.executeAAIGetCall(execution, queryIdAAIRequest) - String returnCode = response.getStatusCode() - execution.setVariable(Prefix + "aaiIdReturnCode", returnCode) - - msoLogger.debug(" ***** AAI Response Code : " + returnCode) + AAIResourcesClient client = new AAIResourcesClient() + AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.L3_NETWORK, networkId).depth(Depth.ONE) + L3Network network = client.get(uri, NotFoundException.class).asBean(L3Network.class).get() - String aaiResponseAsString = response.getResponseBodyAsString() + execution.setVariable(Prefix + "queryIdAAIResponse", network) - if (returnCode=='200') { - execution.setVariable(Prefix + "queryIdAAIResponse", aaiResponseAsString) - msoLogger.debug(" QueryAAINetworkId Success REST Response - " + "\n" + aaiResponseAsString) - - String netId = utils.getNodeText(aaiResponseAsString, "network-id") - execution.setVariable(Prefix + "networkId", netId) - String netName = utils.getNodeText(aaiResponseAsString, "network-name") - execution.setVariable(Prefix + "networkName", netName) - - } else { - if (returnCode=='404') { - String dataErrorMessage = "Response Error from QueryAAINetworkId is 404 (Not Found)." - msoLogger.debug(" AAI Query Failed. " + dataErrorMessage) - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) - - } else { - if (aaiResponseAsString.contains("RESTFault")) { - WorkflowException exceptionObject = exceptionUtil.MapAAIExceptionToWorkflowException(aaiResponseAsString, execution) - execution.setVariable("WorkflowException", exceptionObject) - throw new BpmnError("MSOWorkflowException") - - } else { - // aai all errors - String dataErrorMessage = "Unexpected Response from QueryAAINetworkId - " + returnCode - msoLogger.debug("Unexpected Response from QueryAAINetworkId - " + dataErrorMessage) - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) - - } - } - } + String netId = network.getNetworkId() + execution.setVariable(Prefix + "networkId", netId) + String netName = network.getNetworkName() + execution.setVariable(Prefix + "networkName", netName) - } catch (BpmnError e) { - throw e; + } catch (NotFoundException e) { + String dataErrorMessage = "Response Error from QueryAAINetworkId is 404 (Not Found)." + msoLogger.debug(" AAI Query Failed. " + dataErrorMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) } catch (Exception ex) { String exceptionMessage = "Bpmn error encountered in DoCreateNetworkInstance flow. callRESTQueryAAINetworkId() - " + ex.getMessage() @@ -586,61 +521,28 @@ public class DoCreateNetworkInstance extends AbstractServiceTaskProcessor { // get variables String networkId = execution.getVariable(Prefix + "networkId") String netId = networkId - networkId = UriUtils.encode(networkId,"UTF-8") - - // Prepare AA&I url - AaiUtil aaiUriUtil = new AaiUtil(this) - AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.L3_NETWORK, networkId) - uri.depth(Depth.ALL) - String requeryIdAAIRequest = aaiUriUtil.createAaiUri(uri) - - execution.setVariable(Prefix + "requeryIdAAIRequest", requeryIdAAIRequest) - msoLogger.debug(Prefix + "requeryIdAAIRequest - " + "\n" + requeryIdAAIRequest) - - APIResponse response = aaiUriUtil.executeAAIGetCall(execution, requeryIdAAIRequest) - String returnCode = response.getStatusCode() - execution.setVariable(Prefix + "aaiRequeryIdReturnCode", returnCode) - msoLogger.debug(" ***** AAI ReQuery Response Code : " + returnCode) - String aaiResponseAsString = response.getResponseBodyAsString() + AAIResourcesClient client = new AAIResourcesClient() + AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.L3_NETWORK, networkId).depth(Depth.ONE) + L3Network network = client.get(uri, NotFoundException.class).asBean(L3Network.class).get() - if (returnCode=='200') { - execution.setVariable(Prefix + "requeryIdAAIResponse", aaiResponseAsString) - msoLogger.debug(" ReQueryAAINetworkId Success REST Response - " + "\n" + aaiResponseAsString) + execution.setVariable(Prefix + "aaiRequeryIdReturnCode", "200") + execution.setVariable(Prefix + "requeryIdAAIResponse", network) - String netName = utils.getNodeText(aaiResponseAsString, "network-name") - String networkOutputs = - """<network-outputs> + String netName = network.getNetworkName() + String networkOutputs = + """<network-outputs> <network-id>${MsoUtils.xmlEscape(netId)}</network-id> <network-name>${MsoUtils.xmlEscape(netName)}</network-name> </network-outputs>""" - execution.setVariable(Prefix + "networkOutputs", networkOutputs) - msoLogger.debug(" networkOutputs - " + '\n' + networkOutputs) - - } else { - if (returnCode=='404') { - String dataErrorMessage = "Response Error from ReQueryAAINetworkId is 404 (Not Found)." - msoLogger.debug(" AAI ReQuery Failed. - " + dataErrorMessage) - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) - - } else { - if (aaiResponseAsString.contains("RESTFault")) { - WorkflowException exceptionObject = exceptionUtil.MapAAIExceptionToWorkflowException(aaiResponseAsString, execution) - execution.setVariable("WorkflowException", exceptionObject) - throw new BpmnError("MSOWorkflowException") - - } else { - // aai all errors - String dataErrorMessage = "Unexpected Response from ReQueryAAINetworkId - " + returnCode - msoLogger.debug(dataErrorMessage) - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) + execution.setVariable(Prefix + "networkOutputs", networkOutputs) + msoLogger.debug(" networkOutputs - " + '\n' + networkOutputs) - } - } - } - } catch (BpmnError e) { - throw e; + } catch (NotFoundException e) { + String dataErrorMessage = "Response Error from ReQueryAAINetworkId is 404 (Not Found)." + msoLogger.debug(" AAI ReQuery Failed. - " + dataErrorMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) } catch (Exception ex) { String exceptionMessage = "Bpmn error encountered in DoCreateNetworkInstance flow. callRESTReQueryAAINetworkId() - " + ex.getMessage() @@ -659,72 +561,57 @@ public class DoCreateNetworkInstance extends AbstractServiceTaskProcessor { try { - // get variables - String queryIdAAIResponse = execution.getVariable(Prefix + "queryIdAAIResponse").replace('<?xml version="1.0" encoding="UTF-8"?>', "") - String relationship = networkUtils.getFirstNodeXml(queryIdAAIResponse, "relationship-list").trim().replace("tag0:","").replace(":tag0","") - msoLogger.debug(" relationship - " + relationship) - - // Check if Vnf Binding is present, then build a List of vnfBinding - List vpnBindingUri = networkUtils.getVnfBindingObject(relationship) - int vpnCount = vpnBindingUri.size() - execution.setVariable(Prefix + "vpnCount", vpnCount) - msoLogger.debug(Prefix + "vpnCount - " + vpnCount) - - if (vpnCount > 0) { - execution.setVariable(Prefix + "vpnBindings", vpnBindingUri) - msoLogger.debug(" vpnBindingUri List - " + vpnBindingUri) - - String routeTargets = "" - // AII loop call using list vpnBindings - for(i in 0..vpnBindingUri.size()-1) { - int counting = i+1 - - String vpnBindingId = vpnBindingUri[i].substring(vpnBindingUri[i].indexOf("/vpn-binding/")+13, vpnBindingUri[i].length()) - if (vpnBindingId.charAt(vpnBindingId.length()-1) == '/') { - vpnBindingId = vpnBindingId.substring(0, vpnBindingId.length()-1) - } - - AAIResourcesClient resourceClient = new AAIResourcesClient() - AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.VPN_BINDING, vpnBindingId) - AAIResultWrapper wrapper = resourceClient.get(uri.depth(Depth.TWO), NotFoundException.class) - - Optional<VpnBinding> binding = wrapper.asBean(VpnBinding.class) - - String routeTarget = "" - String routeRole = "" - if(binding.get().getRouteTargets() != null) { - List<RouteTarget> targets = binding.get().getRouteTargets().getRouteTarget() - for(RouteTarget target : targets) { - routeTarget = target.getGlobalRouteTarget() - routeRole = target.getRouteTargetRole() - routeTargets += "<routeTargets>" + '\n' + - " <routeTarget>" + routeTarget + "</routeTarget>" + '\n' + - " <routeTargetRole>" + routeRole + "</routeTargetRole>" + '\n' + - "</routeTargets>" + '\n' + AAIResourcesClient client = new AAIResourcesClient() + AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.L3_NETWORK, execution.getVariable(Prefix + "networkId")) + Optional<Relationships> relationships = client.get(uri, NotFoundException.class).getRelationships() + if(relationships.isPresent()){ + List<AAIResourceUri> uris = relationships.get().getRelatedAAIUris(AAIObjectType.VPN_BINDING) + + msoLogger.debug(Prefix + "vpnCount - " + uris.size()) + + if (uris.size() > 0) { + String routeTargets = "" + for(AAIResourceUri u : uris) { + + AAIResultWrapper wrapper = client.get(u.depth(Depth.TWO), NotFoundException.class) + Optional<VpnBinding> binding = wrapper.asBean(VpnBinding.class) + + String routeTarget = "" + String routeRole = "" + if(binding.get().getRouteTargets() != null) { + List<RouteTarget> targets = binding.get().getRouteTargets().getRouteTarget() + for(RouteTarget target : targets) { + routeTarget = target.getGlobalRouteTarget() + routeRole = target.getRouteTargetRole() + routeTargets += "<routeTargets>" + '\n' + + " <routeTarget>" + routeTarget + "</routeTarget>" + '\n' + + " <routeTargetRole>" + routeRole + "</routeTargetRole>" + '\n' + + "</routeTargets>" + '\n' + } } - } - } // end loop + } // end loop - execution.setVariable(Prefix + "routeCollection", routeTargets) - msoLogger.debug(Prefix + "routeCollection - " + '\n' + routeTargets) + execution.setVariable(Prefix + "routeCollection", routeTargets) + msoLogger.debug(Prefix + "routeCollection - " + '\n' + routeTargets) - } else { - // reset return code to success - execution.setVariable(Prefix + "aaiQqueryVpnBindingReturnCode", "200") - AaiUtil aaiUriUtil = new AaiUtil(this) - String schemaVersion = aaiUriUtil.getNamespace() - String aaiStubResponse = - """ <rest:payload contentType="text/xml" xmlns:rest="http://schemas.activebpel.org/REST/2007/12/01/aeREST.xsd"> + } else { + // reset return code to success + execution.setVariable(Prefix + "aaiQqueryVpnBindingReturnCode", "200") + AaiUtil aaiUriUtil = new AaiUtil(this) + String schemaVersion = aaiUriUtil.getNamespace() + String aaiStubResponse = + """ <rest:payload contentType="text/xml" xmlns:rest="http://schemas.activebpel.org/REST/2007/12/01/aeREST.xsd"> <vpn-binding xmlns="${schemaVersion}"> <global-route-target/> </vpn-binding> </rest:payload>""" - String aaiStubResponseAsXml = utils.formatXml(aaiStubResponse) - execution.setVariable(Prefix + "queryVpnBindingAAIResponse", aaiStubResponseAsXml) - execution.setVariable(Prefix + "routeCollection", "<routeTargets/>") - msoLogger.debug(" No vpnBinding, using this stub as response - " + '\n' + aaiStubResponseAsXml) + String aaiStubResponseAsXml = utils.formatXml(aaiStubResponse) + execution.setVariable(Prefix + "queryVpnBindingAAIResponse", aaiStubResponseAsXml) + execution.setVariable(Prefix + "routeCollection", "<routeTargets/>") + msoLogger.debug(" No vpnBinding, using this stub as response - " + '\n' + aaiStubResponseAsXml) + } } } catch (NotFoundException e) { @@ -746,111 +633,62 @@ public class DoCreateNetworkInstance extends AbstractServiceTaskProcessor { msoLogger.debug(" ***** Inside callRESTQueryAAINetworkPolicy() of DoCreateNetworkInstance ***** " ) try { - // get variables - String queryIdAAIResponse = execution.getVariable(Prefix + "queryIdAAIResponse").replace('<?xml version="1.0" encoding="UTF-8"?>', "") - String relationship = networkUtils.getFirstNodeXml(queryIdAAIResponse, "relationship-list").trim().replace("tag0:","").replace(":tag0","") - msoLogger.debug(" relationship - " + relationship) - - // Check if Network Policy is present, then build a List of network policy - List networkPolicyUriList = networkUtils.getNetworkPolicyObject(relationship) - int networkPolicyCount = networkPolicyUriList.size() - execution.setVariable(Prefix + "networkPolicyCount", networkPolicyCount) - msoLogger.debug(Prefix + "networkPolicyCount - " + networkPolicyCount) + AAIResourcesClient client = new AAIResourcesClient() + AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.L3_NETWORK, execution.getVariable(Prefix + "networkId")) + Optional<Relationships> relationships = client.get(uri, NotFoundException.class).getRelationships() + if(relationships.isPresent()){ + List<AAIResourceUri> uris = relationships.get().getRelatedAAIUris(AAIObjectType.NETWORK_POLICY) - AaiUtil aaiUriUtil = new AaiUtil(this) + execution.setVariable(Prefix + "networkPolicyCount", uris.size()) + msoLogger.debug(Prefix + "networkPolicyCount - " + uris.size()) - if (networkPolicyCount > 0) { - execution.setVariable(Prefix + "networkPolicyUriList", networkPolicyUriList) - msoLogger.debug(" networkPolicyUri List - " + networkPolicyUriList) + if (uris.size() > 0) { - String networkPolicies = "" - // AII loop call using list vpnBindings - for (i in 0..networkPolicyUriList.size()-1) { + String networkPolicies = "" + // AII loop call using list vpnBindings + for(AAIResourceUri u : uris) { - int counting = i+1 + NetworkPolicy p = client.get(u, NotFoundException.class).asBean(NetworkPolicy.class).get() - // Note: By default, the network policy url is found in 'related-link' of the response, - // so, the default in URN mappings for this is set to "" (ie, space), unless forced to use the URN mapping. + execution.setVariable(Prefix + "aaiQqueryNetworkPolicyReturnCode", "200") - URI uri = UriBuilder.fromUri(networkPolicyUriList[i]).build() + String networkPolicy = p.getNetworkPolicyFqdn() + networkPolicies += "<policyFqdns>" + networkPolicy + "</policyFqdns>" + '\n' - AAIResourceUri aaiUri = AAIUriFactory.createResourceFromExistingURI(AAIObjectType.NETWORK_POLICY, uri) - aaiUri.depth(Depth.ALL) - String queryNetworkPolicyAAIRequest = aaiUriUtil.createAaiUri(aaiUri) + } // end loop - execution.setVariable(Prefix + "queryNetworkPolicyAAIRequest", queryNetworkPolicyAAIRequest) - msoLogger.debug(Prefix + "queryNetworkPolicyAAIRequest, , NetworkPolicy #" + counting + " : " + "\n" + queryNetworkPolicyAAIRequest) + execution.setVariable(Prefix + "networkCollection", networkPolicies) + msoLogger.debug(Prefix + "networkCollection - " + '\n' + networkPolicies) - APIResponse response = aaiUriUtil.executeAAIGetCall(execution, queryNetworkPolicyAAIRequest) - String returnCode = response.getStatusCode() - execution.setVariable(Prefix + "aaiQqueryNetworkPolicyReturnCode", returnCode) - msoLogger.debug(" ***** AAI query network policy Response Code, NetworkPolicy #" + counting + " : " + returnCode) - - String aaiResponseAsString = response.getResponseBodyAsString() - - if (returnCode=='200') { - execution.setVariable(Prefix + "queryNetworkPolicyAAIResponse", aaiResponseAsString) - msoLogger.debug(" QueryAAINetworkPolicy Success REST Response, , NetworkPolicy #" + counting + " : " + "\n" + aaiResponseAsString) - - String networkPolicy = "" - if (utils.nodeExists(aaiResponseAsString, "network-policy-fqdn")) { - networkPolicy = utils.getNodeText(aaiResponseAsString, "network-policy-fqdn") - networkPolicies += "<policyFqdns>" + networkPolicy + "</policyFqdns>" + '\n' - } - - } else { - if (returnCode=='404') { - String dataErrorMessage = "Response Error from QueryAAINetworkPolicy is 404 (Not Found)." - msoLogger.debug(dataErrorMessage) - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) - - } else { - if (aaiResponseAsString.contains("RESTFault")) { - WorkflowException exceptionObject = exceptionUtil.MapAAIExceptionToWorkflowException(aaiResponseAsString, execution) - execution.setVariable("WorkflowException", exceptionObject) - throw new BpmnError("MSOWorkflowException") - - } else { - // aai all errors - String dataErrorMessage = "Unexpected Response from QueryAAINetworkPolicy - " + returnCode - msoLogger.debug(dataErrorMessage) - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) - - } - } - } - - } // end loop - - execution.setVariable(Prefix + "networkCollection", networkPolicies) - msoLogger.debug(Prefix + "networkCollection - " + '\n' + networkPolicies) - - } else { - // reset return code to success - execution.setVariable(Prefix + "aaiQqueryNetworkPolicyReturnCode", "200") - String schemaVersion = aaiUriUtil.getNamespace() - String aaiStubResponse = - """ <rest:payload contentType="text/xml" xmlns:rest="http://schemas.activebpel.org/REST/2007/12/01/aeREST.xsd"> + } else { + // reset return code to success + execution.setVariable(Prefix + "aaiQqueryNetworkPolicyReturnCode", "200") + AaiUtil aaiUriUtil = new AaiUtil(this) + String schemaVersion = aaiUriUtil.getNamespace() + String aaiStubResponse = + """ <rest:payload contentType="text/xml" xmlns:rest="http://schemas.activebpel.org/REST/2007/12/01/aeREST.xsd"> <network-policy xmlns="${schemaVersion}"> <network-policy-fqdn/> </network-policy> </rest:payload>""" - String aaiStubResponseAsXml = utils.formatXml(aaiStubResponse) - execution.setVariable(Prefix + "queryNetworkPolicyAAIResponse", aaiStubResponseAsXml) - execution.setVariable(Prefix + "networkCollection", "<policyFqdns/>") - msoLogger.debug(" No net policies, using this stub as response - " + '\n' + aaiStubResponseAsXml) + String aaiStubResponseAsXml = utils.formatXml(aaiStubResponse) + execution.setVariable(Prefix + "queryNetworkPolicyAAIResponse", aaiStubResponseAsXml) + execution.setVariable(Prefix + "networkCollection", "<policyFqdns/>") + msoLogger.debug(" No net policies, using this stub as response - " + '\n' + aaiStubResponseAsXml) + } } + } catch (NotFoundException e) { + String dataErrorMessage = "Response Error from QueryAAINetworkPolicy is 404 (Not Found)." + msoLogger.debug(dataErrorMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) - } catch (BpmnError e) { - throw e; - - } catch (Exception ex) { - String exceptionMessage = "Bpmn error encountered in DoCreateNetworkInstance flow. callRESTQueryAAINetworkPolicy() - " + ex.getMessage() - msoLogger.debug(exceptionMessage) - exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + } catch (Exception ex) { + String exceptionMessage = "Bpmn error encountered in DoCreateNetworkInstance flow. callRESTQueryAAINetworkPolicy() - " + ex.getMessage() + msoLogger.debug(exceptionMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) - } + } } @@ -861,103 +699,57 @@ public class DoCreateNetworkInstance extends AbstractServiceTaskProcessor { msoLogger.debug(" ***** Inside callRESTQueryAAINetworkTableRef() of DoCreateNetworkInstance ***** " ) try { - // get variables - String queryIdAAIResponse = execution.getVariable(Prefix + "queryIdAAIResponse").replace('<?xml version="1.0" encoding="UTF-8"?>', "") - String relationship = networkUtils.getFirstNodeXml(queryIdAAIResponse, "relationship-list").trim().replace("tag0:","").replace(":tag0","") - msoLogger.debug(" relationship - " + relationship) - - // Check if Network TableREf is present, then build a List of network policy - List networkTableRefUriList = networkUtils.getNetworkTableRefObject(relationship) - int networkTableRefCount = networkTableRefUriList.size() - execution.setVariable(Prefix + "networkTableRefCount", networkTableRefCount) - msoLogger.debug(Prefix + "networkTableRefCount - " + networkTableRefCount) - String aai_endpoint = UrnPropertiesReader.getVariable("aai.endpoint", execution) - AaiUtil aaiUriUtil = new AaiUtil(this) + AAIResourcesClient client = new AAIResourcesClient() + AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.L3_NETWORK, execution.getVariable(Prefix + "networkId")) + Optional<Relationships> relationships = client.get(uri, NotFoundException.class).getRelationships() + if(relationships.isPresent()){ + List<AAIResourceUri> uris = relationships.get().getRelatedAAIUris(AAIObjectType.ROUTE_TABLE_REFERENCE) - if (networkTableRefCount > 0) { - execution.setVariable(Prefix + "networkTableRefUriList", networkTableRefUriList) - msoLogger.debug(" networkTableRefUri List - " + networkTableRefUriList) + execution.setVariable(Prefix + "networkTableRefCount", uris.size()) + msoLogger.debug(Prefix + "networkTableRefCount - " + uris.size()) - // AII loop call using list vpnBindings - String networkTableRefs = "" - for (i in 0..networkTableRefUriList.size()-1) { - int counting = i+1 + if (uris.size() > 0) { - // prepare url using tableRef - URI uri = UriBuilder.fromUri(networkTableRefUriList[i]).build() + // AII loop call using list vpnBindings + String networkTableRefs = "" + for(AAIResourceUri u : uris) { - AAIResourceUri aaiUri = AAIUriFactory.createResourceFromExistingURI(AAIObjectType.ROUTE_TABLE_REFERENCE, uri) - aaiUri.depth(Depth.ALL) - String queryNetworkTableRefAAIRequest = aaiUriUtil.createAaiUri(aaiUri) + RouteTableReference rt = client.get(u, NotFoundException.class).asBean(RouteTableReference.class).get() - execution.setVariable(Prefix + "queryNetworkTableRefAAIRequest", queryNetworkTableRefAAIRequest) - msoLogger.debug(Prefix + "queryNetworkTableRefAAIRequest, , NetworkTableRef #" + counting + " : " + "\n" + queryNetworkTableRefAAIRequest) + String networkTableRef = rt.getRouteTableReferenceFqdn() + networkTableRefs += "<routeTableFqdns>" + networkTableRef + "</routeTableFqdns>" + '\n' - APIResponse response = aaiUriUtil.executeAAIGetCall(execution, queryNetworkTableRefAAIRequest) - String returnCode = response.getStatusCode() - execution.setVariable(Prefix + "aaiQqueryNetworkTableRefReturnCode", returnCode) - msoLogger.debug(" ***** AAI query network Table Reference Response Code, NetworkTableRef #" + counting + " : " + returnCode) - - String aaiResponseAsString = response.getResponseBodyAsString() - - if (returnCode=='200') { - execution.setVariable(Prefix + "queryNetworkTableRefAAIResponse", aaiResponseAsString) - msoLogger.debug(" QueryAAINetworkTableRef Success REST Response, , NetworkTableRef #" + counting + " : " + "\n" + aaiResponseAsString) - - String networkTableRef = "" - if (utils.nodeExists(aaiResponseAsString, "route-table-reference-fqdn")) { - networkTableRef = utils.getNodeText(aaiResponseAsString, "route-table-reference-fqdn") - networkTableRefs += "<routeTableFqdns>" + networkTableRef + "</routeTableFqdns>" + '\n' - } - - } else { - if (returnCode=='404') { - String dataErrorMessage = "Response Error from QueryAAINetworkTableRef is 404 (Not Found)." - msoLogger.debug(dataErrorMessage) - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) - - } else { - if (aaiResponseAsString.contains("RESTFault")) { - WorkflowException exceptionObject = exceptionUtil.MapAAIExceptionToWorkflowException(aaiResponseAsString, execution) - execution.setVariable("WorkflowException", exceptionObject) - throw new BpmnError("MSOWorkflowException") - - } else { - // aai all errors - String dataErrorMessage = "Unexpected Response from QueryAAINetworkTableRef - " + returnCode - msoLogger.debug(dataErrorMessage) - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) - - } - } - } - } // end loop + } // end loop - execution.setVariable(Prefix + "tableRefCollection", networkTableRefs) - msoLogger.debug(Prefix + "tableRefCollection - " + '\n' + networkTableRefs) + execution.setVariable(Prefix + "tableRefCollection", networkTableRefs) + msoLogger.debug(Prefix + "tableRefCollection - " + '\n' + networkTableRefs) - } else { - // reset return code to success - execution.setVariable(Prefix + "aaiQqueryNetworkTableRefReturnCode", "200") - String schemaVersion = aaiUriUtil.getNamespace() - String aaiStubResponse = - """ <rest:payload contentType="text/xml" xmlns:rest="http://schemas.activebpel.org/REST/2007/12/01/aeREST.xsd"> + } else { + // reset return code to success + execution.setVariable(Prefix + "aaiQqueryNetworkTableRefReturnCode", "200") + AaiUtil aaiUriUtil = new AaiUtil(this) + String schemaVersion = aaiUriUtil.getNamespace() + String aaiStubResponse = + """ <rest:payload contentType="text/xml" xmlns:rest="http://schemas.activebpel.org/REST/2007/12/01/aeREST.xsd"> <route-table-references xmlns="${schemaVersion}"> <route-table-reference-fqdn/> </route-table-references> </rest:payload>""" - String aaiStubResponseAsXml = utils.formatXml(aaiStubResponse) - execution.setVariable(Prefix + "queryNetworkTableRefAAIResponse", aaiStubResponseAsXml) - execution.setVariable(Prefix + "tableRefCollection", "<routeTableFqdns/>") - msoLogger.debug(" No net table references, using this stub as response - " + '\n' + aaiStubResponseAsXml) + String aaiStubResponseAsXml = utils.formatXml(aaiStubResponse) + execution.setVariable(Prefix + "queryNetworkTableRefAAIResponse", aaiStubResponseAsXml) + execution.setVariable(Prefix + "tableRefCollection", "<routeTableFqdns/>") + msoLogger.debug(" No net table references, using this stub as response - " + '\n' + aaiStubResponseAsXml) + } } - } catch (BpmnError e) { - throw e; + } catch (NotFoundException e) { + String dataErrorMessage = "Response Error from QueryAAINetworkTableRef is 404 (Not Found)." + msoLogger.debug(dataErrorMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) } catch (Exception ex) { String exceptionMessage = "Bpmn error encountered in DoCreateNetworkInstance flow. callRESTQueryAAINetworkTableRef() - " + ex.getMessage() @@ -973,80 +765,82 @@ public class DoCreateNetworkInstance extends AbstractServiceTaskProcessor { execution.setVariable("prefix",Prefix) - msoLogger.debug(" ***** Inside callRESTUpdateContrailAAINetwork() of DoCreateNetworkInstance ***** " ) + msoLogger.trace(" ***** Inside callRESTUpdateContrailAAINetwork() of DoCreateNetworkInstance ***** " ) try { // get variables String networkId = execution.getVariable(Prefix + "networkId") - networkId = UriUtils.encode(networkId,"UTF-8") - String requeryIdAAIResponse = execution.getVariable(Prefix + "requeryIdAAIResponse") + L3Network requeryIdAAIResponse = execution.getVariable(Prefix + "requeryIdAAIResponse") String createNetworkResponse = execution.getVariable(Prefix + "createNetworkResponse") - // Prepare url - AaiUtil aaiUriUtil = new AaiUtil(this) + L3Network l3Network = new L3Network() + if (StringUtils.isBlank(requeryIdAAIResponse.getHeatStackId())) { + if (utils.nodeExists(createNetworkResponse, 'networkStackId')) { + l3Network.setHeatStackId(utils.getNodeText(createNetworkResponse, 'networkStackId')) + } + } + if (StringUtils.isBlank(requeryIdAAIResponse.getNeutronNetworkId())) { + if (utils.nodeExists(createNetworkResponse, 'neutronNetworkId')) { + l3Network.setNeutronNetworkId(utils.getNodeText(createNetworkResponse, 'neutronNetworkId')) + } + } + if (StringUtils.isBlank(requeryIdAAIResponse.getContrailNetworkFqdn())) { + if (utils.nodeExists(createNetworkResponse, 'networkFqdn')) { + l3Network.setContrailNetworkFqdn(utils.getNodeText(createNetworkResponse, 'networkFqdn')) + } + } + + String status = utils.getNodeText(createNetworkResponse, 'orchestration-status') + if(status.equals("pending-create") || status.equals("PendingCreate")){ + l3Network.setOrchestrationStatus("Created") + }else{ + l3Network.setOrchestrationStatus("Active") + } + msoLogger.debug("Updating l3-network in AAI" ) + + AAIResourcesClient client = new AAIResourcesClient() AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.L3_NETWORK, networkId) - uri.depth(Depth.ALL) - String updateContrailAAIUrlRequest = aaiUriUtil.createAaiUri(uri) - - execution.setVariable(Prefix + "updateContrailAAIUrlRequest", updateContrailAAIUrlRequest) - msoLogger.debug(Prefix + "updateContrailAAIUrlRequest - " + "\n" + updateContrailAAIUrlRequest) - - //Prepare payload (PUT) - String schemaVersion = aaiUriUtil.getNamespaceFromUri(updateContrailAAIUrlRequest) - String payload = networkUtils.ContrailNetworkCreatedUpdate(requeryIdAAIResponse, createNetworkResponse, schemaVersion) - String payloadXml = utils.formatXml(payload) - execution.setVariable(Prefix + "updateContrailAAIPayloadRequest", payloadXml) - msoLogger.debug(" 'payload' to Update Contrail - " + "\n" + payloadXml) - - APIResponse response = aaiUriUtil.executeAAIPutCall(execution, updateContrailAAIUrlRequest, payloadXml) - - String returnCode = response.getStatusCode() - execution.setVariable(Prefix + "aaiUpdateContrailReturnCode", returnCode) - msoLogger.debug(" ***** AAI Update Contrail Response Code : " + returnCode) - String aaiUpdateContrailResponseAsString = response.getResponseBodyAsString() - if (returnCode=='200') { - execution.setVariable(Prefix + "updateContrailAAIResponse", aaiUpdateContrailResponseAsString) - msoLogger.debug(" AAI Update Contrail Success REST Response - " + "\n" + aaiUpdateContrailResponseAsString) - // Point-of-no-return is set to false, rollback not needed. - String rollbackEnabled = execution.getVariable(Prefix + "rollbackEnabled") - if (rollbackEnabled == "true") { - execution.setVariable(Prefix + "isPONR", false) - } else { - execution.setVariable(Prefix + "isPONR", true) - } - msoLogger.debug(Prefix + "isPONR" + ": " + execution.getVariable(Prefix + "isPONR")) - } else { - if (returnCode=='404') { - String dataErrorMessage = " Response Error from UpdateContrailAAINetwork is 404 (Not Found)." - msoLogger.debug(dataErrorMessage) - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) + client.update(uri, l3Network) + + if(requeryIdAAIResponse.getSubnets() != null){ + for(Subnet s:requeryIdAAIResponse.getSubnets().getSubnet()){ + String subnetOrchStatus = s.getOrchestrationStatus() + String subnetId = s.getSubnetId() + Subnet subnet = new Subnet() + subnet.setNeutronSubnetId(networkUtils.extractNeutSubId(createNetworkResponse, subnetId)) + if(subnetOrchStatus.equals("pending-create") || subnetOrchStatus.equals("PendingCreate") ){ + subnet.setOrchestrationStatus("Created") + }else{ + subnet.setOrchestrationStatus("Active") + } + + msoLogger.debug("Updating subnet in AAI" ) + AAIResourceUri subUri = AAIUriFactory.createResourceUri(AAIObjectType.SUBNET, networkId, subnetId) + client.update(subUri, subnet) - } else { - if (aaiUpdateContrailResponseAsString.contains("RESTFault")) { - WorkflowException exceptionObject = exceptionUtil.MapAAIExceptionToWorkflowException(aaiUpdateContrailResponseAsString, execution) - execution.setVariable("WorkflowException", exceptionObject) - throw new BpmnError("MSOWorkflowException") - - } else { - // aai all errors - String errorMessage = "Unexpected Response from UpdateContrailAAINetwork - " + returnCode - msoLogger.debug(errorMessage) - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, errorMessage) - } } } + String rollbackEnabled = execution.getVariable(Prefix + "rollbackEnabled") + if (rollbackEnabled == "true") { + execution.setVariable(Prefix + "isPONR", false) + } else { + execution.setVariable(Prefix + "isPONR", true) + } + msoLogger.debug(Prefix + "isPONR" + ": " + execution.getVariable(Prefix + "isPONR")) + } catch (BpmnError e) { throw e; - + } catch (NotFoundException e) { + String dataErrorMessage = " Response Error from UpdateContrailAAINetwork is 404 (Not Found)." + msoLogger.debug(dataErrorMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) } catch (Exception ex) { String exceptionMessage = "Bpmn error encountered in DoCreateNetworkInstance flow. callRESTUpdateContrailAAINetwork() - " + ex.getMessage() msoLogger.debug(exceptionMessage) exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) - } - } public void prepareCreateNetworkRequest (DelegateExecution execution) { @@ -1066,7 +860,7 @@ public class DoCreateNetworkInstance extends AbstractServiceTaskProcessor { String source = execution.getVariable(Prefix + "source") String requestInput = execution.getVariable(Prefix + "networkRequest") - String queryIdResponse = execution.getVariable(Prefix + "queryIdAAIResponse") + L3Network queryIdResponse = execution.getVariable(Prefix + "queryIdAAIResponse") String cloudRegionId = execution.getVariable(Prefix + "cloudRegionPo") String backoutOnFailure = execution.getVariable(Prefix + "rollbackEnabled") diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateNetworkInstanceRollback.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateNetworkInstanceRollback.groovy index 7e00f05b90..fd6a4a1cde 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateNetworkInstanceRollback.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateNetworkInstanceRollback.groovy @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -18,33 +18,25 @@ * ============LICENSE_END========================================================= */ -package org.onap.so.bpmn.infrastructure.scripts; +package org.onap.so.bpmn.infrastructure.scripts -import groovy.xml.XmlUtil -import groovy.json.* import org.onap.so.bpmn.core.UrnPropertiesReader import org.onap.so.bpmn.core.json.JsonUtils +import org.onap.so.client.HttpClient +import org.onap.so.client.HttpClientFactory import org.onap.so.logger.MsoLogger -import org.onap.so.logger.MessageEnum - import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor import org.onap.so.bpmn.common.scripts.ExceptionUtil import org.onap.so.bpmn.common.scripts.NetworkUtils import org.onap.so.bpmn.common.scripts.SDNCAdapterUtils import org.onap.so.bpmn.common.scripts.VidUtils import org.onap.so.bpmn.core.WorkflowException -import org.onap.so.rest.APIResponse; -import org.onap.so.rest.RESTClient -import org.onap.so.rest.RESTConfig - -import java.util.UUID; +import org.onap.so.utils.TargetEntity +import javax.ws.rs.core.Response import org.camunda.bpm.engine.delegate.BpmnError import org.camunda.bpm.engine.delegate.DelegateExecution -import org.apache.commons.lang3.* -import org.apache.commons.codec.binary.Base64; -import org.springframework.web.util.UriUtils /** * This groovy class supports the <class>DoCreateNetworkInstance.bpmn</class> process. @@ -61,7 +53,7 @@ public class DoCreateNetworkInstanceRollback extends AbstractServiceTaskProcesso SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils() def className = getClass().getSimpleName() - + /** * This method is executed during the preProcessRequest task of the <class>DoCreateNetworkInstanceRollback.bpmn</class> process. * @param execution @@ -73,7 +65,7 @@ public class DoCreateNetworkInstanceRollback extends AbstractServiceTaskProcesso execution.setVariable(Prefix + "rollbackSDNCRequest", null) execution.setVariable(Prefix + "rollbackActivateSDNCRequest", null) execution.setVariable(Prefix + "WorkflowException", null) - + execution.setVariable(Prefix + "rollbackNetworkRequest", "") execution.setVariable(Prefix + "rollbackNetworkResponse", "") execution.setVariable(Prefix + "rollbackNetworkReturnCode", "") @@ -81,7 +73,7 @@ public class DoCreateNetworkInstanceRollback extends AbstractServiceTaskProcesso execution.setVariable(Prefix + "rollbackSDNCRequest", "") execution.setVariable(Prefix + "rollbackSDNCResponse", "") execution.setVariable(Prefix + "rollbackSDNCReturnCode", "") - + execution.setVariable(Prefix + "rollbackActivateSDNCRequest", "") execution.setVariable(Prefix + "rollbackActivateSDNCResponse", "") execution.setVariable(Prefix + "rollbackActivateSDNCReturnCode", "") @@ -103,18 +95,18 @@ public class DoCreateNetworkInstanceRollback extends AbstractServiceTaskProcesso public void preProcessRequest (DelegateExecution execution) { def isDebugEnabled=execution.getVariable("isDebugLogEnabled") execution.setVariable("prefix",Prefix) - + msoLogger.trace("Inside preProcessRequest() of " + className + ".groovy") try { // initialize flow variables InitializeProcessVariables(execution) - + // GET Incoming request/variables String rollbackNetworkRequest = null String rollbackSDNCRequest = null String rollbackActivateSDNCRequest = null - + // Partial Rollback Map<String, String> rollbackData = execution.getVariable("rollbackData") if (rollbackData != null && rollbackData instanceof Map) { @@ -122,7 +114,7 @@ public class DoCreateNetworkInstanceRollback extends AbstractServiceTaskProcesso if(rollbackData.containsKey("rollbackSDNCRequest")) { rollbackSDNCRequest = rollbackData["rollbackSDNCRequest"] } - + if(rollbackData.containsKey("rollbackNetworkRequest")) { rollbackNetworkRequest = rollbackData["rollbackNetworkRequest"] } @@ -130,14 +122,14 @@ public class DoCreateNetworkInstanceRollback extends AbstractServiceTaskProcesso if(rollbackData.containsKey("rollbackActivateSDNCRequest")) { rollbackActivateSDNCRequest = rollbackData["rollbackActivateSDNCRequest"] } - + } - + execution.setVariable(Prefix + "rollbackNetworkRequest", rollbackNetworkRequest) execution.setVariable(Prefix + "rollbackSDNCRequest", rollbackSDNCRequest) execution.setVariable(Prefix + "rollbackActivateSDNCRequest", rollbackActivateSDNCRequest) msoLogger.debug("'rollbackData': " + '\n' + execution.getVariable("rollbackData")) - + String sdncVersion = execution.getVariable("sdncVersion") msoLogger.debug("sdncVersion? : " + sdncVersion) @@ -147,7 +139,7 @@ public class DoCreateNetworkInstanceRollback extends AbstractServiceTaskProcesso def encodedString = utils.getBasicAuth(basicAuthValuePO, UrnPropertiesReader.getVariable("mso.msoKey", execution)) execution.setVariable("BasicAuthHeaderValuePO",encodedString) execution.setVariable("BasicAuthHeaderValueSDNC", encodedString) - + } catch (IOException ex) { String exceptionMessage = "Exception Encountered in DoCreateNetworkInstance, PreProcessRequest() - " String dataErrorMessage = exceptionMessage + " Unable to encode PO/SDNC user/password string - " + ex.getMessage() @@ -168,88 +160,80 @@ public class DoCreateNetworkInstanceRollback extends AbstractServiceTaskProcesso } else { // called by: Macro - Full Rollback, WorkflowException = null execution.setVariable(Prefix + "fullRollback", true) - + } msoLogger.debug("*** fullRollback? : " + execution.getVariable(Prefix + "fullRollback")) - - + + } catch (BpmnError e) { throw e; - + } catch (Exception ex) { // caught exception String exceptionMessage = "Exception Encountered in PreProcessRequest() of " + className + ".groovy ***** : " + ex.getMessage() msoLogger.debug(exceptionMessage) exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) - + } } - + public void callPONetworkAdapter (DelegateExecution execution) { def isDebugEnabled=execution.getVariable("isDebugLogEnabled") execution.setVariable("prefix",Prefix) msoLogger.trace("Inside callPONetworkAdapter() of " + className + "") - + try { String poUrl = UrnPropertiesReader.getVariable("mso.adapters.network.rest.endpoint",execution) String rollbackSDNCRequest = execution.getVariable(Prefix + "rollbackSDNCRequest") String networkId = utils.getNodeText(rollbackSDNCRequest, "network-id") - + String rollbackNetworkRequest = execution.getVariable(Prefix + "rollbackNetworkRequest") String urlRollbackPoNetwork = poUrl+ "/" + networkId + "/rollback" msoLogger.debug("'urlRollbackPoNetwork': " + urlRollbackPoNetwork) execution.setVariable(Prefix + "urlRollbackPoNetwork", urlRollbackPoNetwork) - RESTConfig config = new RESTConfig(urlRollbackPoNetwork) - RESTClient client = new RESTClient(config). - addHeader("Content-Type", "application/xml"). - addAuthorizationHeader(execution.getVariable("BasicAuthHeaderValuePO")); - - APIResponse response = client.httpDelete(rollbackNetworkRequest) - String responseCode = response.getStatusCode() - String responseBody = response.getResponseBodyAsString() - - execution.setVariable(Prefix + "rollbackNetworkReturnCode", responseCode) - execution.setVariable(Prefix + "rollbackNetworkResponse", responseBody) - - msoLogger.debug(" Network Adapter rollback responseCode: " + responseCode) - msoLogger.debug(" Network Adapter rollback responseBody: " + responseBody) - - + URL url = new URL(urlRollbackPoNetwork) + HttpClient httpClient = new HttpClientFactory().newXmlClient(url, TargetEntity.OPENSTACK_ADAPTER) + httpClient.addAdditionalHeader("Authorization", execution.getVariable("BasicAuthHeaderValuePO")) + Response response = httpClient.delete(rollbackNetworkRequest) + + execution.setVariable(Prefix + "rollbackNetworkReturnCode", response.getStatus()) + + msoLogger.debug(" Network Adapter rollback responseCode: " + response.getStatus()) + + } catch (Exception ex) { String exceptionMessage = "Exception Encountered in callPONetworkAdapter() of DoCreateNetworkInstanceRollback flow - " + ex.getMessage() msoLogger.debug(exceptionMessage) exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) } - + } - - + + public void validateRollbackResponses (DelegateExecution execution) { def isDebugEnabled=execution.getVariable("isDebugLogEnabled") execution.setVariable("prefix",Prefix) msoLogger.trace("Inside validateRollbackResponses() of DoCreateNetworkInstanceRollback") - + try { // validate PO network rollback response String rollbackNetworkErrorMessages = "" String rollbackNetworkReturnCode = "200" if (execution.getVariable(Prefix + "rollbackNetworkRequest") != null) { rollbackNetworkReturnCode = execution.getVariable(Prefix + "rollbackNetworkReturnCode") - String rollbackNetworkResponse = execution.getVariable(Prefix + "rollbackNetworkResponse") msoLogger.debug(" NetworkRollback Code - " + rollbackNetworkReturnCode) - msoLogger.debug(" NetworkRollback Response - " + rollbackNetworkResponse) if (rollbackNetworkReturnCode != "200") { rollbackNetworkErrorMessages = " + PO Network rollback failed. " } else { rollbackNetworkErrorMessages = " + PO Network rollback completed." } } - + // validate SDNC rollback response String rollbackSdncErrorMessages = "" String rollbackSDNCReturnCode = "200" @@ -270,13 +254,13 @@ public class DoCreateNetworkInstanceRollback extends AbstractServiceTaskProcesso } } else { rollbackSdncErrorMessages = " + SNDC assign rollback completed." - } + } } else { rollbackSdncErrorMessages = " + SDNC assign rollback failed. " } msoLogger.debug(" SDNC assign rollback Code - " + rollbackSDNCReturnCode) msoLogger.debug(" SDNC assign rollback Response - " + rollbackSDNCResponse) - } + } // validate SDNC activate rollback response String rollbackActivateSdncErrorMessages = "" @@ -303,15 +287,15 @@ public class DoCreateNetworkInstanceRollback extends AbstractServiceTaskProcesso } msoLogger.debug(" SDNC activate rollback Code - " + rollbackActivateSDNCReturnCode) msoLogger.debug(" SDNC activate rollback Response - " + rollbackActivateSDNCResponse) - } + } String statusMessage = "" int errorCode = 7000 msoLogger.debug("*** fullRollback? : " + execution.getVariable(Prefix + "fullRollback")) - if (execution.getVariable(Prefix + "fullRollback") == false) { - // original WorkflowException, - WorkflowException wfe = execution.getVariable(Prefix + "WorkflowException") + if (execution.getVariable(Prefix + "fullRollback") == false) { + // original WorkflowException, + WorkflowException wfe = execution.getVariable(Prefix + "WorkflowException") if (wfe != null) { // rollback due to failure in DoCreate - Partial rollback statusMessage = wfe.getErrorMessage() @@ -325,7 +309,7 @@ public class DoCreateNetworkInstanceRollback extends AbstractServiceTaskProcesso if (rollbackNetworkReturnCode == "200" && rollbackSDNCReturnCode == "200" && rollbackActivateSDNCReturnCode == "200") { execution.setVariable("rolledBack", true) execution.setVariable("wasDeleted", true) - + } else { execution.setVariable("rolledBack", false) execution.setVariable("wasDeleted", true) @@ -336,8 +320,8 @@ public class DoCreateNetworkInstanceRollback extends AbstractServiceTaskProcesso String processKey = getProcessKey(execution); WorkflowException exception = new WorkflowException(processKey, errorCode, statusMessage); execution.setVariable("workflowException", exception); - - } else { + + } else { // rollback due to failures in Main flow (Macro) - Full rollback // WorkflowException = null if (rollbackNetworkReturnCode == "200" && rollbackSDNCReturnCode == "200" && rollbackActivateSDNCReturnCode == "200") { @@ -351,9 +335,9 @@ public class DoCreateNetworkInstanceRollback extends AbstractServiceTaskProcesso exceptionUtil.buildWorkflowException(execution, 7000, exceptionMessage) throw new BpmnError("MSOWorkflowException") } - - } - + + } + } catch (Exception ex) { String errorMessage = "See Previous Camunda flows for cause of Error: Undetermined Exception." @@ -370,18 +354,18 @@ public class DoCreateNetworkInstanceRollback extends AbstractServiceTaskProcesso // ******************************* - + public void processJavaException(DelegateExecution execution){ def isDebugEnabled=execution.getVariable("isDebugLogEnabled") execution.setVariable("prefix",Prefix) - + try{ msoLogger.debug("Caught a Java Exception in " + Prefix) msoLogger.debug("Started processJavaException Method") msoLogger.debug("Variables List: " + execution.getVariables()) execution.setVariable("UnexpectedError", "Caught a Java Lang Exception - " + Prefix) // Adding this line temporarily until this flows error handling gets updated exceptionUtil.buildWorkflowException(execution, 500, "Caught a Java Lang Exception") - + }catch(Exception e){ msoLogger.debug("Caught Exception during processJavaException Method: " + e) execution.setVariable("UnexpectedError", "Exception in processJavaException method - " + Prefix) // Adding this line temporarily until this flows error handling gets updated diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateResources.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateResources.groovy index c4513b0144..6096f16b18 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateResources.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateResources.groovy @@ -20,21 +20,12 @@ package org.onap.so.bpmn.infrastructure.scripts +import org.onap.so.bpmn.common.scripts.CatalogDbUtilsFactory import org.onap.so.bpmn.infrastructure.properties.BPMNProperties - -import java.util.ArrayList -import java.util.Iterator -import java.util.List import org.apache.commons.lang3.StringUtils import org.apache.http.HttpResponse import org.camunda.bpm.engine.delegate.BpmnError import org.camunda.bpm.engine.delegate.DelegateExecution -import org.codehaus.groovy.runtime.ArrayUtil -import org.codehaus.groovy.runtime.ScriptBytecodeAdapter -import org.codehaus.groovy.runtime.callsite.CallSite -import org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation -import org.codehaus.groovy.runtime.typehandling.ShortTypeHandling -import org.json.JSONArray import org.json.JSONObject import org.onap.so.bpmn.common.recipe.BpmnRestClient import org.onap.so.bpmn.common.recipe.ResourceInput @@ -48,7 +39,6 @@ import org.onap.so.bpmn.core.domain.ServiceDecomposition import org.onap.so.bpmn.core.domain.VnfResource import org.onap.so.bpmn.core.json.JsonUtils import org.onap.so.bpmn.common.resource.ResourceRequestBuilder -import org.onap.so.logger.MessageEnum import org.onap.so.logger.MsoLogger @@ -75,7 +65,7 @@ public class DoCreateResources extends AbstractServiceTaskProcessor{ ExceptionUtil exceptionUtil = new ExceptionUtil() JsonUtils jsonUtil = new JsonUtils() - CatalogDbUtils cutils = new CatalogDbUtils() + CatalogDbUtils catalogDbUtils = new CatalogDbUtilsFactory().create() public void preProcessRequest(DelegateExecution execution) { msoLogger.trace("preProcessRequest ") @@ -260,7 +250,7 @@ public class DoCreateResources extends AbstractServiceTaskProcessor{ // requestAction is action, not opertiontype //String requestAction = resourceInput.getOperationType() String requestAction = "createInstance" - JSONObject resourceRecipe = cutils.getResourceRecipe(execution, resourceModelUUID, requestAction) + JSONObject resourceRecipe = catalogDbUtils.getResourceRecipe(execution, resourceModelUUID, requestAction) if (resourceRecipe != null) { String recipeURL = BPMNProperties.getProperty("bpelURL", "http://so-bpmn-infra.onap:8081") + resourceRecipe.getString("orchestrationUri") diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateServiceInstance.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateServiceInstance.groovy index 6d41923bdf..c04bbd4806 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateServiceInstance.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateServiceInstance.groovy @@ -22,13 +22,12 @@ package org.onap.so.bpmn.infrastructure.scripts; import static org.apache.commons.lang3.StringUtils.*; -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.OwningEntity -import org.onap.so.bpmn.common.scripts.AaiUtil import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor import org.onap.so.bpmn.common.scripts.CatalogDbUtils +import org.onap.so.bpmn.common.scripts.CatalogDbUtilsFactory import org.onap.so.bpmn.common.scripts.ExceptionUtil import org.onap.so.bpmn.common.scripts.MsoUtils import org.onap.so.bpmn.common.scripts.SDNCAdapterUtils @@ -42,15 +41,10 @@ import org.onap.so.bpmn.core.json.JsonUtils import org.onap.so.bpmn.infrastructure.aai.groovyflows.AAICreateResources 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.AAIUri 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 - -import groovy.json.* /** * This groovy class supports the <class>DoCreateServiceInstance.bpmn</class> process. @@ -84,7 +78,7 @@ public class DoCreateServiceInstance extends AbstractServiceTaskProcessor { String Prefix="DCRESI_" ExceptionUtil exceptionUtil = new ExceptionUtil() JsonUtils jsonUtil = new JsonUtils() - CatalogDbUtils cutils = new CatalogDbUtils() + CatalogDbUtils catalogDbUtils = new CatalogDbUtilsFactory().create() public void preProcessRequest (DelegateExecution execution) { def isDebugEnabled = execution.getVariable("isDebugLogEnabled") @@ -278,7 +272,7 @@ public class DoCreateServiceInstance extends AbstractServiceTaskProcessor { if (siParamsXml == null) siParamsXml = "" execution.setVariable("siParamsXml", siParamsXml) - + } catch (BpmnError e) { throw e; } catch (Exception ex){ @@ -291,70 +285,19 @@ public class DoCreateServiceInstance extends AbstractServiceTaskProcessor { public void getAAICustomerById (DelegateExecution execution) { // https://{aaiEP}/aai/v8/business/customers/customer/{globalCustomerId} - def isDebugEnabled = execution.getVariable("isDebugLogEnabled") - String msg = "" try { String globalCustomerId = execution.getVariable("globalSubscriberId") //VID to AAI name map msoLogger.debug(" ***** getAAICustomerById ***** globalCustomerId:" + globalCustomerId) - AaiUtil aaiUriUtil = new AaiUtil(this) - AAIUri uri = AAIUriFactory.createResourceUri(AAIObjectType.CUSTOMER, globalCustomerId) - String getAAICustomerUrl = aaiUriUtil.createAaiUri(uri) - - if (isBlank(getAAICustomerUrl)) - { - msg = "AAI URL is invalid. Endpoint:" + getAAICustomerUrl - msoLogger.debug(msg) - exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) - } - - msoLogger.debug("getAAICustomerById Url:" + getAAICustomerUrl) - APIResponse response = aaiUriUtil.executeAAIGetCall(execution, getAAICustomerUrl) - String returnCode = response.getStatusCode() - String aaiResponseAsString = response.getResponseBodyAsString() - - msg = "getAAICustomerById ResponseCode:" + returnCode + " ResponseString:" + aaiResponseAsString - msoLogger.debug(msg) - - if (returnCode=='200') { - // Customer found by ID. FLow to proceed. - msoLogger.debug(msg) - - //TODO Deferred - //we might verify that service-subscription with matching name exists - //and throw error if not. If not checked, we will get exception in subsequent step on Create call - //in 1610 we assume both customer & service subscription were pre-created - - } else { - if (returnCode=='404') { - msg = "GlobalCustomerId:" + globalCustomerId + " not found (404) in AAI" - msoLogger.debug(msg) - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg) - - } else { - if (aaiResponseAsString.contains("RESTFault")) { - msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, aaiResponseAsString, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, ""); - WorkflowException workflowException = exceptionUtil.MapAAIExceptionToWorkflowException(aaiResponseAsString, execution) - execution.setVariable("WorkflowException", workflowException) - throw new BpmnError("MSOWorkflowException") - - } else { - // aai all errors - msg = "Error in getAAICustomerById ResponseCode:" + returnCode - msoLogger.debug(msg) - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg) - } - } + if(!getAAIClient().exists(uri)){ + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "GlobalCustomerId:" + globalCustomerId + " not found (404) in AAI") } - } catch (BpmnError e) { throw e; } catch (Exception ex) { - msg = "Exception in getAAICustomerById. " + ex.getMessage() - msoLogger.debug(msg) - exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, "Exception in getAAICustomerById. " + ex.getMessage()) } msoLogger.trace("Exit getAAICustomerById") @@ -374,14 +317,14 @@ public class DoCreateServiceInstance extends AbstractServiceTaskProcessor { { oStatus = "Created" } - + //QUERY CATALOG DB AND GET WORKLOAD / ENVIRONMENT CONTEXT String environmentContext = "" String workloadContext ="" String modelInvariantUuid = execution.getVariable("modelInvariantUuid") try{ - String json = cutils.getServiceResourcesByServiceModelInvariantUuidString(execution,modelInvariantUuid ) + String json = catalogDbUtils.getServiceResourcesByServiceModelInvariantUuidString(execution,modelInvariantUuid ) msoLogger.debug("JSON IS: "+json) @@ -396,7 +339,7 @@ public class DoCreateServiceInstance extends AbstractServiceTaskProcessor { msoLogger.debug(msg) exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) } - + org.onap.aai.domain.yang.ServiceInstance si = new org.onap.aai.domain.yang.ServiceInstance() si.setServiceInstanceName(execution.getVariable("serviceInstanceName")) si.setServiceType(serviceType) @@ -405,7 +348,7 @@ public class DoCreateServiceInstance extends AbstractServiceTaskProcessor { si.setModelInvariantId(modelInvariantUuid) si.setModelVersionId(execution.getVariable("modelUuid")) si.setEnvironmentContext(environmentContext) - si.setWorkloadContext(workloadContext) + si.setWorkloadContext(workloadContext) AAIResourcesClient client = new AAIResourcesClient() AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, execution.getVariable("globalSubscriberId"), execution.getVariable("subscriptionServiceType"), serviceInstanceId) diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateServiceInstanceRollback.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateServiceInstanceRollback.groovy index dd56b8f2cc..e80941e212 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateServiceInstanceRollback.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateServiceInstanceRollback.groovy @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -30,9 +30,6 @@ import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor import org.onap.so.bpmn.common.scripts.SDNCAdapterUtils import org.onap.so.bpmn.core.RollbackData import org.onap.so.bpmn.core.WorkflowException -import org.onap.so.rest.APIResponse; -import org.onap.so.rest.RESTClient -import org.onap.so.rest.RESTConfig import org.onap.so.logger.MsoLogger import org.onap.so.logger.MessageEnum @@ -57,7 +54,7 @@ import org.springframework.web.util.UriUtils; * rollbackAAI * rollbackSDNC * sdncRollbackRequest - * + * * * Outputs: * @param - rollbackError @@ -66,7 +63,7 @@ import org.springframework.web.util.UriUtils; */ public class DoCreateServiceInstanceRollback extends AbstractServiceTaskProcessor{ private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, DoCreateServiceInstanceRollback.class); - + String Prefix="DCRESIRB_" @@ -141,7 +138,7 @@ public class DoCreateServiceInstanceRollback extends AbstractServiceTaskProcesso } public void validateSDNCResponse(DelegateExecution execution, String response, String method) { - + msoLogger.trace("validateSDNCResponse") String msg = "" try { @@ -149,7 +146,7 @@ public class DoCreateServiceInstanceRollback extends AbstractServiceTaskProcesso boolean successIndicator = execution.getVariable("SDNCA_SuccessIndicator") msoLogger.debug("SDNCResponse: " + response) msoLogger.debug("workflowException: " + workflowException) - + SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils(this) sdncAdapterUtils.validateSDNCResponse(execution, response, workflowException, successIndicator) @@ -174,7 +171,7 @@ public class DoCreateServiceInstanceRollback extends AbstractServiceTaskProcesso } public void postProcessRequest(DelegateExecution execution) { - + msoLogger.trace("postProcessRequest") String msg = "" try { @@ -208,7 +205,7 @@ public class DoCreateServiceInstanceRollback extends AbstractServiceTaskProcesso } public void processRollbackException(DelegateExecution execution){ - + msoLogger.trace("processRollbackException") try{ msoLogger.debug("Caught an Exception in DoCreateServiceInstanceRollback") @@ -226,7 +223,7 @@ public class DoCreateServiceInstanceRollback extends AbstractServiceTaskProcesso } public void processRollbackJavaException(DelegateExecution execution){ - + msoLogger.trace("processRollbackJavaException") try{ execution.setVariable("rollbackData", null) diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVFCNetworkServiceInstance.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVFCNetworkServiceInstance.groovy index 0502f7949a..33d0e25d7d 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVFCNetworkServiceInstance.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVFCNetworkServiceInstance.groovy @@ -20,6 +20,7 @@ package org.onap.so.bpmn.infrastructure.scripts +import org.onap.so.client.HttpClientFactory 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; @@ -28,18 +29,14 @@ import org.camunda.bpm.engine.delegate.DelegateExecution import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor import org.onap.so.bpmn.common.scripts.ExceptionUtil import org.onap.so.bpmn.core.json.JsonUtils -//import org.onap.so.client.HttpClient +import org.onap.so.client.HttpClient import org.onap.so.logger.MessageEnum import org.onap.so.logger.MsoLogger -import org.onap.so.rest.APIResponse -import org.onap.so.rest.RESTClient -import org.onap.so.rest.RESTConfig import org.onap.so.bpmn.core.UrnPropertiesReader -//import org.onap.so.utils.TargetEntity +import org.onap.so.utils.TargetEntity -import groovy.json.* -//import javax.ws.rs.core.Response +import javax.ws.rs.core.Response /** * This groovy class supports the <class>DoCreateVFCNetworkServiceInstance.bpmn</class> process. @@ -141,7 +138,7 @@ public class DoCreateVFCNetworkServiceInstance extends AbstractServiceTaskProces "nsOperationKey":${nsOperationKey}, "nsParameters":${nsParameters} }""" - APIResponse apiResponse = postRequest(execution, vfcAdapterUrl + "/ns", reqBody) + Response apiResponse = postRequest(execution, vfcAdapterUrl + "/ns", reqBody) String returnCode = apiResponse.getStatus() String aaiResponseAsString = apiResponse.readEntity(String.class) String nsInstanceId = ""; @@ -170,7 +167,7 @@ public class DoCreateVFCNetworkServiceInstance extends AbstractServiceTaskProces }""" String nsInstanceId = execution.getVariable("nsInstanceId") String url = vfcAdapterUrl + "/ns/" +nsInstanceId + "/instantiate" - APIResponse apiResponse = postRequest(execution, url, reqBody) + Response apiResponse = postRequest(execution, url, reqBody) String returnCode = apiResponse.getStatus() String aaiResponseAsString = apiResponse.readEntity(String.class) String jobId = ""; @@ -190,7 +187,7 @@ public class DoCreateVFCNetworkServiceInstance extends AbstractServiceTaskProces String jobId = execution.getVariable("jobId") String nsOperationKey = execution.getVariable("nsOperationKey"); String url = vfcAdapterUrl + "/jobs/" + jobId - APIResponse apiResponse = postRequest(execution, url, nsOperationKey) + Response apiResponse = postRequest(execution, url, nsOperationKey) String returnCode = apiResponse.getStatus() String aaiResponseAsString = apiResponse.readEntity(String.class) String operationStatus = "error" @@ -243,38 +240,29 @@ public class DoCreateVFCNetworkServiceInstance extends AbstractServiceTaskProces * url: the url of the request * requestBody: the body of the request */ - private APIResponse postRequest(DelegateExecution execution, String urlString, String requestBody){ + private Response postRequest(DelegateExecution execution, String urlString, String requestBody){ msoLogger.trace("Started Execute VFC adapter Post Process") msoLogger.debug("url:"+urlString +"\nrequestBody:"+ requestBody) - APIResponse apiResponse = null - try{ - // Get the Basic Auth credentials for the VFCAdapter, username is 'bpel', auth is '07a7159d3bf51a0e53be7a8f89699be7' - def basicAuthHeaderValue = "" - RESTConfig config = new RESTConfig(urlString) - RESTClient client = null; - int statusCode = 0; - - // user 'bepl' authHeader is the same with mso.db.auth - String basicAuthValuedb = UrnPropertiesReader.getVariable("mso.db.auth", execution) - msoLogger.debug("basicAuthValuedb: " + basicAuthValuedb) - - client = new RESTClient(config) - client.addHeader("Accept", "application/json") - client.addAuthorizationHeader(basicAuthValuedb) - client.addHeader("Content-Type", "application/json") - - apiResponse = client.httpPost(requestBody) - statusCode = apiResponse.getStatusCode() - - msoLogger.debug("response code:"+ apiResponse.getStatusCode() +"\nresponse body:"+ apiResponse.getResponseBodyAsString()) - - }catch(Exception e){ - msoLogger.error("Exception occured while executing VF-C Post Call. Exception is: \n" + e.getMessage()); - throw new BpmnError("MSOWorkflowException") - } - - msoLogger.trace("Completed Execute VF-C adapter Post Process ") - + Response apiResponse = null + try{ + + URL url = new URL(urlString); + + // Get the Basic Auth credentials for the VFCAdapter, username is 'bpel', auth is '07a7159d3bf51a0e53be7a8f89699be7' + // user 'bepl' authHeader is the same with mso.db.auth + String basicAuthValuedb = UrnPropertiesReader.getVariable("mso.db.auth", execution) + HttpClient httpClient = new HttpClientFactory().newJsonClient(url, TargetEntity.VNF_ADAPTER) + httpClient.addAdditionalHeader("Accept", "application/json") + httpClient.addAdditionalHeader("Authorization", basicAuthValuedb) + + apiResponse = httpClient.post(requestBody) + + msoLogger.debug("response code:"+ apiResponse.getStatus() +"\nresponse body:"+ apiResponse.readEntity(String.class)) + msoLogger.trace("Completed Execute VF-C adapter Post Process") + }catch(Exception e){ + msoLogger.error("Exception occured while executing VFC Adapter Post Call" + e.getMessage ()); + throw new BpmnError("MSOWorkflowException") + } return apiResponse } } diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVfModule.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVfModule.groovy index 74926ce5b7..53e3525036 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVfModule.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVfModule.groovy @@ -20,8 +20,11 @@ package org.onap.so.bpmn.infrastructure.scripts -import org.onap.so.db.catalog.beans.HomingInstance +import org.onap.so.bpmn.common.scripts.CatalogDbUtilsFactory +import org.onap.so.client.HttpClientFactory +import javax.ws.rs.core.MediaType +import javax.ws.rs.core.Response import javax.xml.parsers.DocumentBuilder import javax.xml.parsers.DocumentBuilderFactory @@ -30,6 +33,7 @@ import org.camunda.bpm.engine.delegate.DelegateExecution import org.json.JSONArray import org.json.JSONObject import org.onap.aai.domain.yang.GenericVnf +import org.onap.aai.domain.yang.NetworkPolicy import org.onap.so.bpmn.common.scripts.AaiUtil import org.onap.so.bpmn.common.scripts.CatalogDbUtils import org.onap.so.bpmn.common.scripts.ExceptionUtil @@ -41,11 +45,10 @@ import org.onap.so.bpmn.common.util.OofInfraUtils import org.onap.so.bpmn.core.RollbackData import org.onap.so.bpmn.core.UrnPropertiesReader import org.onap.so.bpmn.core.WorkflowException - import org.onap.so.bpmn.core.domain.VnfResource import org.onap.so.bpmn.core.json.DecomposeJsonUtil import org.onap.so.bpmn.core.json.JsonUtils -import org.onap.so.client.graphinventory.entities.uri.Depth +import org.onap.so.client.HttpClient import org.onap.so.client.aai.AAIObjectPlurals import org.onap.so.client.aai.AAIObjectType; import org.onap.so.client.aai.AAIResourcesClient @@ -53,13 +56,13 @@ import org.onap.so.client.aai.entities.AAIResultWrapper import org.onap.so.client.aai.entities.uri.AAIResourceUri import org.onap.so.client.aai.entities.uri.AAIUri import org.onap.so.client.aai.entities.uri.AAIUriFactory; +import org.onap.so.client.graphinventory.entities.uri.Depth import org.onap.so.constants.Defaults +import org.onap.so.db.catalog.beans.HomingInstance import org.onap.so.logger.MessageEnum import org.onap.so.logger.MsoLogger -import org.onap.so.rest.APIResponse -import org.onap.so.rest.RESTClient -import org.onap.so.rest.RESTConfig -import org.springframework.web.util.UriUtils + +import org.onap.so.utils.TargetEntity import org.w3c.dom.Document import org.w3c.dom.Element import org.w3c.dom.NamedNodeMap @@ -79,8 +82,9 @@ public class DoCreateVfModule extends VfModuleBase { JsonUtils jsonUtil = new JsonUtils() SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils(this) OofInfraUtils oofInfraUtils = new OofInfraUtils() - CatalogDbUtils catalog = new CatalogDbUtils() + CatalogDbUtils catalogDbUtils = new CatalogDbUtilsFactory().create() DecomposeJsonUtil decomposeJsonUtils = new DecomposeJsonUtil() + private final HttpClientFactory httpClientFactory = new HttpClientFactory() /** * Validates the request message and sets up the workflow. @@ -287,7 +291,7 @@ public class DoCreateVfModule extends VfModuleBase { String serviceType ="" try{ - String json = catalog.getServiceResourcesByServiceModelInvariantUuidString(execution,modelInvariantUuid ) + String json = catalogDbUtils.getServiceResourcesByServiceModelInvariantUuidString(execution,modelInvariantUuid ) serviceType = jsonUtil.getJsonValue(json, "serviceResources.serviceType") }catch(BpmnError e){ throw e @@ -687,28 +691,26 @@ public class DoCreateVfModule extends VfModuleBase { String endPoint = aaiUriUtil.createAaiUri(uri) try { - RESTConfig config = new RESTConfig(endPoint); - def responseData = '' - def aaiRequestId = UUID.randomUUID().toString() - RESTClient client = new RESTClient(config). - addHeader('X-TransactionId', aaiRequestId). - addHeader('X-FromAppId', 'MSO'). - addHeader('Content-Type', 'application/xml'). - addHeader('Accept','application/xml'); + HttpClient client = httpClientFactory.newXmlClient(new URL(endPoint), TargetEntity.AAI) + client.addAdditionalHeader('X-TransactionId', UUID.randomUUID().toString()) + client.addAdditionalHeader('X-FromAppId', 'MSO') + client.addAdditionalHeader('Content-Type', MediaType.APPLICATION_XML) + client.addAdditionalHeader('Accept', MediaType.APPLICATION_XML) + msoLogger.debug('sending GET to AAI endpoint \'' + endPoint + '\'') - APIResponse response = client.httpGet() + Response response = client.get() - responseData = response.getResponseBodyAsString() + String responseData = response.readEntity(String.class) if (responseData != null) { msoLogger.debug("Received generic VNF data: " + responseData) } - execution.setVariable('DCVFM_queryAAIVfModuleResponseCode', response.getStatusCode()) + execution.setVariable('DCVFM_queryAAIVfModuleResponseCode', response.getStatus()) execution.setVariable('DCVFM_queryAAIVfModuleResponse', responseData) - msoLogger.debug('Response code:' + response.getStatusCode()) + msoLogger.debug('Response code:' + response.getStatus()) msoLogger.debug('Response:' + System.lineSeparator() + responseData) - if (response.getStatusCode() == 200) { + if (response.getStatus() == 200) { // Parse the VNF record from A&AI to find base module info msoLogger.debug('Parsing the VNF data to find base module info') if (responseData != null) { @@ -771,31 +773,31 @@ public class DoCreateVfModule extends VfModuleBase { AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectPlurals.VF_MODULE, vnfId).queryParam("vf-module-name",vfModuleName) String endPoint = aaiUriUtil.createAaiUri(uri) + HttpClient client = httpClientFactory.newXmlClient(new URL(endPoint), TargetEntity.AAI) + client.addAdditionalHeader('X-TransactionId', UUID.randomUUID().toString()) + client.addAdditionalHeader('X-FromAppId', 'MSO') + client.addAdditionalHeader('Content-Type', MediaType.APPLICATION_XML) + client.addAdditionalHeader('Accept', MediaType.APPLICATION_XML) + try { - RESTConfig config = new RESTConfig(endPoint); def responseData = '' - def aaiRequestId = UUID.randomUUID().toString() - RESTClient client = new RESTClient(config). - addHeader('X-TransactionId', aaiRequestId). - addHeader('X-FromAppId', 'MSO'). - addHeader('Content-Type', 'application/xml'). - addHeader('Accept','application/xml'); + msoLogger.debug('sending GET to AAI endpoint \'' + endPoint + '\'') - APIResponse response = client.httpGet() + Response response = client.get() msoLogger.debug("createVfModule - invoking httpGet() to AAI") - responseData = response.getResponseBodyAsString() + responseData = response.readEntity(String.class) if (responseData != null) { msoLogger.debug("Received generic VNF data: " + responseData) } - execution.setVariable('DCVFM_queryAAIVfModuleForStatusResponseCode', response.getStatusCode()) + execution.setVariable('DCVFM_queryAAIVfModuleForStatusResponseCode', response.getStatus()) execution.setVariable('DCVFM_queryAAIVfModuleForStatusResponse', responseData) - msoLogger.debug('Response code:' + response.getStatusCode()) + msoLogger.debug('Response code:' + response.getStatus()) msoLogger.debug('Response:' + System.lineSeparator() + responseData) // Retrieve VF Module info and its orchestration status; if not found, do nothing - if (response.getStatusCode() == 200) { + if (response.getStatus() == 200) { // Parse the VNF record from A&AI to find base module info msoLogger.debug('Parsing the VNF data to find orchestration status') if (responseData != null) { @@ -1050,7 +1052,7 @@ public class DoCreateVfModule extends VfModuleBase { svcInstId = serviceInstanceId } - def createVnfARequest = """ + String createVnfARequest = """ <createVfModuleRequest> <cloudSiteId>${MsoUtils.xmlEscape(cloudSiteId)}</cloudSiteId> <tenantId>${MsoUtils.xmlEscape(tenantId)}</tenantId> @@ -1909,50 +1911,17 @@ public class DoCreateVfModule extends VfModuleBase { def networkPolicyId = UUID.randomUUID().toString() msoLogger.debug("Adding network-policy with network-policy-id " + networkPolicyId) - String aaiNamespace = aaiUriUtil.getNamespace() - msoLogger.debug('AAI namespace is: ' + aaiNamespace) - String payload = """<network-policy xmlns="${aaiNamespace}"> - <network-policy-id>${MsoUtils.xmlEscape(networkPolicyId)}</network-policy-id> - <network-policy-fqdn>${MsoUtils.xmlEscape(fqdn)}</network-policy-fqdn> - <heat-stack-id>${MsoUtils.xmlEscape(execution.getVariable("DCVFM_heatStackId"))}</heat-stack-id> - </network-policy>""" as String - - execution.setVariable("DCVFM_addNetworkPolicyAAIRequestBody", payload) - - AAIResourceUri addUri = AAIUriFactory.createResourceUri(AAIObjectType.NETWORK_POLICY, networkPolicyId) - String addNetworkPolicyAAIRequest = aaiUriUtil.createAaiUri(addUri) - - msoLogger.debug("AAI request endpoint: " + addNetworkPolicyAAIRequest) - - def aaiRequestIdPut = UUID.randomUUID().toString() - RESTConfig configPut = new RESTConfig(addNetworkPolicyAAIRequest); - RESTClient clientPut = new RESTClient(configPut).addHeader("X-TransactionId", aaiRequestIdPut) - .addHeader("X-FromAppId", "MSO") - .addHeader("Content-Type", "application/xml") - .addHeader("Accept","application/xml"); - msoLogger.debug("invoking PUT call to AAI with payload:"+System.lineSeparator()+payload) - APIResponse responsePut = clientPut.httpPut(payload) - int returnCodePut = responsePut.getStatusCode() - execution.setVariable("DCVFM_aaiAddNetworkPolicyReturnCode", returnCodePut) - msoLogger.debug(" ***** AAI add network policy Response Code, NetworkPolicy #" + counting + " : " + returnCodePut) - - String aaiResponseAsStringPut = responsePut.getResponseBodyAsString() - if (isOneOf(returnCodePut, 200, 201)) { - msoLogger.debug("The return code from adding network policy is: " + returnCodePut) - // This network policy was created in AAI successfully - execution.setVariable("DCVFM_addNetworkPolicyAAIResponse", aaiResponseAsStringPut) - msoLogger.debug(" AddAAINetworkPolicy Success REST Response, , NetworkPolicy #" + counting + " : " + "\n" + aaiResponseAsStringPut) - rollbackData.put("VFMODULE", "rollbackCreateNetworkPoliciesAAI", "true") - rollbackData.put("VFMODULE", "contrailNetworkPolicyFqdn" + i, fqdn) - execution.setVariable("rollbackData", rollbackData) - - } else { - // aai all errors - String putErrorMessage = "Unable to add network-policy to AAI createNetworkPoliciesInAAI - " + returnCodePut - msoLogger.debug(putErrorMessage) - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, putErrorMessage) - } - + NetworkPolicy policy = new NetworkPolicy() + policy.setNetworkPolicyId(networkPolicyId) + policy.setNetworkPolicyFqdn(fqdn) + policy.setHeatStackId(execution.getVariable("DCVFM_heatStackId")) + + AAIResourceUri netUri = AAIUriFactory.createResourceUri(AAIObjectType.NETWORK_POLICY, networkPolicyId) + resourceClient.create(netUri, policy) + + rollbackData.put("VFMODULE", "rollbackCreateNetworkPoliciesAAI", "true") + rollbackData.put("VFMODULE", "contrailNetworkPolicyFqdn" + i, fqdn) + execution.setVariable("rollbackData", rollbackData) } } // end loop @@ -1965,7 +1934,6 @@ public class DoCreateVfModule extends VfModuleBase { } catch (BpmnError e) { throw e; - } catch (Exception ex) { String exceptionMessage = "Bpmn error encountered in DoCreateVfModule flow. createNetworkPoliciesInAAI() - " + ex.getMessage() msoLogger.debug(exceptionMessage) @@ -2085,7 +2053,7 @@ public class DoCreateVfModule extends VfModuleBase { msoLogger.debug("vnfModelCustomizationUuid: " + vnfModelCustomizationUuid) - JSONArray vnfs = catalog.getAllVnfsByVnfModelCustomizationUuid(execution, vnfModelCustomizationUuid, "v2") + JSONArray vnfs = catalogDbUtils.getAllVnfsByVnfModelCustomizationUuid(execution, vnfModelCustomizationUuid, "v2") msoLogger.debug("Incoming Query Catalog DB for Vnf Response is: " + vnfModelCustomizationUuid) // Only one match here diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVfModuleRollback.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVfModuleRollback.groovy index a553127c5c..55a84575f4 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVfModuleRollback.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVfModuleRollback.groovy @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -21,6 +21,8 @@ package org.onap.so.bpmn.infrastructure.scripts import org.camunda.bpm.engine.delegate.BpmnError import org.camunda.bpm.engine.delegate.DelegateExecution +import org.onap.aai.domain.yang.NetworkPolicies +import org.onap.aai.domain.yang.NetworkPolicy import org.onap.so.bpmn.common.scripts.AaiUtil import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor import org.onap.so.bpmn.common.scripts.ExceptionUtil @@ -34,14 +36,15 @@ 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 + import org.springframework.web.util.UriUtils +import javax.ws.rs.NotFoundException public class DoCreateVfModuleRollback extends AbstractServiceTaskProcessor{ private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, DoCreateVfModuleRollback.class); - + def Prefix="DCVFMR_" ExceptionUtil exceptionUtil = new ExceptionUtil() @@ -52,7 +55,7 @@ public class DoCreateVfModuleRollback extends AbstractServiceTaskProcessor{ // parse the incoming DELETE_VF_MODULE request for the Generic Vnf and Vf Module Ids // and formulate the outgoing request for PrepareUpdateAAIVfModuleRequest public void preProcessRequest(DelegateExecution execution) { - + initProcessVariables(execution) @@ -60,10 +63,10 @@ public class DoCreateVfModuleRollback extends AbstractServiceTaskProcessor{ execution.setVariable("rolledBack", null) execution.setVariable("rollbackError", null) - + def rollbackData = execution.getVariable("rollbackData") msoLogger.debug("RollbackData:" + rollbackData) - + if (rollbackData != null) { String vnfId = rollbackData.get("VFMODULE", "vnfid") execution.setVariable("DCVFMR_vnfId", vnfId) @@ -103,9 +106,9 @@ public class DoCreateVfModuleRollback extends AbstractServiceTaskProcessor{ createdNetworkPolicyFqdnList.add(fqdn) msoLogger.debug("got fqdn # " + i + ": " + fqdn) i = i + 1 - + } - + execution.setVariable("DCVFMR_createdNetworkPolicyFqdnList", createdNetworkPolicyFqdnList) String oamManagementV4Address = rollbackData.get("VFMODULE", "oamManagementV4Address") execution.setVariable("DCVFMR_oamManagementV4Address", oamManagementV4Address) @@ -121,7 +124,7 @@ public class DoCreateVfModuleRollback extends AbstractServiceTaskProcessor{ execution.setVariable("DCVFMR_rollbackCreateAAIVfModule", rollbackData.get("VFMODULE", "rollbackCreateAAIVfModule")) execution.setVariable("DCVFMR_rollbackCreateNetworkPoliciesAAI", rollbackData.get("VFMODULE", "rollbackCreateNetworkPoliciesAAI")) execution.setVariable("DCVFMR_rollbackUpdateVnfAAI", rollbackData.get("VFMODULE", "rollbackUpdateVnfAAI")) - + // formulate the request for PrepareUpdateAAIVfModule String request = """<PrepareUpdateAAIVfModuleRequest> <vnf-id>${MsoUtils.xmlEscape(vnfId)}</vnf-id> @@ -133,11 +136,11 @@ public class DoCreateVfModuleRollback extends AbstractServiceTaskProcessor{ } else { execution.setVariable("skipRollback", true) } - + if (execution.getVariable("disableRollback").equals("true" )) { execution.setVariable("skipRollback", true) } - + } catch (BpmnError e) { throw e; } catch (Exception ex){ @@ -150,14 +153,14 @@ public class DoCreateVfModuleRollback extends AbstractServiceTaskProcessor{ // build a SDNC vnf-topology-operation request for the specified action // (note: the action passed is expected to be 'changedelete' or 'delete') public void prepSDNCAdapterRequest(DelegateExecution execution) { - + String srvInstId = execution.getVariable("DCVFMR_serviceInstanceId") String uuid = execution.getVariable('testReqId') // for junits if(uuid==null){ uuid = execution.getVariable("DCVFMR_requestId") + "-" + System.currentTimeMillis() } - + def callbackUrl = UrnPropertiesReader.getVariable("mso.workflow.sdncadapter.callback",execution) String source = execution.getVariable("DCVFMR_source") @@ -240,21 +243,21 @@ public class DoCreateVfModuleRollback extends AbstractServiceTaskProcessor{ } public void preProcessSDNCDeactivateRequest(DelegateExecution execution){ - + execution.setVariable("prefix", Prefix) msoLogger.trace("STARTED preProcessSDNCDeactivateRequest") - + def serviceInstanceId = execution.getVariable("DCVFMR_serviceInstanceId") - + try{ //Build SDNC Request - + String deactivateSDNCRequest = buildSDNCRequest(execution, serviceInstanceId, "deactivate") - + deactivateSDNCRequest = utils.formatXml(deactivateSDNCRequest) execution.setVariable("DCVFMR_deactivateSDNCRequest", deactivateSDNCRequest) msoLogger.debug("Outgoing DeactivateSDNCRequest is: \n" + deactivateSDNCRequest) - + }catch(Exception e){ msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception Occured Processing preProcessSDNCDeactivateRequest.", "BPMN", MsoLogger.getServiceName(),MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occurred during preProcessSDNCDeactivateRequest Method:\n" + e.getMessage()) @@ -272,12 +275,12 @@ public class DoCreateVfModuleRollback extends AbstractServiceTaskProcessor{ msoLogger.trace("STARTED preProcessSDNCUnassignRequest Process") try{ String serviceInstanceId = execution.getVariable("DCVFMR_serviceInstanceId") - + String unassignSDNCRequest = buildSDNCRequest(execution, serviceInstanceId, "unassign") - + execution.setVariable("DCVFMR_unassignSDNCRequest", unassignSDNCRequest) msoLogger.debug("Outgoing UnassignSDNCRequest is: \n" + unassignSDNCRequest) - + }catch(Exception e){ msoLogger.debug("Exception Occured Processing preProcessSDNCUnassignRequest. Exception is:\n" + e) exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occured during preProcessSDNCUnassignRequest Method:\n" + e.getMessage()) @@ -286,7 +289,7 @@ public class DoCreateVfModuleRollback extends AbstractServiceTaskProcessor{ } public String buildSDNCRequest(DelegateExecution execution, String svcInstId, String action){ - + String uuid = execution.getVariable('testReqId') // for junits if(uuid==null){ uuid = execution.getVariable("DCVFMR_requestId") + "-" + System.currentTimeMillis() @@ -298,9 +301,9 @@ public class DoCreateVfModuleRollback extends AbstractServiceTaskProcessor{ def vfModuleId = execution.getVariable("DCVFMR_vfModuleId") def source = execution.getVariable("DCVFMR_source") def vnfId = execution.getVariable("DCVFMR_vnfId") - + def sdncVersion = execution.getVariable("sdncVersion") - + String sdncRequest = """<sdncadapterworkflow:SDNCAdapterWorkflowRequest xmlns:ns5="http://org.onap/so/request/types/v1" xmlns:sdncadapterworkflow="http://org.onap/so/workflow/schema/v1" @@ -324,29 +327,29 @@ public class DoCreateVfModuleRollback extends AbstractServiceTaskProcessor{ </request-information> <service-information> <service-id/> - <subscription-service-type/> + <subscription-service-type/> <service-instance-id>${MsoUtils.xmlEscape(serviceInstanceId)}</service-instance-id> <global-customer-id/> </service-information> <vnf-information> <vnf-id>${MsoUtils.xmlEscape(vnfId)}</vnf-id> - <vnf-type/> + <vnf-type/> </vnf-information> <vf-module-information> <vf-module-id>${MsoUtils.xmlEscape(vfModuleId)}</vf-module-id> </vf-module-information> - <vf-module-request-input/> + <vf-module-request-input/> </sdncadapterworkflow:SDNCRequestData> </sdncadapterworkflow:SDNCAdapterWorkflowRequest>""" - + msoLogger.debug("sdncRequest: " + sdncRequest) return sdncRequest } - + // parse the incoming DELETE_VF_MODULE request // and formulate the outgoing VnfAdapterDeleteV1 request public void prepVNFAdapterRequest(DelegateExecution execution) { - + String requestId = UUID.randomUUID().toString() String origRequestId = execution.getVariable("DCVFMR_requestId") String srvInstId = execution.getVariable("DCVFMR_serviceInstanceId") @@ -387,7 +390,7 @@ public class DoCreateVfModuleRollback extends AbstractServiceTaskProcessor{ // parse the incoming DELETE_VF_MODULE request // and formulate the outgoing UpdateAAIVfModuleRequest request public void prepUpdateAAIVfModule(DelegateExecution execution) { - + String vnfId = execution.getVariable("DCVFMR_vnfId") String vfModuleId = execution.getVariable("DCVFMR_vfModuleId") // formulate the request for UpdateAAIVfModule @@ -400,11 +403,11 @@ public class DoCreateVfModuleRollback extends AbstractServiceTaskProcessor{ msoLogger.debug("UpdateAAIVfModuleRequest :" + request) execution.setVariable("UpdateAAIVfModuleRequest", request) } - + // parse the incoming DELETE_VF_MODULE request // and formulate the outgoing UpdateAAIVfModuleRequest request public void prepUpdateAAIVfModuleToAssigned(DelegateExecution execution) { - + String vnfId = execution.getVariable("DCVFMR_vnfId") String vfModuleId = execution.getVariable("DCVFMR_vfModuleId") // formulate the request for UpdateAAIVfModule @@ -421,7 +424,7 @@ public class DoCreateVfModuleRollback extends AbstractServiceTaskProcessor{ // parse the incoming DELETE_VF_MODULE request // and formulate the outgoing DeleteAAIVfModuleRequest request public void prepDeleteAAIVfModule(DelegateExecution execution) { - + String vnfId = execution.getVariable("DCVFMR_vnfId") String vfModuleId = execution.getVariable("DCVFMR_vfModuleId") // formulate the request for UpdateAAIVfModule @@ -436,7 +439,7 @@ public class DoCreateVfModuleRollback extends AbstractServiceTaskProcessor{ // generates a WorkflowException if // - public void handleDoDeleteVfModuleFailure(DelegateExecution execution) { - + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "AAI error occurred deleting the Generic Vnf"+ execution.getVariable("DoDVfMod_deleteGenericVnfResponse"), "BPMN", MsoLogger.getServiceName(),MsoLogger.ErrorCode.UnknownError); String processKey = getProcessKey(execution); exceptionUtil.buildWorkflowException(execution, 5000, "Failure in DoDeleteVfModule") @@ -444,7 +447,7 @@ public class DoCreateVfModuleRollback extends AbstractServiceTaskProcessor{ } public void sdncValidateResponse(DelegateExecution execution, String response){ - + execution.setVariable("prefix",Prefix) WorkflowException workflowException = execution.getVariable("WorkflowException") @@ -490,81 +493,48 @@ public class DoCreateVfModuleRollback extends AbstractServiceTaskProcessor{ int counting = i+1 String fqdn = fqdnList[i] - // Query AAI for this network policy FQDN - AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectPlurals.NETWORK_POLICY) - uri.queryParam("network-policy-fqdn", fqdn) - String queryNetworkPolicyByFqdnAAIRequest = aaiUriUtil.createAaiUri(uri) - - msoLogger.debug("AAI request endpoint: " + queryNetworkPolicyByFqdnAAIRequest) - - def aaiRequestId = UUID.randomUUID().toString() - APIResponse response = aaiUriUtil.executeAAIGetCall(execution, queryNetworkPolicyByFqdnAAIRequest) - int returnCode = response.getStatusCode() - execution.setVariable(Prefix + "aaiQueryNetworkPolicyByFqdnReturnCode", returnCode) - msoLogger.debug("AAI query network policy Response Code, NetworkPolicy #" + counting + " : " + returnCode) - - String aaiResponseAsString = response.getResponseBodyAsString() - - if (isOneOf(returnCode, 200, 201)) { - msoLogger.debug("The return code is: " + returnCode) - // This network policy FQDN exists in AAI - need to delete it now - execution.setVariable(Prefix + "queryNetworkPolicyByFqdnAAIResponse", aaiResponseAsString) - msoLogger.debug("QueryAAINetworkPolicyByFQDN Success REST Response, , NetworkPolicy #" + counting + " : " + "\n" + aaiResponseAsString) - // Retrieve the network policy id for this FQDN - def networkPolicyId = utils.getNodeText(aaiResponseAsString, "network-policy-id") - msoLogger.debug("Deleting network-policy with network-policy-id " + networkPolicyId) - - // Retrieve the resource version for this network policy - def resourceVersion = utils.getNodeText(aaiResponseAsString, "resource-version") - msoLogger.debug("Deleting network-policy with resource-version " + resourceVersion) - - AAIResourceUri delUri = AAIUriFactory.createResourceUri(AAIObjectType.NETWORK_POLICY, networkPolicyId) - delUri.resourceVersion(resourceVersion) - String delNetworkPolicyAAIRequest = aaiUriUtil.createAaiUri(delUri) - - msoLogger.debug("AAI request endpoint: " + delNetworkPolicyAAIRequest) - - def aaiRequestIdDel = UUID.randomUUID().toString() - msoLogger.debug("Sending DELETE call to AAI with Endpoint /n" + delNetworkPolicyAAIRequest) - - APIResponse responseDel = aaiUriUtil.executeAAIDeleteCall(execution, delNetworkPolicyAAIRequest) - - int returnCodeDel = responseDel.getStatusCode() - execution.setVariable(Prefix + "aaiDeleteNetworkPolicyReturnCode", returnCodeDel) - msoLogger.debug("AAI delete network policy Response Code, NetworkPolicy #" + counting + " : " + returnCodeDel) - - if (isOneOf(returnCodeDel, 200, 201, 204)) { - msoLogger.debug("The return code from deleting network policy is: " + returnCodeDel) - // This network policy was deleted from AAI successfully - msoLogger.debug(" DelAAINetworkPolicy Success REST Response, , NetworkPolicy #" + counting + " : ") - - } else { - // aai all errors - String delErrorMessage = "Unable to delete network-policy to AAI deleteNetworkPoliciesFromAAI - " + returnCodeDel - msoLogger.debug(delErrorMessage) - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, delErrorMessage) - } - } else if (returnCode == 404) { - // This network policy FQDN is not in AAI. No need to delete. - msoLogger.debug("The return code is: " + returnCode) - msoLogger.debug("This network policy FQDN is not in AAI: " + fqdn) - } else { - if (aaiResponseAsString.contains("RESTFault")) { - WorkflowException exceptionObject = exceptionUtil.MapAAIExceptionToWorkflowException(aaiResponseAsString, execution) - execution.setVariable("WorkflowException", exceptionObject) - throw new BpmnError("MSOWorkflowException") - - } else { - // aai all errors - String dataErrorMessage = "Unexpected Response from deleteNetworkPoliciesFromAAI - " + returnCode - msoLogger.debug(dataErrorMessage) - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) - - } - } - - - + try { + // Query AAI for this network policy FQDN + AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectPlurals.NETWORK_POLICY) + uri.queryParam("network-policy-fqdn", fqdn) + Optional<NetworkPolicies> networkPolicies = getAAIClient().get(NetworkPolicies.class, uri) + + if (networkPolicies.isPresent() && !networkPolicies.get().getNetworkPolicy().isEmpty()) { + execution.setVariable(Prefix + "aaiQueryNetworkPolicyByFqdnReturnCode", 200) + NetworkPolicy networkPolicy = networkPolicies.get().getNetworkPolicy().get(0) + + try{ + AAIResourceUri delUri = AAIUriFactory.createResourceUri(AAIObjectType.NETWORK_POLICY, networkPolicy.getNetworkPolicyId()) + getAAIClient().delete(delUri) + execution.setVariable(Prefix + "aaiDeleteNetworkPolicyReturnCode", 200) + msoLogger.debug("AAI delete network policy Response Code, NetworkPolicy #" + counting + " : " + 200) + msoLogger.debug("The return code from deleting network policy is: " + 200) + // This network policy was deleted from AAI successfully + msoLogger.debug(" DelAAINetworkPolicy Success REST Response, , NetworkPolicy #" + counting + " : ") + }catch(NotFoundException ne){ + // This network policy FQDN is not in AAI. No need to delete. + execution.setVariable(Prefix + "aaiDeleteNetworkPolicyReturnCode", 404) + msoLogger.debug("The return code is: " + 404) + msoLogger.debug("This network policy FQDN is not in AAI: " + fqdn) + }catch(Exception e){ + // aai all errors + String delErrorMessage = "Unable to delete network-policy to AAI deleteNetworkPoliciesFromAAI - " + e.getMessage() + msoLogger.debug(delErrorMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, delErrorMessage) + } + } else { + // This network policy FQDN is not in AAI. No need to delete. + msoLogger.debug("This network policy FQDN is not in AAI: " + fqdn) + } + }catch (BpmnError e){ + throw e + } + catch (Exception e) { + // aai all errors + String dataErrorMessage = "Unexpected Response from deleteNetworkPoliciesFromAAI - " + e.getMessage() + msoLogger.debug(dataErrorMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) + } } // end loop @@ -633,35 +603,35 @@ public class DoCreateVfModuleRollback extends AbstractServiceTaskProcessor{ exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in preProcessUpdateAAIGenericVnf((): ' + e.getMessage()) } } - + public void setSuccessfulRollbackStatus (DelegateExecution execution){ - + execution.setVariable("prefix", Prefix) msoLogger.trace("STARTED setSuccessfulRollbackStatus") - + try{ // Set rolledBack to true, rollbackError to null execution.setVariable("rolledBack", true) execution.setVariable("rollbackError", null) - + }catch(Exception e){ msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception Occured Processing setSuccessfulRollbackStatus.", "BPMN", MsoLogger.getServiceName(),MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occurred during setSuccessfulRollbackStatus Method:\n" + e.getMessage()) } msoLogger.trace("COMPLETED setSuccessfulRollbackStatus") } - + public void setFailedRollbackStatus (DelegateExecution execution){ - + execution.setVariable("prefix", Prefix) msoLogger.trace("STARTED setFailedRollbackStatus") - + try{ // Set rolledBack to false, rollbackError to actual value, rollbackData to null execution.setVariable("rolledBack", false) execution.setVariable("rollbackError", 'Caught exception in DoCreateVfModuleRollback') execution.setVariable("rollbackData", null) - + }catch(Exception e){ msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception Occured Processing setFailedRollbackStatus.", "BPMN", MsoLogger.getServiceName(),MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occurred during setFailedRollbackStatus Method:\n" + e.getMessage()) diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVfModuleVolumeRollback.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVfModuleVolumeRollback.groovy index 8968c751c5..f61d2b98e3 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVfModuleVolumeRollback.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVfModuleVolumeRollback.groovy @@ -18,36 +18,24 @@ * ============LICENSE_END========================================================= */ -package org.onap.so.bpmn.infrastructure.scripts; +package org.onap.so.bpmn.infrastructure.scripts -import groovy.xml.XmlUtil -import groovy.json.* - - -import java.util.UUID; - -import org.camunda.bpm.engine.delegate.BpmnError import org.camunda.bpm.engine.delegate.DelegateExecution -import org.apache.commons.lang3.* -import org.apache.commons.codec.binary.Base64; -import org.onap.so.bpmn.common.scripts.AaiUtil +import org.onap.aai.domain.yang.VolumeGroups import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor import org.onap.so.bpmn.common.scripts.ExceptionUtil import org.onap.so.bpmn.common.scripts.VidUtils import org.onap.so.bpmn.core.RollbackData -import org.onap.so.bpmn.core.WorkflowException import org.onap.so.bpmn.core.json.JsonUtils +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.aai.AAIObjectType -import org.onap.so.client.aai.AAIObjectPlurals import org.onap.so.constants.Defaults -import org.onap.so.rest.APIResponse -import org.springframework.web.util.UriUtils import org.onap.so.logger.MsoLogger -import org.onap.so.logger.MessageEnum +import javax.ws.rs.NotFoundException public class DoCreateVfModuleVolumeRollback extends AbstractServiceTaskProcessor { private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, DoCreateVfModuleVolumeRollback.class); @@ -129,95 +117,46 @@ public class DoCreateVfModuleVolumeRollback extends AbstractServiceTaskProcessor /** * Query AAI volume group by name * @param execution - * @param isDebugEnabled + * @param cloudRegion + * @return */ - public void callRESTQueryAAIVolGrpName(DelegateExecution execution, isDebugEnabled) { + private String callRESTQueryAAIVolGrpName(DelegateExecution execution, String cloudRegion) { def volumeGroupName = execution.getVariable('DCVFMODVOLRBK_volumeGroupName') - def cloudRegion = execution.getVariable('DCVFMODVOLRBK_lcpCloudRegionId') - // This is for stub testing def testVolumeGroupName = execution.getVariable('test-volume-group-name') if (testVolumeGroupName != null && testVolumeGroupName.length() > 0) { volumeGroupName = testVolumeGroupName } - AaiUtil aaiUtil = new AaiUtil(this) - AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectPlurals.VOLUME_GROUP, Defaults.CLOUD_OWNER.toString(), cloudRegion).queryParam("volume-group-name", volumeGroupName) - def queryAAIVolumeNameRequest = aaiUtil.createAaiUri(uri) - - msoLogger.debug('Query AAI volume group by name: ' + queryAAIVolumeNameRequest) - - APIResponse response = aaiUtil.executeAAIGetCall(execution, queryAAIVolumeNameRequest) - - String returnCode = response.getStatusCode() - String aaiResponseAsString = response.getResponseBodyAsString() - - msoLogger.debug("AAI query volume group by name return code: " + returnCode) - msoLogger.debug("AAI query volume group by name response: " + aaiResponseAsString) - - ExceptionUtil exceptionUtil = new ExceptionUtil() - - execution.setVariable(prefix+"queryAAIVolGrpNameResponse", aaiResponseAsString) - execution.setVariable(prefix+'AaiReturnCode', returnCode) - - if (returnCode=='200') { - // @TODO: verify error code - // @TODO: create class of literals representing error codes - execution.setVariable(prefix+'queryAAIVolGrpNameResponse', aaiResponseAsString) - msoLogger.debug("Volume Group Name $volumeGroupName exists in AAI.") - } else { - if (returnCode=='404') { - msoLogger.debug("Volume Group Name $volumeGroupName does not exist in AAI.") - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Volume group $volumeGroupName not found in AAI. Response code: 404") + try { + Optional<VolumeGroups> volumeGroups = getAAIClient().get(VolumeGroups.class, uri) + if (volumeGroups.isPresent()) { + return volumeGroups.get().getVolumeGroup().get(0).getVolumeGroupId() } else { - WorkflowException aWorkflowException = exceptionUtil.MapAAIExceptionToWorkflowException(aaiResponseAsString, execution) - throw new BpmnError("MSOWorkflowException") + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Volume group $volumeGroupName not found in AAI. Response code: 404") } + } catch (Exception e) { + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, e.getMessage()) } + return null } public void callRESTDeleteAAIVolumeGroup(DelegateExecution execution, isDebugEnabled) { - callRESTQueryAAIVolGrpName(execution, isDebugEnabled) - - def queryAaiVolumeGroupResponse = execution.getVariable(prefix+'queryAAIVolGrpNameResponse') - - def volumeGroupId = utils.getNodeText(queryAaiVolumeGroupResponse, "volume-group-id") - def resourceVersion = utils.getNodeText(queryAaiVolumeGroupResponse, "resource-version") - - def cloudRegion = execution.getVariable("DCVFMODVOLRBK_lcpCloudRegionId") - - AaiUtil aaiUtil = new AaiUtil(this) - - AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.VOLUME_GROUP, Defaults.CLOUD_OWNER.toString(), cloudRegion, volumeGroupId).resourceVersion(resourceVersion) - def deleteAAIVolumeGrpIdRequest = aaiUtil.createAaiUri(uri) - - msoLogger.debug('Delete AAI volume group : ' + deleteAAIVolumeGrpIdRequest) + String cloudRegion = execution.getVariable("DCVFMODVOLRBK_lcpCloudRegionId") + String volumeGroupId = callRESTQueryAAIVolGrpName(execution, cloudRegion) - APIResponse response = aaiUtil.executeAAIDeleteCall(execution, deleteAAIVolumeGrpIdRequest) - - String returnCode = response.getStatusCode() - String aaiResponseAsString = response.getResponseBodyAsString() - - msoLogger.debug("AAI delete volume group return code: " + returnCode) - msoLogger.debug("AAI delete volume group response: " + aaiResponseAsString) - - ExceptionUtil exceptionUtil = new ExceptionUtil() - - def volumeGroupNameFound = prefix+'volumeGroupNameFound' - if (returnCode=='200' || returnCode=='204' ) { - msoLogger.debug("Volume group $volumeGroupId deleted.") - } else { - if (returnCode=='404') { - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Volume group $volumeGroupId not found for delete in AAI Response code: 404") - } else { - WorkflowException aWorkflowException = exceptionUtil.MapAAIExceptionToWorkflowException(aaiResponseAsString, execution) - throw new BpmnError("MSOWorkflowException") - } + AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.VOLUME_GROUP, Defaults.CLOUD_OWNER.toString(), cloudRegion, volumeGroupId) + try { + getAAIClient().delete(uri) + }catch(NotFoundException ignored){ + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Volume group $volumeGroupId not found for delete in AAI Response code: 404") + }catch(Exception e){ + exceptionUtil.buildAndThrowWorkflowException(execution, 2500,e.getMessage()) } } diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVfModuleVolumeV2.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVfModuleVolumeV2.groovy index cf5c214d3f..87f598db5d 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVfModuleVolumeV2.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVfModuleVolumeV2.groovy @@ -20,37 +20,36 @@ package org.onap.so.bpmn.infrastructure.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.GenericVnf +import org.onap.aai.domain.yang.VolumeGroup +import org.onap.aai.domain.yang.VolumeGroups import org.onap.so.bpmn.common.scripts.AaiUtil import org.onap.so.bpmn.common.scripts.ExceptionUtil import org.onap.so.bpmn.common.scripts.MsoUtils -import org.onap.so.bpmn.common.scripts.NetworkUtils -import org.onap.so.bpmn.common.scripts.VfModuleBase; +import org.onap.so.bpmn.common.scripts.VfModuleBase import org.onap.so.bpmn.core.RollbackData import org.onap.so.bpmn.core.UrnPropertiesReader import org.onap.so.bpmn.core.WorkflowException -import org.onap.so.bpmn.core.json.JsonUtils; -import org.onap.so.logger.MsoLogger -import org.onap.so.rest.APIResponse -import org.springframework.web.util.UriUtils -import org.onap.so.client.aai.AAIResourcesClient -import org.onap.so.client.aai.AAIObjectType +import org.onap.so.bpmn.core.json.JsonUtils import org.onap.so.client.aai.AAIObjectPlurals -import org.onap.so.client.aai.entities.AAIResultWrapper -import org.onap.so.client.aai.entities.Relationships +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.constants.Defaults -import org.json.JSONObject +import org.onap.so.db.catalog.beans.OrchestrationStatus +import org.onap.so.logger.MsoLogger + import javax.ws.rs.NotFoundException class DoCreateVfModuleVolumeV2 extends VfModuleBase { - private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, DoCreateVfModuleVolumeV2.class); + private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, DoCreateVfModuleVolumeV2.class) String prefix='DCVFMODVOLV2_' JsonUtils jsonUtil = new JsonUtils() + private ExceptionUtil exceptionUtil = new ExceptionUtil() /** @@ -156,7 +155,7 @@ class DoCreateVfModuleVolumeV2 extends VfModuleBase { } }catch(BpmnError e) { - throw e; + throw e }catch (Exception ex){ String msg = "Exception in getServiceInstance. " + ex.getMessage() msoLogger.debug(msg) @@ -216,43 +215,23 @@ class DoCreateVfModuleVolumeV2 extends VfModuleBase { def volumeGroupName = execution.getVariable('volumeGroupName') def cloudRegion = execution.getVariable('lcpCloudRegionId') - // This is for stub testing - def testVolumeGroupName = execution.getVariable('test-volume-group-name') - if (testVolumeGroupName != null && testVolumeGroupName.length() > 0) { - volumeGroupName = testVolumeGroupName - } - - AaiUtil aaiUtil = new AaiUtil(this) - - AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectPlurals.VOLUME_GROUP, Defaults.CLOUD_OWNER.toString(), cloudRegion).queryParam("volume-group-name", volumeGroupName) - def queryAAIVolumeNameRequest = aaiUtil.createAaiUri(uri) - - msoLogger.debug('Query AAI volume group by name: ' + queryAAIVolumeNameRequest) - - APIResponse response = aaiUtil.executeAAIGetCall(execution, queryAAIVolumeNameRequest) - - String returnCode = response.getStatusCode() - String aaiResponseAsString = response.getResponseBodyAsString() - - msoLogger.debug("AAI query volume group by name return code: " + returnCode) - msoLogger.debug("AAI query volume group by name response: " + aaiResponseAsString) - - ExceptionUtil exceptionUtil = new ExceptionUtil() - - execution.setVariable(prefix+"queryAAIVolGrpNameResponse", aaiResponseAsString) - execution.setVariable(prefix+'AaiReturnCode', returnCode) - - if (returnCode=='200') { - execution.setVariable(prefix+'queryAAIVolGrpNameResponse', aaiResponseAsString) - msoLogger.debug("Volume Group Name $volumeGroupName exists in AAI.") - } else { - if (returnCode=='404') { - msoLogger.debug("Volume Group Name $volumeGroupName does not exist in AAI.") - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Volume group $volumeGroupName not found in AAI. Response code: 404") - } else { - WorkflowException aWorkflowException = exceptionUtil.MapAAIExceptionToWorkflowException(aaiResponseAsString, execution) - throw new BpmnError("MSOWorkflowException") + try { + AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectPlurals.VOLUME_GROUP, Defaults.CLOUD_OWNER.toString(), cloudRegion).queryParam("volume-group-name", volumeGroupName) + Optional<VolumeGroups> volumeGroups = getAAIClient().get(VolumeGroups.class,uri) + if(volumeGroups.isPresent()){ + VolumeGroup volumeGroup = volumeGroups.get().getVolumeGroup().get(0); + execution.setVariable(prefix+'AaiReturnCode', 200) + execution.setVariable("queriedVolumeGroupId",volumeGroup.getVolumeGroupId()) + msoLogger.debug("Volume Group Name $volumeGroupName exists in AAI.") + }else{ + execution.setVariable(prefix+'AaiReturnCode', 404) + exceptionUtil.buildAndThrowWorkflowException(execution,25000, "Volume Group Name $volumeGroupName does not exist in AAI.") } + }catch(BpmnError error){ + throw error + }catch(Exception e){ + execution.setVariable(prefix+'AaiReturnCode', 500) + exceptionUtil.buildAndThrowWorkflowException(execution,25000, "Exception in get volume group by name: " + e.getMessage()) } } @@ -297,7 +276,6 @@ class DoCreateVfModuleVolumeV2 extends VfModuleBase { def tenantId = execution.getVariable("tenantId") def cloudRegion = execution.getVariable('lcpCloudRegionId') def cloudOwner = execution.getVariable('cloudOwner') - msoLogger.debug("volumeGroupId: " + volumeGroupId) def testGroupId = execution.getVariable('test-volume-group-id') if (testGroupId != null && testGroupId.trim() != '') { @@ -306,62 +284,44 @@ class DoCreateVfModuleVolumeV2 extends VfModuleBase { execution.setVariable("test-volume-group-name", "MSOTESTVOL101a-vSAMP12_base_vol_module-0") } - msoLogger.debug("volumeGroupId to be used: " + volumeGroupId) - - AaiUtil aaiUtil = new AaiUtil(this) - - AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.VOLUME_GROUP, Defaults.CLOUD_OWNER.toString(), cloudRegion, volumeGroupId) - def createAAIVolumeGrpNameUrlRequest = aaiUtil.createAaiUri(uri) + VolumeGroup volumeGroup = new VolumeGroup() + volumeGroup.setVolumeGroupId(volumeGroupId) + volumeGroup.setVolumeGroupName(volumeName) + volumeGroup.setVnfType(vnfType) + volumeGroup.setOrchestrationStatus(OrchestrationStatus.PENDING.toString()) + volumeGroup.setModelCustomizationId(modelCustomizationId) - String namespace = aaiUtil.getNamespaceFromUri(createAAIVolumeGrpNameUrlRequest) - msoLogger.debug("AAI namespace is: " + namespace) - - msoLogger.debug("Request URL for PUT: " + createAAIVolumeGrpNameUrlRequest) - - NetworkUtils networkUtils = new NetworkUtils() - String payload = networkUtils.createCloudRegionVolumeRequest(volumeGroupId, volumeName, vnfType, vnfId, tenantId, cloudOwner, cloudRegion, namespace, modelCustomizationId) - String payloadXml = utils.formatXml(payload) - msoLogger.debug("Request payload for PUT: " + payloadXml) - - APIResponse response = aaiUtil.executeAAIPutCall(execution, createAAIVolumeGrpNameUrlRequest, payloadXml) - - String returnCode = response.getStatusCode() - String aaiResponseAsString = response.getResponseBodyAsString() - - msoLogger.debug("AAI create volume group return code: " + returnCode) - msoLogger.debug("AAI create volume group response: " + aaiResponseAsString) - - execution.setVariable(prefix+"createAAIVolumeGrpNameReturnCode", returnCode) - execution.setVariable(prefix+"createAAIVolumeGrpNameResponse", aaiResponseAsString) - - ExceptionUtil exceptionUtil = new ExceptionUtil() + msoLogger.debug("volumeGroupId to be used: " + volumeGroupId) - if (returnCode =='201') { + AAIResourceUri volumeGroupUri = AAIUriFactory.createResourceUri(AAIObjectType.VOLUME_GROUP, cloudOwner, cloudRegion, volumeGroupId) + AAIResourceUri tenantUri = AAIUriFactory.createResourceUri(AAIObjectType.TENANT, cloudOwner, cloudRegion, tenantId) + AAIResourceUri vnfUri = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId) + try { + getAAIClient().create(volumeGroupUri, volumeGroup) + getAAIClient().connect(volumeGroupUri, vnfUri) + getAAIClient().connect(volumeGroupUri, tenantUri) + execution.setVariable("queriedVolumeGroupId", volumeGroupId) RollbackData rollbackData = execution.getVariable("rollbackData") rollbackData.put("DCVFMODULEVOL", "isAAIRollbackNeeded", "true") - } else { - execution.setVariable(prefix+"isErrorMessageException", true) - if (returnCode=='404') { - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Unable to create volume group in AAI. Response code: 404") - } else { - WorkflowException aWorkflowException = exceptionUtil.MapAAIExceptionToWorkflowException(aaiResponseAsString, execution) - msoLogger.debug(" AAI Adapter Query Failed. WorkflowException - " + "\n" + aWorkflowException) - throw new BpmnError("MSOWorkflowException") - } + } catch (NotFoundException ignored) { + execution.setVariable(prefix + "isErrorMessageException", true) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Unable to create volume group in AAI. Response code: 404") + } catch (Exception ex) { + execution.setVariable(prefix + "isErrorMessageException", true) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, ex.getMessage()) } } - /** * Prepare VNF adapter create request XML * @param execution */ public void prepareVnfAdapterCreateRequest(DelegateExecution execution, isDebugEnabled) { - def aaiGenericVnfResponse = execution.getVariable(prefix+'AAIQueryGenericVfnResponse') - def vnfId = utils.getNodeText(aaiGenericVnfResponse, 'vnf-id') - def vnfName = utils.getNodeText(aaiGenericVnfResponse, 'vnf-name') - def vnfType = utils.getNodeText(aaiGenericVnfResponse, "vnf-type") + GenericVnf aaiGenericVnfResponse = execution.getVariable(prefix+'AAIQueryGenericVfnResponse') + def vnfId = aaiGenericVnfResponse.getVnfId() + def vnfName = aaiGenericVnfResponse.getVnfName() + def vnfType = aaiGenericVnfResponse.getVnfType() def requestId = execution.getVariable('msoRequestId') def serviceId = execution.getVariable('serviceInstanceId') @@ -392,7 +352,7 @@ class DoCreateVfModuleVolumeV2 extends VfModuleBase { Map<String, String> paramsMap = execution.getVariable("vfModuleInputParams") for (Map.Entry<String, String> entry : paramsMap.entrySet()) { String paramsXml - String paramName = entry.getKey(); + String paramName = entry.getKey() String paramValue = entry.getValue() paramsXml = """ <entry> @@ -485,7 +445,7 @@ class DoCreateVfModuleVolumeV2 extends VfModuleBase { public String buildRollbackVolumeGroupRequestXml(volumeGroupId, cloudSiteId, tenantId, requestId, serviceId, messageId, notificationUrl) { - def request = """ + String request = """ <rollbackVolumeGroupRequest> <volumeGroupRollback> <volumeGroupId>${MsoUtils.xmlEscape(volumeGroupId)}</volumeGroupId> @@ -539,54 +499,30 @@ class DoCreateVfModuleVolumeV2 extends VfModuleBase { * @param isDebugEnabled */ public void callRESTUpdateCreatedVolGrpName(DelegateExecution execution, isDebugEnabled) { - - String requeryAAIVolGrpNameResponse = execution.getVariable(prefix+"queryAAIVolGrpNameResponse") - String volumeGroupId = utils.getNodeText(requeryAAIVolGrpNameResponse, "volume-group-id") + String volumeGroupId = execution.getVariable("queriedVolumeGroupId") String modelCustomizationId = execution.getVariable("modelCustomizationId") String cloudRegion = execution.getVariable("lcpCloudRegionId") - - AaiUtil aaiUtil = new AaiUtil(this) - - AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.VOLUME_GROUP, Defaults.CLOUD_OWNER.toString(), cloudRegion, volumeGroupId) - def updateAAIVolumeGroupUrlRequest = aaiUtil.createAaiUri(uri) - - String namespace = aaiUtil.getNamespaceFromUri(updateAAIVolumeGroupUrlRequest) - - msoLogger.debug("updateAAIVolumeGroupUrlRequest - " + updateAAIVolumeGroupUrlRequest) - + String cloudOwner = execution.getVariable('cloudOwner') String createVnfAResponse = execution.getVariable(prefix+"createVnfAResponse") def heatStackID = utils.getNodeText(createVnfAResponse, "volumeGroupStackId") + AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.VOLUME_GROUP, cloudOwner, cloudRegion, volumeGroupId) execution.setVariable(prefix+"heatStackId", heatStackID) - NetworkUtils networkUtils = new NetworkUtils() - String payload = networkUtils.updateCloudRegionVolumeRequest(requeryAAIVolGrpNameResponse, heatStackID, namespace, modelCustomizationId) - String payloadXml = utils.formatXml(payload) - - msoLogger.debug("Payload to Update Created VolumeGroupName - " + "\n" + payloadXml) - - APIResponse response = aaiUtil.executeAAIPutCall(execution, updateAAIVolumeGroupUrlRequest, payloadXml) - - String returnCode = response.getStatusCode() - String aaiResponseAsString = response.getResponseBodyAsString() - - msoLogger.debug("AAI create volume group return code: " + returnCode) - msoLogger.debug("AAI create volume group response: " + aaiResponseAsString) - - ExceptionUtil exceptionUtil = new ExceptionUtil() - - if (returnCode =='200') { - execution.setVariable(prefix+"updateCreatedAAIVolumeGrpNameResponse", aaiResponseAsString) + VolumeGroup volumeGroup = new VolumeGroup() + volumeGroup.setHeatStackId(heatStackID) + volumeGroup.setModelCustomizationId(modelCustomizationId) + try { + getAAIClient().update(uri, volumeGroup) execution.setVariable(prefix+"isPONR", true) - } else { + }catch(NotFoundException ignored){ execution.setVariable(prefix+"isErrorMessageException", true) - if (returnCode=='404') { - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Unable to update volume group in AAI. Response code: 404") - } else { - WorkflowException aWorkflowException = exceptionUtil.MapAAIExceptionToWorkflowException(aaiResponseAsString, execution) - msoLogger.debug(" AAI Adapter Query Failed. WorkflowException - " + "\n" + aWorkflowException) - throw new BpmnError("MSOWorkflowException") - } + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Unable to update volume group in AAI. Response code: 404") + }catch(BpmnError error){ + throw error + }catch(Exception e){ + execution.setVariable(prefix+"isErrorMessageException", true) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "AAI Adapter Query Failed. "+ e.getMessage()) } } @@ -599,35 +535,16 @@ class DoCreateVfModuleVolumeV2 extends VfModuleBase { public void callRESTQueryAAIGenericVnf(DelegateExecution execution, isDebugEnabled) { def vnfId = execution.getVariable('vnfId') - - AaiUtil aaiUtil = new AaiUtil(this) AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId) - String queryAAIRequest = aaiUtil.createAaiUri(uri) - - msoLogger.debug("AAI query generic vnf endpoint: " + queryAAIRequest) - - APIResponse response = aaiUtil.executeAAIGetCall(execution, queryAAIRequest) - - String returnCode = response.getStatusCode() - String aaiResponseAsString = response.getResponseBodyAsString() - - msoLogger.debug("AAI query generic vnf return code: " + returnCode) - msoLogger.debug("AAI query generic vnf response: " + aaiResponseAsString) - - ExceptionUtil exceptionUtil = new ExceptionUtil() - - if (returnCode=='200') { - msoLogger.debug('Generic vnf ' + vnfId + ' found in AAI.') - execution.setVariable(prefix+'AAIQueryGenericVfnResponse', aaiResponseAsString) - } else { - if (returnCode=='404') { - def message = 'Generic vnf ' + vnfId + ' was not found in AAI. Return code: 404.' - msoLogger.debug(message) - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, message) + try { + Optional<GenericVnf> genericVnf = getAAIClient().get(GenericVnf.class, uri) + if (genericVnf.isPresent()) { + execution.setVariable(prefix + 'AAIQueryGenericVfnResponse', genericVnf.get()) } else { - WorkflowException aWorkflowException = exceptionUtil.MapAAIExceptionToWorkflowException(aaiResponseAsString, execution) - throw new BpmnError("MSOWorkflowException") + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, 'Generic vnf ' + vnfId + ' was not found in AAI. Return code: 404.') } + }catch(Exception e){ + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Exception in get generic VNF: " + e.getMessage()) } } diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVnfAndModules.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVnfAndModules.groovy index 31f2977210..88e7b34dcd 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVnfAndModules.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVnfAndModules.groovy @@ -20,14 +20,11 @@ package org.onap.so.bpmn.infrastructure.scripts -import java.util.UUID; - -import java.util.List - import org.json.JSONObject; import org.json.JSONArray; import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor import org.onap.so.bpmn.common.scripts.CatalogDbUtils +import org.onap.so.bpmn.common.scripts.CatalogDbUtilsFactory import org.onap.so.bpmn.common.scripts.ExceptionUtil import org.onap.so.bpmn.common.scripts.VidUtils import org.onap.so.bpmn.core.RollbackData @@ -59,7 +56,7 @@ class DoCreateVnfAndModules extends AbstractServiceTaskProcessor { ExceptionUtil exceptionUtil = new ExceptionUtil() JsonUtils jsonUtil = new JsonUtils() VidUtils vidUtils = new VidUtils(this) - CatalogDbUtils cutils = new CatalogDbUtils() + CatalogDbUtils catalogDbUtils = new CatalogDbUtilsFactory().create() /** * This method gets and validates the incoming @@ -199,8 +196,8 @@ class DoCreateVnfAndModules extends AbstractServiceTaskProcessor { } msoLogger.debug("querying Catalog DB by vnfModelCustomizationUuid: " + vnfModelCustomizationUuid) - JSONArray vnfs = cutils.getAllVnfsByVnfModelCustomizationUuid(execution, - vnfModelCustomizationUuid) + JSONArray vnfs = catalogDbUtils.getAllVnfsByVnfModelCustomizationUuid(execution, + vnfModelCustomizationUuid, "v1") msoLogger.debug("obtained VNF list") // Only one match here JSONObject vnfObject = vnfs[0] diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteE2EServiceInstance.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteE2EServiceInstance.groovy index 5f50afa613..48f255bf91 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteE2EServiceInstance.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteE2EServiceInstance.groovy @@ -19,39 +19,35 @@ */ package org.onap.so.bpmn.infrastructure.scripts -import org.onap.so.logger.MsoLogger - -import static org.apache.commons.lang3.StringUtils.*; - -import javax.ws.rs.core.Response -import javax.xml.parsers.DocumentBuilder -import javax.xml.parsers.DocumentBuilderFactory - -import org.apache.commons.lang3.* +import groovy.json.JsonOutput +import groovy.json.JsonSlurper +import org.apache.commons.lang3.StringUtils import org.camunda.bpm.engine.delegate.BpmnError import org.camunda.bpm.engine.delegate.DelegateExecution import org.json.JSONArray import org.json.JSONObject - import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor import org.onap.so.bpmn.common.scripts.ExceptionUtil import org.onap.so.bpmn.common.scripts.MsoUtils +import org.onap.so.bpmn.core.UrnPropertiesReader import org.onap.so.bpmn.core.WorkflowException import org.onap.so.bpmn.core.domain.Resource import org.onap.so.bpmn.core.domain.ServiceDecomposition -import org.onap.so.bpmn.core.UrnPropertiesReader - -import org.onap.so.utils.TargetEntity import org.onap.so.bpmn.core.json.JsonUtils import org.onap.so.client.HttpClient +import org.onap.so.client.HttpClientFactory +import org.onap.so.logger.MsoLogger +import org.onap.so.utils.TargetEntity import org.springframework.web.util.UriUtils 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 groovy.json.* +import javax.ws.rs.core.Response +import javax.xml.parsers.DocumentBuilder +import javax.xml.parsers.DocumentBuilderFactory + +import static org.apache.commons.lang3.StringUtils.isBlank /** * This groovy class supports the <class>DoDeleteE2EServiceInstance.bpmn</class> process. @@ -347,7 +343,7 @@ public class DoDeleteE2EServiceInstance extends AbstractServiceTaskProcessor { String serviceAaiPath = "${aai_endpoint}${urlLink}" URL url = new URL(serviceAaiPath) - HttpClient client = new HttpClient(url, "application/xml", TargetEntity.AAI) + HttpClient client = new HttpClientFactory().newXmlClient(url, TargetEntity.AAI) Response response = client.get() diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteNetworkInstance.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteNetworkInstance.groovy index 3812c081f5..67fbb97797 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteNetworkInstance.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteNetworkInstance.groovy @@ -18,11 +18,11 @@ * ============LICENSE_END========================================================= */ -package org.onap.so.bpmn.infrastructure.scripts; +package org.onap.so.bpmn.infrastructure.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.common.scripts.AaiUtil import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor import org.onap.so.bpmn.common.scripts.ExceptionUtil @@ -33,19 +33,23 @@ import org.onap.so.bpmn.common.scripts.VidUtils import org.onap.so.bpmn.core.UrnPropertiesReader import org.onap.so.bpmn.core.WorkflowException import org.onap.so.bpmn.core.json.JsonUtils +import org.onap.so.client.HttpClient +import org.onap.so.client.HttpClientFactory 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.client.graphinventory.entities.uri.Depth import org.onap.so.constants.Defaults import org.onap.so.logger.MessageEnum import org.onap.so.logger.MsoLogger -import org.onap.so.rest.APIResponse; -import org.onap.so.rest.RESTClient -import org.onap.so.rest.RESTConfig + import org.springframework.web.util.UriUtils +import org.onap.so.utils.TargetEntity -import groovy.json.* +import groovy.json.JsonOutput +import javax.ws.rs.core.Response public class DoDeleteNetworkInstance extends AbstractServiceTaskProcessor { private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, DoDeleteNetworkInstance.class); @@ -71,7 +75,6 @@ public class DoDeleteNetworkInstance extends AbstractServiceTaskProcessor { execution.setVariable(Prefix + "networkInputs", "") execution.setVariable(Prefix + "tenantId", "") - execution.setVariable(Prefix + "queryAAIRequest","") execution.setVariable(Prefix + "queryAAIResponse", "") execution.setVariable(Prefix + "aaiReturnCode", "") execution.setVariable(Prefix + "isAAIGood", false) @@ -246,85 +249,52 @@ public class DoDeleteNetworkInstance extends AbstractServiceTaskProcessor { String networkInputs = execution.getVariable(Prefix + "networkInputs") String networkId = utils.getNodeText(networkInputs, "network-id") networkId = UriUtils.encode(networkId,"UTF-8") - - // Prepare AA&I url - AaiUtil aaiUriUtil = new AaiUtil(this) - AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.L3_NETWORK, networkId) - uri.depth(Depth.ALL) - - String queryAAIRequest = aaiUriUtil.createAaiUri(uri) - msoLogger.debug(queryAAIRequest) - execution.setVariable(Prefix + "queryAAIRequest", queryAAIRequest) - msoLogger.debug(Prefix + "AAIRequest - " + "\n" + queryAAIRequest) - - RESTConfig config = new RESTConfig(queryAAIRequest); - ExceptionUtil exceptionUtil = new ExceptionUtil() Boolean isVfRelationshipExist = false try { - APIResponse response = aaiUriUtil.executeAAIGetCall(execution, queryAAIRequest) - String returnCode = response.getStatusCode() - execution.setVariable(Prefix + "aaiReturnCode", returnCode) - - msoLogger.debug(" ***** AAI Response Code : " + returnCode) - - String aaiResponseAsString = response.getResponseBodyAsString() - execution.setVariable(Prefix + "queryAAIResponse", aaiResponseAsString) - - if (returnCode=='200' || returnCode=='204') { - msoLogger.debug(aaiResponseAsString) + AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.L3_NETWORK, networkId).depth(Depth.ALL) + Optional<L3Network> l3Network = getAAIClient().get(L3Network.class,uri); + AAIResultWrapper wrapper = getAAIClient().get(uri); + Optional<Relationships> relationships = wrapper.getRelationships() + + if (l3Network.isPresent()) { + execution.setVariable(Prefix + "aaiReturnCode", 200) + execution.setVariable(Prefix + "queryAAIResponse", l3Network.get()) execution.setVariable(Prefix + "isAAIGood", true) - msoLogger.debug(" AAI Query Success REST Response - " + "\n" + aaiResponseAsString) - // verify if vf or vnf relationship exist - if (utils.nodeExists(aaiResponseAsString, "relationship")) { - NetworkUtils networkUtils = new NetworkUtils() - isVfRelationshipExist = networkUtils.isVfRelationshipExist(aaiResponseAsString) - execution.setVariable(Prefix + "isVfRelationshipExist", isVfRelationshipExist) - if (isVfRelationshipExist == true) { + if (relationships.isPresent()){ + if(relationships.get().getRelatedAAIUris(AAIObjectType.VF_MODULE).isEmpty()){ + execution.setVariable(Prefix + "isVfRelationshipExist", true) + isVfRelationshipExist = true String relationshipMessage = "AAI Query Success Response but 'vf-module' relationship exist, not allowed to delete: network Id: " + networkId exceptionUtil.buildWorkflowException(execution, 2500, relationshipMessage) - - } else { - // verify if lcpCloudRegion was sent as input, if not get value from AAI Response - if (execution.getVariable(Prefix + "lcpCloudRegion") == null ) { - String lcpCloudRegion = networkUtils.getCloudRegion(aaiResponseAsString) - execution.setVariable(Prefix + "lcpCloudRegion", lcpCloudRegion) - msoLogger.debug(" Get AAI getCloudRegion() : " + lcpCloudRegion) + }else{ + List<AAIResourceUri> tenantURIList = relationships.get().getRelatedAAIUris(AAIObjectType.TENANT) + for(AAIResourceUri tenantURI: tenantURIList){ + if(execution.getVariable(Prefix + "tenantId") == null) { + String tenantId = tenantURI.getURIKeys().get("tenant-id") + execution.setVariable(Prefix + "tenantId", tenantId) + msoLogger.debug(" Get AAI getTenantId() : " + tenantId) + } } - if (execution.getVariable(Prefix + "tenantId") == null ) { - String tenantId = networkUtils.getTenantId(aaiResponseAsString) - execution.setVariable(Prefix + "tenantId", tenantId) - msoLogger.debug(" Get AAI getTenantId() : " + tenantId) + List<AAIResourceUri> cloudRegionURIList = relationships.get().getRelatedAAIUris(AAIObjectType.CLOUD_REGION) + for(AAIResourceUri tenantURI: cloudRegionURIList){ + if(execution.getVariable(Prefix + "lcpCloudRegion") == null) { + String lcpCloudRegion = tenantURI.getURIKeys().get("cloud-region-id") + execution.setVariable(Prefix + "lcpCloudRegion", lcpCloudRegion) + msoLogger.debug(" Get AAI getCloudRegion() : " + lcpCloudRegion) + } } - } } msoLogger.debug(Prefix + "isVfRelationshipExist - " + isVfRelationshipExist) - } else { + // not found // empty aai response + execution.setVariable(Prefix + "aaiReturnCode", 404) execution.setVariable(Prefix + "isAAIGood", false) - if (returnCode=='404' || aaiResponseAsString == "" || aaiResponseAsString == null) { - // not found // empty aai response - execution.setVariable(Prefix + "isSilentSuccess", true) - msoLogger.debug(" AAI Query is Silent Success") - - } else { - if (aaiResponseAsString.contains("RESTFault")) { - WorkflowException exceptionObject = exceptionUtil.MapAAIExceptionToWorkflowException(aaiResponseAsString, execution) - execution.setVariable("WorkflowException", exceptionObject) - - } else { - // aai all errors - String dataErrorMessage = "Unexpected Error Response from callRESTQueryAAI() - " + returnCode - msoLogger.debug(dataErrorMessage) - exceptionUtil.buildWorkflowException(execution, 2500, dataErrorMessage) - - } - } + execution.setVariable(Prefix + "isSilentSuccess", true) + msoLogger.debug(" AAI Query is Silent Success") } - msoLogger.debug(" AAI Query call, isAAIGood? : " + execution.getVariable(Prefix + "isAAIGood")) - } catch (Exception ex) { // caught exception String exceptionMessage = "Exception Encountered in DoDeleteNetworkInstance, callRESTQueryAAI() - " + ex.getMessage() @@ -392,13 +362,12 @@ public class DoDeleteNetworkInstance extends AbstractServiceTaskProcessor { String cloudSiteId = execution.getVariable(Prefix + "cloudRegionPo") String tenantId = execution.getVariable(Prefix + "tenantId") - String queryAAIResponse = execution.getVariable(Prefix + "queryAAIResponse") - String networkType = utils.getNodeText(queryAAIResponse, "network-type") - String networkId = utils.getNodeText(queryAAIResponse, "network-id") - String backoutOnFailure = execution.getVariable(Prefix + "rollbackEnabled") + L3Network l3Network = execution.getVariable(Prefix + "queryAAIResponse") + String networkType = l3Network.getNetworkType() + String networkId = l3Network.getNetworkId() String networkStackId = "" - networkStackId = utils.getNodeText(queryAAIResponse, "heat-stack-id") + networkStackId = l3Network.getHeatStackId() if (networkStackId == 'null' || networkStackId == "" || networkStackId == null) { networkStackId = "force_delete" } @@ -480,17 +449,14 @@ public class DoDeleteNetworkInstance extends AbstractServiceTaskProcessor { String vnfAdapterUrl = UrnPropertiesReader.getVariable("mso.adapters.network.rest.endpoint",execution) String vnfAdapterRequest = execution.getVariable(Prefix + "deleteNetworkRequest") - RESTConfig config = new RESTConfig(vnfAdapterUrl) - RESTClient client = new RESTClient(config). - addHeader("Content-Type", "application/xml"). - addAuthorizationHeader(execution.getVariable("BasicAuthHeaderValuePO")); - - APIResponse response; - - response = client.httpDelete(vnfAdapterRequest) + URL url = new URL(vnfAdapterUrl) + HttpClient httpClient = new HttpClientFactory().newXmlClient(url, TargetEntity.OPENSTACK_ADAPTER) + httpClient.accept = "application/xml" + httpClient.addAdditionalHeader("Authorization", execution.getVariable("BasicAuthHeaderValuePO")) + Response response = httpClient.delete(vnfAdapterRequest) - execution.setVariable(Prefix + "networkReturnCode", response.getStatusCode()) - execution.setVariable(Prefix + "deleteNetworkResponse", response.getResponseBodyAsString()) + execution.setVariable(Prefix + "deleteNetworkResponse", response.readEntity(String.class)) + execution.setVariable(Prefix + "networkReturnCode", response.getStatus()) } catch (Exception ex) { // caught exception @@ -531,7 +497,7 @@ public class DoDeleteNetworkInstance extends AbstractServiceTaskProcessor { } execution.setVariable(Prefix + "requestId", requestId) msoLogger.debug(Prefix + "requestId " + requestId) - String queryAAIResponse = execution.getVariable(Prefix + "queryAAIResponse") + L3Network queryAAIResponse = execution.getVariable(Prefix + "queryAAIResponse") SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils() String cloudRegionId = execution.getVariable(Prefix + "cloudRegionSdnc") @@ -1006,7 +972,7 @@ public class DoDeleteNetworkInstance extends AbstractServiceTaskProcessor { } execution.setVariable(Prefix + "requestId", requestId) - String queryAAIResponse = execution.getVariable(Prefix + "queryAAIResponse") + L3Network queryAAIResponse = execution.getVariable(Prefix + "queryAAIResponse") SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils() String cloudRegionId = execution.getVariable(Prefix + "cloudRegionSdnc") diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteNetworkInstanceRollback.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteNetworkInstanceRollback.groovy index ca6e21eedc..1db7475cba 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteNetworkInstanceRollback.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteNetworkInstanceRollback.groovy @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -30,9 +30,7 @@ import org.onap.so.bpmn.common.scripts.NetworkUtils import org.onap.so.bpmn.common.scripts.SDNCAdapterUtils import org.onap.so.bpmn.common.scripts.VidUtils import org.onap.so.bpmn.core.WorkflowException -import org.onap.so.rest.APIResponse; -import org.onap.so.rest.RESTClient -import org.onap.so.rest.RESTConfig + import java.util.UUID; @@ -51,7 +49,7 @@ import org.onap.so.logger.MsoLogger */ public class DoDeleteNetworkInstanceRollback extends AbstractServiceTaskProcessor { private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, DoDeleteNetworkInstanceRollback.class); - + String Prefix="DELNWKIR_" ExceptionUtil exceptionUtil = new ExceptionUtil() JsonUtils jsonUtil = new JsonUtils() @@ -60,16 +58,16 @@ public class DoDeleteNetworkInstanceRollback extends AbstractServiceTaskProcesso SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils() def className = getClass().getSimpleName() - + /** * This method is executed during the preProcessRequest task of the <class>DoDeleteNetworkInstanceRollback.bpmn</class> process. * @param execution */ public InitializeProcessVariables(DelegateExecution execution){ /* Initialize all the process variables in this block */ - + execution.setVariable(Prefix + "WorkflowException", null) - + execution.setVariable(Prefix + "rollbackDeactivateSDNCRequest", null) execution.setVariable(Prefix + "rollbackDeactivateSDNCResponse", "") execution.setVariable(Prefix + "rollbackDeactivateSDNCReturnCode", "") @@ -77,11 +75,11 @@ public class DoDeleteNetworkInstanceRollback extends AbstractServiceTaskProcesso execution.setVariable(Prefix + "rollbackSDNCRequest", "") execution.setVariable(Prefix + "rollbackSDNCResponse", "") execution.setVariable(Prefix + "rollbackSDNCReturnCode", "") - + execution.setVariable(Prefix + "rollbackNetworkRequest", null) execution.setVariable(Prefix + "rollbackNetworkResponse", "") execution.setVariable(Prefix + "rollbackNetworkReturnCode", "") - + execution.setVariable(Prefix + "Success", false) execution.setVariable(Prefix + "fullRollback", false) @@ -97,13 +95,13 @@ public class DoDeleteNetworkInstanceRollback extends AbstractServiceTaskProcesso public void preProcessRequest (DelegateExecution execution) { execution.setVariable("prefix",Prefix) - + msoLogger.trace("Inside preProcessRequest() of " + className + ".groovy ") try { // initialize flow variables InitializeProcessVariables(execution) - + // GET Incoming request/variables String rollbackDeactivateSDNCRequest = null String rollbackSDNCRequest = null @@ -111,20 +109,20 @@ public class DoDeleteNetworkInstanceRollback extends AbstractServiceTaskProcesso Map<String, String> rollbackData = execution.getVariable("rollbackData") if (rollbackData != null && rollbackData instanceof Map) { - + if(rollbackData.containsKey("rollbackDeactivateSDNCRequest")) { rollbackDeactivateSDNCRequest = rollbackData["rollbackDeactivateSDNCRequest"] } - + if(rollbackData.containsKey("rollbackSDNCRequest")) { rollbackSDNCRequest = rollbackData["rollbackSDNCRequest"] } - + if(rollbackData.containsKey("rollbackNetworkRequest")) { rollbackNetworkRequest = rollbackData["rollbackNetworkRequest"] } } - + execution.setVariable(Prefix + "rollbackNetworkRequest", rollbackNetworkRequest) execution.setVariable(Prefix + "rollbackSDNCRequest", rollbackSDNCRequest) execution.setVariable(Prefix + "rollbackDeactivateSDNCRequest", rollbackDeactivateSDNCRequest) @@ -132,14 +130,14 @@ public class DoDeleteNetworkInstanceRollback extends AbstractServiceTaskProcesso String sdncVersion = execution.getVariable("sdncVersion") msoLogger.debug("sdncVersion? : " + sdncVersion) - + // PO Authorization Info / headers Authorization= String basicAuthValuePO = UrnPropertiesReader.getVariable("mso.adapters.po.auth",execution) try { def encodedString = utils.getBasicAuth(basicAuthValuePO, UrnPropertiesReader.getVariable("mso.msoKey", execution)) execution.setVariable("BasicAuthHeaderValuePO",encodedString) execution.setVariable("BasicAuthHeaderValueSDNC", encodedString) - + } catch (IOException ex) { String exceptionMessage = "Exception Encountered in DoCreateNetworkInstance, PreProcessRequest() - " String dataErrorMessage = exceptionMessage + " Unable to encode PO/SDNC user/password string - " + ex.getMessage() @@ -160,31 +158,31 @@ public class DoDeleteNetworkInstanceRollback extends AbstractServiceTaskProcesso } else { // called by: Macro - Full Rollback, WorkflowException = null execution.setVariable(Prefix + "fullRollback", true) - + } - + msoLogger.debug("*** fullRollback? : " + execution.getVariable(Prefix + "fullRollback")) - + } catch (BpmnError e) { throw e; - + } catch (Exception ex) { sendSyncError(execution) // caught exception String exceptionMessage = "Exception Encountered in PreProcessRequest() of " + className + ".groovy ***** : " + ex.getMessage() msoLogger.debug(exceptionMessage) exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) - + } } - + public void validateRollbackResponses (DelegateExecution execution) { execution.setVariable("prefix",Prefix) msoLogger.trace("Inside validateRollbackResponses() of DoDeleteNetworkInstanceRollback ") - + try { // validate SDNC activate response @@ -212,7 +210,7 @@ public class DoDeleteNetworkInstanceRollback extends AbstractServiceTaskProcesso msoLogger.debug(" SDNC deactivate rollback Code - " + rollbackDeactivateSDNCReturnCode) msoLogger.debug(" SDNC deactivate rollback Response - " + rollbackDeactivateSDNCResponse) } - + // validate SDNC rollback response String rollbackSdncErrorMessages = "" String rollbackSDNCReturnCode = "200" @@ -239,7 +237,7 @@ public class DoDeleteNetworkInstanceRollback extends AbstractServiceTaskProcesso msoLogger.debug(" SDNC assign rollback Code - " + rollbackSDNCReturnCode) msoLogger.debug(" SDNC assign rollback Response - " + rollbackSDNCResponse) } - + // validate PO network rollback response String rollbackNetworkErrorMessages = "" String rollbackNetworkReturnCode = "200" @@ -251,11 +249,11 @@ public class DoDeleteNetworkInstanceRollback extends AbstractServiceTaskProcesso } else { rollbackNetworkErrorMessages = " + PO Network rollback completed." } - + msoLogger.debug(" NetworkRollback Code - " + rollbackNetworkReturnCode) msoLogger.debug(" NetworkRollback Response - " + rollbackNetworkResponse) } - + String statusMessage = "" int errorCode = 7000 msoLogger.debug("*** fullRollback? : " + execution.getVariable(Prefix + "fullRollback")) @@ -273,7 +271,7 @@ public class DoDeleteNetworkInstanceRollback extends AbstractServiceTaskProcesso if (rollbackDeactivateSDNCReturnCode == "200" && rollbackNetworkReturnCode == "200" && rollbackSDNCReturnCode == "200") { execution.setVariable("rolledBack", true) execution.setVariable("wasDeleted", true) - + } else { execution.setVariable("rolledBack", false) execution.setVariable("wasDeleted", true) @@ -284,12 +282,12 @@ public class DoDeleteNetworkInstanceRollback extends AbstractServiceTaskProcesso String processKey = getProcessKey(execution); WorkflowException exception = new WorkflowException(processKey, errorCode, statusMessage); execution.setVariable("workflowException", exception); - + } else { // rollback due to failures in Main flow (Macro or a-ala-carte) - Full rollback if (rollbackDeactivateSDNCReturnCode == "200" && rollbackNetworkReturnCode == "200" && rollbackSDNCReturnCode == "200") { execution.setVariable("rollbackSuccessful", true) - execution.setVariable("rollbackError", false) + execution.setVariable("rollbackError", false) } else { String exceptionMessage = "Network Delete Rollback was not Successful. " msoLogger.debug(exceptionMessage) @@ -297,9 +295,9 @@ public class DoDeleteNetworkInstanceRollback extends AbstractServiceTaskProcesso execution.setVariable("rollbackError", true) exceptionUtil.buildWorkflowException(execution, 7000, exceptionMessage) throw new BpmnError("MSOWorkflowException") - } - } - + } + } + } catch (Exception ex) { String errorMessage = "See Previous Camunda flows for cause of Error: Undetermined Exception." String exceptionMessage = " Bpmn error encountered in DoDeleteNetworkInstanceRollback flow. validateRollbackResponses() - " + errorMessage + ": " + ex.getMessage() @@ -315,18 +313,18 @@ public class DoDeleteNetworkInstanceRollback extends AbstractServiceTaskProcesso // ******************************* - + public void processJavaException(DelegateExecution execution){ execution.setVariable("prefix",Prefix) - + try{ msoLogger.debug("Caught a Java Exception in " + Prefix) msoLogger.debug("Started processJavaException Method") msoLogger.debug("Variables List: " + execution.getVariables()) execution.setVariable("UnexpectedError", "Caught a Java Lang Exception - " + Prefix) // Adding this line temporarily until this flows error handling gets updated exceptionUtil.buildWorkflowException(execution, 500, "Caught a Java Lang Exception") - + }catch(Exception e){ msoLogger.debug("Caught Exception during processJavaException Method: " + e) execution.setVariable("UnexpectedError", "Exception in processJavaException method - " + Prefix) // Adding this line temporarily until this flows error handling gets updated diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteResourcesV1.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteResourcesV1.groovy index 61e62d3eba..6a31095920 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteResourcesV1.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteResourcesV1.groovy @@ -20,6 +20,8 @@ */ package org.onap.so.bpmn.infrastructure.scripts +import org.onap.so.bpmn.common.scripts.CatalogDbUtilsFactory + import static org.apache.commons.lang3.StringUtils.isBlank import org.apache.commons.lang3.StringUtils @@ -65,7 +67,7 @@ public class DoDeleteResourcesV1 extends AbstractServiceTaskProcessor { String Prefix="DDR_" ExceptionUtil exceptionUtil = new ExceptionUtil() JsonUtils jsonUtil = new JsonUtils() - CatalogDbUtils cutils = new CatalogDbUtils() + CatalogDbUtils catalogDbUtils = new CatalogDbUtilsFactory().create() public void preProcessRequest (DelegateExecution execution) { msoLogger.debug(" ***** preProcessRequest *****") @@ -239,7 +241,7 @@ public class DoDeleteResourcesV1 extends AbstractServiceTaskProcessor { Resource currentResource = execution.getVariable("currentResource") String action = "deleteInstance" - JSONObject resourceRecipe = cutils.getResourceRecipe(execution, currentResource.getModelInfo().getModelUuid(), action) + JSONObject resourceRecipe = catalogDbUtils.getResourceRecipe(execution, currentResource.getModelInfo().getModelUuid(), action) String recipeUri = resourceRecipe.getString("orchestrationUri") int recipeTimeout = resourceRecipe.getInt("recipeTimeout") String recipeParamXsd = resourceRecipe.get("paramXSD") diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteVFCNetworkServiceInstance.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteVFCNetworkServiceInstance.groovy index 5ff93363d2..7c8a1d70e1 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteVFCNetworkServiceInstance.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteVFCNetworkServiceInstance.groovy @@ -25,19 +25,16 @@ import org.camunda.bpm.engine.delegate.DelegateExecution import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor import org.onap.so.bpmn.common.scripts.ExceptionUtil import org.onap.so.bpmn.core.json.JsonUtils -//import org.onap.so.client.HttpClient +import org.onap.so.client.HttpClient +import org.onap.so.client.HttpClientFactory 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.MessageEnum import org.onap.so.logger.MsoLogger -import org.onap.so.rest.APIResponse -import org.onap.so.rest.RESTClient -import org.onap.so.rest.RESTConfig -//import org.onap.so.utils.TargetEntity +import org.onap.so.utils.TargetEntity import org.onap.so.bpmn.core.UrnPropertiesReader -//import javax.ws.rs.core.Response +import javax.ws.rs.core.Response /** * This groovy class supports the <class>DoDeleteVFCNetworkServiceInstance.bpmn</class> process. * flow for E2E ServiceInstance Delete @@ -48,6 +45,7 @@ public class DoDeleteVFCNetworkServiceInstance extends AbstractServiceTaskProces ExceptionUtil exceptionUtil = new ExceptionUtil() JsonUtils jsonUtil = new JsonUtils() + private final HttpClientFactory httpClientFactory = new HttpClientFactory() /** * Pre Process the BPMN Flow Request @@ -139,9 +137,8 @@ public class DoDeleteVFCNetworkServiceInstance extends AbstractServiceTaskProces String vfcAdapterUrl = execution.getVariable("vfcAdapterUrl") String nsOperationKey = execution.getVariable("nsOperationKey"); String url = vfcAdapterUrl + "/ns/" + execution.getVariable("nsInstanceId") - APIResponse apiResponse = deleteRequest(execution, url, nsOperationKey) - String returnCode = apiResponse.getStatusCode() - String aaiResponseAsString = apiResponse.getResponseBodyAsString() + Response apiResponse = deleteRequest(execution, url, nsOperationKey) + String returnCode = apiResponse.getStatus() String operationStatus = "error"; if(returnCode== "200" || returnCode== "202"){ operationStatus = "finished" @@ -160,9 +157,9 @@ public class DoDeleteVFCNetworkServiceInstance extends AbstractServiceTaskProces String vfcAdapterUrl = execution.getVariable("vfcAdapterUrl") String nsOperationKey = execution.getVariable("nsOperationKey") String url = vfcAdapterUrl + "/ns/" + execution.getVariable("nsInstanceId") + "/terminate" - APIResponse apiResponse = postRequest(execution, url, nsOperationKey) - String returnCode = apiResponse.getStatusCode() - String aaiResponseAsString = apiResponse.getResponseBodyAsString() + Response apiResponse = postRequest(execution, url, nsOperationKey) + String returnCode = apiResponse.getStatus() + String aaiResponseAsString = apiResponse.readEntity(String.class) String jobId = ""; if(returnCode== "200" || returnCode== "202"){ jobId = jsonUtil.getJsonValue(aaiResponseAsString, "jobId") @@ -181,9 +178,9 @@ public class DoDeleteVFCNetworkServiceInstance extends AbstractServiceTaskProces String jobId = execution.getVariable("jobId") String nsOperationKey = execution.getVariable("nsOperationKey"); String url = vfcAdapterUrl + "/jobs/" + execution.getVariable("jobId") - APIResponse apiResponse = postRequest(execution, url, nsOperationKey) - String returnCode = apiResponse.getStatusCode() - String apiResponseAsString = apiResponse.getResponseBodyAsString() + Response apiResponse = postRequest(execution, url, nsOperationKey) + String returnCode = apiResponse.getStatus() + String apiResponseAsString = apiResponse.readEntity(String.class) String operationProgress = "100" if(returnCode== "200"){ operationProgress = jsonUtil.getJsonValue(apiResponseAsString, "responseDescriptor.progress") @@ -215,32 +212,26 @@ public class DoDeleteVFCNetworkServiceInstance extends AbstractServiceTaskProces * url: the url of the request * requestBody: the body of the request */ - private APIResponse postRequest(DelegateExecution execution, String urlString, String requestBody){ + private Response postRequest(DelegateExecution execution, String urlString, String requestBody){ msoLogger.trace("Started Execute VFC adapter Post Process ") msoLogger.info("url:"+urlString +"\nrequestBody:"+ requestBody) - APIResponse apiResponse = null + Response apiResponse = null try{ + URL url = new URL(urlString); + // Get the Basic Auth credentials for the VFCAdapter, username is 'bpel', auth is '07a7159d3bf51a0e53be7a8f89699be7' - def basicAuthHeaderValue = "" - RESTConfig config = new RESTConfig(urlString) - RESTClient client = null; - int statusCode = 0; - - // user 'bepl' authHeader is the same with mso.db.auth - String basicAuthValuedb = UrnPropertiesReader.getVariable("mso.db.auth", execution) - msoLogger.debug("basicAuthValuedb: " + basicAuthValuedb) - - client = new RESTClient(config) - client.addHeader("Accept", "application/json") - client.addAuthorizationHeader(basicAuthValuedb) - client.addHeader("Content-Type", "application/json") - - apiResponse = client.httpPost(requestBody) - statusCode = apiResponse.getStatusCode() - - msoLogger.debug("response code:"+ apiResponse.getStatusCode() +"\nresponse body:"+ apiResponse.getResponseBodyAsString()) - + // user 'bepl' authHeader is the same with mso.db.auth + String basicAuthValuedb = UrnPropertiesReader.getVariable("mso.db.auth", execution) + HttpClient httpClient = httpClientFactory.newJsonClient(url, TargetEntity.VNF_ADAPTER) + httpClient.addAdditionalHeader("Accept", "application/json") + httpClient.addAdditionalHeader("Authorization", basicAuthValuedb) + + apiResponse = httpClient.post(requestBody) + + msoLogger.debug("response code:"+ apiResponse.getStatus() +"\nresponse body:"+ apiResponse.readEntity(String.class)) + + msoLogger.trace("Completed Execute VF-C adapter Post Process ") }catch(Exception e){ msoLogger.error("Exception occured while executing VF-C Post Call. Exception is: \n" + e.getMessage()); throw new BpmnError("MSOWorkflowException") @@ -252,37 +243,28 @@ public class DoDeleteVFCNetworkServiceInstance extends AbstractServiceTaskProces * url: the url of the request * requestBody: the body of the request */ - private APIResponse deleteRequest(DelegateExecution execution, String url, String requestBody){ + private Response deleteRequest(DelegateExecution execution, String url, String requestBody){ msoLogger.trace("Started Execute VFC adapter Delete Process ") msoLogger.info("url:"+url +"\nrequestBody:"+ requestBody) - - APIResponse apiResponse = null - try{ - // Get the Basic Auth credentials for the VFCAdapter, username is 'bpel', auth is '07a7159d3bf51a0e53be7a8f89699be7' - def basicAuthHeaderValue = "" - RESTConfig config = new RESTConfig(url) - RESTClient client = null; - int statusCode = 0; - - // user 'bepl' authHeader is the same with mso.db.auth - String basicAuthValuedb = UrnPropertiesReader.getVariable("mso.db.auth", execution) - msoLogger.debug("basicAuthValuedb: " + basicAuthValuedb) - - client = new RESTClient(config) - client.addHeader("Accept", "application/json") - client.addAuthorizationHeader(basicAuthValuedb) - client.addHeader("Content-Type", "application/json") - - apiResponse = client.httpDelete(requestBody) - statusCode = apiResponse.getStatusCode() - - msoLogger.debug("response code:"+ apiResponse.getStatusCode() +"\nresponse body:"+ apiResponse.getResponseBodyAsString()) + Response r + try{ + + URL Url = new URL(url) + // Get the Basic Auth credentials for the VFCAdapter, username is 'bpel', auth is '07a7159d3bf51a0e53be7a8f89699be7' + // user 'bepl' authHeader is the same with mso.db.auth + String basicAuthValuedb = UrnPropertiesReader.getVariable("mso.db.auth", execution) + HttpClient httpClient = httpClientFactory.newJsonClient(url, TargetEntity.VNF_ADAPTER) + httpClient.addAdditionalHeader("Accept", "application/json") + httpClient.addAdditionalHeader("Authorization", basicAuthValuedb) + httpClient.addAdditionalHeader("Content-Type", "application/json") + r = httpClient.delete(requestBody) - }catch(Exception e){ - msoLogger.error("Exception occured while executing VF-C Delete Call. Exception is: \n" + e.getMessage()); - throw new BpmnError("MSOWorkflowException") - } - return apiResponse + msoLogger.trace("Completed Execute VF-C adapter Delete Process ") + }catch(Exception e){ + msoLogger.error("Exception occured while executing VF-C Post Call. Exception is: \n" + e.getMessage()); + throw new BpmnError("MSOWorkflowException") + } + return r } } diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteVfModule.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteVfModule.groovy index 85e67c51a7..3bc481ab01 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteVfModule.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteVfModule.groovy @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,6 +20,9 @@ package org.onap.so.bpmn.infrastructure.scripts +import org.onap.aai.domain.yang.NetworkPolicies +import org.onap.aai.domain.yang.NetworkPolicy + import javax.xml.parsers.DocumentBuilder import javax.xml.parsers.DocumentBuilderFactory @@ -40,9 +43,6 @@ 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 -import org.onap.so.rest.RESTClient -import org.onap.so.rest.RESTConfig import org.springframework.web.util.UriUtils import org.w3c.dom.Document import org.w3c.dom.Element @@ -63,7 +63,7 @@ import org.xml.sax.InputSource * @param - vfModuleModelInfo * @param - cloudConfiguration* * @param - sdncVersion ("1610") -* @param - retainResources +* @param - retainResources * @param - aLaCarte * * Outputs: @@ -130,11 +130,11 @@ public class DoDeleteVfModule extends AbstractServiceTaskProcessor{ def vfModuleModelName = jsonUtil.getJsonValue(vfModuleModelInfo, "modelName") execution.setVariable("vfModuleModelName", vfModuleModelName) // retainResources - def retainResources = execution.getVariable("retainResources") + def retainResources = execution.getVariable("retainResources") if (retainResources == null) { retainResources = false } - execution.setVariable("retainResources", retainResources) + execution.setVariable("retainResources", retainResources) } else { @@ -203,7 +203,7 @@ public class DoDeleteVfModule extends AbstractServiceTaskProcessor{ if(uuid==null){ uuid = execution.getVariable("requestId") + "-" + System.currentTimeMillis() } - + def srvInstId = execution.getVariable("srvInstId") def callbackUrl = UrnPropertiesReader.getVariable("mso.workflow.sdncadapter.callback",execution) String requestId = execution.getVariable("requestId") @@ -226,7 +226,7 @@ public class DoDeleteVfModule extends AbstractServiceTaskProcessor{ boolean retainResources = execution.getVariable("retainResources") String requestSubActionString = "" if (retainResources) { - requestSubActionString = "<request-sub-action>RetainResource</request-sub-action>" + requestSubActionString = "<request-sub-action>RetainResource</request-sub-action>" } String request = """<sdncadapterworkflow:SDNCAdapterWorkflowRequest xmlns:ns5="http://org.onap/so/request/types/v1" xmlns:sdncadapterworkflow="http://org.onap/so/workflow/schema/v1" @@ -474,99 +474,50 @@ public class DoDeleteVfModule extends AbstractServiceTaskProcessor{ execution.setVariable("DoDVfMod_networkPolicyFqdnCount", fqdnCount) msoLogger.debug("DoDVfMod_networkPolicyFqdnCount - " + fqdnCount) - AaiUtil aaiUriUtil = new AaiUtil(this) - if (fqdnCount > 0) { // AII loop call over contrail network policy fqdn list for (i in 0..fqdnCount-1) { - - int counting = i+1 String fqdn = fqdnList[i] - // Query AAI for this network policy FQDN AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectPlurals.NETWORK_POLICY) uri.queryParam("network-policy-fqdn", fqdn) - String queryNetworkPolicyByFqdnAAIRequest = aaiUriUtil.createAaiUri(uri) - msoLogger.debug("AAI request endpoint: " + queryNetworkPolicyByFqdnAAIRequest) - - APIResponse response = aaiUriUtil.executeAAIGetCall(execution, queryNetworkPolicyByFqdnAAIRequest) - int returnCode = response.getStatusCode() - execution.setVariable("DCVFM_aaiQueryNetworkPolicyByFqdnReturnCode", returnCode) - msoLogger.debug(" ***** AAI query network policy Response Code, NetworkPolicy #" + counting + " : " + returnCode) - - String aaiResponseAsString = response.getResponseBodyAsString() - - if (isOneOf(returnCode, 200, 201)) { - msoLogger.debug("The return code is: " + returnCode) - // This network policy FQDN exists in AAI - need to delete it now - msoLogger.debug(aaiResponseAsString) - execution.setVariable("DoDVfMod_queryNetworkPolicyByFqdnAAIResponse", aaiResponseAsString) - msoLogger.debug("QueryAAINetworkPolicyByFQDN Success REST Response, , NetworkPolicy #" + counting + " : " + "\n" + aaiResponseAsString) - // Retrieve the network policy id for this FQDN - def networkPolicyId = utils.getNodeText(aaiResponseAsString, "network-policy-id") - msoLogger.debug("Deleting network-policy with network-policy-id " + networkPolicyId) - - // Retrieve the resource version for this network policy - def resourceVersion = utils.getNodeText(aaiResponseAsString, "resource-version") - msoLogger.debug("Deleting network-policy with resource-version " + resourceVersion) - - AAIResourceUri delUri = AAIUriFactory.createResourceUri(AAIObjectType.NETWORK_POLICY, networkPolicyId) - delUri.resourceVersion(resourceVersion) - String delNetworkPolicyAAIRequest = aaiUriUtil.createAaiUri(delUri) - - msoLogger.debug("AAI request endpoint: " + delNetworkPolicyAAIRequest) - - msoLogger.debug("invoking DELETE call to AAI") - msoLogger.debug("Sending DELETE call to AAI with Endpoint /n" + delNetworkPolicyAAIRequest) - APIResponse responseDel = aaiUriUtil.executeAAIDeleteCall(execution, delNetworkPolicyAAIRequest) - int returnCodeDel = responseDel.getStatusCode() - execution.setVariable("DoDVfMod_aaiDeleteNetworkPolicyReturnCode", returnCodeDel) - msoLogger.debug(" ***** AAI delete network policy Response Code, NetworkPolicy #" + counting + " : " + returnCodeDel) - - if (isOneOf(returnCodeDel, 200, 201, 204)) { - msoLogger.debug("The return code from deleting network policy is: " + returnCodeDel) - // This network policy was deleted from AAI successfully - msoLogger.debug(" DelAAINetworkPolicy Success REST Response, , NetworkPolicy #" + counting + " : ") - + try { + Optional<NetworkPolicies> networkPolicies = getAAIClient().get(NetworkPolicies.class, uri) + if (networkPolicies.isPresent() && !networkPolicies.get().getNetworkPolicy().isEmpty()) { + // This network policy FQDN exists in AAI - need to delete it now + NetworkPolicy networkPolicy = networkPolicies.get().getNetworkPolicy().get(0) + execution.setVariable("DCVFM_aaiQueryNetworkPolicyByFqdnReturnCode", 200) + // Retrieve the network policy id for this FQDN + def networkPolicyId = networkPolicy.getNetworkPolicyId() + msoLogger.debug("Deleting network-policy with network-policy-id " + networkPolicyId) + try { + AAIResourceUri delUri = AAIUriFactory.createResourceUri(AAIObjectType.NETWORK_POLICY, networkPolicyId) + getAAIClient().delete(delUri) + execution.setVariable("DoDVfMod_aaiDeleteNetworkPolicyReturnCode", 200) + } catch (Exception e) { + execution.setVariable("DoDVfMod_aaiDeleteNetworkPolicyReturnCode", 500) + String delErrorMessage = "Unable to delete network-policy to AAI deleteNetworkPoliciesFromAAI - " + e.getMessage() + msoLogger.debug(delErrorMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, delErrorMessage) + } } else { - // aai all errors - String delErrorMessage = "Unable to delete network-policy to AAI deleteNetworkPoliciesFromAAI - " + returnCodeDel - msoLogger.debug(delErrorMessage) - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, delErrorMessage) + execution.setVariable("DCVFM_aaiQueryNetworkPolicyByFqdnReturnCode", 404) + // This network policy FQDN is not in AAI. No need to delete. + msoLogger.debug("The return code is: " + 404) + msoLogger.debug("This network policy FQDN is not in AAI: " + fqdn) + msoLogger.debug("Network policy FQDN is not in AAI") } - } else if (returnCode == 404) { - // This network policy FQDN is not in AAI. No need to delete. - msoLogger.debug("The return code is: " + returnCode) - msoLogger.debug("This network policy FQDN is not in AAI: " + fqdn) - msoLogger.debug("Network policy FQDN is not in AAI") - } else { - if (aaiResponseAsString.contains("RESTFault")) { - WorkflowException exceptionObject = exceptionUtil.MapAAIExceptionToWorkflowException(aaiResponseAsString, execution) - execution.setVariable("WorkflowException", exceptionObject) - throw new BpmnError("MSOWorkflowException") - - } else { + }catch(Exception e ) { // aai all errors - String dataErrorMessage = "Unexpected Response from deleteNetworkPoliciesFromAAI - " + returnCode + String dataErrorMessage = "Unexpected Response from deleteNetworkPoliciesFromAAI - " + e.getMessage() msoLogger.debug(dataErrorMessage) - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) - - } } - - - } // end loop - - } else { msoLogger.debug("No contrail network policies to query/create") - } - } catch (BpmnError e) { throw e; - } catch (Exception ex) { String exceptionMessage = "Bpmn error encountered in DoDeletVfModule flow. deleteNetworkPoliciesFromAAI() - " + ex.getMessage() msoLogger.debug(exceptionMessage) @@ -624,7 +575,7 @@ public class DoDeleteVfModule extends AbstractServiceTaskProcessor{ exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in prepUpdateAAIGenericVnf(): ' + e.getMessage()) } } - + /** * Using the vnfId and vfModuleId provided in the inputs, * query AAI to get the corresponding VF Module info. @@ -639,58 +590,25 @@ public class DoDeleteVfModule extends AbstractServiceTaskProcessor{ 'execution=' + execution.getId() + ')' msoLogger.trace('Entered ' + method) - + execution.setVariable(Prefix + 'orchestrationStatus', '') try { def vnfId = execution.getVariable('vnfId') def vfModuleId = execution.getVariable('vfModuleId') - AaiUtil aaiUriUtil = new AaiUtil(this) AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.VF_MODULE, vnfId, vfModuleId) - String endPoint = aaiUriUtil.createAaiUri(uri) - - msoLogger.debug("AAI endPoint: " + endPoint) try { - RESTConfig config = new RESTConfig(endPoint); - def responseData = '' - def aaiRequestId = UUID.randomUUID().toString() - RESTClient client = new RESTClient(config). - addHeader('X-TransactionId', aaiRequestId). - addHeader('X-FromAppId', 'MSO'). - addHeader('Content-Type', 'application/xml'). - addHeader('Accept','application/xml'); - msoLogger.debug('sending GET to AAI endpoint \'' + endPoint + '\'') - APIResponse response = client.httpGet() - msoLogger.debug("createVfModule - invoking httpGet() to AAI") - - responseData = response.getResponseBodyAsString() - if (responseData != null) { - msoLogger.debug("Received generic VNF data: " + responseData) - - } - - msoLogger.debug("deleteVfModule - queryAAIVfModule Response: " + responseData) - msoLogger.debug("deleteVfModule - queryAAIVfModule ResponseCode: " + response.getStatusCode()) - - execution.setVariable(Prefix + 'queryAAIVfModuleForStatusResponseCode', response.getStatusCode()) - execution.setVariable(Prefix + 'queryAAIVfModuleForStatusResponse', responseData) - msoLogger.debug('Response code:' + response.getStatusCode()) - msoLogger.debug('Response:' + System.lineSeparator() + responseData) + Optional<org.onap.aai.domain.yang.VfModule> vfModule = getAAIClient().get(org.onap.aai.domain.yang.VfModule.class, uri); // Retrieve VF Module info and its orchestration status; if not found, do nothing - if (response.getStatusCode() == 200) { - // Parse the VNF record from A&AI to find base module info - msoLogger.debug('Parsing the VNF data to find orchestration status') - if (responseData != null) { - def vfModuleText = utils.getNodeXml(responseData, "vf-module") - //def xmlVfModule= new XmlSlurper().parseText(vfModuleText) - def orchestrationStatus = utils.getNodeText(vfModuleText, "orchestration-status") - execution.setVariable(Prefix + "orchestrationStatus", orchestrationStatus) - msoLogger.debug("Received orchestration status from A&AI: " + orchestrationStatus) - - } - } + if (vfModule.isPresent()) { + execution.setVariable(Prefix + 'queryAAIVfModuleForStatusResponseCode', 200) + execution.setVariable(Prefix + 'queryAAIVfModuleForStatusResponse', vfModule.get()) + def orchestrationStatus = vfModule.get().getOrchestrationStatus() + execution.setVariable(Prefix + "orchestrationStatus", orchestrationStatus) + msoLogger.debug("Received orchestration status from A&AI: " + orchestrationStatus) + } } catch (Exception ex) { ex.printStackTrace() msoLogger.debug('Exception occurred while executing AAI GET:' + ex.getMessage()) @@ -709,4 +627,4 @@ public class DoDeleteVfModule extends AbstractServiceTaskProcessor{ -}
\ No newline at end of file +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteVfModuleFromVnf.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteVfModuleFromVnf.groovy index d90c316832..abc83b2784 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteVfModuleFromVnf.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteVfModuleFromVnf.groovy @@ -20,15 +20,18 @@ package org.onap.so.bpmn.infrastructure.scripts -import static org.apache.commons.lang3.StringUtils.* +import org.onap.aai.domain.yang.GenericVnf +import org.onap.aai.domain.yang.NetworkPolicies +import org.onap.aai.domain.yang.NetworkPolicy +import org.onap.aai.domain.yang.VfModule +import static org.apache.commons.lang3.StringUtils.* import org.camunda.bpm.engine.delegate.BpmnError import org.camunda.bpm.engine.delegate.DelegateExecution import org.onap.so.bpmn.common.scripts.AaiUtil import org.onap.so.bpmn.common.scripts.ExceptionUtil import org.onap.so.bpmn.common.scripts.MsoUtils import org.onap.so.bpmn.common.scripts.SDNCAdapterUtils -import org.onap.so.bpmn.common.scripts.VfModule import org.onap.so.bpmn.common.scripts.VfModuleBase import org.onap.so.bpmn.core.UrnPropertiesReader import org.onap.so.bpmn.core.WorkflowException @@ -40,8 +43,6 @@ 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 -import org.springframework.web.util.UriUtils public class DoDeleteVfModuleFromVnf extends VfModuleBase { private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, DoDeleteVfModuleFromVnf.class); @@ -133,27 +134,17 @@ public class DoDeleteVfModuleFromVnf extends VfModuleBase { try { def vnfId = execution.getVariable('vnfId') - AaiUtil aaiUriUtil = new AaiUtil(this) AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId).depth(Depth.ONE) - - String endPoint = aaiUriUtil.createAaiUri(uri) - - msoLogger.debug("DoDeleteVfModuleFromVnf: AAI endPoint : " + endPoint) - try { - msoLogger.debug("DoDeleteVfModuleFromVnf: - invoking httpGet to AAI") - APIResponse response = aaiUriUtil.executeAAIGetCall(execution, endPoint) - - def responseData = response.getResponseBodyAsString() - execution.setVariable('DDVMFV_getVnfResponseCode', response.getStatusCode()) - execution.setVariable('DDVMFV_getVnfResponse', responseData) - - msoLogger.debug("DoDeleteVfModuleFromVnf: AAI Response : " + responseData) - msoLogger.debug("DoDeleteVfModuleFromVnf: AAI ResponseCode : " + response.getStatusCode()) - - msoLogger.debug('Response code:' + response.getStatusCode()) - msoLogger.debug('Response:' + System.lineSeparator() + responseData) - + Optional<GenericVnf> genericVnf = getAAIClient().get(GenericVnf.class,uri) + + if(genericVnf.isPresent()){ + execution.setVariable('DDVMFV_getVnfResponseCode', 200) + execution.setVariable('DDVMFV_getVnfResponse', genericVnf.get()) + }else{ + execution.setVariable('DDVMFV_getVnfResponseCode', 404) + execution.setVariable('DDVMFV_getVnfResponse', "Generic Vnf not found!") + } } catch (Exception ex) { ex.printStackTrace() msoLogger.debug('Exception occurred while executing AAI GET:' + ex.getMessage()) @@ -185,31 +176,32 @@ public class DoDeleteVfModuleFromVnf extends VfModuleBase { msoLogger.trace('Entered ' + method) try { - def genericVnf = execution.getVariable('DDVMFV_getVnfResponse') + GenericVnf genericVnf = execution.getVariable('DDVMFV_getVnfResponse') def vnfId = execution.getVariable('_vnfId') - def vfModuleId = execution.getVariable('vfModuleId') - def VfModule vfModule = findVfModule(genericVnf, vfModuleId) - if (vfModule == null) { - def String msg = 'VF Module \'' + vfModuleId + '\' does not exist in Generic VNF \'' + vnfId + '\'' + def vfModuleId = execution.getVariable('vfModuleId') + Optional<VfModule> vfModule = Optional.empty() + if(genericVnf.getVfModules()!=null && ! genericVnf.getVfModules().getVfModule().isEmpty()) { + vfModule = genericVnf.getVfModules().getVfModule().stream().filter { v -> v.getVfModuleId().equals(vfModuleId) }.findFirst() + } + if (!vfModule.isPresent()) { + String msg = 'VF Module \'' + vfModuleId + '\' does not exist in Generic VNF \'' + vnfId + '\'' msoLogger.debug(msg) exceptionUtil.buildAndThrowWorkflowException(execution, 1002, msg) } else { - + Boolean isOnlyVfModule = (genericVnf.getVfModules().getVfModule().size() == 1) if (isDebugLogEnabled) { - msoLogger.debug('VF Module \'' + vfModuleId + '\': isBaseVfModule=' + vfModule.isBaseVfModule() + ', isOnlyVfModule=' + vfModule.isOnlyVfModule()) + msoLogger.debug('VF Module \'' + vfModuleId + '\': isBaseVfModule=' + vfModule.get().isIsBaseVfModule() + ', isOnlyVfModule=' + isOnlyVfModule) } - if (vfModule.isBaseVfModule() && !vfModule.isOnlyVfModule()) { - def String msg = 'Cannot delete VF Module \'' + vfModuleId + - '\'since it is the base VF Module and it\'s not the only VF Module in Generic VNF \'' + vnfId + '\'' - msoLogger.debug("Received a BAD Response from VNF Adapter for CREATE_VF_MODULE Call.") - exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "VNF Adapter Error") + if (vfModule.get().isIsBaseVfModule() && !isOnlyVfModule) { + String msg = 'Cannot delete VF Module \'' + vfModuleId + + '\'since it is the base VF Module and it\'s not the only VF Module in Generic VNF \'' + vnfId + '\'' + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 1002,msg) } - - def heatStackId = vfModule.getElementText('heat-stack-id') + def heatStackId = vfModule.get().getHeatStackId() execution.setVariable('DDVMFV_heatStackId', heatStackId) msoLogger.debug('VF Module heatStackId retrieved from AAI: ' + heatStackId) } - msoLogger.trace('Exited ' + method) } catch (BpmnError e) { throw e; @@ -507,80 +499,45 @@ public class DoDeleteVfModuleFromVnf extends VfModuleBase { AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectPlurals.NETWORK_POLICY) uri.queryParam("network-policy-fqdn", fqdn) - String queryNetworkPolicyByFqdnAAIRequest = aaiUriUtil.createAaiUri(uri) - - msoLogger.debug("AAI request endpoint: " + queryNetworkPolicyByFqdnAAIRequest) - - APIResponse response = aaiUriUtil.executeAAIGetCall(execution, queryNetworkPolicyByFqdnAAIRequest) - int returnCode = response.getStatusCode() - execution.setVariable("DCVFM_aaiQueryNetworkPolicyByFqdnReturnCode", returnCode) - msoLogger.debug(" ***** AAI query network policy Response Code, NetworkPolicy #" + counting + " : " + returnCode) - - String aaiResponseAsString = response.getResponseBodyAsString() - - if (isOneOf(returnCode, 200, 201)) { - msoLogger.debug("The return code is: " + returnCode) - // This network policy FQDN exists in AAI - need to delete it now - msoLogger.debug(aaiResponseAsString) - execution.setVariable("DDVFMV_queryNetworkPolicyByFqdnAAIResponse", aaiResponseAsString) - msoLogger.debug("QueryAAINetworkPolicyByFQDN Success REST Response, , NetworkPolicy #" + counting + " : " + "\n" + aaiResponseAsString) - // Retrieve the network policy id for this FQDN - def networkPolicyId = utils.getNodeText(aaiResponseAsString, "network-policy-id") - msoLogger.debug("Deleting network-policy with network-policy-id " + networkPolicyId) - - // Retrieve the resource version for this network policy - def resourceVersion = utils.getNodeText(aaiResponseAsString, "resource-version") - msoLogger.debug("Deleting network-policy with resource-version " + resourceVersion) - - AAIResourceUri delUri = AAIUriFactory.createResourceUri(AAIObjectType.NETWORK_POLICY, networkPolicyId) - delUri.resourceVersion(resourceVersion) - String delNetworkPolicyAAIRequest = aaiUriUtil.createAaiUri(delUri) - - msoLogger.debug("AAI request endpoint: " + delNetworkPolicyAAIRequest) - - msoLogger.debug("invoking DELETE call to AAI") - msoLogger.debug("Sending DELETE call to AAI with Endpoint /n" + delNetworkPolicyAAIRequest) - APIResponse responseDel = aaiUriUtil.executeAAIDeleteCall(execution, delNetworkPolicyAAIRequest) - int returnCodeDel = responseDel.getStatusCode() - execution.setVariable("DDVFMV_aaiDeleteNetworkPolicyReturnCode", returnCodeDel) - msoLogger.debug(" ***** AAI delete network policy Response Code, NetworkPolicy #" + counting + " : " + returnCodeDel) - - if (isOneOf(returnCodeDel, 200, 201, 204)) { - msoLogger.debug("The return code from deleting network policy is: " + returnCodeDel) - // This network policy was deleted from AAI successfully - msoLogger.debug(" DelAAINetworkPolicy Success REST Response, , NetworkPolicy #" + counting + " : ") - - } else { - // aai all errors - String delErrorMessage = "Unable to delete network-policy to AAI deleteNetworkPoliciesFromAAI - " + returnCodeDel - msoLogger.debug(delErrorMessage) - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, delErrorMessage) - } - } else if (returnCode == 404) { - // This network policy FQDN is not in AAI. No need to delete. - msoLogger.debug("The return code is: " + returnCode) - msoLogger.debug("This network policy FQDN is not in AAI: " + fqdn) - msoLogger.debug("Network policy FQDN is not in AAI") - } else { - if (aaiResponseAsString.contains("RESTFault")) { - WorkflowException exceptionObject = exceptionUtil.MapAAIExceptionToWorkflowException(aaiResponseAsString, execution) - execution.setVariable("WorkflowException", exceptionObject) - throw new BpmnError("MSOWorkflowException") - - } else { - // aai all errors - String dataErrorMessage = "Unexpected Response from deleteNetworkPoliciesFromAAI - " + returnCode - msoLogger.debug(dataErrorMessage) - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) - - } - } - - - - } // end loop - + try { + Optional<NetworkPolicies> networkPolicies = getAAIClient().get(NetworkPolicies.class, uri) + + if (networkPolicies.isPresent() && !networkPolicies.get().getNetworkPolicy().isEmpty()) { + NetworkPolicy networkPolicy = networkPolicies.get().getNetworkPolicy().get(0) + execution.setVariable("DCVFM_aaiQueryNetworkPolicyByFqdnReturnCode", 200) + // This network policy FQDN exists in AAI - need to delete it now + // Retrieve the network policy id for this FQDN + def networkPolicyId = networkPolicy.getNetworkPolicyId() + msoLogger.debug("Deleting network-policy with network-policy-id " + networkPolicyId) + + // Retrieve the resource version for this network policy + try { + AAIResourceUri delUri = AAIUriFactory.createResourceUri(AAIObjectType.NETWORK_POLICY, networkPolicyId) + getAAIClient().delete(delUri) + execution.setVariable("DDVFMV_aaiDeleteNetworkPolicyReturnCode", 200) + msoLogger.debug(" ***** AAI delete network policy Response Code, NetworkPolicy #" + counting + " : " + 200) + // This network policy was deleted from AAI successfully + msoLogger.debug(" DelAAINetworkPolicy Success REST Response, , NetworkPolicy #" + counting + " : ") + } catch (Exception e) { + // aai all errors + String delErrorMessage = "Unable to delete network-policy to AAI deleteNetworkPoliciesFromAAI - " + e.getMessage() + msoLogger.debug(delErrorMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, delErrorMessage) + } + } else { + execution.setVariable("DCVFM_aaiQueryNetworkPolicyByFqdnReturnCode", 404) + // This network policy FQDN is not in AAI. No need to delete. + msoLogger.debug("This network policy FQDN is not in AAI: " + fqdn) + msoLogger.debug("Network policy FQDN is not in AAI") + } + } catch (Exception e) { + // aai all errors + String dataErrorMessage = "Unexpected Response from deleteNetworkPoliciesFromAAI - " + e.getMessage() + msoLogger.debug(dataErrorMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) + } + } // end loop } else { msoLogger.debug("No contrail network policies to query/create") diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteVfModuleVolumeV2.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteVfModuleVolumeV2.groovy index 73fd78f0c0..710d13470f 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteVfModuleVolumeV2.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteVfModuleVolumeV2.groovy @@ -20,9 +20,12 @@ package org.onap.so.bpmn.infrastructure.scripts -import org.apache.commons.lang3.* +import org.apache.commons.lang3.StringUtils import org.camunda.bpm.engine.delegate.BpmnError import org.camunda.bpm.engine.delegate.DelegateExecution +import org.onap.aai.domain.yang.Relationship +import org.onap.aai.domain.yang.RelationshipData +import org.onap.aai.domain.yang.VolumeGroup import org.onap.so.bpmn.common.scripts.AaiUtil import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor import org.onap.so.bpmn.common.scripts.ExceptionUtil @@ -30,13 +33,14 @@ import org.onap.so.bpmn.common.scripts.MsoUtils import org.onap.so.bpmn.core.UrnPropertiesReader; import org.onap.so.bpmn.core.WorkflowException import org.onap.so.bpmn.core.json.JsonUtils +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.client.aai.AAIObjectType import org.onap.so.constants.Defaults import org.onap.so.logger.MsoLogger -import org.onap.so.rest.APIResponse -import org.springframework.web.util.UriUtils +import javax.ws.rs.NotFoundException class DoDeleteVfModuleVolumeV2 extends AbstractServiceTaskProcessor{ private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, DoDeleteVfModuleVolumeV2.class); @@ -153,62 +157,52 @@ class DoDeleteVfModuleVolumeV2 extends AbstractServiceTaskProcessor{ } String cloudRegion = execution.getVariable(prefix+'aicCloudRegion') - AaiUtil aaiUtil = new AaiUtil(this) - - AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.VOLUME_GROUP, Defaults.CLOUD_OWNER.toString(), cloudRegion, volumeGroupId) - def queryAAIVolumeGroupRequest = aaiUtil.createAaiUri(uri) - - msoLogger.debug('Query AAI volume group by ID: ' + queryAAIVolumeGroupRequest) - msoLogger.debug('Query AAI volume group by ID: ' + queryAAIVolumeGroupRequest) - - APIResponse response = aaiUtil.executeAAIGetCall(execution, queryAAIVolumeGroupRequest) - - String returnCode = response.getStatusCode() - String aaiResponseAsString = response.getResponseBodyAsString() - - msoLogger.debug("AAI query volume group by id return code: " + returnCode) - msoLogger.debug("AAI query volume group by id response: " + aaiResponseAsString) - msoLogger.debug('AAI query volume group by id return code: ' + returnCode) - msoLogger.debug('AAI query volume group by id response: ' + aaiResponseAsString) - - execution.setVariable(prefix+"queryAAIVolGrpResponse", aaiResponseAsString) - - if (returnCode=='200' || returnCode == '204') { - - def heatStackId = getNodeTextForce(aaiResponseAsString, 'heat-stack-id') - execution.setVariable(prefix+'volumeGroupHeatStackId', heatStackId) - - msoLogger.debug('Heat stack id from AAI response: ' + heatStackId) - - if(hasVfModuleRelationship(aaiResponseAsString)){ - msoLogger.debug('Volume Group ' + volumeGroupId + ' currently in use') - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Volume Group ${volumeGroupId} currently in use - found vf-module relationship.") - } - - def volumeGroupTenantId = getTenantIdFromVolumeGroup(aaiResponseAsString) - msoLogger.debug('Tenant ID from AAI response: ' + volumeGroupTenantId) - - if (volumeGroupTenantId == null) { - msoLogger.debug("Could not find Tenant Id element in Volume Group with Volume Group Id ${volumeGroupId}") - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Could not find Tenant Id element in Volume Group with Volume Group Id ${volumeGroupId}") - } + try { + AAIResourceUri resourceUri = AAIUriFactory.createResourceUri(AAIObjectType.VOLUME_GROUP , Defaults.CLOUD_OWNER.toString(), cloudRegion,volumeGroupId) + Optional<VolumeGroup> volumeGroupOps = getAAIClient().get(VolumeGroup.class,resourceUri) + if(volumeGroupOps.present) { + VolumeGroup volumeGroup = volumeGroupOps.get() + execution.setVariable(prefix + "queryAAIVolGrpResponse", volumeGroup) + def heatStackId = volumeGroup.getHeatStackId()==null ? '' : volumeGroup.getHeatStackId() + execution.setVariable(prefix+'volumeGroupHeatStackId', heatStackId) + + msoLogger.debug('Heat stack id from AAI response: ' + heatStackId) + AAIResultWrapper wrapper = getAAIClient().get(uri); + Optional<Relationships> relationships = wrapper.getRelationships() + String volumeGroupTenantId = null + + if(relationships.isPresent()){ + if(relationships.get().getRelatedAAIUris(AAIObjectType.VF_MODULE)){ + msoLogger.debug('Volume Group ' + volumeGroupId + ' currently in use') + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Volume Group ${volumeGroupId} currently in use - found vf-module relationship.") + } + for(AAIResourceUri aaiResourceUri: relationships.get().getRelatedAAIUris(AAIObjectType.TENANT)){ + volumeGroupTenantId = aaiResourceUri.getURIKeys().get("tenant-id") + } + } - if (volumeGroupTenantId != tenantId) { - def String errorMessage = 'TenantId ' + tenantId + ' in incoming request does not match Tenant Id ' + volumeGroupTenantId + ' retrieved from AAI for Volume Group Id ' + volumeGroupId - msoLogger.debug("Error in DeleteVfModuleVolume: " + errorMessage) - exceptionUtil.buildAndThrowWorkflowException(execution, 5000, errorMessage) - } - msoLogger.debug('Received Tenant Id ' + volumeGroupTenantId + ' from AAI for Volume Group with Volume Group Id ' + volumeGroupId ) - } - else { - if (returnCode=='404') { - msoLogger.debug("Volume Group ${volumeGroupId} not found in AAI") - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Volume Group ${volumeGroupId} not found in AAI. Response code: 404") - } - else { - WorkflowException aWorkflowException = exceptionUtil.MapAAIExceptionToWorkflowException(aaiResponseAsString, execution) - throw new BpmnError("MSOWorkflowException") - } + msoLogger.debug('Tenant ID from AAI response: ' + volumeGroupTenantId) + + if (volumeGroupTenantId == null) { + msoLogger.debug("Could not find Tenant Id element in Volume Group with Volume Group Id ${volumeGroupId}") + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Could not find Tenant Id element in Volume Group with Volume Group Id ${volumeGroupId}") + } + + if (volumeGroupTenantId != tenantId) { + def String errorMessage = 'TenantId ' + tenantId + ' in incoming request does not match Tenant Id ' + volumeGroupTenantId + ' retrieved from AAI for Volume Group Id ' + volumeGroupId + msoLogger.debug("Error in DeleteVfModuleVolume: " + errorMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 5000, errorMessage) + } + msoLogger.debug('Received Tenant Id ' + volumeGroupTenantId + ' from AAI for Volume Group with Volume Group Id ' + volumeGroupId ) + }else{ + execution.setVariable(prefix + "queryAAIVolGrpResponse", "Volume Group ${volumeGroupId} not found in AAI. Response code: 404") + msoLogger.debug("Volume Group ${volumeGroupId} not found in AAI") + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Volume Group ${volumeGroupId} not found in AAI. Response code: 404") + } + }catch (Exception ex) { + execution.setVariable(prefix+"queryAAIVolGrpResponse", ex.getMessage()) + WorkflowException aWorkflowException = exceptionUtil.MapAAIExceptionToWorkflowException(ex.getMessage(), execution) + throw new BpmnError("MSOWorkflowException") } } @@ -262,94 +256,20 @@ class DoDeleteVfModuleVolumeV2 extends AbstractServiceTaskProcessor{ public void callRESTDeleteAAIVolumeGroup(DelegateExecution execution, isDebugEnabled) { // get variables - String queryAAIVolGrpIdResponse = execution.getVariable(prefix+"queryAAIVolGrpResponse") - String groupId = utils.getNodeText(queryAAIVolGrpIdResponse, "volume-group-id") - String resourceVersion = utils.getNodeText(queryAAIVolGrpIdResponse, "resource-version") - - String messageId = UUID.randomUUID().toString() + VolumeGroup volumeGroupResponse = execution.getVariable(prefix+"queryAAIVolGrpResponse") + String volumeGroupId = volumeGroupResponse.getVolumeGroupId() String cloudRegion = execution.getVariable(prefix+'aicCloudRegion') - AaiUtil aaiUtil = new AaiUtil(this) - - AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.VOLUME_GROUP, Defaults.CLOUD_OWNER.toString(), cloudRegion, groupId).resourceVersion(resourceVersion) - def deleteAAIVolumeGrpIdRequest = aaiUtil.createAaiUri(uri) - - msoLogger.debug('Delete AAI volume group : ' + deleteAAIVolumeGrpIdRequest) - msoLogger.debug("Delete AAI volume group : " + deleteAAIVolumeGrpIdRequest) - - APIResponse response = aaiUtil.executeAAIDeleteCall(execution, deleteAAIVolumeGrpIdRequest) - - String returnCode = response.getStatusCode() - String aaiResponseAsString = response.getResponseBodyAsString() - - msoLogger.debug("AAI delete volume group return code: " + returnCode) - msoLogger.debug("AAI delete volume group response: " + aaiResponseAsString) - - ExceptionUtil exceptionUtil = new ExceptionUtil() - if (returnCode=='200' || (returnCode == '204')) { - msoLogger.debug("Volume group $groupId deleted.") - } else { - if (returnCode=='404') { - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Volume group $groupId not found for delete in AAI Response code: 404") - } else { - WorkflowException aWorkflowException = exceptionUtil.MapAAIExceptionToWorkflowException(aaiResponseAsString, execution) - throw new BpmnError("MSOWorkflowException") - } - } - } - - - /** - * Check if volume group has a relationship to vf-module - * @param volumeGroupXml - * @return - */ - private boolean hasVfModuleRelationship(String volumeGroupXml) { - def Node volumeGroupNode = xmlParser.parseText(volumeGroupXml) - def Node relationshipList = utils.getChildNode(volumeGroupNode, 'relationship-list') - if (relationshipList != null) { - def NodeList relationships = utils.getIdenticalChildren(relationshipList, 'relationship') - for (Node relationship in relationships) { - def Node relatedTo = utils.getChildNode(relationship, 'related-to') - if ((relatedTo != null) && (relatedTo.text().equals('vf-module'))) { - def Node relatedLink = utils.getChildNode(relationship, 'related-link') - if (relatedLink !=null && relatedLink.text() != null){ - return true - } - } - } - } - return false + try { + AAIResourceUri resourceUri = AAIUriFactory.createResourceUri(AAIObjectType.VOLUME_GROUP,Defaults.CLOUD_OWNER.toString(), cloudRegion, volumeGroupId) + getAAIClient().delete(resourceUri) + msoLogger.debug("Volume group $volumeGroupId deleted.") + }catch (NotFoundException ex) { + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Volume group $volumeGroupId not found for delete in AAI Response code: 404") + }catch (Exception ex) { + WorkflowException aWorkflowException = exceptionUtil.MapAAIExceptionToWorkflowException(ex.getMessage(), execution) + throw new BpmnError("MSOWorkflowException") + } } - - /** - * Extract the Tenant Id from the Volume Group information returned by AAI. - * @param volumeGroupXml Volume Group XML returned by AAI. - * @return the Tenant Id extracted from the Volume Group information. 'null' is returned if - * the Tenant Id is missing or could not otherwise be extracted. - */ - private String getTenantIdFromVolumeGroup(String volumeGroupXml) { - def Node volumeGroupNode = xmlParser.parseText(volumeGroupXml) - def Node relationshipList = utils.getChildNode(volumeGroupNode, 'relationship-list') - if (relationshipList != null) { - def NodeList relationships = utils.getIdenticalChildren(relationshipList, 'relationship') - for (Node relationship in relationships) { - def Node relatedTo = utils.getChildNode(relationship, 'related-to') - if ((relatedTo != null) && (relatedTo.text().equals('tenant'))) { - def NodeList relationshipDataList = utils.getIdenticalChildren(relationship, 'relationship-data') - for (Node relationshipData in relationshipDataList) { - def Node relationshipKey = utils.getChildNode(relationshipData, 'relationship-key') - if ((relationshipKey != null) && (relationshipKey.text().equals('tenant.tenant-id'))) { - def Node relationshipValue = utils.getChildNode(relationshipData, 'relationship-value') - if (relationshipValue != null) { - return relationshipValue.text() - } - } - } - } - } - } - return null - } } diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteVnfAndModules.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteVnfAndModules.groovy index ddf2706635..6e0c6bb002 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteVnfAndModules.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteVnfAndModules.groovy @@ -20,13 +20,12 @@ package org.onap.so.bpmn.infrastructure.scripts -import static org.apache.commons.lang3.StringUtils.*; - +import org.onap.aai.domain.yang.GenericVnf +import org.onap.aai.domain.yang.VfModule import org.camunda.bpm.engine.delegate.BpmnError import org.camunda.bpm.engine.delegate.DelegateExecution; import org.json.JSONArray; -import org.json.JSONObject; -import org.onap.so.bpmn.common.scripts.AaiUtil +import org.json.JSONObject import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor import org.onap.so.bpmn.common.scripts.ExceptionUtil import org.onap.so.bpmn.common.scripts.MsoUtils @@ -45,8 +44,6 @@ import org.onap.so.client.aai.entities.uri.AAIUriFactory import org.onap.so.client.aai.AAIObjectType import org.onap.so.logger.MessageEnum import org.onap.so.logger.MsoLogger -import org.onap.so.rest.APIResponse -import org.springframework.web.util.UriUtils; /** * This class supports the macro VID Flow @@ -258,61 +255,34 @@ class DoDeleteVnfAndModules extends AbstractServiceTaskProcessor { try { def vnfId = execution.getVariable('vnfId') - AaiUtil aaiUriUtil = new AaiUtil(this) AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId).depth(Depth.ONE) - String endPoint = aaiUriUtil.createAaiUri(uri) - - msoLogger.debug("AAI endPoint: " + endPoint) try { - msoLogger.debug("createVfModule - invoking httpGet() to AAI") - APIResponse response = aaiUriUtil.executeAAIGetCall(execution, endPoint) - - def responseData = response.getResponseBodyAsString() - if (responseData != null) { - msoLogger.debug("Received generic VNF data: " + responseData) - - } - - msoLogger.debug("createVfModule - queryAAIVfModule Response: " + responseData) - msoLogger.debug("createVfModule - queryAAIVfModule ResponseCode: " + response.getStatusCode()) - - execution.setVariable('DCVFM_queryAAIVfModuleResponseCode', response.getStatusCode()) - execution.setVariable('DCVFM_queryAAIVfModuleResponse', responseData) - msoLogger.debug('Response code:' + response.getStatusCode()) - msoLogger.debug('Response:' + System.lineSeparator() + responseData) + Optional<GenericVnf> genericVnfOp = getAAIClient().get(GenericVnf.class,uri) //Map<String, String>[] vfModules = new HashMap<String,String>[] List<ModuleResource> vfModulesFromDecomposition = execution.getVariable("DDVAM_vfModulesFromDecomposition") def vfModulesList = new ArrayList<Map<String,String>>() - def vfModules = null def vfModuleBaseEntry = null - if (response.getStatusCode() == 200) { + if (genericVnfOp.isPresent()) { + execution.setVariable('DCVFM_queryAAIVfModuleResponseCode', 200) + execution.setVariable('DCVFM_queryAAIVfModuleResponse', genericVnfOp.get()) + // Parse the VNF record from A&AI to find base module info - msoLogger.debug('Parsing the VNF data to find base module info') - if (responseData != null) { - def vfModulesText = utils.getNodeXml(responseData, "vf-modules") - msoLogger.debug("vModulesText: " + vfModulesText) - if (vfModulesText != null && !vfModulesText.trim().isEmpty()) { - def xmlVfModules= new XmlSlurper().parseText(vfModulesText) - vfModules = xmlVfModules.'**'.findAll {it.name() == "vf-module"} + if (genericVnfOp.get().getVfModules()!= null && !genericVnfOp.get().getVfModules().getVfModule().isEmpty() ) { + List<VfModule> vfModules = genericVnfOp.get().getVfModules().getVfModule() execution.setVariable("DDVAM_moduleCount", vfModules.size()) - int vfModulesSize = 0 ModelInfo vfModuleModelInfo = null - for (i in 0..vfModules.size()-1) { - def vfModuleXml = groovy.xml.XmlUtil.serialize(vfModules[i]) - + for (VfModule vfModule : vfModules) { Map<String, String> vfModuleEntry = new HashMap<String, String>() - def vfModuleId = utils.getNodeText(vfModuleXml, "vf-module-id") - vfModuleEntry.put("vfModuleId", vfModuleId) - def vfModuleName = utils.getNodeText(vfModuleXml, "vf-module-name") - vfModuleEntry.put("vfModuleName", vfModuleName) + vfModuleEntry.put("vfModuleId", vfModule.getVfModuleId()) + vfModuleEntry.put("vfModuleName", vfModule.getVfModuleName()) // Find the model for this vf module in decomposition if specified if (vfModulesFromDecomposition != null) { msoLogger.debug("vfModulesFromDecomposition is not null") - def vfModuleUuid = utils.getNodeText(vfModuleXml, "model-version-id") + def vfModuleUuid = vfModule.getModelVersionId() if (vfModuleUuid == null) { - vfModuleUuid = utils.getNodeText(vfModuleXml, "persona-model-version") + vfModuleUuid = vfModule.getPersonaModelVersion() } msoLogger.debug("vfModule UUID is: " + vfModuleUuid) for (j in 0..vfModulesFromDecomposition.size()-1) { @@ -335,9 +305,8 @@ class DoDeleteVnfAndModules extends AbstractServiceTaskProcessor { } - def isBaseVfModule = utils.getNodeText(vfModuleXml, "is-base-vf-module") // Save base vf module for last - if (isBaseVfModule == "true") { + if (vfModule.isIsBaseVfModule()) { vfModuleBaseEntry = vfModuleEntry } else { @@ -348,8 +317,10 @@ class DoDeleteVnfAndModules extends AbstractServiceTaskProcessor { vfModulesList.add(vfModuleBaseEntry) } } - - } + }else{ + execution.setVariable('DCVFM_queryAAIVfModuleResponseCode', 404) + execution.setVariable('DCVFM_queryAAIVfModuleResponse', "Generic Vnf not found") + } execution.setVariable("DDVAM_vfModules", vfModulesList) } catch (Exception ex) { diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoScaleVFCNetworkServiceInstance.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoScaleVFCNetworkServiceInstance.groovy index a99f6e993e..19d30bb9b1 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoScaleVFCNetworkServiceInstance.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoScaleVFCNetworkServiceInstance.groovy @@ -29,8 +29,9 @@ import org.onap.so.bpmn.common.scripts.ExceptionUtil import org.onap.so.bpmn.core.json.JsonUtils import org.camunda.bpm.engine.delegate.BpmnError -import org.camunda.bpm.engine.runtime.Execution import com.fasterxml.jackson.databind.ObjectMapper +import org.onap.so.client.HttpClientFactory + import javax.ws.rs.core.Response import org.onap.so.bpmn.infrastructure.vfcmodel.ScaleResource @@ -201,7 +202,7 @@ public class DoScaleVFCNetworkServiceInstance extends AbstractServiceTaskProcess try{ URL url = new URL(urlString); - HttpClient httpClient = new HttpClient(url, "application/json", TargetEntity.VNF_ADAPTER) + HttpClient httpClient = new HttpClientFactory().newJsonClient(url, TargetEntity.VNF_ADAPTER) httpClient.addAdditionalHeader("Authorization", "Basic QlBFTENsaWVudDpwYXNzd29yZDEk") apiResponse = httpClient.post(requestBody) diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoUpdateE2EServiceInstance.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoUpdateE2EServiceInstance.groovy index 2c539a1022..baa695af09 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoUpdateE2EServiceInstance.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoUpdateE2EServiceInstance.groovy @@ -310,8 +310,8 @@ public class DoUpdateE2EServiceInstance extends AbstractServiceTaskProcessor { try { org.onap.aai.domain.yang.ServiceInstance si = execution.getVariable("serviceInstanceData") - AAIResourcesClient client = new AAIResourcesClient() - AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, serviceInstanceId) + AAIResourcesClient client = new AAIResourcesClient() + AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, serviceInstanceId) client.update(uri, si) } catch (BpmnError e) { diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoUpdateNetworkInstance.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoUpdateNetworkInstance.groovy index dbacd48809..6dd8085bae 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoUpdateNetworkInstance.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoUpdateNetworkInstance.groovy @@ -21,7 +21,8 @@ package org.onap.so.bpmn.infrastructure.scripts; import javax.ws.rs.core.UriBuilder - +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 @@ -43,10 +44,20 @@ import org.onap.so.client.aai.entities.AAIResultWrapper import org.onap.so.client.graphinventory.entities.uri.Depth import org.onap.so.constants.Defaults import org.onap.so.logger.MsoLogger -import org.onap.so.rest.APIResponse + import org.springframework.web.util.UriUtils +import org.w3c.dom.Document +import org.w3c.dom.Element +import org.w3c.dom.NamedNodeMap +import org.w3c.dom.Node +import org.w3c.dom.NodeList; +import org.xml.sax.InputSource import org.onap.aai.domain.yang.VpnBinding +import org.onap.aai.domain.yang.L3Network +import org.onap.aai.domain.yang.NetworkPolicy +import org.onap.aai.domain.yang.RouteTableReference import org.onap.aai.domain.yang.RouteTarget +import org.onap.aai.domain.yang.Subnet import javax.ws.rs.NotFoundException import groovy.json.* @@ -405,56 +416,21 @@ public class DoUpdateNetworkInstance extends AbstractServiceTaskProcessor { // get variables String networkRequest = execution.getVariable(Prefix + "networkRequest") String networkId = utils.getNodeText(networkRequest, "network-id") - networkId = UriUtils.encode(networkId,"UTF-8") execution.setVariable(Prefix + "networkId", networkId) - // Prepare AA&I url - AaiUtil aaiUriUtil = new AaiUtil(this) - AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.L3_NETWORK, networkId) - uri.depth(Depth.ALL) - String queryIdAAIRequest = aaiUriUtil.createAaiUri(uri) - - msoLogger.debug(queryIdAAIRequest) - execution.setVariable(Prefix + "queryIdAAIRequest", queryIdAAIRequest) - msoLogger.debug(Prefix + "queryIdAAIRequest - " + "\n" + queryIdAAIRequest) - - APIResponse response = aaiUriUtil.executeAAIGetCall(execution, queryIdAAIRequest) - String returnCode = response.getStatusCode() - execution.setVariable(Prefix + "aaiIdReturnCode", returnCode) - msoLogger.debug(" ***** AAI Response Code : " + returnCode) - - String aaiResponseAsString = response.getResponseBodyAsString() + AAIResourcesClient client = new AAIResourcesClient() + AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.L3_NETWORK, networkId).depth(Depth.ONE) + AAIResultWrapper network = client.get(uri, NotFoundException.class) - if (returnCode=='200') { - msoLogger.debug(aaiResponseAsString) - execution.setVariable(Prefix + "queryIdAAIResponse", aaiResponseAsString) - msoLogger.debug(" QueryAAINetworkId Success REST Response - " + "\n" + aaiResponseAsString) + execution.setVariable(Prefix + "aaiIdReturnCode", "200") - } else { - if (returnCode=='404') { - String dataErrorMessage = "Response Error from QueryAAINetworkId is 404 (Not Found)." - msoLogger.debug(" AAI Query Failed. " + dataErrorMessage) - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) + execution.setVariable(Prefix + "queryIdAAIResponse", network) - } else { - if (aaiResponseAsString.contains("RESTFault")) { - WorkflowException exceptionObject = exceptionUtil.MapAAIExceptionToWorkflowException(aaiResponseAsString, execution) - execution.setVariable("WorkflowException", exceptionObject) - throw new BpmnError("MSOWorkflowException") - - } else { - // aai all errors - String dataErrorMessage = "Unexpected Response from QueryAAINetworkId - " + returnCode - msoLogger.debug("Unexpected Response from QueryAAINetworkId - " + dataErrorMessage) - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) - - } - } - } - - } catch (BpmnError e) { - throw e; + } catch (NotFoundException e) { + String dataErrorMessage = "Response Error from QueryAAINetworkId is 404 (Not Found)." + msoLogger.debug(" AAI Query Failed. " + dataErrorMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) } catch (Exception ex) { String exceptionMessage = "Bpmn error encountered in DoUpdateNetworkInstance flow. callRESTQueryAAINetworkId() - " + ex.getMessage() msoLogger.debug(exceptionMessage) @@ -474,65 +450,29 @@ public class DoUpdateNetworkInstance extends AbstractServiceTaskProcessor { // get variables String networkRequest = execution.getVariable(Prefix + "networkRequest") String networkId = utils.getNodeText(networkRequest, "network-id") - networkId = UriUtils.encode(networkId,"UTF-8") - - // Prepare AA&I url - AaiUtil aaiUriUtil = new AaiUtil(this) - AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.L3_NETWORK, networkId) - uri.depth(Depth.ALL) - String requeryIdAAIRequest = aaiUriUtil.createAaiUri(uri) - - msoLogger.debug(requeryIdAAIRequest) - execution.setVariable(Prefix + "requeryIdAAIRequest", requeryIdAAIRequest) - msoLogger.debug(" UPDNETI_requeryIdAAIRequest - " + "\n" + requeryIdAAIRequest) - - APIResponse response = aaiUriUtil.executeAAIGetCall(execution, requeryIdAAIRequest) - String returnCode = response.getStatusCode() - execution.setVariable(Prefix + "aaiRequeryIdReturnCode", returnCode) - msoLogger.debug(" ***** AAI ReQuery Response Code : " + returnCode) - String aaiResponseAsString = response.getResponseBodyAsString() + AAIResourcesClient client = new AAIResourcesClient() + AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.L3_NETWORK, networkId).depth(Depth.ONE) + AAIResultWrapper network = client.get(uri, NotFoundException.class) - if (returnCode=='200') { - msoLogger.debug(aaiResponseAsString) - execution.setVariable(Prefix + "requeryIdAAIResponse", aaiResponseAsString) - msoLogger.debug(" ReQueryAAINetworkId Success REST Response - " + "\n" + aaiResponseAsString) + execution.setVariable(Prefix + "aaiRequeryIdReturnCode", "200") + execution.setVariable(Prefix + "requeryIdAAIResponse", network) - String netId = utils.getNodeText(aaiResponseAsString, "network-id") - String netName = utils.getNodeText(aaiResponseAsString, "network-name") - String networkOutputs = - """<network-outputs> + L3Network net = network.asBean(L3Network.class).get() + String netId = net.getNetworkId() + String netName = net.getNetworkName() + String networkOutputs = + """<network-outputs> <network-id>${MsoUtils.xmlEscape(netId)}</network-id> <network-name>${MsoUtils.xmlEscape(netName)}</network-name> </network-outputs>""" - execution.setVariable(Prefix + "networkOutputs", networkOutputs) - msoLogger.debug(" networkOutputs - " + '\n' + networkOutputs) - - } else { - if (returnCode=='404') { - String dataErrorMessage = "Response Error from ReQueryAAINetworkId is 404 (Not Found)." - msoLogger.debug(" AAI ReQuery Failed. - " + dataErrorMessage) - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) - - } else { - if (aaiResponseAsString.contains("RESTFault")) { - WorkflowException exceptionObject = exceptionUtil.MapAAIExceptionToWorkflowException(aaiResponseAsString, execution) - execution.setVariable("WorkflowException", exceptionObject) - throw new BpmnError("MSOWorkflowException") - - } else { - // aai all errors - String dataErrorMessage = "Unexpected Response from ReQueryAAINetworkId - " + returnCode - msoLogger.debug(dataErrorMessage) - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) - - } - } - } - - } catch (BpmnError e) { - throw e; + execution.setVariable(Prefix + "networkOutputs", networkOutputs) + msoLogger.debug(" networkOutputs - " + '\n' + networkOutputs) + } catch (NotFoundException e) { + String dataErrorMessage = "Response Error from ReQueryAAINetworkId is 404 (Not Found)." + msoLogger.debug(" AAI ReQuery Failed. - " + dataErrorMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) } catch (Exception ex) { String exceptionMessage = "Bpmn error encountered in DoUpdateNetworkInstance flow. callRESTReQueryAAINetworkId() - " + ex.getMessage() msoLogger.debug(exceptionMessage) @@ -551,71 +491,56 @@ public class DoUpdateNetworkInstance extends AbstractServiceTaskProcessor { try { // get variables - String queryIdAAIResponse = execution.getVariable(Prefix + "requeryIdAAIResponse").replace('<?xml version="1.0" encoding="UTF-8"?>', "") - String relationship = networkUtils.getFirstNodeXml(queryIdAAIResponse, "relationship-list").trim().replace("tag0:","").replace(":tag0","") - msoLogger.debug(" relationship - " + relationship) - - // Check if Vnf Binding is present, then build a List of vnfBinding - List vpnBindingUri = networkUtils.getVnfBindingObject(relationship) - int vpnCount = vpnBindingUri.size() - execution.setVariable(Prefix + "vpnCount", vpnCount) - msoLogger.debug(" UPDNETI_vpnCount - " + vpnCount) - - if (vpnCount > 0) { - execution.setVariable(Prefix + "vpnBindings", vpnBindingUri) - msoLogger.debug(" vpnBindingUri List - " + vpnBindingUri) - - String routeTargets = "" - // AII loop call using list vpnBindings - for(i in 0..vpnBindingUri.size()-1) { - int counting = i+1 - - String vpnBindingId = vpnBindingUri[i].substring(vpnBindingUri[i].indexOf("/vpn-binding/")+13, vpnBindingUri[i].length()) - if (vpnBindingId.charAt(vpnBindingId.length()-1) == '/') { - vpnBindingId = vpnBindingId.substring(0, vpnBindingId.length()-1) - } - - AAIResourcesClient resourceClient = new AAIResourcesClient() - AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.VPN_BINDING, vpnBindingId) - AAIResultWrapper wrapper = resourceClient.get(uri.depth(Depth.TWO), NotFoundException.class) - - Optional<VpnBinding> binding = wrapper.asBean(VpnBinding.class) - - String routeTarget = "" - String routeRole = "" - if(binding.get().getRouteTargets() != null) { - List<RouteTarget> targets = binding.get().getRouteTargets().getRouteTarget() - for(RouteTarget target : targets) { - routeTarget = target.getGlobalRouteTarget() - routeRole = target.getRouteTargetRole() - routeTargets += "<routeTargets>" + '\n' + - " <routeTarget>" + routeTarget + "</routeTarget>" + '\n' + - " <routeTargetRole>" + routeRole + "</routeTargetRole>" + '\n' + - "</routeTargets>" + '\n' + AAIResultWrapper queryIdAAIResponse = execution.getVariable(Prefix + "requeryIdAAIResponse") + if(queryIdAAIResponse.getRelationships().isPresent()){ + List<AAIResourceUri> uris = queryIdAAIResponse.getRelationships().get().getRelatedAAIUris(AAIObjectType.VPN_BINDING) + + msoLogger.debug(Prefix + "vpnCount - " + uris.size()) + + if (uris.size() > 0) { + String routeTargets = "" + for(AAIResourceUri u : uris) { + + AAIResourcesClient client = new AAIResourcesClient() + AAIResultWrapper wrapper = client.get(u.depth(Depth.TWO), NotFoundException.class) + Optional<VpnBinding> binding = wrapper.asBean(VpnBinding.class) + + String routeTarget = "" + String routeRole = "" + if(binding.get().getRouteTargets() != null) { + List<RouteTarget> targets = binding.get().getRouteTargets().getRouteTarget() + for(RouteTarget target : targets) { + routeTarget = target.getGlobalRouteTarget() + routeRole = target.getRouteTargetRole() + routeTargets += "<routeTargets>" + '\n' + + " <routeTarget>" + routeTarget + "</routeTarget>" + '\n' + + " <routeTargetRole>" + routeRole + "</routeTargetRole>" + '\n' + + "</routeTargets>" + '\n' + } } - } - } // end loop + } // end loop - execution.setVariable(Prefix + "routeCollection", routeTargets) - msoLogger.debug(" UPDNETI_routeCollection - " + '\n' + routeTargets) + execution.setVariable(Prefix + "routeCollection", routeTargets) + msoLogger.debug(" UPDNETI_routeCollection - " + '\n' + routeTargets) - } else { - // reset return code to success - execution.setVariable(Prefix + "aaiQqueryVpnBindingReturnCode", "200") - AaiUtil aaiUriUtil = new AaiUtil(this) - String schemaVersion = aaiUriUtil.getNamespace() - String aaiStubResponse = - """ <rest:payload contentType="text/xml" xmlns:rest="http://schemas.activebpel.org/REST/2007/12/01/aeREST.xsd"> + } else { + // reset return code to success + execution.setVariable(Prefix + "aaiQqueryVpnBindingReturnCode", "200") + AaiUtil aaiUriUtil = new AaiUtil(this) + String schemaVersion = aaiUriUtil.getNamespace() + String aaiStubResponse = + """ <rest:payload contentType="text/xml" xmlns:rest="http://schemas.activebpel.org/REST/2007/12/01/aeREST.xsd"> <vpn-binding xmlns="${schemaVersion}"> <global-route-target/> </vpn-binding> </rest:payload>""" - String aaiStubResponseAsXml = utils.formatXml(aaiStubResponse) - execution.setVariable(Prefix + "queryVpnBindingAAIResponse", aaiStubResponseAsXml) - execution.setVariable(Prefix + "routeCollection", "<routeTargets/>") - msoLogger.debug(" No vpnBinding, using this stub as response - " + '\n' + aaiStubResponseAsXml) + String aaiStubResponseAsXml = utils.formatXml(aaiStubResponse) + execution.setVariable(Prefix + "queryVpnBindingAAIResponse", aaiStubResponseAsXml) + execution.setVariable(Prefix + "routeCollection", "<routeTargets/>") + msoLogger.debug(" No vpnBinding, using this stub as response - " + '\n' + aaiStubResponseAsXml) + } } } catch (NotFoundException e) { @@ -638,103 +563,55 @@ public class DoUpdateNetworkInstance extends AbstractServiceTaskProcessor { try { // get variables - String queryIdAAIResponse = execution.getVariable(Prefix + "requeryIdAAIResponse").replace('<?xml version="1.0" encoding="UTF-8"?>', "") - String relationship = networkUtils.getFirstNodeXml(queryIdAAIResponse, "relationship-list").trim().replace("tag0:","").replace(":tag0","") - msoLogger.debug(" relationship - " + relationship) - - // Check if Network Policy is present, then build a List of network policy - List networkPolicyUriList = networkUtils.getNetworkPolicyObject(relationship) - int networkPolicyCount = networkPolicyUriList.size() - execution.setVariable(Prefix + "networkPolicyCount", networkPolicyCount) - msoLogger.debug(" UPDNETI_networkPolicyCount - " + networkPolicyCount) - - AaiUtil aaiUriUtil = new AaiUtil(this) + AAIResultWrapper queryIdAAIResponse = execution.getVariable(Prefix + "requeryIdAAIResponse") + if(queryIdAAIResponse.getRelationships().isPresent()){ + List<AAIResourceUri> uris = queryIdAAIResponse.getRelationships().get().getRelatedAAIUris(AAIObjectType.NETWORK_POLICY) - if (networkPolicyCount > 0) { - execution.setVariable(Prefix + "networkPolicyUriList", networkPolicyUriList) - msoLogger.debug(" networkPolicyUri List - " + networkPolicyUriList) + execution.setVariable(Prefix + "networkPolicyCount", uris.size()) + msoLogger.debug(Prefix + "networkPolicyCount - " + uris.size()) - String networkPolicies = "" - // AII loop call using list vpnBindings - for (i in 0..networkPolicyUriList.size()-1) { + if (uris.size() > 0) { - int counting = i+1 + String networkPolicies = "" + // AII loop call using list vpnBindings + for(AAIResourceUri u : uris) { - URI uri = UriBuilder.fromUri(networkPolicyUriList[i]).build() + AAIResourcesClient client = new AAIResourcesClient() + NetworkPolicy p = client.get(u, NotFoundException.class).asBean(NetworkPolicy.class).get() - AAIResourceUri aaiUri = AAIUriFactory.createResourceFromExistingURI(AAIObjectType.NETWORK_POLICY, uri) - aaiUri.depth(Depth.ALL) - String queryNetworkPolicyAAIRequest = aaiUriUtil.createAaiUri(aaiUri) + execution.setVariable(Prefix + "aaiQqueryNetworkPolicyReturnCode", "200") - msoLogger.debug(queryNetworkPolicyAAIRequest) - execution.setVariable(Prefix + "queryNetworkPolicyAAIRequest", queryNetworkPolicyAAIRequest) - msoLogger.debug(" UPDNETI_queryNetworkPolicyAAIRequest, , NetworkPolicy #" + counting + " : " + "\n" + queryNetworkPolicyAAIRequest) + String networkPolicy = p.getNetworkPolicyFqdn() + networkPolicies += "<policyFqdns>" + networkPolicy + "</policyFqdns>" + '\n' - APIResponse response = aaiUriUtil.executeAAIGetCall(execution, queryNetworkPolicyAAIRequest) - String returnCode = response.getStatusCode() - execution.setVariable(Prefix + "aaiQqueryNetworkPolicyReturnCode", returnCode) - msoLogger.debug(" ***** AAI query network policy Response Code, NetworkPolicy #" + counting + " : " + returnCode) + } // end loop - String aaiResponseAsString = response.getResponseBodyAsString() - - if (returnCode=='200') { - msoLogger.debug(aaiResponseAsString) - execution.setVariable(Prefix + "queryNetworkPolicyAAIResponse", aaiResponseAsString) - msoLogger.debug(" QueryAAINetworkPolicy Success REST Response, , NetworkPolicy #" + counting + " : " + "\n" + aaiResponseAsString) - - String networkPolicy = "" - if (utils.nodeExists(aaiResponseAsString, "network-policy-fqdn")) { - networkPolicy = utils.getNodeText(aaiResponseAsString, "network-policy-fqdn") - networkPolicies += "<policyFqdns>" + networkPolicy + "</policyFqdns>" + '\n' - } + execution.setVariable(Prefix + "networkCollection", networkPolicies) + msoLogger.debug(" UPDNETI_networkCollection - " + '\n' + networkPolicies) - } else { - if (returnCode=='404') { - String dataErrorMessage = "Response Error from QueryAAINetworkPolicy is 404 (Not Found)." - msoLogger.debug(dataErrorMessage) - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) - - } else { - if (aaiResponseAsString.contains("RESTFault")) { - WorkflowException exceptionObject = exceptionUtil.MapAAIExceptionToWorkflowException(aaiResponseAsString, execution) - execution.setVariable("WorkflowException", exceptionObject) - throw new BpmnError("MSOWorkflowException") - - } else { - // aai all errors - String dataErrorMessage = "Unexpected Response from QueryAAINetworkPolicy - " + returnCode - msoLogger.debug(dataErrorMessage) - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) - - } - } - } - - } // end loop - - execution.setVariable(Prefix + "networkCollection", networkPolicies) - msoLogger.debug(" UPDNETI_networkCollection - " + '\n' + networkPolicies) - - } else { - // reset return code to success - execution.setVariable(Prefix + "aaiQqueryNetworkPolicyReturnCode", "200") - String schemaVersion = aaiUriUtil.getNamespace() - String aaiStubResponse = - """ <rest:payload contentType="text/xml" xmlns:rest="http://schemas.activebpel.org/REST/2007/12/01/aeREST.xsd"> + } else { + // reset return code to success + execution.setVariable(Prefix + "aaiQqueryNetworkPolicyReturnCode", "200") + AaiUtil aaiUriUtil = new AaiUtil(this) + String schemaVersion = aaiUriUtil.getNamespace() + String aaiStubResponse = + """ <rest:payload contentType="text/xml" xmlns:rest="http://schemas.activebpel.org/REST/2007/12/01/aeREST.xsd"> <network-policy xmlns="${schemaVersion}"> <network-policy-fqdn/> </network-policy> </rest:payload>""" - String aaiStubResponseAsXml = utils.formatXml(aaiStubResponse) - execution.setVariable(Prefix + "queryNetworkPolicyAAIResponse", aaiStubResponseAsXml) - execution.setVariable(Prefix + "networkCollection", "<policyFqdns/>") - msoLogger.debug(" No net policies, using this stub as response - " + '\n' + aaiStubResponseAsXml) + String aaiStubResponseAsXml = utils.formatXml(aaiStubResponse) + execution.setVariable(Prefix + "queryNetworkPolicyAAIResponse", aaiStubResponseAsXml) + execution.setVariable(Prefix + "networkCollection", "<policyFqdns/>") + msoLogger.debug(" No net policies, using this stub as response - " + '\n' + aaiStubResponseAsXml) + } } - } catch (BpmnError e) { - throw e; - + } catch (NotFoundException e) { + String dataErrorMessage = "Response Error from QueryAAINetworkPolicy is 404 (Not Found)." + msoLogger.debug(dataErrorMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) } catch (Exception ex) { String exceptionMessage = "Bpmn error encountered in DoUpdateNetworkInstance flow. callRESTQueryAAINetworkPolicy() - " + ex.getMessage() msoLogger.debug(exceptionMessage) @@ -751,105 +628,56 @@ public class DoUpdateNetworkInstance extends AbstractServiceTaskProcessor { msoLogger.debug(" ***** Inside callRESTQueryAAINetworkTableRef of DoUpdateNetworkInstance ***** " ) try { - // get variables - String queryIdAAIResponse = execution.getVariable(Prefix + "requeryIdAAIResponse").replace('<?xml version="1.0" encoding="UTF-8"?>', "") - String relationship = networkUtils.getFirstNodeXml(queryIdAAIResponse, "relationship-list").trim().replace("tag0:","").replace(":tag0","") - msoLogger.debug(" relationship - " + relationship) + AAIResultWrapper queryIdAAIResponse = execution.getVariable(Prefix + "requeryIdAAIResponse") + if(queryIdAAIResponse.getRelationships().isPresent()){ + List<AAIResourceUri> uris = queryIdAAIResponse.getRelationships().get().getRelatedAAIUris(AAIObjectType.ROUTE_TABLE_REFERENCE) - // Check if Network TableREf is present, then build a List of network policy - List networkTableRefUriList = networkUtils.getNetworkTableRefObject(relationship) - int networkTableRefCount = networkTableRefUriList.size() - execution.setVariable(Prefix + "networkTableRefCount", networkTableRefCount) - msoLogger.debug(" UPDNETI_networkTableRefCount - " + networkTableRefCount) + execution.setVariable(Prefix + "networkTableRefCount", uris.size()) + msoLogger.debug(Prefix + "networkTableRefCount - " + uris.size()) - String aai_endpoint = UrnPropertiesReader.getVariable("aai.endpoint", execution) - AaiUtil aaiUriUtil = new AaiUtil(this) - - if (networkTableRefCount > 0) { - execution.setVariable(Prefix + "networkTableRefUriList", networkTableRefUriList) - msoLogger.debug(" networkTableRefUri List - " + networkTableRefUriList) - - // AII loop call using list vpnBindings - String networkTableRefs = "" - for (i in 0..networkTableRefUriList.size()-1) { - - int counting = i+1 + msoLogger.debug(" UPDNETI_networkTableRefCount - " + uris.size()) + if (uris.size() > 0) { - // prepare url using tableRef - URI uri = UriBuilder.fromUri(networkTableRefUriList[i]).build() + execution.setVariable(Prefix + "aaiQqueryNetworkTableRefReturnCode", "200") - AAIResourceUri aaiUri = AAIUriFactory.createResourceFromExistingURI(AAIObjectType.ROUTE_TABLE_REFERENCE, uri) - aaiUri.depth(Depth.ALL) - String queryNetworkTableRefAAIRequest = aaiUriUtil.createAaiUri(aaiUri) + // AII loop call using list vpnBindings + String networkTableRefs = "" + for(AAIResourceUri u : uris) { - msoLogger.debug(queryNetworkTableRefAAIRequest) - execution.setVariable(Prefix + "queryNetworkTableRefAAIRequest", queryNetworkTableRefAAIRequest) - msoLogger.debug(" UPDNETI_queryNetworkTableRefAAIRequest, , NetworkTableRef #" + counting + " : " + "\n" + queryNetworkTableRefAAIRequest) + AAIResourcesClient client = new AAIResourcesClient() + RouteTableReference rt = client.get(u, NotFoundException.class).asBean(RouteTableReference.class).get() - APIResponse response = aaiUriUtil.executeAAIGetCall(execution, queryNetworkTableRefAAIRequest) - String returnCode = response.getStatusCode() - execution.setVariable(Prefix + "aaiQqueryNetworkTableRefReturnCode", returnCode) - msoLogger.debug(" ***** AAI query network Table Reference Response Code, NetworkTableRef #" + counting + " : " + returnCode) + String networkTableRef = rt.getRouteTableReferenceFqdn() + networkTableRefs += "<routeTableFqdns>" + networkTableRef + "</routeTableFqdns>" + '\n' - String aaiResponseAsString = response.getResponseBodyAsString() + } // end loop - if (returnCode=='200') { - msoLogger.debug(aaiResponseAsString) - execution.setVariable(Prefix + "queryNetworkTableRefAAIResponse", aaiResponseAsString) - msoLogger.debug(" QueryAAINetworkTableRef Success REST Response, , NetworkTableRef #" + counting + " : " + "\n" + aaiResponseAsString) + execution.setVariable(Prefix + "tableRefCollection", networkTableRefs) + msoLogger.debug(" UPDNETI_tableRefCollection - " + '\n' + networkTableRefs) - String networkTableRef = "" - if (utils.nodeExists(aaiResponseAsString, "route-table-reference-fqdn")) { - networkTableRef = utils.getNodeText(aaiResponseAsString, "route-table-reference-fqdn") - networkTableRefs += "<routeTableFqdns>" + networkTableRef + "</routeTableFqdns>" + '\n' - } - - } else { - if (returnCode=='404') { - String dataErrorMessage = "Response Error from QueryAAINetworkTableRef is 404 (Not Found)." - msoLogger.debug(dataErrorMessage) - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) - - } else { - if (aaiResponseAsString.contains("RESTFault")) { - WorkflowException exceptionObject = exceptionUtil.MapAAIExceptionToWorkflowException(aaiResponseAsString, execution) - execution.setVariable("WorkflowException", exceptionObject) - throw new BpmnError("MSOWorkflowException") - - } else { - // aai all errors - String dataErrorMessage = "Unexpected Response from QueryAAINetworkTableRef - " + returnCode - msoLogger.debug(dataErrorMessage) - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) - - } - } - } - - } // end loop - - execution.setVariable(Prefix + "tableRefCollection", networkTableRefs) - msoLogger.debug(" UPDNETI_tableRefCollection - " + '\n' + networkTableRefs) - - } else { - // reset return code to success - execution.setVariable(Prefix + "aaiQqueryNetworkTableRefReturnCode", "200") - String schemaVersion = aaiUriUtil.getNamespace() - String aaiStubResponse = - """ <rest:payload contentType="text/xml" xmlns:rest="http://schemas.activebpel.org/REST/2007/12/01/aeREST.xsd"> + } else { + // reset return code to success + execution.setVariable(Prefix + "aaiQqueryNetworkTableRefReturnCode", "200") + AaiUtil aaiUriUtil = new AaiUtil(this) + String schemaVersion = aaiUriUtil.getNamespace() + String aaiStubResponse = + """ <rest:payload contentType="text/xml" xmlns:rest="http://schemas.activebpel.org/REST/2007/12/01/aeREST.xsd"> <route-table-references xmlns="${schemaVersion}"> <route-table-reference-fqdn/> </route-table-references> </rest:payload>""" - String aaiStubResponseAsXml = utils.formatXml(aaiStubResponse) - execution.setVariable(Prefix + "queryNetworkTableRefAAIResponse", aaiStubResponseAsXml) - execution.setVariable(Prefix + "tableRefCollection", "<routeTableFqdns/>") - msoLogger.debug(" No net table references, using this stub as response - " + '\n' + aaiStubResponseAsXml) + String aaiStubResponseAsXml = utils.formatXml(aaiStubResponse) + execution.setVariable(Prefix + "queryNetworkTableRefAAIResponse", aaiStubResponseAsXml) + execution.setVariable(Prefix + "tableRefCollection", "<routeTableFqdns/>") + msoLogger.debug(" No net table references, using this stub as response - " + '\n' + aaiStubResponseAsXml) + } } - } catch (BpmnError e) { - throw e; + } catch (NotFoundException e) { + String dataErrorMessage = "Response Error from QueryAAINetworkTableRef is 404 (Not Found)." + msoLogger.debug(dataErrorMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) } catch (Exception ex) { String exceptionMessage = "Bpmn error encountered in DoUpdateNetworkInstance flow. callRESTQueryAAINetworkTableRef() - " + ex.getMessage() @@ -861,76 +689,73 @@ public class DoUpdateNetworkInstance extends AbstractServiceTaskProcessor { } public void callRESTUpdateContrailAAINetwork(DelegateExecution execution) { - execution.setVariable("prefix", Prefix) - msoLogger.debug(" ***** Inside callRESTUpdateContrailAAINetwork of DoUpdateNetworkInstance ***** " ) - try { // get variables String networkRequest = execution.getVariable(Prefix + "networkRequest") String networkId = utils.getNodeText(networkRequest, "network-id") - networkId = UriUtils.encode(networkId,"UTF-8") - String requeryIdAAIResponse = execution.getVariable(Prefix + "requeryIdAAIResponse") + AAIResultWrapper requeryIdAAIResponse = execution.getVariable(Prefix + "requeryIdAAIResponse") String updateNetworkResponse = execution.getVariable(Prefix + "updateNetworkResponse") - // Prepare url - AaiUtil aaiUriUtil = new AaiUtil(this) - AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.L3_NETWORK, networkId) - uri.depth(Depth.ALL) - String updateContrailAAIUrlRequest = aaiUriUtil.createAaiUri(uri) - - msoLogger.debug(updateContrailAAIUrlRequest) - execution.setVariable(Prefix + "updateContrailAAIUrlRequest", updateContrailAAIUrlRequest) - msoLogger.debug(" UPDNETI_updateContrailAAIUrlRequest - " + "\n" + updateContrailAAIUrlRequest) - - //Prepare payload (PUT) - String schemaVersion = aaiUriUtil.getNamespaceFromUri(updateContrailAAIUrlRequest) - String payload = networkUtils.ContrailNetworkCreatedUpdate(requeryIdAAIResponse, updateNetworkResponse, schemaVersion) - String payloadXml = utils.formatXml(payload) - msoLogger.debug(payloadXml) - execution.setVariable(Prefix + "updateContrailAAIPayloadRequest", payloadXml) - msoLogger.debug(" 'payload' to Update Contrail - " + "\n" + payloadXml) - - APIResponse response = aaiUriUtil.executeAAIPutCall(execution, updateContrailAAIUrlRequest, payload) - String returnCode = response.getStatusCode() - String aaiUpdateContrailResponseAsString = response.getResponseBodyAsString() - - execution.setVariable(Prefix + "aaiUpdateContrailReturnCode", returnCode) - msoLogger.debug(" ***** AAI Update Contrail Response Code : " + returnCode) - - - if (returnCode=='200') { - msoLogger.debug(aaiUpdateContrailResponseAsString) - execution.setVariable(Prefix + "updateContrailAAIResponse", aaiUpdateContrailResponseAsString) - msoLogger.debug(" AAI Update Contrail Success REST Response - " + "\n" + aaiUpdateContrailResponseAsString) - // Point-of-no-return is set to false, rollback not needed. - execution.setVariable(Prefix + "isPONR", true) - + L3Network oldL3Network = requeryIdAAIResponse.asBean(L3Network.class).get() + L3Network l3Network = new L3Network() + if (oldL3Network.getHeatStackId() != null) { } else { - if (returnCode=='404') { - String dataErrorMessage = " Response Error from UpdateContrailAAINetwork is 404 (Not Found)." - msoLogger.debug(dataErrorMessage) - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) + if (utils.nodeExists(updateNetworkResponse, 'networkStackId')) { + l3Network.setHeatStackId(utils.getNodeText(updateNetworkResponse, 'networkStackId')) + } + } + if (oldL3Network.getNeutronNetworkId() != null) { + } else { + if (utils.nodeExists(updateNetworkResponse, 'neutronNetworkId')) { + l3Network.setNeutronNetworkId(utils.getNodeText(updateNetworkResponse, 'neutronNetworkId')) + } + } + if (oldL3Network.getContrailNetworkFqdn() != null) { + } else { + if (utils.nodeExists(updateNetworkResponse, 'networkFqdn')) { + l3Network.setContrailNetworkFqdn(utils.getNodeText(updateNetworkResponse, 'networkFqdn')) + } + } - } else { - if (aaiUpdateContrailResponseAsString.contains("RESTFault")) { - WorkflowException exceptionObject = exceptionUtil.MapAAIExceptionToWorkflowException(aaiUpdateContrailResponseAsString, execution) - execution.setVariable("WorkflowException", exceptionObject) - throw new BpmnError("MSOWorkflowException") - - } else { - // aai all errors - String errorMessage = "Unexpected Response from UpdateContrailAAINetwork - " + returnCode - msoLogger.debug(errorMessage) - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, errorMessage) - } + String status = utils.getNodeText(updateNetworkResponse, 'orchestration-status') + if(status.equals("pending-create") || status.equals("PendingCreate")){ + l3Network.setOrchestrationStatus("Created") + }else{ + l3Network.setOrchestrationStatus("Active") + } + + AAIResourcesClient client = new AAIResourcesClient() + AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.L3_NETWORK, networkId) + client.update(uri, l3Network) + + List<Subnet> subnets = oldL3Network.getSubnets().getSubnet() + for(Subnet s:subnets){ + String subnetOrchStatus = s.getOrchestrationStatus() + String subnetId = s.getSubnetId() + + Subnet subnet = new Subnet() + String neutronSubnetId = networkUtils.extractNeutSubId(updateNetworkResponse, subnetId) + subnet.setNeutronSubnetId(neutronSubnetId) + if(subnetOrchStatus.equals("pending-create") || subnetOrchStatus.equals("PendingCreate") ){ + subnet.setOrchestrationStatus("Created") + }else{ + subnet.setOrchestrationStatus("Active") } + + AAIResourceUri subUri = AAIUriFactory.createResourceUri(AAIObjectType.SUBNET, networkId, subnetId) + client.update(subUri, subnet) } + execution.setVariable(Prefix + "isPONR", true) + } catch (BpmnError e) { throw e; - + } catch (NotFoundException e) { + String dataErrorMessage = " Response Error from UpdateContrailAAINetwork is 404 (Not Found)." + msoLogger.debug(dataErrorMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) } catch (Exception ex) { String exceptionMessage = "Bpmn error encountered in DoUpdateNetworkInstance flow. callRESTUpdateContrailAAINetwork() - " + ex.getMessage() msoLogger.debug(exceptionMessage) @@ -1000,7 +825,8 @@ public class DoUpdateNetworkInstance extends AbstractServiceTaskProcessor { String serviceInstanceId = utils.getNodeText(updateNetworkInput, "service-instance-id") - String queryAAIResponse = execution.getVariable(Prefix + "queryIdAAIResponse") + AAIResultWrapper wrapper = execution.getVariable(Prefix + "queryIdAAIResponse") + L3Network queryAAIResponse = wrapper.asBean(L3Network.class).get() // 1. prepare assign topology via SDNC Adapter SUBFLOW call String sndcTopologyCreateRequest = sdncAdapterUtils.sdncTopologyRequestV2(execution, updateNetworkInput, serviceInstanceId, sdncCallback, "changeassign", "NetworkActivateRequest", cloudRegionId, networkId, queryAAIResponse, null) diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoUpdateNetworkInstanceRollback.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoUpdateNetworkInstanceRollback.groovy index 8a13b3c392..eaba51ac6f 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoUpdateNetworkInstanceRollback.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoUpdateNetworkInstanceRollback.groovy @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -32,7 +32,7 @@ import org.onap.so.bpmn.common.scripts.VidUtils import org.onap.so.bpmn.core.WorkflowException import org.onap.so.bpmn.core.UrnPropertiesReader import org.onap.so.bpmn.core.json.JsonUtils -import org.onap.so.rest.APIResponse + import java.util.UUID; @@ -51,7 +51,7 @@ import org.onap.so.logger.MsoLogger */ public class DoUpdateNetworkInstanceRollback extends AbstractServiceTaskProcessor { private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, DoUpdateNetworkInstanceRollback.class); - + String Prefix="UPDNETIR_" ExceptionUtil exceptionUtil = new ExceptionUtil() JsonUtils jsonUtil = new JsonUtils() @@ -128,7 +128,7 @@ public class DoUpdateNetworkInstanceRollback extends AbstractServiceTaskProcesso // PO Authorization Info / headers Authorization= String basicAuthValuePO = UrnPropertiesReader.getVariable("mso.adapters.po.auth",execution) - + try { def encodedString = utils.getBasicAuth(basicAuthValuePO, UrnPropertiesReader.getVariable("mso.msoKey", execution)) execution.setVariable("BasicAuthHeaderValuePO",encodedString) diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoUpdateVfModule.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoUpdateVfModule.groovy index 33cb6d4760..06c7002dff 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoUpdateVfModule.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoUpdateVfModule.groovy @@ -22,13 +22,14 @@ package org.onap.so.bpmn.infrastructure.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.common.scripts.AaiUtil import org.onap.so.bpmn.common.scripts.CatalogDbUtils +import org.onap.so.bpmn.common.scripts.CatalogDbUtilsFactory import org.onap.so.bpmn.common.scripts.ExceptionUtil import org.onap.so.bpmn.common.scripts.MsoUtils import org.onap.so.bpmn.common.scripts.NetworkUtils import org.onap.so.bpmn.common.scripts.SDNCAdapterUtils -import org.onap.so.bpmn.common.scripts.VfModule import org.onap.so.bpmn.common.scripts.VfModuleBase import org.onap.so.bpmn.core.UrnPropertiesReader import org.onap.so.bpmn.core.WorkflowException @@ -37,22 +38,19 @@ import org.onap.so.client.graphinventory.entities.uri.Depth 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.AAIUri import org.onap.so.client.aai.entities.uri.AAIUriFactory; import org.onap.so.client.aai.entities.uri.AAIResourceUri import org.onap.so.constants.Defaults import org.onap.so.logger.MessageEnum import org.onap.so.logger.MsoLogger -import org.onap.so.rest.APIResponse -import org.springframework.web.util.UriUtils public class DoUpdateVfModule extends VfModuleBase { private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, DoUpdateVfModule.class); ExceptionUtil exceptionUtil = new ExceptionUtil() JsonUtils jsonUtil = new JsonUtils() - CatalogDbUtils catalog = new CatalogDbUtils() + CatalogDbUtils catalogDbUtils = new CatalogDbUtilsFactory().create() /** * Initialize the flow's variables. @@ -254,7 +252,7 @@ public class DoUpdateVfModule extends VfModuleBase { String serviceType ="" try{ - String json = catalog.getServiceResourcesByServiceModelInvariantUuidString(execution,modelInvariantUuid ) + String json = catalogDbUtils.getServiceResourcesByServiceModelInvariantUuidString(execution,modelInvariantUuid ) serviceType = jsonUtil.getJsonValue(json, "serviceResources.serviceType") }catch(BpmnError e){ throw e @@ -982,55 +980,26 @@ public class DoUpdateVfModule extends VfModuleBase { try { def vnfId = execution.getVariable('DOUPVfMod_vnfId') - def vfModuleId = execution.getVariable('DOUPVfMod_vfModuleId') - - AaiUtil aaiUriUtil = new AaiUtil(this) - AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId).depth(Depth.ONE) - String endPoint = aaiUriUtil.createAaiUri(uri) - - msoLogger.debug("AAI endPoint: " + endPoint) try { - def aaiRequestId = UUID.randomUUID().toString() - msoLogger.debug('sending GET to AAI endpoint \'' + endPoint + '\'') - APIResponse response = aaiUriUtil.executeAAIGetCall(execution, endPoint) - msoLogger.debug("createVfModule - invoking httpGet() to AAI") - - def responseData = response.getResponseBodyAsString() - if (responseData != null) { - msoLogger.debug("Received generic VNF data: " + responseData) - - } - - msoLogger.debug("createVfModule - queryAAIVfModule Response: " + responseData) - msoLogger.debug("createVfModule - queryAAIVfModule ResponseCode: " + response.getStatusCode()) - - execution.setVariable('DOUPVfMod_queryAAIVfModuleResponseCode', response.getStatusCode()) - execution.setVariable('DOUPVfMod_queryAAIVfModuleResponse', responseData) - msoLogger.debug('Response code:' + response.getStatusCode()) - msoLogger.debug('Response:' + System.lineSeparator() + responseData) - if (response.getStatusCode() == 200) { - // Parse the VNF record from A&AI to find base module info + Optional<GenericVnf> genericVnf = getAAIClient().get(GenericVnf.class,uri) + if (genericVnf.isPresent()) { + execution.setVariable('DOUPVfMod_queryAAIVfModuleResponseCode', 200) + execution.setVariable('DOUPVfMod_queryAAIVfModuleResponse', genericVnf.get()) + // Parse the VNF record from A&AI to find base module info msoLogger.debug('Parsing the VNF data to find base module info') - if (responseData != null) { - def vfModulesText = utils.getNodeXml(responseData, "vf-modules") - def xmlVfModules= new XmlSlurper().parseText(vfModulesText) - def vfModules = xmlVfModules.'**'.findAll {it.name() == "vf-module"} - int vfModulesSize = 0 - for (i in 0..vfModules.size()-1) { - def vfModuleXml = groovy.xml.XmlUtil.serialize(vfModules[i]) - def isBaseVfModule = utils.getNodeText(vfModuleXml, "is-base-vf-module") - - if (isBaseVfModule == "true") { - String baseModuleId = utils.getNodeText(vfModuleXml, "vf-module-id") + if (genericVnf.get().getVfModules()!=null && !genericVnf.get().getVfModules().getVfModule().isEmpty()) { + Optional<org.onap.aai.domain.yang.VfModule> vfmodule = genericVnf.get().getVfModules().getVfModule().stream(). + filter{v-> v.isIsBaseVfModule()}.findFirst() + if (vfmodule.isPresent()) { + String baseModuleId = vfmodule.get().getVfModuleId() execution.setVariable("DOUPVfMod_baseVfModuleId", baseModuleId) msoLogger.debug('Received baseVfModuleId: ' + baseModuleId) - String baseModuleHeatStackId = utils.getNodeText(vfModuleXml, "heat-stack-id") + String baseModuleHeatStackId = vfmodule.get().getHeatStackId() execution.setVariable("DOUPVfMod_baseVfModuleHeatStackId", baseModuleHeatStackId) msoLogger.debug('Received baseVfModuleHeatStackId: ' + baseModuleHeatStackId) } - } } } } catch (Exception ex) { diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoUpdateVnfAndModules.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoUpdateVnfAndModules.groovy index afe01b9243..9eb05cf64a 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoUpdateVnfAndModules.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoUpdateVnfAndModules.groovy @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,30 +20,27 @@ package org.onap.so.bpmn.infrastructure.scripts -import static org.apache.commons.lang3.StringUtils.*; +import org.onap.so.client.HttpClientFactory +import javax.ws.rs.core.Response import org.camunda.bpm.engine.delegate.BpmnError import org.camunda.bpm.engine.delegate.DelegateExecution; import org.onap.so.bpmn.common.scripts.AaiUtil import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor import org.onap.so.bpmn.common.scripts.ExceptionUtil import org.onap.so.bpmn.common.scripts.MsoUtils -import org.onap.so.bpmn.core.UrnPropertiesReader import org.onap.so.bpmn.core.domain.ModelInfo import org.onap.so.bpmn.core.domain.ModuleResource import org.onap.so.bpmn.core.domain.VnfResource import org.onap.so.bpmn.core.json.JsonUtils import org.onap.so.client.graphinventory.entities.uri.Depth -import org.onap.so.client.aai.AAIObjectType; -import org.onap.so.client.aai.AAIResourcesClient +import org.onap.so.client.HttpClient +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.MessageEnum import org.onap.so.logger.MsoLogger -import org.onap.so.rest.APIResponse -import org.onap.so.rest.RESTClient -import org.onap.so.rest.RESTConfig -import org.springframework.web.util.UriUtils; +import org.onap.so.utils.TargetEntity /** * This class supports the VID Flow @@ -54,14 +51,14 @@ class DoUpdateVnfAndModules extends AbstractServiceTaskProcessor { String Prefix="DUVAM_" ExceptionUtil exceptionUtil = new ExceptionUtil() - JsonUtils jsonUtil = new JsonUtils() + JsonUtils jsonUtil = new JsonUtils() /** * This method gets and validates the incoming * request. * * @param - execution - * + * */ public void preProcessRequest(DelegateExecution execution) { @@ -69,66 +66,66 @@ class DoUpdateVnfAndModules extends AbstractServiceTaskProcessor { msoLogger.trace("STARTED DoUpdateVnfAndModules PreProcessRequest Process") try{ - // Get Variables - + // Get Variables + String requestId = execution.getVariable("msoRequestId") - execution.setVariable("requestId", requestId) + execution.setVariable("requestId", requestId) execution.setVariable("mso-request-id", requestId) msoLogger.debug("Incoming Request Id is: " + requestId) - String serviceInstanceId = execution.getVariable("serviceInstanceId") + String serviceInstanceId = execution.getVariable("serviceInstanceId") msoLogger.debug("Incoming Service Instance Id is: " + serviceInstanceId) - String vnfId = execution.getVariable("vnfId") - msoLogger.debug("Incoming Vnf Id is: " + vnfId) - + String vnfId = execution.getVariable("vnfId") + msoLogger.debug("Incoming Vnf Id is: " + vnfId) + String source = "VID" execution.setVariable("DUVAM_source", source) msoLogger.debug("Incoming Source is: " + source) - + String sdncVersion = execution.getVariable("sdncVersion") if (sdncVersion == null) { sdncVersion = "1702" } execution.setVariable("DUVAM_sdncVersion", sdncVersion) msoLogger.debug("Incoming Sdnc Version is: " + sdncVersion) - - VnfResource vnfResource = (VnfResource) execution.getVariable("vnfResourceDecomposition") - + + VnfResource vnfResource = (VnfResource) execution.getVariable("vnfResourceDecomposition") + String vnfModelInfo = execution.getVariable("vnfModelInfo") String serviceModelInfo = execution.getVariable("serviceModelInfo") - + String serviceId = execution.getVariable("productFamilyId") execution.setVariable("DUVAM_serviceId", serviceId) - msoLogger.debug("Incoming Service Id is: " + serviceId) - - String modelUuid = jsonUtil.getJsonValue(vnfModelInfo, "modelUuid") + msoLogger.debug("Incoming Service Id is: " + serviceId) + + String modelUuid = jsonUtil.getJsonValue(vnfModelInfo, "modelUuid") execution.setVariable("DUVAM_modelUuid", modelUuid) - msoLogger.debug("Incoming modelUuid is: " + modelUuid) - - String modelCustomizationUuid = jsonUtil.getJsonValue(vnfModelInfo, "modelCustomizationUuid") + msoLogger.debug("Incoming modelUuid is: " + modelUuid) + + String modelCustomizationUuid = jsonUtil.getJsonValue(vnfModelInfo, "modelCustomizationUuid") execution.setVariable("DUVAM_modelCustomizationUuid", modelCustomizationUuid) msoLogger.debug("Incoming Model Customization Uuid is: " + modelCustomizationUuid) - + String cloudSiteId = execution.getVariable("lcpCloudRegionId") execution.setVariable("DUVAM_cloudSiteId", cloudSiteId) msoLogger.debug("Incoming Cloud Site Id is: " + cloudSiteId) - + String tenantId = execution.getVariable("tenantId") execution.setVariable("DUVAM_tenantId", tenantId) msoLogger.debug("Incoming Tenant Id is: " + tenantId) - + String globalSubscriberId = execution.getVariable("globalSubscriberId") if (globalSubscriberId == null) { globalSubscriberId = "" } execution.setVariable("DUVAM_globalSubscriberId", globalSubscriberId) msoLogger.debug("Incoming Global Subscriber Id is: " + globalSubscriberId) - + execution.setVariable("DUVAM_moduleCount", 0) execution.setVariable("DUVAM_nextModule", 0) - - + + }catch(BpmnError b){ msoLogger.debug("Rethrowing MSOWorkflowException") throw b @@ -138,8 +135,8 @@ class DoUpdateVnfAndModules extends AbstractServiceTaskProcessor { } msoLogger.trace("COMPLETED DoUpdateVnfAndModules PreProcessRequest Process ") - } - + } + /** * Using the received vnfId and vfModuleId, query AAI to get the corresponding VNF info. * A 200 response is expected with the VNF info in the response body. Will find out the base module info. @@ -155,43 +152,43 @@ class DoUpdateVnfAndModules extends AbstractServiceTaskProcessor { try { def vnfId = execution.getVariable('vnfId') - + AaiUtil aaiUriUtil = new AaiUtil(this) AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId).depth(Depth.ONE) String endPoint = aaiUriUtil.createAaiUri(uri) msoLogger.debug("AAI endPoint: " + endPoint) try { - RESTConfig config = new RESTConfig(endPoint); + HttpClient client = new HttpClientFactory().newXmlClient(new URL(endPoint), TargetEntity.AAI) + client.addAdditionalHeader('X-TransactionId', UUID.randomUUID().toString()) + client.addAdditionalHeader('X-FromAppId', 'MSO') + client.addAdditionalHeader('Content-Type', 'application/xml') + client.addAdditionalHeader('Accept','application/xml') + def responseData = '' - def aaiRequestId = UUID.randomUUID().toString() - RESTClient client = new RESTClient(config). - addHeader('X-TransactionId', aaiRequestId). - addHeader('X-FromAppId', 'MSO'). - addHeader('Content-Type', 'application/xml'). - addHeader('Accept','application/xml'); + msoLogger.debug('sending GET to AAI endpoint \'' + endPoint + '\'') - APIResponse response = client.httpGet() + Response response = client.get() msoLogger.debug("createVfModule - invoking httpGet() to AAI") - responseData = response.getResponseBodyAsString() + responseData = response.readEntity(String.class) if (responseData != null) { msoLogger.debug("Received generic VNF data: " + responseData) } msoLogger.debug("createVfModule - queryAAIVfModule Response: " + responseData) - msoLogger.debug("createVfModule - queryAAIVfModule ResponseCode: " + response.getStatusCode()) + msoLogger.debug("createVfModule - queryAAIVfModule ResponseCode: " + response.getStatus()) - execution.setVariable('DUVAM_queryAAIVfModuleResponseCode', response.getStatusCode()) + execution.setVariable('DUVAM_queryAAIVfModuleResponseCode', response.getStatus()) execution.setVariable('DUVAM_queryAAIVfModuleResponse', responseData) - msoLogger.debug('Response code:' + response.getStatusCode()) + msoLogger.debug('Response code:' + response.getStatus()) msoLogger.debug('Response:' + System.lineSeparator() + responseData) //Map<String, String>[] vfModules = new HashMap<String,String>[] def vfModulesList = new ArrayList<Map<String,String>>() def vfModules = null def vfModuleBaseEntry = null - if (response.getStatusCode() == 200) { + if (response.getStatus() == 200) { // Parse the VNF record from A&AI to find base module info msoLogger.debug('Parsing the VNF data to find base module info') if (responseData != null) { @@ -204,7 +201,7 @@ class DoUpdateVnfAndModules extends AbstractServiceTaskProcessor { int vfModulesSize = 0 for (i in 0..vfModules.size()-1) { def vfModuleXml = groovy.xml.XmlUtil.serialize(vfModules[i]) - + Map<String, String> vfModuleEntry = new HashMap<String, String>() def vfModuleId = utils.getNodeText(vfModuleXml, "vf-module-id") vfModuleEntry.put("vfModuleId", vfModuleId) @@ -216,20 +213,20 @@ class DoUpdateVnfAndModules extends AbstractServiceTaskProcessor { vfModuleEntry.put("modelUuid", modelUuid) def modelCustomizationUuid = utils.getNodeText(vfModuleXml, "model-customization-id") vfModuleEntry.put("modelCustomizationUuid", modelCustomizationUuid) - + def isBaseVfModule = utils.getNodeText(vfModuleXml, "is-base-vf-module") vfModuleEntry.put("isBaseVfModule", isBaseVfModule) - + String volumeGroupId = '' - + msoLogger.debug("Next module!") def vfModuleRelationships = vfModules[i].'**'.findAll {it.name() == 'relationship-data'} if (vfModuleRelationships.size() > 0) { - for (j in 0..vfModuleRelationships.size()-1) { + for (j in 0..vfModuleRelationships.size()-1) { if (vfModuleRelationships[j] != null) { - - def relationshipKey = vfModuleRelationships[j].'**'.findAll {it.name() == 'relationship-key'} - + + def relationshipKey = vfModuleRelationships[j].'**'.findAll {it.name() == 'relationship-key'} + if (relationshipKey[0] == 'volume-group.volume-group-id') { def relationshipValue = vfModuleRelationships[j].'**'.findAll {it.name() == 'relationship-value'} volumeGroupId = relationshipValue[0] @@ -238,25 +235,25 @@ class DoUpdateVnfAndModules extends AbstractServiceTaskProcessor { } } } - + vfModuleEntry.put("volumeGroupId", volumeGroupId) msoLogger.debug("volumeGroupId is: " + volumeGroupId) // Save base vf module to add it to the start of the list later - if (isBaseVfModule == "true") { + if (isBaseVfModule == "true") { vfModuleBaseEntry = vfModuleEntry } - else { + else { vfModulesList.add(vfModuleEntry) } } // Start the list with the base module if any if (vfModuleBaseEntry != null) { vfModulesList.add(0, vfModuleBaseEntry) - } + } } - - } + + } } else { msoLogger.debug('Response code from AAI GET is: ' + response.getStatusCode()) @@ -276,44 +273,44 @@ class DoUpdateVnfAndModules extends AbstractServiceTaskProcessor { exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in queryAAIVfModule(): ' + e.getMessage()) } } - + public void prepareNextModuleToUpdate(DelegateExecution execution){ execution.setVariable("prefix", Prefix) msoLogger.trace("STARTED prepareNextModuleToUpdate ") - + try { int i = execution.getVariable("DUVAM_nextModule") def vfModules = execution.getVariable("DUVAM_vfModules") def vfModule = vfModules[i] - + def vfModuleId = vfModule.get("vfModuleId") execution.setVariable("DUVAM_vfModuleId", vfModuleId) - + def vfModuleName = vfModule.get("vfModuleName") execution.setVariable("DUVAM_vfModuleName", vfModuleName) - + def isBaseVfModule = vfModule.get("isBaseVfModule") execution.setVariable("DUVAM_isBaseVfModule", isBaseVfModule) - + String modelInvariantUuid = vfModule.get("modelInvariantUuid") - msoLogger.debug("ModelInvariantUuid: " + modelInvariantUuid) - + msoLogger.debug("ModelInvariantUuid: " + modelInvariantUuid) + def volumeGroupId = vfModule.get("volumeGroupId") execution.setVariable("DUVAM_volumeGroupId", volumeGroupId) execution.setVariable("DUVAM_volumeGroupName", "") - + VnfResource vnfResource = (VnfResource) execution.getVariable("vnfResourceDecomposition") List<ModuleResource> moduleResources = vnfResource.getVfModules() - + if (moduleResources != null && !moduleResources.isEmpty()) { - - for (j in 0..moduleResources.size()-1) { + + for (j in 0..moduleResources.size()-1) { ModelInfo modelInfo = moduleResources[j].getModelInfo() String modelInvariantUuidFromDecomposition = modelInfo.getModelInvariantUuid() msoLogger.debug("modelInvariantUuidFromDecomposition: " + modelInvariantUuidFromDecomposition) - + if (modelInvariantUuid.equals(modelInvariantUuidFromDecomposition)) { String vfModuleModelInfo = modelInfo.toJsonString() String vfModuleModelInfoValue = jsonUtil.getJsonValue(vfModuleModelInfo, "modelInfo") @@ -321,18 +318,18 @@ class DoUpdateVnfAndModules extends AbstractServiceTaskProcessor { msoLogger.debug("vfModuleModelInfo: " + vfModuleModelInfoValue) break } - + } - } - + } + }catch(Exception e){ msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception Occured Processing preProcessAddOnModule. Exception is:\n" + e, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occurred during prepareNextModuleToUpdate Method:\n" + e.getMessage()) } msoLogger.trace("COMPLETED prepareNextModuleToUpdate ") } - - + + /** * Prepare a Request for invoking the UpdateAAIGenericVnf subflow. * @@ -344,25 +341,25 @@ class DoUpdateVnfAndModules extends AbstractServiceTaskProcessor { ')' msoLogger.trace('Entered ' + method) - - try { + + try { def vnfId = execution.getVariable('vnfId') VnfResource vnfResource = (VnfResource) execution.getVariable("vnfResourceDecomposition") ModelInfo vnfDecompModelInfo = vnfResource.getModelInfo() String vnfModelInfo = execution.getVariable("vnfModelInfo") String modelUuid = execution.getVariable("DUVAM_modelUuid") if (modelUuid == null || modelUuid.isEmpty()) { - modelUuid = vnfDecompModelInfo.getModelUuid() + modelUuid = vnfDecompModelInfo.getModelUuid() } String modelCustomizationUuid = execution.getVariable("DUVAM_modelCustomizationUuid") if (modelCustomizationUuid == null || modelCustomizationUuid.isEmpty()) { modelCustomizationUuid = vnfDecompModelInfo.getModelCustomizationUuid() - } + } String nfType = vnfResource.getNfType() String nfTypeString = '' if (nfType != null && !nfType.isEmpty()) { nfTypeString = "<nf-type>" + nfType + "</nf-type>" - } + } String nfRole = vnfResource.getNfRole() String nfRoleString = '' if (nfRole != null && !nfRole.isEmpty()) { @@ -377,8 +374,8 @@ class DoUpdateVnfAndModules extends AbstractServiceTaskProcessor { String nfNamingCodeString = '' if (nfNamingCode != null && !nfNamingCode.isEmpty()) { nfNamingCodeString = "<nf-naming-code>" + nfNamingCode + "</nf-naming-code>" - } - + } + String updateAAIGenericVnfRequest = """ <UpdateAAIGenericVnfRequest> <vnf-id>${MsoUtils.xmlEscape(vnfId)}</vnf-id> @@ -394,8 +391,8 @@ class DoUpdateVnfAndModules extends AbstractServiceTaskProcessor { execution.setVariable('DUVAM_updateAAIGenericVnfRequest', updateAAIGenericVnfRequest) msoLogger.debug("updateAAIGenericVnfRequest : " + updateAAIGenericVnfRequest) msoLogger.debug('Request for UpdateAAIGenericVnf:\n' + updateAAIGenericVnfRequest) - - + + msoLogger.trace('Exited ' + method) } catch (BpmnError e) { throw e; @@ -404,7 +401,7 @@ class DoUpdateVnfAndModules extends AbstractServiceTaskProcessor { exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in prepUpdateAAIGenericVnf(): ' + e.getMessage()) } } - + /** * APP-C Call - placeholder. * @@ -415,6 +412,6 @@ class DoUpdateVnfAndModules extends AbstractServiceTaskProcessor { 'execution=' + execution.getId() + ')' - msoLogger.trace('Entered ' + method) + msoLogger.trace('Entered ' + method) } } diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/ReplaceVnfInfra.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/ReplaceVnfInfra.groovy index f45e97fa6e..671796f27f 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/ReplaceVnfInfra.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/ReplaceVnfInfra.groovy @@ -341,12 +341,11 @@ public class ReplaceVnfInfra extends VnfCmBase { msoLogger.trace('Entered ' + method) try { - def transactionLoggingUuid = UUID.randomUUID().toString() AAIRestClientImpl client = new AAIRestClientImpl() AAIValidatorImpl aaiValidator = new AAIValidatorImpl() aaiValidator.setClient(client) def vnfId = execution.getVariable("vnfId") - boolean isInMaint = aaiValidator.isVNFLocked(vnfId, transactionLoggingUuid) + boolean isInMaint = aaiValidator.isVNFLocked(vnfId) msoLogger.debug("isInMaint result: " + isInMaint) execution.setVariable('isVnfInMaintenance', isInMaint) @@ -385,12 +384,11 @@ public class ReplaceVnfInfra extends VnfCmBase { execution.setVariable("failedActivity", "AAI") try { - def transactionLoggingUuid = UUID.randomUUID().toString() AAIRestClientImpl client = new AAIRestClientImpl() AAIValidatorImpl aaiValidator = new AAIValidatorImpl() aaiValidator.setClient(client) def vnfId = execution.getVariable("vnfId") - boolean areLocked = aaiValidator.isPhysicalServerLocked(vnfId, transactionLoggingUuid) + boolean areLocked = aaiValidator.isPhysicalServerLocked(vnfId) msoLogger.debug("areLocked result: " + areLocked) execution.setVariable('arePserversLocked', areLocked) @@ -433,17 +431,16 @@ public class ReplaceVnfInfra extends VnfCmBase { execution.setVariable("failedActivity", "AAI") try { - def transactionLoggingUuid = UUID.randomUUID().toString() AAIRestClientImpl client = new AAIRestClientImpl() AAIUpdatorImpl aaiUpdator = new AAIUpdatorImpl() aaiUpdator.setClient(client) def vnfId = execution.getVariable("vnfId") if (inMaint) { - aaiUpdator.updateVnfToLocked(vnfId, transactionLoggingUuid) + aaiUpdator.updateVnfToLocked(vnfId) execution.setVariable("rollbackSetVnfInMaintenanceFlag", true) } else { - aaiUpdator.updateVnfToUnLocked(vnfId, transactionLoggingUuid) + aaiUpdator.updateVnfToUnLocked(vnfId) } msoLogger.trace('Exited ' + method) @@ -453,7 +450,6 @@ public class ReplaceVnfInfra extends VnfCmBase { msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); execution.setVariable("errorCode", "1002") execution.setVariable("errorText", e.getMessage()) - //exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in setVnfInMaintFlagInAAI(): ' + e.getMessage()) } } diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/RollbackVnf.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/RollbackVnf.groovy index d729c770ca..22b44c9ead 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/RollbackVnf.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/RollbackVnf.groovy @@ -8,7 +8,7 @@ * 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. @@ -32,9 +32,7 @@ import org.onap.so.bpmn.common.scripts.ExceptionUtil import org.camunda.bpm.engine.delegate.BpmnError import org.camunda.bpm.engine.impl.cmd.AbstractSetVariableCmd import org.camunda.bpm.engine.delegate.DelegateExecution -import org.onap.so.rest.APIResponse -import org.onap.so.rest.RESTClient -import org.onap.so.rest.RESTConfig + import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor; import org.onap.so.bpmn.common.scripts.VidUtils; import org.onap.so.bpmn.core.RollbackData @@ -61,7 +59,7 @@ public class RollbackVnf extends VnfCmBase { private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, RollbackVnf.class); ExceptionUtil exceptionUtil = new ExceptionUtil() - JsonUtils jsonUtils = new JsonUtils() + JsonUtils jsonUtils = new JsonUtils() def prefix = "VnfIPU_" /** @@ -71,16 +69,16 @@ public class RollbackVnf extends VnfCmBase { */ public void initProcessVariables(DelegateExecution execution) { execution.setVariable('prefix', 'RVnf_') - - execution.setVariable('rollbackSuccessful', false) + + execution.setVariable('rollbackSuccessful', false) execution.setVariable('currentActivity', 'RVnf') execution.setVariable('workStep', null) execution.setVariable('failedActivity', null) - execution.setVariable('errorCode', "0") - execution.setVariable('actionUnlock', Action.Unlock) + execution.setVariable('errorCode', "0") + execution.setVariable('actionUnlock', Action.Unlock) execution.setVariable('actionStart', Action.Start) execution.setVariable('actionResumeTraffic', Action.ResumeTraffic) - + } /** @@ -97,16 +95,16 @@ public class RollbackVnf extends VnfCmBase { msoLogger.trace('Entered ' + method) initProcessVariables(execution) - + try { - + execution.setVariable("rollbackErrorCode", "0") - + if (execution.getVariable("rollbackSetClosedLoopDisabledFlag") == true) { msoLogger.debug("Will call setClosedLoopDisabledFlag") - } + } + - msoLogger.trace('Exited ' + method) } @@ -115,9 +113,9 @@ public class RollbackVnf extends VnfCmBase { msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, " Exception Encountered - " + "\n" + restFaultMessage, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); execution.setVariable("rollbackErrorCode", "1") exceptionUtil.buildAndThrowWorkflowException(execution, 5000, restFaultMessage) - } + } } - + /** * Determine success of rollback execution. * @@ -130,7 +128,7 @@ public class RollbackVnf extends VnfCmBase { initProcessVariables(execution) msoLogger.trace('Entered ' + method) - + def rollbackErrorCode = execution.getVariable('rollbackErrorCode') if (rollbackErrorCode == "0") { execution.setVariable('rollbackSuccessful', true) @@ -140,9 +138,9 @@ public class RollbackVnf extends VnfCmBase { execution.setVariable('rollbackSuccessful', false) msoLogger.debug("rollback unsuccessful") } - - msoLogger.trace('Exited ' + method) - - } - + + msoLogger.trace('Exited ' + method) + + } + } diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/UpdateVfModuleInfraV2.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/UpdateVfModuleInfraV2.groovy index 0972ee184e..1a8df1664f 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/UpdateVfModuleInfraV2.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/UpdateVfModuleInfraV2.groovy @@ -285,9 +285,8 @@ public class UpdateVfModuleInfraV2 { System.out.println("*****************************CheckingPserverFlag*************************") String vnfId = (String)execution.getVariable('vnfId') - String uuid = (String)execution.getVariable('moduleUuid') AAIValidatorImpl aaiVI = new AAIValidatorImpl() - boolean flag = aaiVI.isPhysicalServerLocked(vnfId, uuid) + boolean flag = aaiVI.isPhysicalServerLocked(vnfId) } //check to see if the VFFlag is locked @@ -295,9 +294,8 @@ public class UpdateVfModuleInfraV2 { System.out.print("*****************************VfFlagCheck*************************") String vnfId = (String)execution.getVariable('vnfId') - String uuid = (String)execution.getVariable('moduleUuid') AAIValidatorImpl aaiVI = new AAIValidatorImpl() - boolean flag = aaiVI.isVNFLocked(vnfId, uuid) + boolean flag = aaiVI.isVNFLocked(vnfId) } //lock the VF Flag diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/UpdateVfModuleVolume.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/UpdateVfModuleVolume.groovy index 0f9a0ad292..5b1270a947 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/UpdateVfModuleVolume.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/UpdateVfModuleVolume.groovy @@ -20,25 +20,27 @@ package org.onap.so.bpmn.infrastructure.scripts -import org.apache.commons.lang3.* +import org.apache.commons.collections.CollectionUtils import org.camunda.bpm.engine.delegate.BpmnError import org.camunda.bpm.engine.delegate.DelegateExecution -import org.onap.so.bpmn.common.scripts.AaiUtil +import org.onap.aai.domain.yang.VolumeGroup import org.onap.so.bpmn.common.scripts.ExceptionUtil import org.onap.so.bpmn.common.scripts.MsoUtils import org.onap.so.bpmn.common.scripts.VfModuleBase -import org.onap.so.bpmn.core.UrnPropertiesReader; +import org.onap.so.bpmn.core.UrnPropertiesReader import org.onap.so.bpmn.core.WorkflowException 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 -import org.onap.so.rest.APIResponse +import static org.apache.commons.lang.StringUtils.isEmpty class UpdateVfModuleVolume extends VfModuleBase { - private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, UpdateVfModuleVolume.class); + private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, UpdateVfModuleVolume.class) ExceptionUtil exceptionUtil = new ExceptionUtil() @@ -103,7 +105,7 @@ class UpdateVfModuleVolume extends VfModuleBase { } catch (BpmnError bpmnError) { throw bpmnError } catch (Exception e) { - msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e) exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in preProcessRequest(): ' + e.getMessage()) } } @@ -152,9 +154,9 @@ class UpdateVfModuleVolume extends VfModuleBase { sendWorkflowResponse(execution, 200, synchResponse) msoLogger.debug("UpdateVfModuleVolume Synch Response: " + synchResponse) } catch (BpmnError e) { - throw e; + throw e } catch (Exception e) { - msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e) exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in sendSynchResponse(): ' + e.getMessage()) } } @@ -175,45 +177,35 @@ class UpdateVfModuleVolume extends VfModuleBase { try { def volumeGroupId = execution.getVariable('UPDVfModVol_volumeGroupId') def aicCloudRegion = execution.getVariable('UPDVfModVol_aicCloudRegion') - - AaiUtil aaiUtil = new AaiUtil(this) - AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.VOLUME_GROUP, Defaults.CLOUD_OWNER.toString(), aicCloudRegion, volumeGroupId) - String endPoint = aaiUtil.createAaiUri(uri) - - - msoLogger.debug('Sending GET to AAI endpoint \'' + endPoint + '\'') - msoLogger.debug("UpdateVfModuleVolume sending GET for quering AAI endpoint: " + endPoint) - - APIResponse response = aaiUtil.executeAAIGetCall(execution, endPoint) - def int statusCode = response.getStatusCode() - def responseData = response.getResponseBodyAsString() - msoLogger.debug('Response code:' + statusCode) - msoLogger.debug('Response:' + System.lineSeparator() + responseData) - msoLogger.debug("UpdateVfModuleVolume response data: " + responseData) - - def volumeGroup = responseData - def heatStackId = getNodeTextForce(volumeGroup, 'heat-stack-id') - execution.setVariable('UPDVfModVol_volumeGroupHeatStackId', heatStackId) - if ((statusCode == 200) || (statusCode == 204)) { - def volumeGroupTenantId = getTenantIdFromVolumeGroup(volumeGroup) - if (volumeGroupTenantId == null) { - throw new Exception('Could not find Tenant Id element in Volume Group with Volume Group Id \'' + volumeGroupId + '\'' - + '\', AIC Cloud Region \'' + aicCloudRegion + '\'') + AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.VOLUME_GROUP, Defaults.CLOUD_OWNER.toString(),aicCloudRegion,volumeGroupId) + AAIResultWrapper wrapper = getAAIClient().get(uri) + Optional<VolumeGroup> volumeGroup = wrapper.asBean(VolumeGroup.class) + if(volumeGroup.isPresent()){ + def heatStackId = volumeGroup.get().getHeatStackId() + execution.setVariable('UPDVfModVol_volumeGroupHeatStackId', heatStackId) + Optional<Relationships> relationships = wrapper.getRelationships() + if(relationships.isPresent()){ + List<AAIResourceUri> resourceUriList = relationships.get().getRelatedAAIUris(AAIObjectType.TENANT) + if(CollectionUtils.isNotEmpty(resourceUriList)){ + AAIResourceUri tenantUri = resourceUriList.get(0) + String volumeGroupTenantId = tenantUri.getURIKeys().get("tenant-id") + if( isEmpty(volumeGroupTenantId)){ + exceptionUtil.buildAndThrowWorkflowException(execution,2500,"Could not find Tenant Id element in Volume Group with Volume Group Id" + volumeGroupId + ", AIC Cloud Region" + aicCloudRegion) + } + execution.setVariable('UPDVfModVol_volumeGroupTenantId', volumeGroupTenantId) + msoLogger.debug("Received Tenant Id: " + volumeGroupTenantId + "from AAI for Volume Group with Volume Group Id: " + volumeGroupId + ", AIC Cloud Region" + aicCloudRegion) + }else{ + exceptionUtil.buildAndThrowWorkflowException(execution,2500,"Could not find Tenant Id element in Volume Group with Volume Group Id" + volumeGroupId + ", AIC Cloud Region" + aicCloudRegion) + } } - execution.setVariable('UPDVfModVol_volumeGroupTenantId', volumeGroupTenantId) - msoLogger.debug('Received Tenant Id \'' + volumeGroupTenantId + '\' from AAI for Volume Group with Volume Group Id \'' + volumeGroupId + '\'' - + '\', AIC Cloud Region \'' + aicCloudRegion + '\'') - } else if (statusCode == 404) { - throw new Exception('Volume Group \'' + volumeGroupId + '\' not found at AAI') - } else { - throw new Exception('Bad status code ' + statusCode + ' received from AAI; Response data: ' + responseData) + }else{ + exceptionUtil.buildAndThrowWorkflowException(execution,2500,"Volume Group" + volumeGroupId + " not found at AAI") } - msoLogger.trace('Exited ' + method) } catch (BpmnError e) { - throw e; + throw e } catch (Exception e) { - msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e) exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in queryAAIForVolumeGroup(): ' + e.getMessage()) } } @@ -279,9 +271,9 @@ class UpdateVfModuleVolume extends VfModuleBase { msoLogger.debug("UpdateVfModuleVolume Request for VNFAdapter Rest: " + vnfAdapterRestRequest) msoLogger.trace('Exited ' + method) } catch (BpmnError e) { - throw e; + throw e } catch (Exception e) { - msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e) exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in prepVnfAdapterRest(): ' + e.getMessage()) } } @@ -323,9 +315,9 @@ class UpdateVfModuleVolume extends VfModuleBase { msoLogger.debug("UpdateVfModuleVolume Request for Updating DB for Infra: " + updateInfraRequest) msoLogger.trace('Exited ' + method) } catch (BpmnError e) { - throw e; + throw e } catch (Exception e) { - msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e) exceptionUtil.buildWorkflowException(execution, 1002, 'Error in prepDbInfraDbRequest(): ' + e.getMessage()) } } @@ -360,9 +352,9 @@ class UpdateVfModuleVolume extends VfModuleBase { msoLogger.trace('Exited ' + method) } catch (BpmnError e) { - throw e; + throw e } catch (Exception e) { - msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e) exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in prepCompletionHandlerRequest(): ' + e.getMessage()) } } @@ -409,9 +401,9 @@ class UpdateVfModuleVolume extends VfModuleBase { msoLogger.trace('Exited ' + method) } catch (BpmnError e) { - throw e; + throw e } catch (Exception e) { - msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e) exceptionUtil.buildWorkflowException(execution, 1002, 'Error in prepFalloutHandler(): ' + e.getMessage()) } } @@ -429,7 +421,7 @@ class UpdateVfModuleVolume extends VfModuleBase { msoLogger.trace('Entered ' + method) - String processKey = getProcessKey(execution); + String processKey = getProcessKey(execution) def volumeGroupId = execution.getVariable('UPDVfModVol_volumeGroupId') def aicCloudRegion = execution.getVariable('UPDVfModVol_aicCloudRegion') def tenantId = execution.getVariable('UPDVfModVol_tenantId') @@ -438,10 +430,10 @@ class UpdateVfModuleVolume extends VfModuleBase { def String errorMessage = 'TenantId \'' + tenantId + '\' in incoming request does not match Tenant Id \'' + volumeGroupTenantId + '\' retrieved from AAI for Volume Group Id \'' + volumeGroupId + '\', AIC Cloud Region \'' + aicCloudRegion + '\'' - msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Error in UpdateVfModuleVol: ' + errorMessage, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception"); + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Error in UpdateVfModuleVol: ' + errorMessage, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception") - WorkflowException exception = new WorkflowException(processKey, 5000, errorMessage); - execution.setVariable("WorkflowException", exception); + WorkflowException exception = new WorkflowException(processKey, 5000, errorMessage) + execution.setVariable("WorkflowException", exception) msoLogger.trace('Exited ' + method) msoLogger.debug("UpdateVfModuleVolume workflowException in Tenant Mismatch: " + errorMessage) diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/UpdateVfModuleVolumeInfraV1.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/UpdateVfModuleVolumeInfraV1.groovy index ce93db522e..49da398a87 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/UpdateVfModuleVolumeInfraV1.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/UpdateVfModuleVolumeInfraV1.groovy @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,142 +20,147 @@ package org.onap.so.bpmn.infrastructure.scripts -import org.apache.commons.lang3.* +import groovy.json.JsonException import org.camunda.bpm.engine.delegate.BpmnError import org.camunda.bpm.engine.delegate.DelegateExecution -import org.onap.so.bpmn.common.scripts.AaiUtil; -import org.onap.so.bpmn.common.scripts.ExceptionUtil; +import org.onap.aai.domain.yang.GenericVnf +import org.onap.aai.domain.yang.VfModule +import org.onap.aai.domain.yang.VolumeGroup +import org.onap.so.bpmn.common.scripts.ExceptionUtil import org.onap.so.bpmn.common.scripts.MsoUtils -import org.onap.so.bpmn.common.scripts.VfModuleBase; -import org.onap.so.bpmn.common.scripts.VidUtils; +import org.onap.so.bpmn.common.scripts.VfModuleBase +import org.onap.so.bpmn.common.scripts.VidUtils import org.onap.so.bpmn.core.UrnPropertiesReader import org.onap.so.bpmn.core.WorkflowException -import org.onap.so.client.aai.AAIObjectType; -import org.onap.so.client.aai.AAIResourcesClient +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.client.aai.entities.uri.AAIUriFactory +import org.onap.so.constants.Defaults import org.onap.so.logger.MessageEnum import org.onap.so.logger.MsoLogger -import org.onap.so.rest.APIResponse -import org.springframework.web.util.UriUtils +import static org.apache.cxf.common.util.CollectionUtils.isEmpty import groovy.json.JsonSlurper +import javax.ws.rs.core.UriBuilder + class UpdateVfModuleVolumeInfraV1 extends VfModuleBase { - private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, UpdateVfModuleVolumeInfraV1.class); - - /** - * Initialize the flow's variables. - * - * @param execution The flow's execution instance. - */ - private void initProcessVariables(DelegateExecution execution) { - execution.setVariable('prefix', 'UPDVfModVol_') - execution.setVariable('UPDVfModVol_Request', null) - execution.setVariable('UPDVfModVol_requestInfo', null) - execution.setVariable('UPDVfModVol_requestId', null) - execution.setVariable('UPDVfModVol_source', null) - execution.setVariable('UPDVfModVol_volumeInputs', null) - execution.setVariable('UPDVfModVol_volumeGroupId', null) - execution.setVariable('UPDVfModVol_vnfType', null) - execution.setVariable('UPDVfModVol_serviceId', null) - execution.setVariable('UPDVfModVol_aicCloudRegion', null) - execution.setVariable('UPDVfModVol_tenantId', null) - execution.setVariable('UPDVfModVol_volumeParams', null) - execution.setVariable('UPDVfModVol_volumeGroupHeatStackId', null) - execution.setVariable('UPDVfModVol_volumeGroupTenantId', null) - execution.setVariable('UpdateVfModuleVolumeSuccessIndicator', false) - } - - - /** - * Perform initial processing, such as request validation, initialization of variables, etc. - * * @param execution - */ - public void preProcessRequest (DelegateExecution execution) { - def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - preProcessRequest(execution, isDebugEnabled) - } - - public void preProcessRequest(DelegateExecution execution, isDebugLogEnabled) { - - initProcessVariables(execution) - String jsonRequest = validateRequest(execution) - - def request = "" - - try { - def jsonSlurper = new JsonSlurper() - Map reqMap = jsonSlurper.parseText(jsonRequest) - - def serviceInstanceId = execution.getVariable('serviceInstanceId') - def volumeGroupId = execution.getVariable('volumeGroupId') - //def vnfId = execution.getVariable('vnfId') - - def vidUtils = new VidUtils(this) - request = vidUtils.createXmlVolumeRequest(reqMap, 'UPDATE_VF_MODULE_VOL', serviceInstanceId, volumeGroupId) - - execution.setVariable('UPDVfModVol_Request', request) - execution.setVariable("UPDVfModVol_isVidRequest", true) - - //need to get persona-model-id aka model-invariantId to use later to validate vf-module relation in AAI - - def modelInvariantId = reqMap.requestDetails.modelInfo.modelInvariantUuid ?: '' - execution.setVariable('UPDVfModVol_modelInvariantId', modelInvariantId) - - msoLogger.debug("modelInvariantId from request: " + modelInvariantId) - msoLogger.debug("XML request:\n" + request) - } - catch(groovy.json.JsonException je) { - msoLogger.debug(" Request is in XML format.") - // assume request is in XML format - proceed as usual to process XML request - } - - def requestId = execution.getVariable('mso-request-id') - - def requestInfo = getRequiredNodeXml(execution, request, 'request-info') - execution.setVariable('UPDVfModVol_requestInfo', requestInfo) - execution.setVariable('UPDVfModVol_requestId', requestId) - //execution.setVariable('UPDVfModVol_requestId', getRequiredNodeText(execution, requestInfo, 'request-id')) - execution.setVariable('UPDVfModVol_source', getNodeTextForce(requestInfo, 'source')) - - def volumeInputs = getRequiredNodeXml(execution, request, 'volume-inputs') - execution.setVariable('UPDVfModVol_volumeInputs', volumeInputs) - execution.setVariable('UPDVfModVol_volumeGroupId', getRequiredNodeText(execution, volumeInputs, 'volume-group-id')) - execution.setVariable('UPDVfModVol_vnfType', getRequiredNodeText(execution, volumeInputs, 'vnf-type')) - execution.setVariable('UPDVfModVol_vnfVersion', getRequiredNodeText(execution, volumeInputs, 'asdc-service-model-version')) - execution.setVariable('UPDVfModVol_serviceId', utils.getNodeText(volumeInputs, 'service-id')) - execution.setVariable('UPDVfModVol_aicCloudRegion', getRequiredNodeText(execution, volumeInputs, 'aic-cloud-region')) - execution.setVariable('UPDVfModVol_tenantId', getRequiredNodeText(execution, volumeInputs, 'tenant-id')) - //execution.setVariable('UPDVfModVol_modelCustomizationId', getRequiredNodeText(execution, volumeInputs, 'model-customization-id')) - - setBasicDBAuthHeader(execution, isDebugLogEnabled) - - def volumeParams = utils.getNodeXml(request, 'volume-params') - execution.setVariable('UPDVfModVol_volumeParams', volumeParams) - } - - /** - * Prepare and send the synchronous response. - * - * @param execution The flow's execution instance. - */ - public void sendSynchResponse(DelegateExecution execution, isDebugLogEnabled) { - - def requestInfo = execution.getVariable('UPDVfModVol_requestInfo') - def requestId = execution.getVariable('UPDVfModVol_requestId') - def source = execution.getVariable('UPDVfModVol_source') - def progress = getNodeTextForce(requestInfo, 'progress') - if (progress.isEmpty()) { - progress = '0' - } - def startTime = getNodeTextForce(requestInfo, 'start-time') - if (startTime.isEmpty()) { - startTime = System.currentTimeMillis() - } - def volumeInputs = execution.getVariable('UPDVfModVol_volumeInputs') - - String xmlSyncResponse = """ + private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, UpdateVfModuleVolumeInfraV1.class) + private ExceptionUtil exceptionUtil = new ExceptionUtil() + + /** + * Initialize the flow's variables. + * + * @param execution The flow's execution instance. + */ + private void initProcessVariables(DelegateExecution execution) { + execution.setVariable('prefix', 'UPDVfModVol_') + execution.setVariable('UPDVfModVol_Request', null) + execution.setVariable('UPDVfModVol_requestInfo', null) + execution.setVariable('UPDVfModVol_requestId', null) + execution.setVariable('UPDVfModVol_source', null) + execution.setVariable('UPDVfModVol_volumeInputs', null) + execution.setVariable('UPDVfModVol_volumeGroupId', null) + execution.setVariable('UPDVfModVol_vnfType', null) + execution.setVariable('UPDVfModVol_serviceId', null) + execution.setVariable('UPDVfModVol_aicCloudRegion', null) + execution.setVariable('UPDVfModVol_tenantId', null) + execution.setVariable('UPDVfModVol_volumeParams', null) + execution.setVariable('UPDVfModVol_volumeGroupHeatStackId', null) + execution.setVariable('UPDVfModVol_volumeGroupTenantId', null) + execution.setVariable('UpdateVfModuleVolumeSuccessIndicator', false) + } + + /** + * Perform initial processing, such as request validation, initialization of variables, etc. + * * @param execution + */ + public void preProcessRequest(DelegateExecution execution) { + def isDebugEnabled = execution.getVariable("isDebugLogEnabled") + preProcessRequest(execution, isDebugEnabled) + } + + public void preProcessRequest(DelegateExecution execution, isDebugLogEnabled) { + + initProcessVariables(execution) + String jsonRequest = validateRequest(execution) + + def request = "" + + try { + def jsonSlurper = new JsonSlurper() + Map reqMap = jsonSlurper.parseText(jsonRequest) + + def serviceInstanceId = execution.getVariable('serviceInstanceId') + def volumeGroupId = execution.getVariable('volumeGroupId') + //def vnfId = execution.getVariable('vnfId') + + def vidUtils = new VidUtils(this) + request = vidUtils.createXmlVolumeRequest(reqMap, 'UPDATE_VF_MODULE_VOL', serviceInstanceId, volumeGroupId) + + execution.setVariable('UPDVfModVol_Request', request) + execution.setVariable("UPDVfModVol_isVidRequest", true) + + //need to get persona-model-id aka model-invariantId to use later to validate vf-module relation in AAI + + def modelInvariantId = reqMap.requestDetails.modelInfo.modelInvariantUuid ?: '' + execution.setVariable('UPDVfModVol_modelInvariantId', modelInvariantId) + + msoLogger.debug("modelInvariantId from request: " + modelInvariantId) + msoLogger.debug("XML request:\n" + request) + } + catch (JsonException je) { + msoLogger.debug(" Request is in XML format.") + // assume request is in XML format - proceed as usual to process XML request + } + + def requestId = execution.getVariable('mso-request-id') + + def requestInfo = getRequiredNodeXml(execution, request, 'request-info') + execution.setVariable('UPDVfModVol_requestInfo', requestInfo) + execution.setVariable('UPDVfModVol_requestId', requestId) + //execution.setVariable('UPDVfModVol_requestId', getRequiredNodeText(execution, requestInfo, 'request-id')) + execution.setVariable('UPDVfModVol_source', getNodeTextForce(requestInfo, 'source')) + + def volumeInputs = getRequiredNodeXml(execution, request, 'volume-inputs') + execution.setVariable('UPDVfModVol_volumeInputs', volumeInputs) + execution.setVariable('UPDVfModVol_volumeGroupId', getRequiredNodeText(execution, volumeInputs, 'volume-group-id')) + execution.setVariable('UPDVfModVol_vnfType', getRequiredNodeText(execution, volumeInputs, 'vnf-type')) + execution.setVariable('UPDVfModVol_vnfVersion', getRequiredNodeText(execution, volumeInputs, 'asdc-service-model-version')) + execution.setVariable('UPDVfModVol_serviceId', utils.getNodeText(volumeInputs, 'service-id')) + execution.setVariable('UPDVfModVol_aicCloudRegion', getRequiredNodeText(execution, volumeInputs, 'aic-cloud-region')) + execution.setVariable('UPDVfModVol_tenantId', getRequiredNodeText(execution, volumeInputs, 'tenant-id')) + //execution.setVariable('UPDVfModVol_modelCustomizationId', getRequiredNodeText(execution, volumeInputs, 'model-customization-id')) + + setBasicDBAuthHeader(execution, isDebugLogEnabled) + + def volumeParams = utils.getNodeXml(request, 'volume-params') + execution.setVariable('UPDVfModVol_volumeParams', volumeParams) + } + + /** + * Prepare and send the synchronous response. + * + * @param execution The flow's execution instance. + */ + public void sendSynchResponse(DelegateExecution execution, isDebugLogEnabled) { + + def requestInfo = execution.getVariable('UPDVfModVol_requestInfo') + def requestId = execution.getVariable('UPDVfModVol_requestId') + def source = execution.getVariable('UPDVfModVol_source') + def progress = getNodeTextForce(requestInfo, 'progress') + if (progress.isEmpty()) { + progress = '0' + } + def startTime = getNodeTextForce(requestInfo, 'start-time') + if (startTime.isEmpty()) { + startTime = System.currentTimeMillis() + } + def volumeInputs = execution.getVariable('UPDVfModVol_volumeInputs') + + String xmlSyncResponse = """ <volume-request xmlns="http://org.onap/so/infra/vnf-request/v1"> <request-info> <request-id>${MsoUtils.xmlEscape(requestId)}</request-id> @@ -169,223 +174,153 @@ class UpdateVfModuleVolumeInfraV1 extends VfModuleBase { </volume-request> """ - def syncResponse = '' - def isVidRequest = execution.getVariable('UPDVfModVol_isVidRequest') - - if(isVidRequest) { - def volumeGroupId = execution.getVariable('volumeGroupId') - syncResponse = """{"requestReferences":{"instanceId":"${volumeGroupId}","requestId":"${requestId}"}}""".trim() - } - else { - syncResponse = utils.formatXml(xmlSyncResponse) - } - - msoLogger.debug('Sync response: ' + syncResponse) - execution.setVariable('UPDVfModVol_syncResponseSent', true) - sendWorkflowResponse(execution, 200, syncResponse) - } - - /** - * Prepare a Request for querying AAI for Volume Group information using the - * Volume Group Id and Aic Cloud Region. - * @param execution The flow's execution instance. - */ - public void queryAAIForVolumeGroup(DelegateExecution execution, isDebugLogEnabled) { - - def volumeGroupId = execution.getVariable('UPDVfModVol_volumeGroupId') - def aicCloudRegion = execution.getVariable('UPDVfModVol_aicCloudRegion') - - AaiUtil aaiUtil = new AaiUtil(this) - - AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.VOLUME_GROUP, Defaults.CLOUD_OWNER.toString(), aicCloudRegion, volumeGroupId) - def queryAAIVolumeGroupRequest = aaiUtil.createAaiUri(uri) - - msoLogger.debug('Query AAI volume group by ID: ' + queryAAIVolumeGroupRequest) - msoLogger.debug('Query AAI volume group by ID: ' + queryAAIVolumeGroupRequest) - - APIResponse response = aaiUtil.executeAAIGetCall(execution, queryAAIVolumeGroupRequest) - - String returnCode = response.getStatusCode() - String aaiResponseAsString = response.getResponseBodyAsString() - - msoLogger.debug("AAI query volume group by id return code: " + returnCode) - msoLogger.debug("AAI query volume group by id response: " + aaiResponseAsString) - - msoLogger.debug("AAI Volume Group return code: " + returnCode) - msoLogger.debug("AAI Volume Group response: " + aaiResponseAsString) - - ExceptionUtil exceptionUtil = new ExceptionUtil() - - if ((returnCode == '200') || (returnCode == '204')) { - - execution.setVariable('UPDVfModVol_aaiVolumeGroupResponse', aaiResponseAsString) - //def heatStackId = getNodeTextForce(aaiResponseAsString, 'heat-stack-id') - //execution.setVariable('UPDVfModVol_volumeGroupHeatStackId', heatStackId) - - def volumeGroupTenantId = getTenantIdFromVolumeGroup(aaiResponseAsString) - if (volumeGroupTenantId == null) { - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Could not find Tenant Id element in Volume Group with Volume Group Id " + volumeGroupId - + ", AIC Cloud Region " + aicCloudRegion) - } - execution.setVariable('UPDVfModVol_volumeGroupTenantId', volumeGroupTenantId) - msoLogger.debug("Received Tenant Id " + volumeGroupTenantId + " from AAI for Volume Group with Volume Group Id " + volumeGroupId + ", AIC Cloud Region " + aicCloudRegion) - - def relatedVfModuleLink = getRelatedVfModuleRelatedLink(aaiResponseAsString) - msoLogger.debug("Related VF Module link: " + relatedVfModuleLink) - execution.setVariable('UPDVfModVol_relatedVfModuleLink', relatedVfModuleLink) - - } - else if (returnCode == '404') { - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Volume Group " + volumeGroupId + " not found at AAI") - } - else { - WorkflowException aWorkflowException = exceptionUtil.MapAAIExceptionToWorkflowException(aaiResponseAsString, execution) - throw new BpmnError("MSOWorkflowException") - } - } - - /** - * Query AAI service instance - * @param execution - * @param isDebugEnabled - */ - public void queryAAIForGenericVnf(DelegateExecution execution, isDebugEnabled) { - - def vnfId = execution.getVariable('vnfId') - - AaiUtil aaiUtil = new AaiUtil(this) - AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId) - String queryAAIRequest = aaiUtil.createAaiUri(uri) - - msoLogger.debug("AAI query generic vnf request: " + queryAAIRequest) - - APIResponse response = aaiUtil.executeAAIGetCall(execution, queryAAIRequest) - - String returnCode = response.getStatusCode() - String aaiResponseAsString = response.getResponseBodyAsString() - - msoLogger.debug("AAI query generic vnf return code: " + returnCode) - msoLogger.debug("AAI query generic vnf response: " + aaiResponseAsString) - - ExceptionUtil exceptionUtil = new ExceptionUtil() - - if (returnCode=='200') { - msoLogger.debug('Generic vnf ' + vnfId + ' found in AAI.') - execution.setVariable('UPDVfModVol_AAIQueryGenericVfnResponse', aaiResponseAsString) - } else { - if (returnCode=='404') { - def message = 'Generic vnf ' + vnfId + ' was not found in AAI. Return code: 404.' - msoLogger.debug(message) - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, message) - } else { - WorkflowException aWorkflowException = exceptionUtil.MapAAIExceptionToWorkflowException(aaiResponseAsString, execution) - throw new BpmnError("MSOWorkflowException") - } - } - } - - /** - * Query AAI for VF Module using vf-module-id - * @param execution - * @param isDebugLogEnabled - */ - public void queryAAIForVfModule(DelegateExecution execution, isDebugLogEnabled) { - - AaiUtil aaiUtil = new AaiUtil(this) - String queryAAIVfModuleRequest = execution.getVariable('UPDVfModVol_relatedVfModuleLink') - execution.setVariable('UPDVfModVol_personaModelId', '') - - msoLogger.debug('Query AAI VF Module: ' + queryAAIVfModuleRequest) - msoLogger.debug('Query AAI VF Module: ' + queryAAIVfModuleRequest) - - def aaiUrl = UrnPropertiesReader.getVariable("aai.endpoint", execution) - msoLogger.debug('A&AI URL: ' + aaiUrl) - - def requestEndpoint = aaiUrl + queryAAIVfModuleRequest - msoLogger.debug('A&AI request endpoint: ' + requestEndpoint) - - APIResponse response = aaiUtil.executeAAIGetCall(execution, requestEndpoint) - - String returnCode = response.getStatusCode() - String aaiResponseAsString = response.getResponseBodyAsString() - - msoLogger.debug("AAI query vf-module: " + returnCode) - msoLogger.debug("AAI query vf-module response: " + aaiResponseAsString) - - msoLogger.debug("AAI query vf-module:: " + returnCode) - msoLogger.debug("AAI query vf-module response: " + aaiResponseAsString) - - ExceptionUtil exceptionUtil = new ExceptionUtil() - - if ((returnCode == '200') || (returnCode == '204')) { - def personaModelId = utils.getNodeText(aaiResponseAsString, 'model-invariant-id') - if(personaModelId == null) { - //check old attribute name - personaModelId = utils.getNodeText(aaiResponseAsString, 'persona-model-id') - } - msoLogger.debug("vfModule personaModelId: " + personaModelId) - execution.setVariable('UPDVfModVol_personaModelId', personaModelId) - } - else if (returnCode == '404') { - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "VF Module not found at AAI") - } - else { - WorkflowException aWorkflowException = exceptionUtil.MapAAIExceptionToWorkflowException(aaiResponseAsString, execution) - throw new BpmnError("MSOWorkflowException") - } - } - /** - * - */ - public String getRelatedVfModuleRelatedLink(xml) { - def list = new XmlSlurper().parseText(xml) - def vfModuleRelationship = list.'**'.find { node -> node.'related-to'.text() == 'vf-module' } - return vfModuleRelationship?.'related-link'?.text() ?: '' - } - - /** - * Prepare a Request for invoking the VnfAdapterRest subflow to do - * a Volume Group update. - * - * @param execution The flow's execution instance. - */ - public void prepVnfAdapterRest(DelegateExecution execution, isDebugLogEnabled) { - - def aicCloudRegion = execution.getVariable('UPDVfModVol_aicCloudRegion') - def tenantId = execution.getVariable('UPDVfModVol_tenantId') - def volumeGroupId = execution.getVariable('UPDVfModVol_volumeGroupId') - - def aaiVolumeGroupResponse = execution.getVariable('UPDVfModVol_aaiVolumeGroupResponse') - def volumeGroupHeatStackId = getNodeTextForce(aaiVolumeGroupResponse, 'heat-stack-id') - def volumeGroupName = getNodeTextForce(aaiVolumeGroupResponse, 'volume-group-name') - def modelCustomizationId = getNodeTextForce(aaiVolumeGroupResponse, 'vf-module-model-customization-id') - if(modelCustomizationId == null) { - // Check old attribute name - modelCustomizationId = getNodeTextForce(aaiVolumeGroupResponse, 'vf-module-persona-model-customization-id') - } - - def vnfType = execution.getVariable('UPDVfModVol_vnfType') - def vnfVersion = execution.getVariable('UPDVfModVol_vnfVersion') - - def aaiGenericVnfResponse = execution.getVariable('UPDVfModVol_AAIQueryGenericVfnResponse') - def vnfId = utils.getNodeText(aaiGenericVnfResponse, 'vnf-id') - def vnfName = utils.getNodeText(aaiGenericVnfResponse, 'vnf-name') - - - def volumeParamsXml = execution.getVariable('UPDVfModVol_volumeParams') - def volumeGroupParams = transformVolumeParamsToEntries(volumeParamsXml) - - def requestId = execution.getVariable('UPDVfModVol_requestId') - def serviceId = execution.getVariable('UPDVfModVol_serviceId') - - def messageId = execution.getVariable('mso-request-id') + '-' + System.currentTimeMillis() - def notificationUrl = createCallbackURL(execution, "VNFAResponse", messageId) - def useQualifiedHostName = UrnPropertiesReader.getVariable("mso.use.qualified.host",execution) - if ('true'.equals(useQualifiedHostName)) { - notificationUrl = utils.getQualifiedHostNameForCallback(notificationUrl) - } - - String vnfAdapterRestRequest = """ + def syncResponse = '' + def isVidRequest = execution.getVariable('UPDVfModVol_isVidRequest') + + if (isVidRequest) { + def volumeGroupId = execution.getVariable('volumeGroupId') + syncResponse = """{"requestReferences":{"instanceId":"${volumeGroupId}","requestId":"${ + requestId + }"}}""".trim() + } else { + syncResponse = utils.formatXml(xmlSyncResponse) + } + + msoLogger.debug('Sync response: ' + syncResponse) + execution.setVariable('UPDVfModVol_syncResponseSent', true) + sendWorkflowResponse(execution, 200, syncResponse) + } + + /** + * Prepare a Request for querying AAI for Volume Group information using the + * Volume Group Id and Aic Cloud Region. + * @param execution The flow's execution instance. + */ + public void queryAAIForVolumeGroup(DelegateExecution execution, isDebugLogEnabled) { + + def volumeGroupId = execution.getVariable('UPDVfModVol_volumeGroupId') + def aicCloudRegion = execution.getVariable('UPDVfModVol_aicCloudRegion') + + try { + AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.VOLUME_GROUP, Defaults.CLOUD_OWNER.toString(), aicCloudRegion, volumeGroupId) + AAIResultWrapper wrapper = getAAIClient().get(uri) + Optional<VolumeGroup> volumeGroup = wrapper.asBean(VolumeGroup.class) + if (volumeGroup.isPresent()) { + execution.setVariable('UPDVfModVol_aaiVolumeGroupResponse', volumeGroup.get()) + Optional<Relationships> relationships = wrapper.getRelationships() + if (relationships.isPresent()) { + List<AAIResourceUri> tenantURIList = relationships.get().getRelatedAAIUris(AAIObjectType.TENANT) + if (!isEmpty(tenantURIList)) { + String volumeGroupTenantId = tenantURIList.get(0).getURIKeys().get("tenant-id") + execution.setVariable('UPDVfModVol_volumeGroupTenantId', volumeGroupTenantId) + msoLogger.debug("Received Tenant Id " + volumeGroupTenantId + " from AAI for Volume Group with Volume Group Id " + volumeGroupId + ", AIC Cloud Region " + aicCloudRegion) + } else { + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Could not find Tenant Id element in Volume Group with Volume Group Id " + volumeGroupId + + ", AIC Cloud Region " + aicCloudRegion) + } + execution.setVariable('UPDVfModVol_relatedVfModuleLink', relationships.get().getRelatedLinks(AAIObjectType.VF_MODULE).get(0)) + + } else { + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Could not find Tenant Id element in Volume Group with Volume Group Id " + volumeGroupId + + ", AIC Cloud Region " + aicCloudRegion) + } + } else { + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Volume Group " + volumeGroupId + " not found at AAI") + } + }catch(BpmnError bpmnError){ + throw bpmnError + }catch(Exception e){ + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured During queryAAIForGenericVnf"+e.getMessage()) + } + } + + /** + * Query AAI service instance + * @param execution + * @param isDebugEnabled + */ + public void queryAAIForGenericVnf(DelegateExecution execution, isDebugEnabled) { + + def vnfId = execution.getVariable('vnfId') + + AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId) + try { + Optional<GenericVnf> genericVnf = getAAIClient().get(GenericVnf.class, uri) + if (genericVnf.isPresent()) { + execution.setVariable('UPDVfModVol_AAIQueryGenericVfnResponse', genericVnf.get()) + } else { + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, 'Generic vnf ' + vnfId + ' was not found in AAI. Return code: 404.') + } + }catch(BpmnError bpmnError){ + throw bpmnError + }catch(Exception e){ + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured During queryAAIForGenericVnf"+e.getMessage()) + } + } + + /** + * Query AAI for VF Module using vf-module-id + * @param execution + * @param isDebugLogEnabled + */ + public void queryAAIForVfModule(DelegateExecution execution, isDebugLogEnabled) { + + String queryAAIVfModuleRequest = execution.getVariable('UPDVfModVol_relatedVfModuleLink') + execution.setVariable('UPDVfModVol_personaModelId', '') + AAIResourceUri uri = AAIUriFactory.createResourceFromExistingURI(AAIObjectType.VF_MODULE, UriBuilder.fromPath(queryAAIVfModuleRequest).build()) + try{ + Optional<VfModule> vfModule = getAAIClient().get(VfModule.class,uri) + if(vfModule.isPresent()){ + execution.setVariable('UPDVfModVol_personaModelId',vfModule.get().getModelInvariantId()) + }else{ + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "VF Module not found at AAI") + } + }catch(BpmnError bpmnError){ + throw bpmnError + }catch(Exception e){ + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Error in queryAAIForVfModule: "+e.getMessage()) + } + } + + /** + * Prepare a Request for invoking the VnfAdapterRest subflow to do + * a Volume Group update. + * + * @param execution The flow's execution instance. + */ + public void prepVnfAdapterRest(DelegateExecution execution, isDebugLogEnabled) { + + def aicCloudRegion = execution.getVariable('UPDVfModVol_aicCloudRegion') + def tenantId = execution.getVariable('UPDVfModVol_tenantId') + def volumeGroupId = execution.getVariable('UPDVfModVol_volumeGroupId') + + VolumeGroup aaiVolumeGroupResponse = execution.getVariable('UPDVfModVol_aaiVolumeGroupResponse') + def volumeGroupHeatStackId = aaiVolumeGroupResponse.getHeatStackId() + def volumeGroupName = aaiVolumeGroupResponse.getVolumeGroupName() + def modelCustomizationId = aaiVolumeGroupResponse.getModelCustomizationId() + + def vnfType = execution.getVariable('UPDVfModVol_vnfType') + def vnfVersion = execution.getVariable('UPDVfModVol_vnfVersion') + + GenericVnf aaiGenericVnfResponse = execution.getVariable('UPDVfModVol_AAIQueryGenericVfnResponse') + def vnfId = aaiGenericVnfResponse.getVnfId() + def vnfName = aaiGenericVnfResponse.getVnfName() + + + def volumeParamsXml = execution.getVariable('UPDVfModVol_volumeParams') + def volumeGroupParams = transformVolumeParamsToEntries(volumeParamsXml) + + def requestId = execution.getVariable('UPDVfModVol_requestId') + def serviceId = execution.getVariable('UPDVfModVol_serviceId') + + def messageId = execution.getVariable('mso-request-id') + '-' + System.currentTimeMillis() + def notificationUrl = createCallbackURL(execution, "VNFAResponse", messageId) + def useQualifiedHostName = UrnPropertiesReader.getVariable("mso.use.qualified.host", execution) + if ('true'.equals(useQualifiedHostName)) { + notificationUrl = utils.getQualifiedHostNameForCallback(notificationUrl) + } + + String vnfAdapterRestRequest = """ <updateVolumeGroupRequest> <cloudSiteId>${MsoUtils.xmlEscape(aicCloudRegion)}</cloudSiteId> <tenantId>${MsoUtils.xmlEscape(tenantId)}</tenantId> @@ -426,22 +361,21 @@ class UpdateVfModuleVolumeInfraV1 extends VfModuleBase { <notificationUrl>${MsoUtils.xmlEscape(notificationUrl)}</notificationUrl> </updateVolumeGroupRequest> """ - vnfAdapterRestRequest = utils.formatXml(vnfAdapterRestRequest) - execution.setVariable('UPDVfModVol_vnfAdapterRestRequest', vnfAdapterRestRequest) - msoLogger.debug('Request for VNFAdapter Rest:\n' + vnfAdapterRestRequest) - } - - /** - * Prepare a Request for updating the DB for this Infra request. - * - * @param execution The flow's execution instance. - */ - public void prepDbInfraDbRequest(DelegateExecution execution, isDebugLogEnabled) { - - def requestId = execution.getVariable('UPDVfModVol_requestId') - ExceptionUtil exceptionUtil = new ExceptionUtil(); - - String updateInfraRequest = """ + vnfAdapterRestRequest = utils.formatXml(vnfAdapterRestRequest) + execution.setVariable('UPDVfModVol_vnfAdapterRestRequest', vnfAdapterRestRequest) + msoLogger.debug('Request for VNFAdapter Rest:\n' + vnfAdapterRestRequest) + } + + /** + * Prepare a Request for updating the DB for this Infra request. + * + * @param execution The flow's execution instance. + */ + public void prepDbInfraDbRequest(DelegateExecution execution, isDebugLogEnabled) { + + def requestId = execution.getVariable('UPDVfModVol_requestId') + + String updateInfraRequest = """ <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:req="http://org.onap.so/requestsdb"> <soapenv:Header/> @@ -456,18 +390,18 @@ class UpdateVfModuleVolumeInfraV1 extends VfModuleBase { </soapenv:Envelope> """ - updateInfraRequest = utils.formatXml(updateInfraRequest) - execution.setVariable('UPDVfModVol_updateInfraRequest', updateInfraRequest) - msoLogger.debug('Request for Update Infra Request:\n' + updateInfraRequest) - } + updateInfraRequest = utils.formatXml(updateInfraRequest) + execution.setVariable('UPDVfModVol_updateInfraRequest', updateInfraRequest) + msoLogger.debug('Request for Update Infra Request:\n' + updateInfraRequest) + } - /** - * Build a "CompletionHandler" request. - * @param execution The flow's execution instance. - */ - public void prepCompletionHandlerRequest(DelegateExecution execution, requestId, action, source, isDebugLogEnabled) { + /** + * Build a "CompletionHandler" request. + * @param execution The flow's execution instance. + */ + public void prepCompletionHandlerRequest(DelegateExecution execution, requestId, action, source, isDebugLogEnabled) { - String content = """ + String content = """ <aetgt:MsoCompletionRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1" xmlns:ns="http://org.onap/so/request/types/v1"> <request-info xmlns="http://org.onap/so/infra/vnf-request/v1"> @@ -476,91 +410,90 @@ class UpdateVfModuleVolumeInfraV1 extends VfModuleBase { <source>${MsoUtils.xmlEscape(source)}</source> </request-info> <aetgt:mso-bpel-name>BPMN VF Module Volume action: UPDATE</aetgt:mso-bpel-name> - </aetgt:MsoCompletionRequest> + </aetgt:MsoCompletionRequest> """ - content = utils.formatXml(content) - msoLogger.debug('Request for Completion Handler:\n' + content) - execution.setVariable('UPDVfModVol_CompletionHandlerRequest', content) - } - + content = utils.formatXml(content) + msoLogger.debug('Request for Completion Handler:\n' + content) + execution.setVariable('UPDVfModVol_CompletionHandlerRequest', content) + } - /** - * Build a "FalloutHandler" request. - * @param execution The flow's execution instance. - */ - public void prepFalloutHandler(DelegateExecution execution, isDebugLogEnabled) { - def requestId = execution.getVariable('UPDVfModVol_requestId') - def source = execution.getVariable('UPDVfModVol_source') + /** + * Build a "FalloutHandler" request. + * @param execution The flow's execution instance. + */ + public void prepFalloutHandler(DelegateExecution execution, isDebugLogEnabled) { + def requestId = execution.getVariable('UPDVfModVol_requestId') + def source = execution.getVariable('UPDVfModVol_source') - String requestInfo = """ + String requestInfo = """ <request-info xmlns="http://org.onap/so/infra/vnf-request/v1"> <request-id>${MsoUtils.xmlEscape(requestId)}</request-id> <action>UPDATE</action> <source>${MsoUtils.xmlEscape(source)}</source> </request-info>""" - def WorkflowException workflowException = execution.getVariable("WorkflowException") - def errorResponseCode = workflowException.getErrorCode() - def errorResponseMsg = workflowException.getErrorMessage() - def encErrorResponseMsg = "" - if (errorResponseMsg != null) { - encErrorResponseMsg = errorResponseMsg - } + WorkflowException workflowException = execution.getVariable("WorkflowException") + def errorResponseCode = workflowException.getErrorCode() + def errorResponseMsg = workflowException.getErrorMessage() + def encErrorResponseMsg = "" + if (errorResponseMsg != null) { + encErrorResponseMsg = errorResponseMsg + } - String content = """ + String content = """ <sdncadapterworkflow:FalloutHandlerRequest xmlns:sdncadapterworkflow="http://org.onap/so/workflow/schema/v1" xmlns:reqtype="http://org.onap/so/request/types/v1" xmlns:msoservtypes="http://org.onap/so/request/types/v1" - xmlns:structuredtypes="http://org.onap/so/structured/types/v1"> + xmlns:structuredtypes="http://org.onap/so/structured/types/v1"> ${requestInfo} <sdncadapterworkflow:WorkflowException> <sdncadapterworkflow:ErrorMessage>${MsoUtils.xmlEscape(encErrorResponseMsg)}</sdncadapterworkflow:ErrorMessage> <sdncadapterworkflow:ErrorCode>${MsoUtils.xmlEscape(errorResponseCode)}</sdncadapterworkflow:ErrorCode> - </sdncadapterworkflow:WorkflowException> + </sdncadapterworkflow:WorkflowException> </sdncadapterworkflow:FalloutHandlerRequest> """ - content = utils.formatXml(content) - msoLogger.debug('Request for Fallout Handler:\n' + content) - execution.setVariable('UPDVfModVol_FalloutHandlerRequest', content) - } - - /** - * Create a WorkflowException for the error case where the Tenant Id from - * AAI did not match the Tenant Id in the incoming request. - * @param execution The flow's execution instance. - */ - public void handleTenantIdMismatch(DelegateExecution execution, isDebugLogEnabled) { - - def volumeGroupId = execution.getVariable('UPDVfModVol_volumeGroupId') - def aicCloudRegion = execution.getVariable('UPDVfModVol_aicCloudRegion') - def tenantId = execution.getVariable('UPDVfModVol_tenantId') - def volumeGroupTenantId = execution.getVariable('UPDVfModVol_volumeGroupTenantId') - - def String errorMessage = "TenantId " + tenantId + " in incoming request does not match Tenant Id " + volumeGroupTenantId + - " retrieved from AAI for Volume Group Id " + volumeGroupId + ", AIC Cloud Region " + aicCloudRegion - - ExceptionUtil exceptionUtil = new ExceptionUtil() - msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Error in UpdateVfModuleVol: ' + errorMessage, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception"); - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, errorMessage) - } - - /** - * Create a WorkflowException for the error case where the Personal Model Id from - * AAI did not match the model invariant ID in the incoming request. - * @param execution The flow's execution instance. - */ - public void handlePersonaModelIdMismatch(DelegateExecution execution, isDebugLogEnabled) { - - def modelInvariantId = execution.getVariable('UPDVfModVol_modelInvariantId') - def personaModelId = execution.getVariable('UPDVfModVol_personaModelId') - - def String errorMessage = "Model Invariant ID " + modelInvariantId + " in incoming request does not match persona model ID " + personaModelId + - " retrieved from AAI for Volume Group Id " - - ExceptionUtil exceptionUtil = new ExceptionUtil() - msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Error in UpdateVfModuleVol: ' + errorMessage, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception"); - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, errorMessage) - } + content = utils.formatXml(content) + msoLogger.debug('Request for Fallout Handler:\n' + content) + execution.setVariable('UPDVfModVol_FalloutHandlerRequest', content) + } + + /** + * Create a WorkflowException for the error case where the Tenant Id from + * AAI did not match the Tenant Id in the incoming request. + * @param execution The flow's execution instance. + */ + public void handleTenantIdMismatch(DelegateExecution execution, isDebugLogEnabled) { + + def volumeGroupId = execution.getVariable('UPDVfModVol_volumeGroupId') + def aicCloudRegion = execution.getVariable('UPDVfModVol_aicCloudRegion') + def tenantId = execution.getVariable('UPDVfModVol_tenantId') + def volumeGroupTenantId = execution.getVariable('UPDVfModVol_volumeGroupTenantId') + + String errorMessage = "TenantId " + tenantId + " in incoming request does not match Tenant Id " + volumeGroupTenantId + + " retrieved from AAI for Volume Group Id " + volumeGroupId + ", AIC Cloud Region " + aicCloudRegion + + ExceptionUtil exceptionUtil = new ExceptionUtil() + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Error in UpdateVfModuleVol: ' + errorMessage, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception") + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, errorMessage) + } + + /** + * Create a WorkflowException for the error case where the Personal Model Id from + * AAI did not match the model invariant ID in the incoming request. + * @param execution The flow's execution instance. + */ + public void handlePersonaModelIdMismatch(DelegateExecution execution, isDebugLogEnabled) { + + def modelInvariantId = execution.getVariable('UPDVfModVol_modelInvariantId') + def personaModelId = execution.getVariable('UPDVfModVol_personaModelId') + + String errorMessage = "Model Invariant ID " + modelInvariantId + " in incoming request does not match persona model ID " + personaModelId + + " retrieved from AAI for Volume Group Id " + + ExceptionUtil exceptionUtil = new ExceptionUtil() + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Error in UpdateVfModuleVol: ' + errorMessage, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception") + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, errorMessage) + } } diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/UpdateVnfInfra.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/UpdateVnfInfra.groovy index 4978faf46c..f8d73ce020 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/UpdateVnfInfra.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/UpdateVnfInfra.groovy @@ -321,12 +321,11 @@ public class UpdateVnfInfra extends VnfCmBase { msoLogger.trace('Entered ' + method) try { - def transactionLoggingUuid = UUID.randomUUID().toString() AAIRestClientImpl client = new AAIRestClientImpl() AAIValidatorImpl aaiValidator = new AAIValidatorImpl() aaiValidator.setClient(client) def vnfId = execution.getVariable("vnfId") - boolean isInMaint = aaiValidator.isVNFLocked(vnfId, transactionLoggingUuid) + boolean isInMaint = aaiValidator.isVNFLocked(vnfId) msoLogger.debug("isInMaint result: " + isInMaint) execution.setVariable('isVnfInMaintenance', isInMaint) @@ -365,12 +364,11 @@ public class UpdateVnfInfra extends VnfCmBase { execution.setVariable("failedActivity", "AAI") try { - def transactionLoggingUuid = UUID.randomUUID().toString() AAIRestClientImpl client = new AAIRestClientImpl() AAIValidatorImpl aaiValidator = new AAIValidatorImpl() aaiValidator.setClient(client) def vnfId = execution.getVariable("vnfId") - boolean areLocked = aaiValidator.isPhysicalServerLocked(vnfId, transactionLoggingUuid) + boolean areLocked = aaiValidator.isPhysicalServerLocked(vnfId) msoLogger.debug("areLocked result: " + areLocked) execution.setVariable('arePserversLocked', areLocked) @@ -413,17 +411,16 @@ public class UpdateVnfInfra extends VnfCmBase { execution.setVariable("failedActivity", "AAI") try { - def transactionLoggingUuid = UUID.randomUUID().toString() AAIRestClientImpl client = new AAIRestClientImpl() AAIUpdatorImpl aaiUpdator = new AAIUpdatorImpl() aaiUpdator.setClient(client) def vnfId = execution.getVariable("vnfId") if (inMaint) { - aaiUpdator.updateVnfToLocked(vnfId, transactionLoggingUuid) + aaiUpdator.updateVnfToLocked(vnfId) execution.setVariable("rollbackSetVnfInMaintenanceFlag", true) } else { - aaiUpdator.updateVnfToUnLocked(vnfId, transactionLoggingUuid) + aaiUpdator.updateVnfToUnLocked(vnfId) } msoLogger.trace('Exited ' + method) @@ -433,7 +430,6 @@ public class UpdateVnfInfra extends VnfCmBase { msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); execution.setVariable("errorCode", "1002") execution.setVariable("errorText", e.getMessage()) - //exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in setVnfInMaintFlagInAAI(): ' + e.getMessage()) } } diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/VnfCmBase.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/VnfCmBase.groovy index fd9d9cc8a3..4237a8d6a4 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/VnfCmBase.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/VnfCmBase.groovy @@ -167,12 +167,11 @@ public abstract class VnfCmBase extends AbstractServiceTaskProcessor { msoLogger.trace('Entered ' + method) try { - def transactionLoggingUuid = UUID.randomUUID().toString() AAIRestClientImpl client = new AAIRestClientImpl() AAIValidatorImpl aaiValidator = new AAIValidatorImpl() aaiValidator.setClient(client) def vnfId = execution.getVariable("vnfId") - boolean isInMaint = aaiValidator.isVNFLocked(vnfId, transactionLoggingUuid) + boolean isInMaint = aaiValidator.isVNFLocked(vnfId) msoLogger.debug("isInMaint result: " + isInMaint) execution.setVariable('isVnfInMaintenance', isInMaint) @@ -355,12 +354,11 @@ public abstract class VnfCmBase extends AbstractServiceTaskProcessor { execution.setVariable("failedActivity", "AAI") try { - def transactionLoggingUuid = UUID.randomUUID().toString() AAIRestClientImpl client = new AAIRestClientImpl() AAIValidatorImpl aaiValidator = new AAIValidatorImpl() aaiValidator.setClient(client) def vnfId = execution.getVariable("vnfId") - boolean areLocked = aaiValidator.isPhysicalServerLocked(vnfId, transactionLoggingUuid) + boolean areLocked = aaiValidator.isPhysicalServerLocked(vnfId) msoLogger.debug("areLocked result: " + areLocked) execution.setVariable('arePserversLocked', areLocked) @@ -403,17 +401,16 @@ public abstract class VnfCmBase extends AbstractServiceTaskProcessor { execution.setVariable("failedActivity", "AAI") try { - def transactionLoggingUuid = UUID.randomUUID().toString() AAIRestClientImpl client = new AAIRestClientImpl() AAIUpdatorImpl aaiUpdator = new AAIUpdatorImpl() aaiUpdator.setClient(client) def vnfId = execution.getVariable("vnfId") if (inMaint) { - aaiUpdator.updateVnfToLocked(vnfId, transactionLoggingUuid) + aaiUpdator.updateVnfToLocked(vnfId) execution.setVariable("rollbackSetVnfInMaintenanceFlag", true) } else { - aaiUpdator.updateVnfToUnLocked(vnfId, transactionLoggingUuid) + aaiUpdator.updateVnfToUnLocked(vnfId) } msoLogger.trace('Exited ' + method) @@ -423,7 +420,6 @@ public abstract class VnfCmBase extends AbstractServiceTaskProcessor { msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); execution.setVariable("errorCode", "1002") execution.setVariable("errorText", e.getMessage()) - //exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in setVnfInMaintFlagInAAI(): ' + e.getMessage()) } } diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/VnfConfigUpdate.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/VnfConfigUpdate.groovy index 8ca2871916..89f40ed680 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/VnfConfigUpdate.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/VnfConfigUpdate.groovy @@ -219,12 +219,11 @@ public class VnfConfigUpdate extends VnfCmBase { msoLogger.trace('Entered ' + method) try { - def transactionLoggingUuid = UUID.randomUUID().toString() AAIRestClientImpl client = new AAIRestClientImpl() AAIValidatorImpl aaiValidator = new AAIValidatorImpl() aaiValidator.setClient(client) def vnfId = execution.getVariable("vnfId") - boolean isInMaint = aaiValidator.isVNFLocked(vnfId, transactionLoggingUuid) + boolean isInMaint = aaiValidator.isVNFLocked(vnfId) msoLogger.debug("isInMaint result: " + isInMaint) execution.setVariable('isVnfInMaintenance', isInMaint) @@ -262,12 +261,11 @@ public class VnfConfigUpdate extends VnfCmBase { execution.setVariable("failedActivity", "AAI") try { - def transactionLoggingUuid = UUID.randomUUID().toString() AAIRestClientImpl client = new AAIRestClientImpl() AAIValidatorImpl aaiValidator = new AAIValidatorImpl() aaiValidator.setClient(client) def vnfId = execution.getVariable("vnfId") - boolean areLocked = aaiValidator.isPhysicalServerLocked(vnfId, transactionLoggingUuid) + boolean areLocked = aaiValidator.isPhysicalServerLocked(vnfId) msoLogger.debug("areLocked result: " + areLocked) execution.setVariable('arePserversLocked', areLocked) @@ -312,17 +310,16 @@ public class VnfConfigUpdate extends VnfCmBase { execution.setVariable("failedActivity", "AAI") try { - def transactionLoggingUuid = UUID.randomUUID().toString() AAIRestClientImpl client = new AAIRestClientImpl() AAIUpdatorImpl aaiUpdator = new AAIUpdatorImpl() aaiUpdator.setClient(client) def vnfId = execution.getVariable("vnfId") if (inMaint) { - aaiUpdator.updateVnfToLocked(vnfId, transactionLoggingUuid) + aaiUpdator.updateVnfToLocked(vnfId) execution.setVariable("rollbackSetVnfInMaintenanceFlag", true) } else { - aaiUpdator.updateVnfToUnLocked(vnfId, transactionLoggingUuid) + aaiUpdator.updateVnfToUnLocked(vnfId) } msoLogger.trace('Exited ' + method) @@ -332,7 +329,6 @@ public class VnfConfigUpdate extends VnfCmBase { msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); execution.setVariable("errorCode", "1002") execution.setVariable("errorText", e.getMessage()) - //exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in setVnfInMaintFlagInAAI(): ' + e.getMessage()) } } diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/VnfInPlaceUpdate.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/VnfInPlaceUpdate.groovy index 2c1b66ded5..84668a5c61 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/VnfInPlaceUpdate.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/VnfInPlaceUpdate.groovy @@ -240,12 +240,11 @@ public class VnfInPlaceUpdate extends VnfCmBase { msoLogger.trace('Entered ' + method) try { - def transactionLoggingUuid = UUID.randomUUID().toString() AAIRestClientImpl client = new AAIRestClientImpl() AAIValidatorImpl aaiValidator = new AAIValidatorImpl() aaiValidator.setClient(client) def vnfId = execution.getVariable("vnfId") - boolean isInMaint = aaiValidator.isVNFLocked(vnfId, transactionLoggingUuid) + boolean isInMaint = aaiValidator.isVNFLocked(vnfId) msoLogger.debug("isInMaint result: " + isInMaint) execution.setVariable('isVnfInMaintenance', isInMaint) @@ -284,12 +283,11 @@ public class VnfInPlaceUpdate extends VnfCmBase { execution.setVariable("failedActivity", "AAI") try { - def transactionLoggingUuid = UUID.randomUUID().toString() AAIRestClientImpl client = new AAIRestClientImpl() AAIValidatorImpl aaiValidator = new AAIValidatorImpl() aaiValidator.setClient(client) def vnfId = execution.getVariable("vnfId") - boolean areLocked = aaiValidator.isPhysicalServerLocked(vnfId, transactionLoggingUuid) + boolean areLocked = aaiValidator.isPhysicalServerLocked(vnfId) msoLogger.debug("areLocked result: " + areLocked) execution.setVariable('arePserversLocked', areLocked) @@ -332,17 +330,16 @@ public class VnfInPlaceUpdate extends VnfCmBase { execution.setVariable("failedActivity", "AAI") try { - def transactionLoggingUuid = UUID.randomUUID().toString() AAIRestClientImpl client = new AAIRestClientImpl() AAIUpdatorImpl aaiUpdator = new AAIUpdatorImpl() aaiUpdator.setClient(client) def vnfId = execution.getVariable("vnfId") if (inMaint) { - aaiUpdator.updateVnfToLocked(vnfId, transactionLoggingUuid) + aaiUpdator.updateVnfToLocked(vnfId) execution.setVariable("rollbackSetVnfInMaintenanceFlag", true) } else { - aaiUpdator.updateVnfToUnLocked(vnfId, transactionLoggingUuid) + aaiUpdator.updateVnfToUnLocked(vnfId) } msoLogger.trace('Exited ' + method) @@ -352,7 +349,6 @@ public class VnfInPlaceUpdate extends VnfCmBase { msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); execution.setVariable("errorCode", "1002") execution.setVariable("errorText", e.getMessage()) - //exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in setVnfInMaintFlagInAAI(): ' + e.getMessage()) } } diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/vcpe/scripts/CreateVcpeResCustService.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/vcpe/scripts/CreateVcpeResCustService.groovy index eea784f591..13d5aad2b0 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/vcpe/scripts/CreateVcpeResCustService.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/vcpe/scripts/CreateVcpeResCustService.groovy @@ -24,7 +24,6 @@ import static org.apache.commons.lang3.StringUtils.* import org.camunda.bpm.engine.delegate.BpmnError import org.camunda.bpm.engine.delegate.DelegateExecution import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor -import org.onap.so.bpmn.common.scripts.CatalogDbUtils import org.onap.so.bpmn.common.scripts.ExceptionUtil import org.onap.so.bpmn.common.scripts.MsoUtils import org.onap.so.bpmn.common.scripts.VidUtils @@ -55,7 +54,6 @@ public class CreateVcpeResCustService extends AbstractServiceTaskProcessor { ExceptionUtil exceptionUtil = new ExceptionUtil() JsonUtils jsonUtil = new JsonUtils() VidUtils vidUtils = new VidUtils() - CatalogDbUtils catalogDbUtils = new CatalogDbUtils() /** * This method is executed during the preProcessRequest task of the <class>CreateServiceInstance.bpmn</class> process. diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/vcpe/scripts/DeleteVcpeResCustService.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/vcpe/scripts/DeleteVcpeResCustService.groovy index 8a3dcbab5d..7a40ef978b 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/vcpe/scripts/DeleteVcpeResCustService.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/vcpe/scripts/DeleteVcpeResCustService.groovy @@ -21,18 +21,15 @@ package org.onap.so.bpmn.vcpe.scripts import org.camunda.bpm.engine.delegate.BpmnError import org.camunda.bpm.engine.delegate.DelegateExecution -import org.onap.so.bpmn.common.scripts.AaiUtil import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor -import org.onap.so.bpmn.common.scripts.CatalogDbUtils import org.onap.so.bpmn.common.scripts.ExceptionUtil import org.onap.so.bpmn.common.scripts.NetworkUtils import org.onap.so.bpmn.common.scripts.VidUtils -import org.onap.so.bpmn.core.UrnPropertiesReader import org.onap.so.bpmn.core.WorkflowException import org.onap.so.bpmn.core.json.JsonUtils import org.onap.so.logger.MessageEnum import org.onap.so.logger.MsoLogger -import org.onap.so.rest.APIResponse + import org.onap.so.client.aai.AAIResourcesClient import org.onap.so.client.aai.AAIObjectType import org.onap.so.client.aai.entities.AAIResultWrapper @@ -40,10 +37,6 @@ 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 javax.ws.rs.NotFoundException -import org.json.JSONObject - -import static org.apache.commons.lang3.StringUtils.isBlank - /** * This groovy class supports the <class>DeleteVcpeResCustService.bpmn</class> process. @@ -60,7 +53,6 @@ public class DeleteVcpeResCustService extends AbstractServiceTaskProcessor { ExceptionUtil exceptionUtil = new ExceptionUtil() JsonUtils jsonUtil = new JsonUtils() VidUtils vidUtils = new VidUtils() - CatalogDbUtils catalogDbUtils = new CatalogDbUtils() NetworkUtils networkUtils = new NetworkUtils() /** diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/vcpe/scripts/DoCreateAllottedResourceBRG.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/vcpe/scripts/DoCreateAllottedResourceBRG.groovy index 723bfd54d7..e7baccd460 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/vcpe/scripts/DoCreateAllottedResourceBRG.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/vcpe/scripts/DoCreateAllottedResourceBRG.groovy @@ -18,33 +18,28 @@ * ============LICENSE_END========================================================= */ -package org.onap.so.bpmn.vcpe.scripts; +package org.onap.so.bpmn.vcpe.scripts -import org.onap.so.bpmn.common.scripts.*; -import org.onap.so.bpmn.common.scripts.AaiUtil +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.delegate.DelegateExecution +import org.onap.aai.domain.yang.AllottedResource +import org.onap.so.bpmn.common.scripts.* import org.onap.so.bpmn.core.RollbackData -import org.onap.so.bpmn.core.WorkflowException import org.onap.so.bpmn.core.UrnPropertiesReader +import org.onap.so.bpmn.core.WorkflowException import org.onap.so.bpmn.core.json.JsonUtils -import org.onap.so.rest.APIResponse - -import java.util.UUID; -import org.camunda.bpm.engine.delegate.BpmnError -import org.camunda.bpm.engine.delegate.DelegateExecution -import org.apache.commons.lang3.* -import org.springframework.web.util.UriUtils; -import static org.apache.commons.lang3.StringUtils.* - -import org.onap.so.logger.MessageEnum -import org.onap.so.logger.MsoLogger -import org.onap.so.client.aai.AAIResourcesClient 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.AAIResourcesClient import org.onap.so.client.aai.entities.uri.AAIResourceUri import org.onap.so.client.aai.entities.uri.AAIUriFactory -import org.json.JSONObject +import org.onap.so.logger.MessageEnum +import org.onap.so.logger.MsoLogger + import javax.ws.rs.NotFoundException +import javax.ws.rs.core.UriBuilder + +import static org.apache.commons.lang3.StringUtils.isBlank + /** * This groovy class supports the <class>DoCreateAllottedResourceBRG.bpmn</class> process. * @@ -233,17 +228,13 @@ public class DoCreateAllottedResourceBRG extends AbstractServiceTaskProcessor{ String serviceInstanceId = execution.getVariable('parentServiceInstanceId') AAIResourcesClient resourceClient = new AAIResourcesClient() - AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.NODES_QUERY, "").queryParam("search-node-type", "service-instance").queryParam("filter", "service-instance-id:EQUALS:" + serviceInstanceId) - String json = resourceClient.get(uri).getJson() - - JSONObject obj = new JSONObject(json) - if(obj.has("result-data")){ - JSONObject ob = obj.getJSONArray("result-data").getJSONObject(0) - String resourceLink = ob.getString("resource-link") - AAIResourceUri siUri = AAIUriFactory.createResourceFromExistingURI(AAIObjectType.SERVICE_INSTANCE, new URI(resourceLink)) + AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, serviceInstanceId) - execution.setVariable("PSI_resourceLink", siUri) - }else{ + try { + //just to make sure the serviceInstance exists + uri.build() + execution.setVariable("PSI_resourceLink", uri) + } catch (NotFoundException e) { exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Service instance was not found in aai") } @@ -262,7 +253,6 @@ public class DoCreateAllottedResourceBRG extends AbstractServiceTaskProcessor{ msoLogger.trace("start createAaiAR") - String msg = "" String allottedResourceId = execution.getVariable("allottedResourceId") if (isBlank(allottedResourceId)) @@ -270,84 +260,32 @@ public class DoCreateAllottedResourceBRG extends AbstractServiceTaskProcessor{ allottedResourceId = UUID.randomUUID().toString() execution.setVariable("allottedResourceId", allottedResourceId) } - String arUrl = "" try { - //AAI PUT - AaiUtil aaiUriUtil = new AaiUtil(this) AAIResourceUri siResourceLink= execution.getVariable("PSI_resourceLink") - AllottedResourceUtils arUtils = new AllottedResourceUtils(this) - arUrl = arUtils.createARUrl(execution, siResourceLink, allottedResourceId) - execution.setVariable("aaiARPath", arUrl) - msoLogger.debug("PUT AllottedResource AAI URL is:\n" + arUrl) - String namespace = aaiUriUtil.getNamespaceFromUri(execution, arUrl) + AAIResourceUri allottedResourceUri = AAIUriFactory.createResourceFromParentURI(siResourceLink, AAIObjectType.ALLOTTED_RESOURCE, allottedResourceId) + execution.setVariable("aaiARPath", allottedResourceUri.build().toString()); String arType = execution.getVariable("allottedResourceType") String arRole = execution.getVariable("allottedResourceRole") String CSI_resourceLink = execution.getVariable("CSI_resourceLink") + String arModelInfo = execution.getVariable("allottedResourceModelInfo") String modelInvariantId = jsonUtil.getJsonValue(arModelInfo, "modelInvariantUuid") String modelVersionId = jsonUtil.getJsonValue(arModelInfo, "modelUuid") - String modelCustomizationId = jsonUtil.getJsonValue(arModelInfo, "modelCustomizationUuid") - - if (modelInvariantId == null) { - modelInvariantId = "" - } - if (modelVersionId == null) { - modelVersionId = "" - } - if (modelCustomizationId == null) { - modelCustomizationId = "" - } - String payload = - """<allotted-resource xmlns="${namespace}"> - <id>${MsoUtils.xmlEscape(allottedResourceId)}</id> - <description></description> - <type>${MsoUtils.xmlEscape(arType)}</type> - <role>${MsoUtils.xmlEscape(arRole)}</role> - <selflink></selflink> - <model-invariant-id>${MsoUtils.xmlEscape(modelInvariantId)}</model-invariant-id> - <model-version-id>${MsoUtils.xmlEscape(modelVersionId)}</model-version-id> - <model-customization-id>${MsoUtils.xmlEscape(modelCustomizationId)}</model-customization-id> - <orchestration-status>PendingCreate</orchestration-status> - <operation-status></operation-status> - <relationship-list> - <relationship> - <related-to>service-instance</related-to> - <related-link>${MsoUtils.xmlEscape(CSI_resourceLink)}</related-link> - </relationship> - </relationship-list> - </allotted-resource>""".trim() - - execution.setVariable("AaiARPayload", payload) - msoLogger.debug(" payload to create AllottedResource in AAI:" + "\n" + payload) - - APIResponse response = aaiUriUtil.executeAAIPutCall(execution, arUrl, payload) - int responseCode = response.getStatusCode() - msoLogger.debug("AllottedResource AAI PUT responseCode:" + responseCode) - - String aaiResponse = response.getResponseBodyAsString() - msoLogger.debug("AllottedResource AAI PUT responseStr:" + aaiResponse) - - //200 OK 201 CREATED 202 ACCEPTED - if(responseCode == 200 || responseCode == 201 || responseCode == 202 ) - { - msoLogger.debug("AAI PUT AllottedResource received a Good Response") - } - else{ - msoLogger.debug("AAI Put AllottedResouce received a Bad Response Code: " + responseCode) - exceptionUtil.MapAAIExceptionToWorkflowExceptionGeneric(execution, aaiResponse, responseCode) - throw new BpmnError("MSOWorkflowException") - } - }catch(BpmnError b){ - msoLogger.debug("Rethrowing MSOWorkflowException") - throw b - } catch (Exception ex) { - msg = "Exception in createAaiAR " + ex.getMessage() - msoLogger.debug(msg) - exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + AllottedResource resource = new AllottedResource() + resource.setId(allottedResourceId) + resource.setType(arType) + resource.setRole(arRole) + resource.setModelInvariantId(modelInvariantId) + resource.setModelVersionId(modelVersionId) + getAAIClient().create(allottedResourceUri, resource) + AAIResourceUri serviceInstanceUri = AAIUriFactory.createResourceFromExistingURI(AAIObjectType.SERVICE_INSTANCE, UriBuilder.fromPath(CSI_resourceLink).build()) + getAAIClient().connect(allottedResourceUri,serviceInstanceUri) + }catch (Exception ex) { + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, "Exception in createAaiAR " + ex.getMessage()) } //start rollback set up @@ -358,7 +296,6 @@ public class DoCreateAllottedResourceBRG extends AbstractServiceTaskProcessor{ rollbackData.put(Prefix, "allottedResourceId", allottedResourceId) rollbackData.put(Prefix, "serviceInstanceId", execution.getVariable("serviceInstanceId")) rollbackData.put(Prefix, "parentServiceInstanceId", execution.getVariable("parentServiceInstanceId")) - rollbackData.put(Prefix, "aaiARPath", arUrl) execution.setVariable("rollbackData", rollbackData) msoLogger.trace("end createAaiAR") } diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/vcpe/scripts/DoCreateAllottedResourceBRGRollback.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/vcpe/scripts/DoCreateAllottedResourceBRGRollback.groovy index 4d4f11c3e5..856c893b47 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/vcpe/scripts/DoCreateAllottedResourceBRGRollback.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/vcpe/scripts/DoCreateAllottedResourceBRGRollback.groovy @@ -18,27 +18,21 @@ * ============LICENSE_END========================================================= */ -package org.onap.so.bpmn.vcpe.scripts; +package org.onap.so.bpmn.vcpe.scripts -import 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.AllottedResource import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor -import org.onap.so.bpmn.core.WorkflowException +import org.onap.so.bpmn.common.scripts.AllottedResourceUtils import org.onap.so.bpmn.common.scripts.ExceptionUtil -import org.onap.so.bpmn.common.scripts.MsoUtils -import org.onap.so.bpmn.common.scripts.AaiUtil import org.onap.so.bpmn.common.scripts.SDNCAdapterUtils -import org.onap.so.rest.APIResponse - -import java.util.UUID; -import org.camunda.bpm.engine.delegate.BpmnError -import org.camunda.bpm.engine.delegate.DelegateExecution -import org.apache.commons.lang3.* -import org.springframework.web.util.UriUtils; -import static org.apache.commons.lang3.StringUtils.* - +import org.onap.so.bpmn.core.WorkflowException import org.onap.so.logger.MessageEnum import org.onap.so.logger.MsoLogger +import static org.apache.commons.lang3.StringUtils.isBlank + /** * This groovy class supports the <class>CreateAllottedResourceBRGRollback.bpmn</class> process. * @@ -141,12 +135,12 @@ public class DoCreateAllottedResourceBRGRollback extends AbstractServiceTaskProc AllottedResourceUtils arUtils = new AllottedResourceUtils(this) String aaiARPath = execution.getVariable("aaiARPath") msoLogger.debug(" aaiARPath:" + aaiARPath) - String ar = null; //need this for getting resourceVersion for delete + Optional<AllottedResource> ar = Optional.empty(); //need this for getting resourceVersion for delete if (!isBlank(aaiARPath)) { ar = arUtils.getARbyLink(execution, aaiARPath, "") } - if (isBlank(ar)) + if(!ar.isPresent()) { msg = "AR not found in AAI at:" + aaiARPath msoLogger.debug(msg) @@ -202,13 +196,8 @@ public class DoCreateAllottedResourceBRGRollback extends AbstractServiceTaskProc try{ msoLogger.trace("start deleteAaiAR") AllottedResourceUtils arUtils = new AllottedResourceUtils(this) - String ar = null //need to get resource-version String arLink = execution.getVariable("aaiARPath") - if (!isBlank(arLink)) - { - ar = arUtils.getARbyLink(execution, arLink, "") - } - arUtils.deleteAR(execution, arLink + '?resource-version=' + UriUtils.encode(execution.getVariable("aaiARResourceVersion"),"UTF-8")) + arUtils.deleteAR(execution, arLink ) } catch (BpmnError e) { throw e; }catch(Exception ex){ diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/vcpe/scripts/DoCreateAllottedResourceTXC.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/vcpe/scripts/DoCreateAllottedResourceTXC.groovy index ef5660c081..56fa3a6730 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/vcpe/scripts/DoCreateAllottedResourceTXC.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/vcpe/scripts/DoCreateAllottedResourceTXC.groovy @@ -18,13 +18,11 @@ * ============LICENSE_END========================================================= */ -package org.onap.so.bpmn.vcpe.scripts; +package org.onap.so.bpmn.vcpe.scripts -import static org.apache.commons.lang3.StringUtils.* - -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.AllottedResource import org.onap.so.bpmn.common.scripts.*; import org.onap.so.bpmn.core.RollbackData import org.onap.so.bpmn.core.UrnPropertiesReader @@ -35,7 +33,9 @@ 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 + +import javax.ws.rs.core.UriBuilder +import static org.apache.commons.lang3.StringUtils.isBlank /** * This groovy class supports the <class>DoCreateAllottedResourceTXC.bpmn</class> process. @@ -190,7 +190,6 @@ public class DoCreateAllottedResourceTXC extends AbstractServiceTaskProcessor{ msoLogger.trace("start createAaiAR") - String msg = "" String allottedResourceId = execution.getVariable("allottedResourceId") if (isBlank(allottedResourceId)) @@ -198,19 +197,13 @@ public class DoCreateAllottedResourceTXC extends AbstractServiceTaskProcessor{ allottedResourceId = UUID.randomUUID().toString() execution.setVariable("allottedResourceId", allottedResourceId) } - String arUrl = "" try { - //AAI PUT - AaiUtil aaiUriUtil = new AaiUtil(this) AAIResourceUri siResourceLink= execution.getVariable("PSI_resourceLink") - AllottedResourceUtils arUtils = new AllottedResourceUtils(this) - arUrl = arUtils.createARUrl(execution, siResourceLink, allottedResourceId) - execution.setVariable("aaiARPath", arUrl) - msoLogger.debug("PUT AllottedResource AAI URL is:\n" + arUrl) - String namespace = aaiUriUtil.getNamespaceFromUri(execution, arUrl) + AAIResourceUri allottedResourceUri = AAIUriFactory.createResourceFromParentURI(siResourceLink, AAIObjectType.ALLOTTED_RESOURCE, allottedResourceId) + execution.setVariable("aaiARPath", allottedResourceUri.build().toString()); String arType = execution.getVariable("allottedResourceType") String arRole = execution.getVariable("allottedResourceRole") String CSI_resourceLink = execution.getVariable("CSI_resourceLink") @@ -218,65 +211,19 @@ public class DoCreateAllottedResourceTXC extends AbstractServiceTaskProcessor{ msoLogger.debug("arModelInfo is:\n" + arModelInfo) String modelInvariantId = jsonUtil.getJsonValue(arModelInfo, "modelInvariantUuid") String modelVersionId = jsonUtil.getJsonValue(arModelInfo, "modelUuid") - String modelCustomizationId = jsonUtil.getJsonValue(arModelInfo, "modelCustomizationUuid") - if (modelInvariantId == null) { - modelInvariantId = "" - } - if (modelVersionId == null) { - modelVersionId = "" - } - if (modelCustomizationId == null) { - modelCustomizationId = "" - } - - String payload = - """<allotted-resource xmlns="${namespace}"> - <id>${MsoUtils.xmlEscape(allottedResourceId)}</id> - <description></description> - <type>${MsoUtils.xmlEscape(arType)}</type> - <role>${MsoUtils.xmlEscape(arRole)}</role> - <selflink></selflink> - <model-invariant-id>${MsoUtils.xmlEscape(modelInvariantId)}</model-invariant-id> - <model-version-id>${MsoUtils.xmlEscape(modelVersionId)}</model-version-id> - <model-customization-id>${MsoUtils.xmlEscape(modelCustomizationId)}</model-customization-id> - <orchestration-status>PendingCreate</orchestration-status> - <operation-status></operation-status> - <relationship-list> - <relationship> - <related-to>service-instance</related-to> - <related-link>${MsoUtils.xmlEscape(CSI_resourceLink)}</related-link> - </relationship> - </relationship-list> - </allotted-resource>""".trim() - - execution.setVariable("AaiARPayload", payload) - msoLogger.debug(" payload to create AllottedResource in AAI:" + "\n" + payload) - - APIResponse response = aaiUriUtil.executeAAIPutCall(execution, arUrl, payload) - int responseCode = response.getStatusCode() - msoLogger.debug("AllottedResource AAI PUT responseCode:" + responseCode) - - String aaiResponse = response.getResponseBodyAsString() - msoLogger.debug("AllottedResource AAI PUT responseStr:" + aaiResponse) - - //200 OK 201 CREATED 202 ACCEPTED - if(responseCode == 200 || responseCode == 201 || responseCode == 202 ) - { - msoLogger.debug("AAI PUT AllottedResource received a Good Response") - } - else{ - msoLogger.debug("AAI Put AllottedResouce received a Bad Response Code: " + responseCode) - exceptionUtil.MapAAIExceptionToWorkflowExceptionGeneric(execution, aaiResponse, responseCode) - throw new BpmnError("MSOWorkflowException") - } - }catch(BpmnError b){ - msoLogger.debug("Rethrowing MSOWorkflowException") - throw b - } catch (Exception ex) { - msg = "Exception in createAaiAR " + ex.getMessage() - msoLogger.debug(msg) - exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + AllottedResource resource = new AllottedResource() + resource.setId(allottedResourceId) + resource.setType(arType) + resource.setRole(arRole) + resource.setModelInvariantId(modelInvariantId) + resource.setModelVersionId(modelVersionId) + getAAIClient().create(allottedResourceUri, resource) + AAIResourceUri serviceInstanceUri = AAIUriFactory.createResourceFromExistingURI(AAIObjectType.SERVICE_INSTANCE, UriBuilder.fromPath(CSI_resourceLink).build()) + getAAIClient().connect(allottedResourceUri,serviceInstanceUri) + + }catch (Exception ex) { + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, "Exception in createAaiAR " + ex.getMessage()) } //start rollback set up @@ -287,7 +234,6 @@ public class DoCreateAllottedResourceTXC extends AbstractServiceTaskProcessor{ rollbackData.put(Prefix, "allottedResourceId", allottedResourceId) rollbackData.put(Prefix, "serviceInstanceId", execution.getVariable("serviceInstanceId")) rollbackData.put(Prefix, "parentServiceInstanceId", execution.getVariable("parentServiceInstanceId")) - rollbackData.put(Prefix, "aaiARPath", arUrl) execution.setVariable("rollbackData", rollbackData) msoLogger.trace("end createAaiAR") } diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/vcpe/scripts/DoCreateAllottedResourceTXCRollback.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/vcpe/scripts/DoCreateAllottedResourceTXCRollback.groovy index 24b919524f..06d557532b 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/vcpe/scripts/DoCreateAllottedResourceTXCRollback.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/vcpe/scripts/DoCreateAllottedResourceTXCRollback.groovy @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -18,8 +18,9 @@ * ============LICENSE_END========================================================= */ -package org.onap.so.bpmn.vcpe.scripts; +package org.onap.so.bpmn.vcpe.scripts +import org.onap.aai.domain.yang.AllottedResource; import org.onap.so.bpmn.common.scripts.*; import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor import org.onap.so.bpmn.core.WorkflowException @@ -27,7 +28,7 @@ import org.onap.so.bpmn.common.scripts.ExceptionUtil import org.onap.so.bpmn.common.scripts.MsoUtils import org.onap.so.bpmn.common.scripts.AaiUtil import org.onap.so.bpmn.common.scripts.SDNCAdapterUtils -import org.onap.so.rest.APIResponse + import java.util.UUID; import org.camunda.bpm.engine.delegate.BpmnError @@ -43,15 +44,15 @@ import org.onap.so.logger.MsoLogger * This groovy class supports the <class>CreateAllottedResourceTXCRollback.bpmn</class> process. * * @author - * + * * Inputs: * @param - msoRequestId * @param - isDebugLogEnabled - * @param - disableRollback - O + * @param - disableRollback - O * @param - rollbackData * * Outputs: - * @param - rollbackError + * @param - rollbackError * @param - rolledBack (no localRB->null, localRB F->false, localRB S->true) * */ @@ -62,31 +63,31 @@ public class DoCreateAllottedResourceTXCRollback extends AbstractServiceTaskProc ExceptionUtil exceptionUtil = new ExceptionUtil() public void preProcessRequest (DelegateExecution execution) { - + String msg = "" msoLogger.trace("start preProcessRequest") execution.setVariable("prefix", Prefix) String rbType = "DCARTXC_" try { - + def rollbackData = execution.getVariable("rollbackData") msoLogger.debug("RollbackData:" + rollbackData) if (rollbackData != null) { if (rollbackData.hasType(rbType)) { - + execution.setVariable("serviceInstanceId", rollbackData.get(rbType, "serviceInstanceId")) execution.setVariable("parentServiceInstanceId", rollbackData.get(rbType, "parentServiceInstanceId")) execution.setVariable("allottedResourceId", rollbackData.get("SERVICEINSTANCE", "allottedResourceId")) - - + + def rollbackAAI = rollbackData.get(rbType, "rollbackAAI") if ("true".equals(rollbackAAI)) { execution.setVariable("rollbackAAI",true) execution.setVariable("aaiARPath", rollbackData.get(rbType, "aaiARPath")) - + } def rollbackSDNC = rollbackData.get(rbType, "rollbackSDNCassign") if ("true".equals(rollbackSDNC)) @@ -95,11 +96,11 @@ public class DoCreateAllottedResourceTXCRollback extends AbstractServiceTaskProc execution.setVariable("deactivateSdnc", rollbackData.get(rbType, "rollbackSDNCactivate")) execution.setVariable("deleteSdnc", rollbackData.get(rbType, "rollbackSDNCcreate")) execution.setVariable("unassignSdnc", rollbackData.get(rbType, "rollbackSDNCassign")) - + msoLogger.debug("sdncDeactivate:\n" + execution.getVariable("deactivateSdnc") ) msoLogger.debug("sdncDelete:\n" + execution.getVariable("deleteSdnc")) msoLogger.debug("sdncUnassign:\n" + execution.getVariable("unassignSdnc")) - + execution.setVariable("sdncDeactivateRequest", rollbackData.get(rbType, "sdncActivateRollbackReq")) execution.setVariable("sdncDeleteRequest", rollbackData.get(rbType, "sdncCreateRollbackReq")) execution.setVariable("sdncUnassignRequest", rollbackData.get(rbType, "sdncAssignRollbackReq")) @@ -121,7 +122,7 @@ public class DoCreateAllottedResourceTXCRollback extends AbstractServiceTaskProc { execution.setVariable("skipRollback", true) } - + }catch(BpmnError b){ msoLogger.debug("Rethrowing MSOWorkflowException") throw b @@ -141,12 +142,12 @@ public class DoCreateAllottedResourceTXCRollback extends AbstractServiceTaskProc AllottedResourceUtils arUtils = new AllottedResourceUtils(this) String aaiARPath = execution.getVariable("aaiARPath") msoLogger.debug(" aaiARPath:" + aaiARPath) - String ar = null; //need this for getting resourceVersion for delete + Optional<AllottedResource> ar = Optional.empty(); //need this for getting resourceVersion for delete if (!isBlank(aaiARPath)) { ar = arUtils.getARbyLink(execution, aaiARPath, "") } - if (isBlank(ar)) + if (!ar.isPresent()) { msg = "AR not found in AAI at:" + aaiARPath msoLogger.debug(msg) @@ -202,13 +203,8 @@ public class DoCreateAllottedResourceTXCRollback extends AbstractServiceTaskProc try{ msoLogger.trace("start deleteAaiAR") AllottedResourceUtils arUtils = new AllottedResourceUtils(this) - String ar = null //need to get resource-version String arLink = execution.getVariable("aaiARPath") - if (!isBlank(arLink)) - { - ar = arUtils.getARbyLink(execution, arLink, "") - } - arUtils.deleteAR(execution, arLink + '?resource-version=' + UriUtils.encode(execution.getVariable("aaiARResourceVersion"),"UTF-8")) + arUtils.deleteAR(execution, arLink) } catch (BpmnError e) { throw e; }catch(Exception ex){ @@ -217,7 +213,7 @@ public class DoCreateAllottedResourceTXCRollback extends AbstractServiceTaskProc } msoLogger.trace("end deleteAaiAR") } - + public void postProcessRequest(DelegateExecution execution) { msoLogger.trace("start postProcessRequest") @@ -240,7 +236,7 @@ public class DoCreateAllottedResourceTXCRollback extends AbstractServiceTaskProc } } - + public void processRollbackException(DelegateExecution execution){ msoLogger.trace("start processRollbackException") diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/vcpe/scripts/DoDeleteAllottedResourceBRG.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/vcpe/scripts/DoDeleteAllottedResourceBRG.groovy index a5125fea73..e39edffe68 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/vcpe/scripts/DoDeleteAllottedResourceBRG.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/vcpe/scripts/DoDeleteAllottedResourceBRG.groovy @@ -18,28 +18,22 @@ * ============LICENSE_END========================================================= */ -package org.onap.so.bpmn.vcpe.scripts; +package org.onap.so.bpmn.vcpe.scripts -import org.onap.so.bpmn.common.scripts.*; -import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor -import org.onap.so.bpmn.core.WorkflowException +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.delegate.DelegateExecution +import org.onap.so.bpmn.common.scripts.AllottedResourceUtils import org.onap.so.bpmn.common.scripts.ExceptionUtil import org.onap.so.bpmn.common.scripts.MsoUtils -import org.onap.so.bpmn.common.scripts.AaiUtil +import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor import org.onap.so.bpmn.common.scripts.SDNCAdapterUtils -import org.onap.so.rest.APIResponse - -import java.util.UUID; -import org.camunda.bpm.engine.delegate.BpmnError -import org.camunda.bpm.engine.delegate.DelegateExecution -import org.apache.commons.lang3.* -import org.springframework.web.util.UriUtils; -import static org.apache.commons.lang3.StringUtils.* -import org.onap.so.bpmn.core.UrnPropertiesReader; - +import org.onap.so.bpmn.core.UrnPropertiesReader +import org.onap.so.bpmn.core.WorkflowException import org.onap.so.logger.MessageEnum import org.onap.so.logger.MsoLogger +import static org.apache.commons.lang3.StringUtils.isBlank + /** * This groovy class supports the <class>DoDeleteAllottedResourceBRG.bpmn</class> process. * @@ -116,20 +110,18 @@ public class DoDeleteAllottedResourceBRG extends AbstractServiceTaskProcessor{ String allottedResourceId = execution.getVariable("allottedResourceId") - AllottedResourceUtils arUtils = new AllottedResourceUtils(this) - String ar = arUtils.getARbyId(execution, allottedResourceId) + AllottedResourceUtils arUtils = getAllottedResourceUtils() + boolean ifExistsAR = arUtils.ifExistsAR(execution, allottedResourceId) String errorMsg = "" - if (isBlank(ar)) // AR was !found - { - errorMsg = "Allotted resource not found in AAI with AllottedResourceId:" + allottedResourceId - } - else - { + if (ifExistsAR){ String aaiARPath = execution.getVariable("aaiARPath") String parentServiceInstanceId = arUtils.getPSIFmARLink(execution, aaiARPath) execution.setVariable("parentServiceInstanceId", parentServiceInstanceId) } + else{ + errorMsg = "Allotted resource not found in AAI with AllottedResourceId:" + allottedResourceId + } if (!isBlank(errorMsg)) { msoLogger.debug(errorMsg) exceptionUtil.buildAndThrowWorkflowException(execution, 500, errorMsg) @@ -349,13 +341,8 @@ public class DoDeleteAllottedResourceBRG extends AbstractServiceTaskProcessor{ try{ AllottedResourceUtils arUtils = new AllottedResourceUtils(this) - String ar = null //need to get resource-version again String arLink = execution.getVariable("aaiARPath") - if (!isBlank(arLink)) - { - ar = arUtils.getARbyLink(execution, arLink, "") - } - arUtils.deleteAR(execution, arLink + '?resource-version=' + UriUtils.encode(execution.getVariable("aaiARResourceVersion"),"UTF-8")) + arUtils.deleteAR(execution, arLink) } catch (BpmnError e) { throw e; }catch(Exception ex){ @@ -365,4 +352,8 @@ public class DoDeleteAllottedResourceBRG extends AbstractServiceTaskProcessor{ msoLogger.trace("end deleteAaiAR") } + public AllottedResourceUtils getAllottedResourceUtils(){ + return new AllottedResourceUtils(this) + } + } diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/vcpe/scripts/DoDeleteAllottedResourceTXC.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/vcpe/scripts/DoDeleteAllottedResourceTXC.groovy index 7ce606e685..f305a7ad0d 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/vcpe/scripts/DoDeleteAllottedResourceTXC.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/vcpe/scripts/DoDeleteAllottedResourceTXC.groovy @@ -18,27 +18,20 @@ * ============LICENSE_END========================================================= */ -package org.onap.so.bpmn.vcpe.scripts; +package org.onap.so.bpmn.vcpe.scripts -import org.onap.so.bpmn.common.scripts.*; -import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor -import org.onap.so.bpmn.core.WorkflowException +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.delegate.DelegateExecution +import org.onap.so.bpmn.common.scripts.AllottedResourceUtils import org.onap.so.bpmn.common.scripts.ExceptionUtil import org.onap.so.bpmn.common.scripts.MsoUtils -import org.onap.so.bpmn.common.scripts.AaiUtil +import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor import org.onap.so.bpmn.common.scripts.SDNCAdapterUtils -import org.onap.so.rest.APIResponse - -import java.util.UUID; -import org.camunda.bpm.engine.delegate.BpmnError -import org.camunda.bpm.engine.delegate.DelegateExecution -import org.apache.commons.lang3.* -import org.springframework.web.util.UriUtils; -import static org.apache.commons.lang3.StringUtils.* -import org.onap.so.bpmn.core.UrnPropertiesReader; - +import org.onap.so.bpmn.core.UrnPropertiesReader +import org.onap.so.bpmn.core.WorkflowException import org.onap.so.logger.MessageEnum import org.onap.so.logger.MsoLogger +import static org.apache.commons.lang3.StringUtils.isBlank /** * This groovy class supports the <class>DoDeleteAllottedResourceTXC.bpmn</class> process. @@ -116,20 +109,18 @@ public class DoDeleteAllottedResourceTXC extends AbstractServiceTaskProcessor{ String allottedResourceId = execution.getVariable("allottedResourceId") - AllottedResourceUtils arUtils = new AllottedResourceUtils(this) - String ar = arUtils.getARbyId(execution, allottedResourceId) + AllottedResourceUtils arUtils = getAllottedResourceUtils() + boolean ifExistsAR = arUtils.ifExistsAR(execution, allottedResourceId) String errorMsg = "" - if (isBlank(ar)) // AR was !found - { - errorMsg = "Allotted resource not found in AAI with AllottedResourceId:" + allottedResourceId - } - else - { + if (ifExistsAR){ String aaiARPath = execution.getVariable("aaiARPath") String parentServiceInstanceId = arUtils.getPSIFmARLink(execution, aaiARPath) execution.setVariable("parentServiceInstanceId", parentServiceInstanceId) } + else{ + errorMsg = "Allotted resource not found in AAI with AllottedResourceId:" + allottedResourceId + } if (!isBlank(errorMsg)) { msoLogger.debug(errorMsg) exceptionUtil.buildAndThrowWorkflowException(execution, 500, errorMsg) @@ -138,6 +129,10 @@ public class DoDeleteAllottedResourceTXC extends AbstractServiceTaskProcessor{ } + public AllottedResourceUtils getAllottedResourceUtils(){ + return new AllottedResourceUtils(this) + } + // aaiARPath set during query (existing AR) public void updateAaiAROrchStatus(DelegateExecution execution, String status){ msoLogger.trace("start updateAaiAROrchStatus") @@ -349,13 +344,8 @@ public class DoDeleteAllottedResourceTXC extends AbstractServiceTaskProcessor{ try{ AllottedResourceUtils arUtils = new AllottedResourceUtils(this) - String ar = null //need to get resource-version again String arLink = execution.getVariable("aaiARPath") - if (!isBlank(arLink)) - { - ar = arUtils.getARbyLink(execution, arLink, "") - } - arUtils.deleteAR(execution, arLink + '?resource-version=' + UriUtils.encode(execution.getVariable("aaiARResourceVersion"),"UTF-8")) + arUtils.deleteAR(execution, arLink) } catch (BpmnError e) { throw e; }catch(Exception ex){ diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/aai/AaiConnectionImpl.java b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/aai/AaiConnectionImpl.java index 8bba435d0c..d57e48781d 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/aai/AaiConnectionImpl.java +++ b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/aai/AaiConnectionImpl.java @@ -21,7 +21,6 @@ package org.onap.so.bpmn.infrastructure.pnf.aai; import java.util.Optional; -import java.util.UUID; import org.onap.aai.domain.yang.Pnf; import org.onap.so.bpmn.infrastructure.pnf.implementation.AaiConnection; import org.onap.so.client.aai.AAIRestClientImpl; @@ -33,12 +32,12 @@ public class AaiConnectionImpl implements AaiConnection { @Override public Optional<Pnf> getEntryFor(String correlationId) { AAIRestClientImpl restClient = new AAIRestClientImpl(); - return restClient.getPnfByName(correlationId, UUID.randomUUID().toString()); + return restClient.getPnfByName(correlationId); } @Override public void createEntry(String correlationId, Pnf entry) { AAIRestClientImpl restClient = new AAIRestClientImpl(); - restClient.createPnf(correlationId, UUID.randomUUID().toString(), entry); + restClient.createPnf(correlationId, entry); } } diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/delegate/CheckAaiForCorrelationIdDelegate.java b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/delegate/CheckAaiForCorrelationIdDelegate.java index b49c4211b1..8d353f134d 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/delegate/CheckAaiForCorrelationIdDelegate.java +++ b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/delegate/CheckAaiForCorrelationIdDelegate.java @@ -24,31 +24,28 @@ import static org.onap.so.bpmn.infrastructure.pnf.delegate.ExecutionVariableName import static org.onap.so.bpmn.infrastructure.pnf.delegate.ExecutionVariableNames.CORRELATION_ID; import java.io.IOException; + import org.camunda.bpm.engine.delegate.DelegateExecution; import org.camunda.bpm.engine.delegate.JavaDelegate; import org.onap.so.bpmn.common.scripts.ExceptionUtil; import org.onap.so.bpmn.infrastructure.pnf.implementation.AaiConnection; -import org.onap.so.bpmn.infrastructure.pnf.implementation.AaiResponse; -import org.onap.so.bpmn.infrastructure.pnf.implementation.CheckAaiForCorrelationIdImplementation; -import org.onap.so.logger.MsoLogger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; /** * Implementation of "Check AAI for correlation_id" task in CreateAndActivatePnfResource.bpmn * - * Inputs: - * - correlationId - String + * Inputs: - correlationId - String * - * Outputs: - * - AAI_CONTAINS_INFO_ABOUT_PNF - local Boolean - * - aaiContainsInfoAboutIp - local Boolean + * Outputs: - aaiContainsInfoAboutPnf - local Boolean */ - @Component public class CheckAaiForCorrelationIdDelegate implements JavaDelegate { - private static MsoLogger LOGGER = MsoLogger.getMsoLogger(MsoLogger.Catalog.GENERAL, CheckAaiForCorrelationIdDelegate.class); - private CheckAaiForCorrelationIdImplementation implementation = new CheckAaiForCorrelationIdImplementation(); + + private static final Logger logger = LoggerFactory.getLogger(CheckAaiForCorrelationIdDelegate.class); + private AaiConnection aaiConnection; @Autowired @@ -57,18 +54,16 @@ public class CheckAaiForCorrelationIdDelegate implements JavaDelegate { } @Override - public void execute(DelegateExecution execution) throws Exception { + public void execute(DelegateExecution execution) { String correlationId = (String) execution.getVariable(CORRELATION_ID); if (correlationId == null) { new ExceptionUtil().buildAndThrowWorkflowException(execution, 500, CORRELATION_ID + " is not set"); } - try { - AaiResponse aaiResponse = implementation.check(correlationId, aaiConnection); - - execution.setVariableLocal(AAI_CONTAINS_INFO_ABOUT_PNF, aaiResponse.getContainsInfoAboutPnf()); + boolean isEntry = aaiConnection.getEntryFor(correlationId).isPresent(); + logger.debug("AAI entry is found for pnf correlation id {}: {}", CORRELATION_ID, isEntry); + execution.setVariableLocal(AAI_CONTAINS_INFO_ABOUT_PNF, isEntry); } catch (IOException e) { - LOGGER.error("IOException",e); new ExceptionUtil().buildAndThrowWorkflowException(execution, 9999, e.getMessage()); } } diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/delegate/CreatePnfEntryInAaiDelegate.java b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/delegate/CreatePnfEntryInAaiDelegate.java index 12cb6ffdff..2268d22bd2 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/delegate/CreatePnfEntryInAaiDelegate.java +++ b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/delegate/CreatePnfEntryInAaiDelegate.java @@ -57,7 +57,6 @@ public class CreatePnfEntryInAaiDelegate implements JavaDelegate { String correlationId = (String) execution.getVariable(CORRELATION_ID); String pnfUuid = (String) execution.getVariable(PNF_UUID); Pnf pnf = new Pnf(); - pnf.setInMaint(true); pnf.setPnfId(pnfUuid); pnf.setPnfName(correlationId); aaiConnection.createEntry(correlationId, pnf); diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/implementation/AaiResponse.java b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/implementation/AaiResponse.java deleted file mode 100644 index 32ecff102f..0000000000 --- a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/implementation/AaiResponse.java +++ /dev/null @@ -1,48 +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.infrastructure.pnf.implementation; - -import java.util.Optional; -import javax.annotation.Nullable; -import javax.validation.constraints.NotNull; - -public enum AaiResponse { - NO_ENTRY(false, false), - ENTRY_NO_IP(true, false), - ENTRY_WITH_IP(true, true); - - private boolean containsInfoAboutPnf; - private boolean containsInfoAboutIp; - - AaiResponse(boolean containsInfoAboutPnf, boolean containsInfoAboutIp) { - this.containsInfoAboutPnf = containsInfoAboutPnf; - this.containsInfoAboutIp = containsInfoAboutIp; - } - - public boolean getContainsInfoAboutPnf() { - return containsInfoAboutPnf; - } - - public boolean getContainsInfoAboutIp() { - return containsInfoAboutIp; - } - -} diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/implementation/CheckAaiForCorrelationIdImplementation.java b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/implementation/CheckAaiForCorrelationIdImplementation.java deleted file mode 100644 index e5fc87db91..0000000000 --- a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/implementation/CheckAaiForCorrelationIdImplementation.java +++ /dev/null @@ -1,50 +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.infrastructure.pnf.implementation; - -import java.io.IOException; -import java.util.Optional; -import org.onap.aai.domain.yang.Pnf; - -public class CheckAaiForCorrelationIdImplementation { - - public AaiResponse check(String correlationId, AaiConnection aaiConnection) throws IOException { - Optional<Pnf> pnf = aaiConnection.getEntryFor(correlationId); - if (!pnf.isPresent()) { - return AaiResponse.NO_ENTRY; - } - - if(extractIp(pnf.get()).isPresent()) { - return AaiResponse.ENTRY_WITH_IP; - } else { - return AaiResponse.ENTRY_NO_IP; - } - } - - private Optional<String> extractIp(Pnf pnf) { - if (pnf.getIpaddressV4Oam() != null) { - return Optional.of(pnf.getIpaddressV4Oam()); - } else { - return Optional.ofNullable(pnf.getIpaddressV6Oam()); - } - } - -} diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/service/ServicePluginFactory.java b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/service/ServicePluginFactory.java index 95b826f331..48c78632dd 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/service/ServicePluginFactory.java +++ b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/service/ServicePluginFactory.java @@ -21,7 +21,6 @@ package org.onap.so.bpmn.infrastructure.workflow.service; import java.io.IOException; -import java.io.UnsupportedEncodingException; import java.net.SocketTimeoutException; import java.util.ArrayList; import java.util.HashMap; @@ -236,12 +235,7 @@ public class ServicePluginFactory { @SuppressWarnings("unchecked") private List<Object> queryAccessTPbyLocationFromInventoryOSS(String locationAddress) { String url = getInventoryOSSEndPoint(); - try { - url += "/oss/inventory?location=" + UriUtils.encode(locationAddress,"UTF-8"); - } catch (UnsupportedEncodingException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } + url += "/oss/inventory?location=" + UriUtils.encode(locationAddress,"UTF-8"); String responseContent = sendRequest(url, "GET", ""); List<Object> accessTPs = new ArrayList<Object>(); if (null != responseContent) { @@ -633,7 +627,9 @@ public class ServicePluginFactory { // in demo we have only one VPN. no cross VPNs, so get first item. Map<String, Object> returnRoute = getReturnRoute(returnList); Map<String, Object> vpnRequestInputs = getVPNResourceRequestInputs(resources); - vpnRequestInputs.putAll(returnRoute); + if(null!=vpnRequestInputs) { + vpnRequestInputs.putAll(returnRoute); + } String newRequest = getJsonString(uuiObject); return newRequest; } diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateSDNCNetworkResourceTest.groovy b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateSDNCNetworkResourceTest.groovy index 7d6de85a8e..8dde45be81 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateSDNCNetworkResourceTest.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateSDNCNetworkResourceTest.groovy @@ -1,3 +1,23 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + package org.onap.so.bpmn.infrastructure.scripts import com.github.tomakehurst.wiremock.junit.WireMockRule @@ -45,6 +65,7 @@ class CreateSDNCNetworkResourceTest extends GroovyTestCase { <RequestData xsi:type="xs:string" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><output xmlns="org:onap:sdnc:northbound:generic-resource"><response-message></response-message><ack-final-indicator>Y</ack-final-indicator><svc-request-id>726420e0-3962-4bf2-9655-aac82fc7055e</svc-request-id><network-response-information><instance-id>9fa732b8-2c54-4eba-926d-464d18c07474</instance-id><object-path>restconf/config/GENERIC-RESOURCE-API:services/service/a99deffb-12e2-4656-8cf2-2d2a996d0f52/service-data/networks/network/9fa732b8-2c54-4eba-926d-464d18c07474/network-data/</object-path></network-response-information><response-code>200</response-code><service-response-information><instance-id>a99deffb-12e2-4656-8cf2-2d2a996d0f52</instance-id></service-response-information></output></RequestData> </sdncadapterworkflow:response-data> </sdncadapterworkflow:SDNCAdapterWorkflowResponse>""" + } private ResourceInput getResInputObj(String modelName) { diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateVFCNSResourceTest.groovy b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateVFCNSResourceTest.groovy new file mode 100644 index 0000000000..d4857503b5 --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateVFCNSResourceTest.groovy @@ -0,0 +1,81 @@ +/*- + * ============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.infrastructure.scripts + +import org.camunda.bpm.engine.delegate.BpmnError +import org.junit.Before +import org.junit.Test +import org.mockito.Mockito +import org.mockito.MockitoAnnotations +import org.mockito.Spy +import org.onap.so.bpmn.common.scripts.MsoGroovyTest +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 javax.ws.rs.NotFoundException + +import static org.junit.Assert.assertEquals +import static org.mockito.ArgumentMatchers.isA +import static org.mockito.Mockito.doNothing +import static org.mockito.Mockito.doThrow +import static org.mockito.Mockito.when + +class CreateVFCNSResourceTest extends MsoGroovyTest{ + + @Spy + CreateVFCNSResource createVFCNSResource + + @Before + void init() throws IOException { + super.init("CreateVFCNSResource") + MockitoAnnotations.initMocks(this); + when(createVFCNSResource.getAAIClient()).thenReturn(client) + } + + @Test + void testaddNSRelationship(){ + when(mockExecution.getVariable("globalSubscriberId")).thenReturn("globalSubscriberId1") + when(mockExecution.getVariable("serviceType")).thenReturn("serviceType") + when(mockExecution.getVariable("serviceInstanceId")).thenReturn("serviceInstanceId") + when(mockExecution.getVariable("nsInstanceId")).thenReturn("nsInstanceId") + doNothing().when(client).connect(isA(AAIResourceUri.class),isA(AAIResourceUri.class)) + createVFCNSResource.addNSRelationship(mockExecution) + AAIResourceUri nsUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE,"globalSubscriberId1","serviceType","nsInstanceId") + AAIResourceUri relatedServiceUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE,"globalSubscriberId1","serviceType","serviceInstanceId") + Mockito.verify(client).connect(nsUri,relatedServiceUri) + } + + @Test + void testaddNSRelationshipError(){ + when(mockExecution.getVariable("globalSubscriberId")).thenReturn("globalSubscriberId1") + when(mockExecution.getVariable("serviceType")).thenReturn("serviceType") + when(mockExecution.getVariable("serviceInstanceId")).thenReturn("serviceInstanceId") + when(mockExecution.getVariable("nsInstanceId")).thenReturn("nsInstanceId") + doThrow(new NotFoundException("Error creating relationship")).when(client).connect(isA(AAIResourceUri.class),isA(AAIResourceUri.class)) + try { + createVFCNSResource.addNSRelationship(mockExecution) + } catch (BpmnError ex) { + assertEquals(ex.getErrorCode(),"MSOWorkflowException") + } + } + +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateVfModuleVolumeInfraV1Test.groovy b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateVfModuleVolumeInfraV1Test.groovy index 2b437d875e..1b92592e37 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateVfModuleVolumeInfraV1Test.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateVfModuleVolumeInfraV1Test.groovy @@ -20,23 +20,34 @@ package org.onap.so.bpmn.infrastructure.scripts +import org.camunda.bpm.engine.delegate.BpmnError import org.camunda.bpm.engine.impl.persistence.entity.ExecutionEntity import org.junit.Before import org.junit.Ignore +import org.junit.Rule import org.junit.Test +import org.junit.rules.ExpectedException import org.junit.runner.RunWith import org.mockito.ArgumentCaptor import org.mockito.MockitoAnnotations import org.mockito.runners.MockitoJUnitRunner +import org.onap.aai.domain.yang.ResultData +import org.onap.aai.domain.yang.SearchResults import org.onap.so.bpmn.common.scripts.MsoGroovyTest +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 static org.junit.Assert.assertEquals import static org.mockito.Mockito.* -@RunWith(MockitoJUnitRunner.class) class CreateVfModuleVolumeInfraV1Test extends MsoGroovyTest { - def jsonRequest = """ + @Rule + public ExpectedException thrown = ExpectedException.none(); + + String jsonRequest = """ { "requestDetails": { "modelInfo": { @@ -103,7 +114,7 @@ class CreateVfModuleVolumeInfraV1Test extends MsoGroovyTest { } """ - def volumeRequestXml = """<volume-request xmlns="http://www.w3.org/2001/XMLSchema"> + String volumeRequestXml = """<volume-request xmlns="http://www.w3.org/2001/XMLSchema"> <request-info> <action>CREATE_VF_MODULE_VOL</action> <source>VID</source> @@ -138,7 +149,7 @@ class CreateVfModuleVolumeInfraV1Test extends MsoGroovyTest { </volume-params> </volume-request>""" - def completeMsoRequestXml = """<aetgt:MsoCompletionRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1" + String completeMsoRequestXml = """<aetgt:MsoCompletionRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1" xmlns:ns="http://org.onap/so/request/types/v1" xmlns="http://org.onap/so/infra/vnf-request/v1"> <request-info> @@ -154,6 +165,7 @@ class CreateVfModuleVolumeInfraV1Test extends MsoGroovyTest { @Before public void init() { + super.init("CreateVfModuleVolumeInfraV1") MockitoAnnotations.initMocks(this) } @@ -162,8 +174,6 @@ class CreateVfModuleVolumeInfraV1Test extends MsoGroovyTest { @Ignore public void testPreProcessRequest() { - ExecutionEntity mockExecution = setupMock('CreateVfModuleVolumeInfraV1') - when(mockExecution.getVariable("prefix")).thenReturn('CVMVINFRAV1_') when(mockExecution.getVariable("bpmnRequest")).thenReturn(jsonRequest) when(mockExecution.getVariable("serviceInstanceId")).thenReturn('') @@ -191,7 +201,6 @@ class CreateVfModuleVolumeInfraV1Test extends MsoGroovyTest { @Test public void testPostProcessResponse() { - ExecutionEntity mockExecution = setupMock('CreateVfModuleVolumeInfraV1') when(mockExecution.getVariable("dbReturnCode")).thenReturn('000') when(mockExecution.getVariable("CVMVINFRAV1_createDBResponse")).thenReturn('') when(mockExecution.getVariable("mso-request-id")).thenReturn('1234') @@ -203,6 +212,23 @@ class CreateVfModuleVolumeInfraV1Test extends MsoGroovyTest { verify(mockExecution).setVariable('CVMVINFRAV1_Success', true) verify(mockExecution).setVariable('CVMVINFRAV1_CompleteMsoProcessRequest', completeMsoRequestXml) } - + @Test + public void testcallRESTQueryAAIServiceInstance() { + CreateVfModuleVolumeInfraV1 createVfModuleVolumeInfraV1 = spy(CreateVfModuleVolumeInfraV1.class) + when(createVfModuleVolumeInfraV1.getAAIClient()).thenReturn(client) + AAIResultWrapper resultWrapper = new AAIResultWrapper(SEARCH_RESULT_AAI_WITH_RESULTDATA) + when(client.get(isA(AAIResourceUri.class))).thenReturn(resultWrapper) + createVfModuleVolumeInfraV1.callRESTQueryAAIServiceInstance(mockExecution,true) + } + + @Test + public void testcallRESTQueryAAIServiceInstance_NoData() { + CreateVfModuleVolumeInfraV1 createVfModuleVolumeInfraV1 = spy(CreateVfModuleVolumeInfraV1.class) + when(createVfModuleVolumeInfraV1.getAAIClient()).thenReturn(client) + AAIResultWrapper resultWrapper = new AAIResultWrapper("{}") + when(client.get(isA(AAIResourceUri.class))).thenReturn(resultWrapper) + thrown.expect(BpmnError.class) + createVfModuleVolumeInfraV1.callRESTQueryAAIServiceInstance(mockExecution,true) + } } diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteVfModuleVolumeInfraV1Test.groovy b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteVfModuleVolumeInfraV1Test.groovy index 0bce32716f..50d5506c23 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteVfModuleVolumeInfraV1Test.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteVfModuleVolumeInfraV1Test.groovy @@ -21,21 +21,51 @@ package org.onap.so.bpmn.infrastructure.scripts import org.camunda.bpm.engine.impl.persistence.entity.ExecutionEntity +import org.junit.Assert import org.junit.Before 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.Spy import org.mockito.runners.MockitoJUnitRunner +import org.onap.aai.domain.yang.VolumeGroup +import org.onap.so.bpmn.common.scripts.DeleteAAIVfModule import org.onap.so.bpmn.common.scripts.MsoGroovyTest import org.onap.so.bpmn.core.WorkflowException +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.client.graphinventory.exceptions.GraphInventoryUriComputationException +import javax.ws.rs.NotFoundException + +import static org.mockito.ArgumentMatchers.eq +import static org.mockito.Mockito.doNothing +import static org.mockito.Mockito.doThrow +import static org.mockito.Mockito.times import static org.mockito.Mockito.verify import static org.mockito.Mockito.when -@RunWith(MockitoJUnitRunner.class) class DeleteVfModuleVolumeInfraV1Test extends MsoGroovyTest { - def deleteVnfAdapterRequestXml = """<deleteVolumeGroupRequest> + @Spy + DeleteVfModuleVolumeInfraV1 deleteVfModuleVolumeInfraV1 ; + + @Captor + static ArgumentCaptor<ExecutionEntity> captor = ArgumentCaptor.forClass(ExecutionEntity.class) + + @Before + void init() throws IOException { + super.init("DeleteVfModuleVolumeInfraV1") + MockitoAnnotations.initMocks(this); + when(deleteVfModuleVolumeInfraV1.getAAIClient()).thenReturn(client) + } + + String deleteVnfAdapterRequestXml = """<deleteVolumeGroupRequest> <cloudSiteId>RDM2WAGPLCP</cloudSiteId> <tenantId>fba1bd1e195a404cacb9ce17a9b2b421</tenantId> <volumeGroupId>78987</volumeGroupId> @@ -49,7 +79,7 @@ class DeleteVfModuleVolumeInfraV1Test extends MsoGroovyTest { <notificationUrl>http://localhost:28080/mso/WorkflowMessage/VNFAResponse/ebb9ef7b-a6a5-40e6-953e-f868f1767677</notificationUrl> </deleteVolumeGroupRequest>""" - def dbRequestXml = """<soapenv:Envelope xmlns:req="http://org.onap.so/requestsdb" + String dbRequestXml = """<soapenv:Envelope xmlns:req="http://org.onap.so/requestsdb" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"> <soapenv:Header/> <soapenv:Body> @@ -64,7 +94,7 @@ class DeleteVfModuleVolumeInfraV1Test extends MsoGroovyTest { </soapenv:Body> </soapenv:Envelope>""" - def completionRequestXml = """<aetgt:MsoCompletionRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1" + String completionRequestXml = """<aetgt:MsoCompletionRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1" xmlns:ns="http://org.onap/so/request/types/v1" xmlns="http://org.onap/so/infra/vnf-request/v1"> <request-info> @@ -76,7 +106,7 @@ class DeleteVfModuleVolumeInfraV1Test extends MsoGroovyTest { <aetgt:mso-bpel-name>BPMN VF Module Volume action: DELETE</aetgt:mso-bpel-name> </aetgt:MsoCompletionRequest>""" - def falloutHandlerRequestXml = """<aetgt:FalloutHandlerRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1" + String falloutHandlerRequestXml = """<aetgt:FalloutHandlerRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1" xmlns:ns="http://org.onap/so/request/types/v1" xmlns="http://org.onap/so/infra/vnf-request/v1"> <request-info> @@ -90,13 +120,7 @@ class DeleteVfModuleVolumeInfraV1Test extends MsoGroovyTest { </aetgt:WorkflowException> </aetgt:FalloutHandlerRequest>""" - @Before - public void init() - { - MockitoAnnotations.initMocks(this) - } - - + @Test public void testPrepareVnfAdapterDeleteRequest() { @@ -164,4 +188,110 @@ class DeleteVfModuleVolumeInfraV1Test extends MsoGroovyTest { verify(mockExecution).setVariable("DELVfModVol_Success", false) verify(mockExecution).setVariable("DELVfModVol_FalloutHandlerRequest", falloutHandlerRequestXml) } + + @Test + void testQueryAAIForVolumeGroup(){ + when(mockExecution.getVariable("DELVfModVol_volumeGroupId")).thenReturn("volumeGroupId1") + when(mockExecution.getVariable("DELVfModVol_aicCloudRegion")).thenReturn("region1") + AAIResultWrapper wrapper = mockVolumeGroupWrapper("region1", "volumeGroupId1", "__files/AAI/VolumeGroupWithTenant.json") + Optional<VolumeGroup> volumeGroupOp = wrapper.asBean(VolumeGroup.class) + deleteVfModuleVolumeInfraV1.queryAAIForVolumeGroup(mockExecution, true) + verify(mockExecution).setVariable("DELVfModVol_volumeGroupTenantId", "Tenant123") + } + + @Test + void testQueryAAIForVolumeGroupWithVfModule(){ + when(mockExecution.getVariable("DELVfModVol_volumeGroupId")).thenReturn("volumeGroupId1") + when(mockExecution.getVariable("DELVfModVol_aicCloudRegion")).thenReturn("region1") + AAIResultWrapper wrapper = mockVolumeGroupWrapper("region1", "volumeGroupId1", "__files/AAI/VolumeGroupWithVfModule.json") + try { + deleteVfModuleVolumeInfraV1.queryAAIForVolumeGroup(mockExecution, true) + } catch (Exception ex) { + println " Test End - Handle catch-throw BpmnError()! " + } + Mockito.verify(mockExecution, times(3)).setVariable(captor.capture(), captor.capture()) + WorkflowException workflowException = captor.getValue() + Assert.assertEquals(2500, workflowException.getErrorCode()) + Assert.assertEquals("Volume Group volumeGroupId1 currently in use - found vf-module relationship.", workflowException.getErrorMessage()) + } + + @Test + void testQueryAAIForVolumeGroupNoTenant(){ + when(mockExecution.getVariable("DELVfModVol_volumeGroupId")).thenReturn("volumeGroupId1") + when(mockExecution.getVariable("DELVfModVol_aicCloudRegion")).thenReturn("region1") + AAIResultWrapper wrapper = mockVolumeGroupWrapper("region1", "volumeGroupId1", "__files/AAI/VolumeGroup.json") + try { + deleteVfModuleVolumeInfraV1.queryAAIForVolumeGroup(mockExecution, true) + } catch (Exception ex) { + println " Test End - Handle catch-throw BpmnError()! " + } + Mockito.verify(mockExecution, times(3)).setVariable(captor.capture(), captor.capture()) + WorkflowException workflowException = captor.getValue() + Assert.assertEquals(2500, workflowException.getErrorCode()) + Assert.assertEquals( "Could not find Tenant Id element in Volume Group with Volume Group Id volumeGroupId1", workflowException.getErrorMessage()) + } + + @Test + void testQueryAAIForVolumeGroupNoId(){ + when(mockExecution.getVariable("DELVfModVol_aicCloudRegion")).thenReturn("region1") + try { + deleteVfModuleVolumeInfraV1.queryAAIForVolumeGroup(mockExecution, true) + } catch (Exception ex) { + println " Test End - Handle catch-throw BpmnError()! " + } + Mockito.verify(mockExecution, times(1)).setVariable(captor.capture(), captor.capture()) + WorkflowException workflowException = captor.getValue() + Assert.assertEquals(2500, workflowException.getErrorCode()) + Assert.assertEquals("volume-group-id is not provided in the request", workflowException.getErrorMessage()) + } + + @Test + void testDeleteVolGrpId(){ + VolumeGroup volumeGroup = new VolumeGroup() + volumeGroup.setVolumeGroupId("volumeGroupId1") + when(mockExecution.getVariable("DELVfModVol_queryAAIVolGrpResponse")).thenReturn(volumeGroup) + when(mockExecution.getVariable("DELVfModVol_aicCloudRegion")).thenReturn("region1") + AAIResourceUri resourceUri = AAIUriFactory.createResourceUri(AAIObjectType.VOLUME_GROUP,CLOUD_OWNER, "region1","volumeGroupId1") + doNothing().when(client).delete(resourceUri) + deleteVfModuleVolumeInfraV1.deleteVolGrpId(mockExecution, true) + verify(client).delete(resourceUri) + } + + @Test + void testDeleteVolGrpIdNotFound(){ + VolumeGroup volumeGroup = new VolumeGroup() + volumeGroup.setVolumeGroupId("volumeGroupId1") + when(mockExecution.getVariable("DELVfModVol_queryAAIVolGrpResponse")).thenReturn(volumeGroup) + when(mockExecution.getVariable("DELVfModVol_aicCloudRegion")).thenReturn("region1") + AAIResourceUri resourceUri = AAIUriFactory.createResourceUri(AAIObjectType.VOLUME_GROUP,CLOUD_OWNER, "region1","volumeGroupId1") + doThrow(new NotFoundException("Not Found")).when(client).delete(resourceUri) + try { + deleteVfModuleVolumeInfraV1.deleteVolGrpId(mockExecution, true) + } catch (Exception ex) { + println " Test End - Handle catch-throw BpmnError()! " + } + Mockito.verify(mockExecution, times(1)).setVariable(captor.capture(), captor.capture()) + WorkflowException workflowException = captor.getValue() + Assert.assertEquals(2500, workflowException.getErrorCode()) + Assert.assertEquals("Volume group volumeGroupId1 not found for delete in AAI Response code: 404", workflowException.getErrorMessage()) + } + + @Test + void testDeleteVolGrpIdError(){ + VolumeGroup volumeGroup = new VolumeGroup() + volumeGroup.setVolumeGroupId("volumeGroupId1") + when(mockExecution.getVariable("DELVfModVol_queryAAIVolGrpResponse")).thenReturn(volumeGroup) + when(mockExecution.getVariable("DELVfModVol_aicCloudRegion")).thenReturn("region1") + AAIResourceUri resourceUri = AAIUriFactory.createResourceUri(AAIObjectType.VOLUME_GROUP,CLOUD_OWNER, "region1","volumeGroupId1") + doThrow(new GraphInventoryUriComputationException("Error")).when(client).delete(resourceUri) + try { + deleteVfModuleVolumeInfraV1.deleteVolGrpId(mockExecution, true) + } catch (Exception ex) { + println " Test End - Handle catch-throw BpmnError()! " + } + Mockito.verify(mockExecution, times(1)).setVariable(captor.capture(), captor.capture()) + WorkflowException workflowException = captor.getValue() + Assert.assertEquals(5000, workflowException.getErrorCode()) + Assert.assertEquals("Received error from A&AI ()", workflowException.getErrorMessage()) + } } diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateE2EServiceInstanceTest.groovy b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateE2EServiceInstanceTest.groovy index d8a82acfa7..fc8bd0da8a 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateE2EServiceInstanceTest.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateE2EServiceInstanceTest.groovy @@ -20,53 +20,54 @@ package org.onap.so.bpmn.infrastructure.scripts -import com.github.tomakehurst.wiremock.junit.WireMockRule -import org.camunda.bpm.engine.ProcessEngineServices -import org.camunda.bpm.engine.RepositoryService +import static com.shazam.shazamcrest.MatcherAssert.assertThat +import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs +import static org.mockito.Mockito.times +import static org.mockito.Mockito.when + import org.camunda.bpm.engine.impl.persistence.entity.ExecutionEntity -import org.camunda.bpm.engine.repository.ProcessDefinition 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.MockitoAnnotations -import org.mockito.runners.MockitoJUnitRunner -import org.onap.so.bpmn.common.scripts.utils.XmlComparator +import org.onap.aai.domain.yang.ServiceInstance +import org.onap.so.bpmn.common.scripts.MsoGroovyTest -import static org.mockito.Mockito.* /** * @author sushilma * @since January 10, 2018 */ -@RunWith(MockitoJUnitRunner.class) -class DoCreateE2EServiceInstanceTest { +class DoCreateE2EServiceInstanceTest extends MsoGroovyTest{ - @Rule - public WireMockRule wireMockRule = new WireMockRule(28090); @Before - public void init() throws IOException { - MockitoAnnotations.initMocks(this); + public void init() { + super.init("DoCreateE2EServiceInstance") } - @Captor static ArgumentCaptor<ExecutionEntity> captor = ArgumentCaptor.forClass(ExecutionEntity.class) - - String expectedServiceInstanceData = """ <service-instance xmlns="http://org.openecomp.aai.inventory/v8"> - <service-instance-id>1234</service-instance-id> - <service-instance-name>volte-service</service-instance-name> - <service-type>voLTE type</service-type> - <service-role>voLTE role</service-role> - <orchestration-status>Created</orchestration-status> - <model-invariant-id>c1d4305f-cdbd-4bbe-9069-a2f4978fd89e</model-invariant-id> - <model-version-id>d4df5c27-98a1-4812-a8aa-c17f055b7a3f</model-version-id> - </service-instance>""" @Test public void testPreProcessRequest(){ - ExecutionEntity mockExecution = setupMock() + mockData() + ServiceInstance expectedServiceInstanceData = getExpectedServiceInstance() + DoCreateE2EServiceInstance serviceInstance = new DoCreateE2EServiceInstance() + serviceInstance.preProcessRequest(mockExecution) + Mockito.verify(mockExecution, times(7)).setVariable(captor.capture(), captor.capture()) + assertThat(captor.getValue(), sameBeanAs(expectedServiceInstanceData)) + } + + private ServiceInstance getExpectedServiceInstance() { + ServiceInstance expectedServiceInstanceData = new ServiceInstance() + expectedServiceInstanceData.setServiceInstanceId("1234") + expectedServiceInstanceData.setServiceInstanceName("volte-service") + expectedServiceInstanceData.setServiceType("E2E Service") + expectedServiceInstanceData.setServiceRole("E2E Service") + expectedServiceInstanceData.setOrchestrationStatus("Created") + return expectedServiceInstanceData + } + + private void mockData() { when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") when(mockExecution.getVariable("globalSubscriberId")).thenReturn("12345") when(mockExecution.getVariable("serviceType")).thenReturn("TRANSPORT") @@ -76,27 +77,8 @@ class DoCreateE2EServiceInstanceTest { when(mockExecution.getVariable("mso.workflow.sdncadapter.callback")).thenReturn("/mso/sdncadapter/") when(mockExecution.getVariable("mso.workflow.global.default.aai.namespace")).thenReturn("http://org.openecomp.aai.inventory/") when(mockExecution.getVariable("mso.workflow.default.aai.customer.version")).thenReturn("8") - DoCreateE2EServiceInstance obj = new DoCreateE2EServiceInstance() - obj.preProcessRequest(mockExecution) - Mockito.verify(mockExecution, times(7)).setVariable(captor.capture(), captor.capture()) - XmlComparator.assertXMLEquals(expectedServiceInstanceData, captor.getValue()) + when(mockExecution.getVariable("mso.workflow.default.aai.v8.customer.uri")).thenReturn('/aai/v8/business/customers/customer') + when(mockExecution.getVariable("URN_mso_workflow_sdncadapter_callback")).thenReturn('/testUrl') } - private ExecutionEntity setupMock() { - ProcessDefinition mockProcessDefinition = mock(ProcessDefinition.class) - when(mockProcessDefinition.getKey()).thenReturn("DoCreateE2EServiceInstance") - RepositoryService mockRepositoryService = mock(RepositoryService.class) - when(mockRepositoryService.getProcessDefinition()).thenReturn(mockProcessDefinition) - when(mockRepositoryService.getProcessDefinition().getKey()).thenReturn("DoCreateE2EServiceInstance") - 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("DoCreateE2EServiceInstance") - when(mockExecution.getProcessInstanceId()).thenReturn("DoCreateE2EServiceInstance") - when(mockExecution.getProcessEngineServices()).thenReturn(mockProcessEngineServices) - when(mockExecution.getProcessEngineServices().getRepositoryService().getProcessDefinition(mockExecution.getProcessDefinitionId())).thenReturn(mockProcessDefinition) - return mockExecution - } } diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateNetworkInstanceTest.groovy b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateNetworkInstanceTest.groovy index 11dbf7d2ee..e8170ed2cb 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateNetworkInstanceTest.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateNetworkInstanceTest.groovy @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -43,9 +43,11 @@ import org.junit.Test import org.junit.runner.RunWith import org.mockito.MockitoAnnotations import org.mockito.runners.MockitoJUnitRunner +import org.onap.aai.domain.yang.L3Network import org.onap.so.bpmn.common.scripts.MsoUtils import org.onap.so.bpmn.core.WorkflowException - +import org.onap.so.client.aai.AAIResourcesClient +import org.onap.so.client.aai.entities.uri.AAIResourceUri import com.github.tomakehurst.wiremock.client.WireMock import com.github.tomakehurst.wiremock.junit.WireMockRule import org.apache.commons.lang3.* @@ -480,7 +482,7 @@ class DoCreateNetworkInstanceTest { <host-route-id>string</host-route-id> <route-prefix>192.10.16.0/24</route-prefix> <next-hop>192.10.16.100/24</next-hop> - <next-hop-type>ip-address</next-hop-type> + <next-hop-type>ip-address</next-hop-type> <resource-version>1505857301954</resource-version> </host-route> <host-route> @@ -508,7 +510,7 @@ class DoCreateNetworkInstanceTest { <host-route-id>string</host-route-id> <route-prefix>192.10.16.0/24</route-prefix> <next-hop>192.10.16.100/24</next-hop> - <next-hop-type>ip-address</next-hop-type> + <next-hop-type>ip-address</next-hop-type> <resource-version>1505857301954</resource-version> </host-route> </host-routes> @@ -1669,7 +1671,7 @@ String createNetworkRequest_Ipv4 = <notificationUrl/> </createNetworkRequest>""" -String createNetworkRequestAlaCarte = +String createNetworkRequestAlaCarte = """<createNetworkRequest> <cloudSiteId>RDM2WAGPLCP</cloudSiteId> <tenantId>7dd5365547234ee8937416c65507d266</tenantId> @@ -1874,8 +1876,8 @@ String createNetworkRequest_SRIOV = <serviceInstanceId/> </msoRequest> </networkRollback> -</rollbackNetworkRequest>""" - +</rollbackNetworkRequest>""" + String createNetworkResponse = """<ns2:createNetworkResponse xmlns:ns2="http://org.onap.so/network" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> @@ -2952,7 +2954,7 @@ String sdncAdapterWorkflowAssignResponse = println "************ preProcessRequest_Payload ************* " - def networkModelInfo = """{"modelUuid": "sn5256d1-5a33-55df-13ab-12abad84e111", + String networkModelInfo = """{"modelUuid": "sn5256d1-5a33-55df-13ab-12abad84e111", "modelName": "CONTRAIL_EXTERNAL", "modelType": "CONTRAIL_EXTERNAL", "modelVersion": "1", @@ -2960,7 +2962,7 @@ String sdncAdapterWorkflowAssignResponse = "modelInvariantUuid": "sn5256d1-5a33-55df-13ab-12abad84e764" }""".trim() - def serviceModelInfo = """{"modelUuid": "36a3a8ea-49a6-4ac8-b06c-89a54544b9b6", + String serviceModelInfo = """{"modelUuid": "36a3a8ea-49a6-4ac8-b06c-89a54544b9b6", "modelName": "HNGW Protected OAM", "modelType": "service", "modelVersion": "1.0", @@ -3053,7 +3055,7 @@ String sdncAdapterWorkflowAssignResponse = when(mockExecution.getVariable("bpmnRequest")).thenReturn(jsonIncomingRequest) // JSON format when(mockExecution.getVariable("sdncVersion")).thenReturn("1610") // 1610 default when(mockExecution.getVariable("disableRollback")).thenReturn(true) - + when(mockExecution.getVariable("mso.adapters.po.auth")).thenReturn("3141634BF7E070AA289CF2892C986C0B") when(mockExecution.getVariable("mso.msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7") @@ -3182,8 +3184,8 @@ String sdncAdapterWorkflowAssignResponse = verify(mockExecution).setVariable(Prefix + "createNetworkRequest", createNetworkRequest) } - - + + @Test //@Ignore public void prepareCreateNetworkRequest_Ipv4() { @@ -3220,7 +3222,7 @@ String sdncAdapterWorkflowAssignResponse = verify(mockExecution).setVariable(Prefix + "createNetworkRequest", createNetworkRequest_Ipv4) } - + @Test //@Ignore public void prepareCreateNetworkRequest_AlaCarte() { @@ -3712,7 +3714,7 @@ String sdncAdapterWorkflowAssignResponse = //MockitoDebuggerImpl preDebugger = new MockitoDebuggerImpl() //preDebugger.printInvocations(mockExecution) - verify(mockExecution, atLeast(1)).setVariable("prefix", Prefix) + verify(mockExecution, atLeast(1)).setVariable("prefix", Prefix) verify(mockExecution, atLeast(1)).setVariable(Prefix + "queryCloudRegionReturnCode", "404") verify(mockExecution).setVariable(Prefix + "cloudRegionPo", "MDTWNJ21") verify(mockExecution).setVariable(Prefix + "cloudRegionSdnc", "AAIAIC25") @@ -3791,7 +3793,7 @@ String sdncAdapterWorkflowAssignResponse = verify(mockExecution, atLeast(2)).setVariable(Prefix + "aaiQqueryVpnBindingReturnCode", "200") } - + @Test //@Ignore public void callRESTQueryAAINetworkVpnBinding_TestScenario01_200() { @@ -4025,26 +4027,25 @@ String sdncAdapterWorkflowAssignResponse = @Test //@Ignore public void callRESTUpdateContrailAAINetworkREST_200() { - - println "************ callRESTUpdateContrailAAINetwork ************* " - + AAIResourcesClient mockClient = mock(AAIResourcesClient.class) WireMock.reset(); - MockPutNetworkIdWithDepth("CreateNetworkV2/createNetwork_updateContrail_AAIResponse_Success.xml", "49c86598-f766-46f8-84f8-8d1c1b10f9b4", "all"); + L3Network network = new L3Network() + //TODO need to inject mock ExecutionEntity mockExecution = setupMock() when(mockExecution.getVariable(Prefix + "networkId")).thenReturn("49c86598-f766-46f8-84f8-8d1c1b10f9b4") - when(mockExecution.getVariable(Prefix + "requeryIdAAIResponse")).thenReturn(queryIdAIIResponse) + when(mockExecution.getVariable(Prefix + "requeryIdAAIResponse")).thenReturn(network) when(mockExecution.getVariable(Prefix + "createNetworkResponse")).thenReturn(createNetworkResponseREST) when(mockExecution.getVariable(Prefix + "messageId")).thenReturn("e8ebf6a0-f8ea-4dc0-8b99-fe98a87722d6") - when(mockExecution.getVariable("aai.endpoint")).thenReturn("http://localhost:8090") + // old: when(mockExecution.getVariable("mso.workflow.DoCreateNetworkInstance.aai.network.l3-network.uri")).thenReturn("/aai/v8/network/l3-networks/l3-network") when(mockExecution.getVariable("mso.workflow.DoCreateNetworkInstance.aai.l3-network.uri")).thenReturn("/aai/v9/network/l3-networks/l3-network") - when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") when(mockExecution.getVariable(Prefix + "rollbackEnabled")).thenReturn("false") when(mockExecution.getVariable("mso.workflow.global.default.aai.namespace")).thenReturn('http://org.openecomp.aai.inventory/') when(mockExecution.getVariable("mso.msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7") when(mockExecution.getVariable("aai.auth")).thenReturn("757A94191D685FD2092AC1490730A4FC") + doNothing().when(mockClient).update(isA(AAIResourceUri.class), isA(L3Network.class)) // preProcessRequest(DelegateExecution execution) DoCreateNetworkInstance DoCreateNetworkInstance = new DoCreateNetworkInstance() DoCreateNetworkInstance.callRESTUpdateContrailAAINetwork(mockExecution) @@ -4102,7 +4103,7 @@ String sdncAdapterWorkflowAssignResponse = } - + @Test //@Ignore diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateServiceInstanceTest.groovy b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateServiceInstanceTest.groovy index 587abbee52..b246caf40e 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateServiceInstanceTest.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateServiceInstanceTest.groovy @@ -21,41 +21,35 @@ package org.onap.so.bpmn.infrastructure.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.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.Rule import org.junit.Test -import org.junit.runner.RunWith -import org.mockito.ArgumentCaptor -import org.mockito.Captor -import org.mockito.Mockito +import org.junit.rules.ExpectedException import org.mockito.MockitoAnnotations -import org.mockito.runners.MockitoJUnitRunner -import org.onap.so.bpmn.core.WorkflowException +import org.onap.so.bpmn.common.scripts.MsoGroovyTest import org.onap.so.bpmn.core.domain.ModelInfo import org.onap.so.bpmn.core.domain.ServiceDecomposition import org.onap.so.bpmn.core.domain.ServiceInstance import org.onap.so.bpmn.mock.StubResponseAAI +import org.onap.so.client.aai.entities.uri.AAIResourceUri import static org.mockito.Mockito.* -@RunWith(MockitoJUnitRunner.class) -class DoCreateServiceInstanceTest { +class DoCreateServiceInstanceTest extends MsoGroovyTest{ def prefix = "DCRESI_" @Rule public WireMockRule wireMockRule = new WireMockRule(28090) - @Captor - static ArgumentCaptor<ExecutionEntity> captor = ArgumentCaptor.forClass(ExecutionEntity.class) + @Rule + public ExpectedException thrown = ExpectedException.none() @Before void init() throws IOException { - MockitoAnnotations.initMocks(this); + super.init("DoCreateServiceInstance") + MockitoAnnotations.initMocks(this) } @Test @@ -96,7 +90,6 @@ class DoCreateServiceInstanceTest { @Test void testGetAAICustomerById() { - ExecutionEntity mockExecution = setupMock() when(mockExecution.getVariable("prefix")).thenReturn(prefix) when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") when(mockExecution.getVariable("globalSubscriberId")).thenReturn("12345") @@ -104,30 +97,41 @@ class DoCreateServiceInstanceTest { when(mockExecution.getVariable("mso.workflow.global.default.aai.namespace")).thenReturn("http://org.openecomp.aai.inventory/") when(mockExecution.getVariable("mso.workflow.custom.DoCreateServiceInstance.aai.version")).thenReturn('8') StubResponseAAI.MockGetCustomer("12345", "") - DoCreateServiceInstance obj = new DoCreateServiceInstance() + DoCreateServiceInstance obj = spy(DoCreateServiceInstance.class) + when(obj.getAAIClient()).thenReturn(client) + when(client.exists(isA(AAIResourceUri.class))).thenReturn(true) obj.getAAICustomerById(mockExecution) + } - verify(mockExecution, times(1)).getVariable("aai.endpoint") + @Test + void testGetAAICustomerById_NoCustFound() { + when(mockExecution.getVariable("prefix")).thenReturn(prefix) + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("globalSubscriberId")).thenReturn("12345") + 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.DoCreateServiceInstance.aai.version")).thenReturn('8') + StubResponseAAI.MockGetCustomer("12345", "") + DoCreateServiceInstance obj = spy(DoCreateServiceInstance.class) + when(obj.getAAIClient()).thenReturn(client) + when(client.exists(isA(AAIResourceUri.class))).thenReturn(false) + thrown.expect(BpmnError.class) + obj.getAAICustomerById(mockExecution) } - private static ExecutionEntity setupMock() { - ProcessDefinition mockProcessDefinition = mock(ProcessDefinition.class) - when(mockProcessDefinition.getKey()).thenReturn("DoCreateServiceInstance") - RepositoryService mockRepositoryService = mock(RepositoryService.class) - when(mockRepositoryService.getProcessDefinition()).thenReturn(mockProcessDefinition) - when(mockRepositoryService.getProcessDefinition().getKey()).thenReturn("DoCreateServiceInstance") - 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("DoCreateServiceInstance") - when(mockExecution.getProcessInstanceId()).thenReturn("DoCreateServiceInstance") - when(mockExecution.getProcessEngineServices()).thenReturn(mockProcessEngineServices) - when(mockExecution.getProcessEngineServices().getRepositoryService().getProcessDefinition(mockExecution.getProcessDefinitionId())).thenReturn(mockProcessDefinition) - - return mockExecution + @Test + void testGetAAICustomerById_Exception() { + when(mockExecution.getVariable("prefix")).thenReturn(prefix) + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("globalSubscriberId")).thenReturn("12345") + 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.DoCreateServiceInstance.aai.version")).thenReturn('8') + StubResponseAAI.MockGetCustomer("12345", "") + DoCreateServiceInstance obj = spy(DoCreateServiceInstance.class) + when(obj.getAAIClient()).thenReturn(client) + when(client.exists(isA(AAIResourceUri.class))).thenThrow(Exception.class) + thrown.expect(Exception.class) + obj.getAAICustomerById(mockExecution) } } diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVFCNetworkServiceInstanceTest.groovy b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVFCNetworkServiceInstanceTest.groovy index 6d9d5e5356..c359f74d7f 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVFCNetworkServiceInstanceTest.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVFCNetworkServiceInstanceTest.groovy @@ -21,40 +21,37 @@ package org.onap.so.bpmn.infrastructure.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.delegate.BpmnError import org.camunda.bpm.engine.impl.persistence.entity.ExecutionEntity -import org.camunda.bpm.engine.repository.ProcessDefinition 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.MockitoAnnotations -import org.mockito.runners.MockitoJUnitRunner - -import static com.github.tomakehurst.wiremock.client.WireMock.aResponse -import static com.github.tomakehurst.wiremock.client.WireMock.put -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.times -import static org.mockito.Mockito.verify +import org.mockito.Spy +import org.onap.so.bpmn.common.scripts.MsoGroovyTest +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 javax.ws.rs.NotFoundException +import static org.junit.Assert.assertEquals +import static org.mockito.ArgumentMatchers.isA +import static org.mockito.Mockito.doNothing +import static org.mockito.Mockito.doThrow import static org.mockito.Mockito.when -/** - * @author sushilma - * @since January 10, 2018 - */ -@RunWith(MockitoJUnitRunner.class) -class DoCreateVFCNetworkServiceInstanceTest { +class DoCreateVFCNetworkServiceInstanceTest extends MsoGroovyTest { + + @Spy + DoCreateVFCNetworkServiceInstance doCreateVFCNetworkServiceInstance - @Rule - public WireMockRule wireMockRule = new WireMockRule(28090) @Before public void init() throws IOException { - MockitoAnnotations.initMocks(this); + super.init("CreateVFCNSResource") + MockitoAnnotations.initMocks(this) + when(doCreateVFCNetworkServiceInstance.getAAIClient()).thenReturn(client) } @Captor @@ -62,45 +59,29 @@ class DoCreateVFCNetworkServiceInstanceTest { @Test public void testAddNSRelationship(){ - ExecutionEntity mockExecution = setupMock() - when(mockExecution.getVariable("aai.endpoint")).thenReturn("http://localhost:28090") when(mockExecution.getVariable("nsInstanceId")).thenReturn("NS12345") when(mockExecution.getVariable("globalSubscriberId")).thenReturn("MSO_dev") when(mockExecution.getVariable("serviceType")).thenReturn("MSO-dev-service-type") when(mockExecution.getVariable("serviceId")).thenReturn("SER12345") - when(mockExecution.getVariable("mso.msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7") - when(mockExecution.getVariable("aai.auth")).thenReturn("757A94191D685FD2092AC1490730A4FC") - MockPutServiceInstance("MSO_dev", "MSO-dev-service-type", "SER12345"); - DoCreateVFCNetworkServiceInstance DoCreateVFCNetworkServiceInstance = new DoCreateVFCNetworkServiceInstance() - DoCreateVFCNetworkServiceInstance.addNSRelationship(mockExecution); - verify(mockExecution, times(1)).getVariable("aai.endpoint") - verify(mockExecution, times(1)).getVariable("mso.msoKey") - verify(mockExecution, times(1)).getVariable("aai.auth") + doNothing().when(client).connect(isA(AAIResourceUri.class),isA(AAIResourceUri.class)) + doCreateVFCNetworkServiceInstance.addNSRelationship(mockExecution); + AAIResourceUri nsUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE,"MSO_dev","MSO-dev-service-type","NS12345") + AAIResourceUri relatedServiceUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE,"MSO_dev","MSO-dev-service-type","SER12345") + Mockito.verify(client).connect(nsUri,relatedServiceUri) } - private ExecutionEntity setupMock() { - ProcessDefinition mockProcessDefinition = mock(ProcessDefinition.class) - when(mockProcessDefinition.getKey()).thenReturn("DoCreateVFCNetworkServiceInstance") - RepositoryService mockRepositoryService = mock(RepositoryService.class) - when(mockRepositoryService.getProcessDefinition()).thenReturn(mockProcessDefinition) - when(mockRepositoryService.getProcessDefinition().getKey()).thenReturn("DoCreateVFCNetworkServiceInstance") - 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("DoCreateVFCNetworkServiceInstance") - when(mockExecution.getProcessInstanceId()).thenReturn("DoCreateVFCNetworkServiceInstance") - when(mockExecution.getProcessEngineServices()).thenReturn(mockProcessEngineServices) - when(mockExecution.getProcessEngineServices().getRepositoryService().getProcessDefinition(mockExecution.getProcessDefinitionId())).thenReturn(mockProcessDefinition) - return mockExecution + @Test + void testaddNSRelationshipError(){ + when(mockExecution.getVariable("globalSubscriberId")).thenReturn("globalSubscriberId1") + when(mockExecution.getVariable("serviceType")).thenReturn("serviceType") + when(mockExecution.getVariable("serviceInstanceId")).thenReturn("serviceInstanceId") + when(mockExecution.getVariable("nsInstanceId")).thenReturn("nsInstanceId") + doThrow(new NotFoundException("Error creating relationship")).when(client).connect(isA(AAIResourceUri.class),isA(AAIResourceUri.class)) + try { + doCreateVFCNetworkServiceInstance.addNSRelationship(mockExecution) + } catch (BpmnError ex) { + assertEquals(ex.getErrorCode(),"MSOWorkflowException") + } } - public static void MockPutServiceInstance(String globalCustId, String subscriptionType, String serviceInstanceId) { - stubFor(put(urlMatching("/aai/v[0-9]+/business/customers/customer/" + globalCustId + "/service-subscriptions/service-subscription/" + subscriptionType + "/service-instances/service-instance/" + serviceInstanceId+"/relationship-list/relationship")) - .willReturn(aResponse() - .withStatus(200) - .withHeader("Content-Type", "text/xml").withBody("") - )); - } } diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVfModuleRollbackTest.groovy b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVfModuleRollbackTest.groovy index c5c6187648..e7ebe23e75 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVfModuleRollbackTest.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVfModuleRollbackTest.groovy @@ -34,20 +34,34 @@ import org.mockito.ArgumentCaptor import org.mockito.Captor import org.mockito.Mockito import org.mockito.MockitoAnnotations +import org.mockito.Spy import org.mockito.runners.MockitoJUnitRunner +import org.onap.aai.domain.yang.NetworkPolicies +import org.onap.aai.domain.yang.NetworkPolicy +import org.onap.so.bpmn.common.scripts.MsoGroovyTest import org.onap.so.bpmn.common.scripts.utils.XmlComparator import org.onap.so.bpmn.core.RollbackData import org.onap.so.bpmn.core.WorkflowException 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.entities.uri.AAIResourceUri +import org.onap.so.client.aai.entities.uri.AAIUriFactory +import org.onap.so.client.graphinventory.exceptions.GraphInventoryUriComputationException + +import javax.ws.rs.NotFoundException import static com.github.tomakehurst.wiremock.client.WireMock.* import static org.mockito.Mockito.* @RunWith(MockitoJUnitRunner.class) -class DoCreateVfModuleRollbackTest { +class DoCreateVfModuleRollbackTest extends MsoGroovyTest{ def prefix = "DCVFMR_" + @Spy + DoCreateVfModuleRollback doCreateVfModuleRollback + @Rule public WireMockRule wireMockRule = new WireMockRule(28090) @@ -56,7 +70,9 @@ class DoCreateVfModuleRollbackTest { @Before void init() throws IOException { - MockitoAnnotations.initMocks(this); + super.init("CreateVFCNSResource") + MockitoAnnotations.initMocks(this) + when(doCreateVfModuleRollback.getAAIClient()).thenReturn(client) } @Test @@ -149,23 +165,90 @@ class DoCreateVfModuleRollbackTest { when(mockExecution.getVariable("prefix")).thenReturn(prefix) when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") when(mockExecution.getVariable("DCVFM_cloudSiteId")).thenReturn("12345") - when(mockExecution.getVariable("mso.workflow.DoCreateVfModuleRollback.aai.network-policy.uri")).thenReturn("/aai/v8/network/network-policies/network-policy") - when(mockExecution.getVariable("mso.workflow.custom.DoCreateVfModuleRollback.aai.version")).thenReturn("8") - 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("rollbackData")).thenReturn(new RollbackData()) List fqdnList = new ArrayList() fqdnList.add("test") when(mockExecution.getVariable(prefix + "createdNetworkPolicyFqdnList")).thenReturn(fqdnList) - mockData() - DoCreateVfModuleRollback obj = new DoCreateVfModuleRollback() - obj.deleteNetworkPoliciesFromAAI(mockExecution) + + AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectPlurals.NETWORK_POLICY) + uri.queryParam("network-policy-fqdn", "test") + NetworkPolicies networkPolicies = new NetworkPolicies(); + NetworkPolicy networkPolicy = new NetworkPolicy(); + networkPolicy.setNetworkPolicyId("NP1") + networkPolicies.getNetworkPolicy().add(networkPolicy) + when(client.get(NetworkPolicies.class, uri)).thenReturn(Optional.of(networkPolicies)) + + AAIResourceUri delUri = AAIUriFactory.createResourceUri(AAIObjectType.NETWORK_POLICY, networkPolicy.getNetworkPolicyId()) + doNothing().when(client).delete(delUri) + + doCreateVfModuleRollback.deleteNetworkPoliciesFromAAI(mockExecution) Mockito.verify(mockExecution).setVariable("prefix", prefix) Mockito.verify(mockExecution).setVariable(prefix + "networkPolicyFqdnCount", 1) Mockito.verify(mockExecution).setVariable(prefix + "aaiQueryNetworkPolicyByFqdnReturnCode", 200) } + @Test + void testDeleteNetworkPoliciesFromAAINotFound() { + ExecutionEntity mockExecution = setupMock() + when(mockExecution.getVariable("prefix")).thenReturn(prefix) + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("DCVFM_cloudSiteId")).thenReturn("12345") + when(mockExecution.getVariable("rollbackData")).thenReturn(new RollbackData()) + List fqdnList = new ArrayList() + fqdnList.add("test") + when(mockExecution.getVariable(prefix + "createdNetworkPolicyFqdnList")).thenReturn(fqdnList) + + AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectPlurals.NETWORK_POLICY) + uri.queryParam("network-policy-fqdn", "test") + NetworkPolicies networkPolicies = new NetworkPolicies(); + NetworkPolicy networkPolicy = new NetworkPolicy(); + networkPolicy.setNetworkPolicyId("NP1") + networkPolicies.getNetworkPolicy().add(networkPolicy) + when(client.get(NetworkPolicies.class, uri)).thenReturn(Optional.of(networkPolicies)) + + AAIResourceUri delUri = AAIUriFactory.createResourceUri(AAIObjectType.NETWORK_POLICY, networkPolicy.getNetworkPolicyId()) + doThrow(new NotFoundException("Not Found!")).when(client).delete(delUri) + + doCreateVfModuleRollback.deleteNetworkPoliciesFromAAI(mockExecution) + + Mockito.verify(mockExecution).setVariable("prefix", prefix) + Mockito.verify(mockExecution).setVariable(prefix + "networkPolicyFqdnCount", 1) + Mockito.verify(mockExecution).setVariable(prefix + "aaiDeleteNetworkPolicyReturnCode", 404) + } + + @Test + void testDeleteNetworkPoliciesFromAAIError() { + ExecutionEntity mockExecution = setupMock() + when(mockExecution.getVariable("prefix")).thenReturn(prefix) + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("DCVFM_cloudSiteId")).thenReturn("12345") + when(mockExecution.getVariable("rollbackData")).thenReturn(new RollbackData()) + List fqdnList = new ArrayList() + fqdnList.add("test") + when(mockExecution.getVariable(prefix + "createdNetworkPolicyFqdnList")).thenReturn(fqdnList) + + AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectPlurals.NETWORK_POLICY) + uri.queryParam("network-policy-fqdn", "test") + NetworkPolicies networkPolicies = new NetworkPolicies(); + NetworkPolicy networkPolicy = new NetworkPolicy(); + networkPolicy.setNetworkPolicyId("NP1") + networkPolicies.getNetworkPolicy().add(networkPolicy) + when(client.get(NetworkPolicies.class, uri)).thenReturn(Optional.of(networkPolicies)) + + AAIResourceUri delUri = AAIUriFactory.createResourceUri(AAIObjectType.NETWORK_POLICY, networkPolicy.getNetworkPolicyId()) + doThrow(new GraphInventoryUriComputationException("Error!")).when(client).delete(delUri) + try { + doCreateVfModuleRollback.deleteNetworkPoliciesFromAAI(mockExecution) + } catch (Exception ex) { + println " Test End - Handle catch-throw BpmnError()! " + } + Mockito.verify(mockExecution, times(4)).setVariable(captor.capture(), captor.capture()) + WorkflowException workflowException = captor.getValue() + Assert.assertEquals(2500, workflowException.getErrorCode()) + Assert.assertEquals("Unable to delete network-policy to AAI deleteNetworkPoliciesFromAAI - Error!", workflowException.getErrorMessage()) + } + private static ExecutionEntity setupMock() { ProcessDefinition mockProcessDefinition = mock(ProcessDefinition.class) diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVfModuleVolumeRollbackTest.groovy b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVfModuleVolumeRollbackTest.groovy new file mode 100644 index 0000000000..5c68cc7fc1 --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVfModuleVolumeRollbackTest.groovy @@ -0,0 +1,63 @@ +/*- + * ============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.infrastructure.scripts; + +import org.junit.Before; +import org.junit.Test +import org.onap.aai.domain.yang.VfModule +import org.onap.aai.domain.yang.VolumeGroup +import org.onap.aai.domain.yang.VolumeGroups; +import org.onap.so.bpmn.common.scripts.MsoGroovyTest +import org.onap.so.client.aai.AAIObjectPlurals +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 org.mockito.Mockito.spy +import static org.mockito.Mockito.when; + +public class DoCreateVfModuleVolumeRollbackTest extends MsoGroovyTest { + + private DoCreateVfModuleVolumeRollback doCreateVfModuleVolumeRollback; + @Before + public void init(){ + super.init("DoCreateVfModuleVolumeRollback"); + doCreateVfModuleVolumeRollback = spy(DoCreateVfModuleVolumeRollback.class); + when(doCreateVfModuleVolumeRollback.getAAIClient()).thenReturn(client) + } + + @Test + void callRESTDeleteAAIVolumeGroupTest(){ + String volumeGroupName = "volumeGroupName" + String cloudRegionId = "cloudRegionId" + when(mockExecution.getVariable("DCVFMODVOLRBK_volumeGroupName")).thenReturn(volumeGroupName) + when(mockExecution.getVariable("DCVFMODVOLRBK_lcpCloudRegionId")).thenReturn(cloudRegionId) + AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectPlurals.VOLUME_GROUP, Defaults.CLOUD_OWNER.toString(), cloudRegionId).queryParam("volume-group-name", volumeGroupName) + VolumeGroup volumeGroup = new VolumeGroup(); + volumeGroup.setVolumeGroupId("volumeGroupId") + VolumeGroups groups = new VolumeGroups(); + groups.getVolumeGroup().add(volumeGroup) + when(client.get(VolumeGroups.class,uri)).thenReturn(Optional.of(groups)) + + doCreateVfModuleVolumeRollback.callRESTDeleteAAIVolumeGroup(mockExecution,null) + } + +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVfModuleVolumeV2Test.groovy b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVfModuleVolumeV2Test.groovy index 91e7086bd3..ddb1fbade4 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVfModuleVolumeV2Test.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVfModuleVolumeV2Test.groovy @@ -20,30 +20,47 @@ package org.onap.so.bpmn.infrastructure.scripts +import org.camunda.bpm.engine.delegate.BpmnError import org.camunda.bpm.engine.impl.persistence.entity.ExecutionEntity import org.junit.Before +import org.junit.Rule import org.junit.Test +import org.junit.rules.ExpectedException import org.junit.runner.RunWith import org.mockito.ArgumentCaptor import org.mockito.Captor import org.mockito.Mockito import org.mockito.MockitoAnnotations import org.mockito.runners.MockitoJUnitRunner +import org.onap.aai.domain.yang.GenericVnf +import org.onap.aai.domain.yang.Volume +import org.onap.aai.domain.yang.VolumeGroup +import org.onap.aai.domain.yang.VolumeGroups import org.onap.so.bpmn.common.scripts.MsoGroovyTest +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.constants.Defaults import static org.junit.Assert.assertEquals import static org.junit.Assert.assertNotNull +import static org.mockito.ArgumentMatchers.anyObject +import static org.mockito.Mockito.spy import static org.mockito.Mockito.times +import static org.mockito.Mockito.verify import static org.mockito.Mockito.when -@RunWith(MockitoJUnitRunner.class) class DoCreateVfModuleVolumeV2Test extends MsoGroovyTest { + private DoCreateVfModuleVolumeV2 doCreateVfModuleVolumeV2; + @Captor static ArgumentCaptor<ExecutionEntity> captor = ArgumentCaptor.forClass(ExecutionEntity.class) - def String volumeRollbackRequest = """ + String volumeRollbackRequest = """ <rollbackVolumeGroupRequest> <volumeGroupRollback> <volumeGroupId>171907d6-cdf0-4e08-953d-81ee104005a7</volumeGroupId> @@ -62,7 +79,7 @@ class DoCreateVfModuleVolumeV2Test extends MsoGroovyTest { </rollbackVolumeGroupRequest> """ - def String volumeRollbackRequestWithStackId = """ + String volumeRollbackRequestWithStackId = """ <rollbackVolumeGroupRequest> <volumeGroupRollback> <volumeGroupId>171907d6-cdf0-4e08-953d-81ee104005a7</volumeGroupId> @@ -86,6 +103,9 @@ class DoCreateVfModuleVolumeV2Test extends MsoGroovyTest { @Before public void init() { + super.init("DoCreateVfModuleVolumeV2") + doCreateVfModuleVolumeV2 = spy(DoCreateVfModuleVolumeV2.class) + when(doCreateVfModuleVolumeV2.getAAIClient()).thenReturn(client) MockitoAnnotations.initMocks(this) } @@ -117,6 +137,7 @@ class DoCreateVfModuleVolumeV2Test extends MsoGroovyTest { ExecutionEntity mockExecution = setupMock('DoCreateVfModuleVolumeV2') when(mockExecution.getVariable("prefix")).thenReturn('DCVFMODVOLV2_') + when(mockExecution.getVariable("DCVFMODVOLV2_AAIQueryGenericVfnResponse")).thenReturn(new GenericVnf()) when(mockExecution.getVariable("serviceInstanceId")).thenReturn('') when(mockExecution.getVariable("vnfId")).thenReturn('test-vnf-id') when(mockExecution.getVariable("mso-request-id")).thenReturn('1234') @@ -132,4 +153,129 @@ class DoCreateVfModuleVolumeV2Test extends MsoGroovyTest { String DCVFMODVOLV2_createVnfARequest = captor.getValue(); assertNotNull(DCVFMODVOLV2_createVnfARequest) } + + @Test + void testcallRESTQueryAAIVolGrpName(){ + String volumeGroupName = "volumeGroupName" + String lcpCloudRegionId = "lcpCloudRegionId" + when(mockExecution.getVariable(volumeGroupName)).thenReturn(volumeGroupName) + when(mockExecution.getVariable(lcpCloudRegionId)).thenReturn(lcpCloudRegionId) + AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectPlurals.VOLUME_GROUP, Defaults.CLOUD_OWNER.toString(), lcpCloudRegionId).queryParam("volume-group-name", volumeGroupName) + VolumeGroups volumeGroups = new VolumeGroups(); + VolumeGroup volumeGroup = new VolumeGroup() + volumeGroup.setVolumeGroupId("volumeGroupId") + volumeGroups.getVolumeGroup().add(volumeGroup); + when(client.get(VolumeGroups.class,uri)).thenReturn(Optional.of(volumeGroups)) + doCreateVfModuleVolumeV2.callRESTQueryAAIVolGrpName(mockExecution,null) + verify(mockExecution).setVariable("DCVFMODVOLV2_AaiReturnCode",200) + } + + @Test + void testcallRESTQueryAAIVolGrpName_NoData(){ + String volumeGroupName = "volumeGroupName" + String lcpCloudRegionId = "lcpCloudRegionId" + when(mockExecution.getVariable(volumeGroupName)).thenReturn(volumeGroupName) + when(mockExecution.getVariable(lcpCloudRegionId)).thenReturn(lcpCloudRegionId) + AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectPlurals.VOLUME_GROUP, Defaults.CLOUD_OWNER.toString(), lcpCloudRegionId).queryParam("volume-group-name", volumeGroupName) + when(client.get(VolumeGroup.class,uri)).thenReturn(Optional.empty()) + thrown.expect(BpmnError.class) + doCreateVfModuleVolumeV2.callRESTQueryAAIVolGrpName(mockExecution,null) + } + + @Test + void testcallRESTUpdateCreatedVolGrpName(){ + String queriedVolumeGroupId = "queriedVolumeGroupId" + String modelCustomizationId = "modelCustomizationId" + String lcpCloudRegionId = "lcpCloudRegionId" + when(mockExecution.getVariable(queriedVolumeGroupId)).thenReturn(queriedVolumeGroupId) + when(mockExecution.getVariable(modelCustomizationId)).thenReturn(modelCustomizationId) + when(mockExecution.getVariable(lcpCloudRegionId)).thenReturn(lcpCloudRegionId) + when(mockExecution.getVariable("DCVFMODVOLV2_createVnfAResponse")).thenReturn("<createVnfAResponse><volumeGroupStackId>volumeGroupStackId</volumeGroupStackId></createVnfAResponse>") + doCreateVfModuleVolumeV2.callRESTUpdateCreatedVolGrpName(mockExecution,null) + verify(mockExecution).setVariable("DCVFMODVOLV2_heatStackId","volumeGroupStackId") + } + + @Test + void testcallRESTUpdateCreatedVolGrpNameException(){ + String queriedVolumeGroupId = "queriedVolumeGroupId" + String modelCustomizationId = "modelCustomizationId" + String lcpCloudRegionId = "lcpCloudRegionId" + when(mockExecution.getVariable(queriedVolumeGroupId)).thenReturn(queriedVolumeGroupId) + when(mockExecution.getVariable(modelCustomizationId)).thenReturn(modelCustomizationId) + when(mockExecution.getVariable(lcpCloudRegionId)).thenReturn(lcpCloudRegionId) + when(mockExecution.getVariable("DCVFMODVOLV2_createVnfAResponse")).thenReturn("<createVnfAResponse><volumeGroupStackId>volumeGroupStackId</volumeGroupStackId></createVnfAResponse>") + when(client.update(anyObject(),anyObject())).thenThrow(Exception.class) + thrown.expect(BpmnError.class) + doCreateVfModuleVolumeV2.callRESTUpdateCreatedVolGrpName(mockExecution,null) + verify(mockExecution).setVariable("DCVFMODVOLV2_heatStackId","volumeGroupStackId") + } + + @Test + void testcallRESTQueryAAIGenericVnf(){ + String vnfId = "vnfId" + when(mockExecution.getVariable(vnfId)).thenReturn(vnfId) + AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId) + GenericVnf genericVnf = new GenericVnf() + genericVnf.setVnfId(vnfId) + when(client.get(GenericVnf.class,uri)).thenReturn(Optional.of(genericVnf)) + doCreateVfModuleVolumeV2.callRESTQueryAAIGenericVnf(mockExecution,null) + verify(mockExecution).setVariable("DCVFMODVOLV2_AAIQueryGenericVfnResponse",genericVnf) + } + + @Test + void testcallRESTQueryAAIGenericVnf_NotFound(){ + String vnfId = "vnfId" + when(mockExecution.getVariable(vnfId)).thenReturn(vnfId) + AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId) + when(client.get(GenericVnf.class,uri)).thenReturn(Optional.empty()) + thrown.expect(BpmnError.class) + doCreateVfModuleVolumeV2.callRESTQueryAAIGenericVnf(mockExecution,null) + } + + @Test + void testcallRESTCreateAAIVolGrpName(){ + String vnfId = "vnfId" + String volumeGroupId = "volumeGroupId" + String volumeGroupName = "volumeGroupName" + String modelCustomizationId = "modelCustomizationId" + String vnfType= "vnfType" + String tenantId = "tenantId" + String lcpCloudRegionId= "lcpCloudRegionId" + String cloudOwner = "cloudOwner" + + when(mockExecution.getVariable(vnfId)).thenReturn(vnfId) + when(mockExecution.getVariable(volumeGroupId)).thenReturn(volumeGroupId) + when(mockExecution.getVariable(volumeGroupName)).thenReturn(volumeGroupName) + when(mockExecution.getVariable(modelCustomizationId)).thenReturn(modelCustomizationId) + when(mockExecution.getVariable(vnfType)).thenReturn(vnfType) + when(mockExecution.getVariable(tenantId)).thenReturn(tenantId) + when(mockExecution.getVariable(lcpCloudRegionId)).thenReturn(lcpCloudRegionId) + when(mockExecution.getVariable(cloudOwner)).thenReturn(cloudOwner) + when(mockExecution.getVariable("rollbackData")).thenReturn(new RollbackData()) + doCreateVfModuleVolumeV2.callRESTCreateAAIVolGrpName(mockExecution,null) + verify(mockExecution).setVariable("queriedVolumeGroupId", "volumeGroupId") + } + + @Test + void testcallRESTCreateAAIVolGrpNameException(){ + String vnfId = "vnfId" + String volumeGroupId = "volumeGroupId" + String volumeGroupName = "volumeGroupName" + String modelCustomizationId = "modelCustomizationId" + String vnfType= "vnfType" + String tenantId = "tenantId" + String lcpCloudRegionId= "lcpCloudRegionId" + String cloudOwner = "cloudOwner" + + when(mockExecution.getVariable(vnfId)).thenReturn(vnfId) + when(mockExecution.getVariable(volumeGroupId)).thenReturn(volumeGroupId) + when(mockExecution.getVariable(volumeGroupName)).thenReturn(volumeGroupName) + when(mockExecution.getVariable(modelCustomizationId)).thenReturn(modelCustomizationId) + when(mockExecution.getVariable(vnfType)).thenReturn(vnfType) + when(mockExecution.getVariable(tenantId)).thenReturn(tenantId) + when(mockExecution.getVariable(lcpCloudRegionId)).thenReturn(lcpCloudRegionId) + when(mockExecution.getVariable(cloudOwner)).thenReturn(cloudOwner) + thrown.expect(BpmnError.class) + doCreateVfModuleVolumeV2.callRESTCreateAAIVolGrpName(mockExecution,null) + } } diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCustomDeleteE2EServiceInstanceTest.groovy b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCustomDeleteE2EServiceInstanceTest.groovy index bbbb82b5aa..4cb21181ec 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCustomDeleteE2EServiceInstanceTest.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCustomDeleteE2EServiceInstanceTest.groovy @@ -34,7 +34,7 @@ import org.onap.so.bpmn.mock.FileUtil import org.onap.so.bpmn.vcpe.scripts.GroovyTestBase import static org.assertj.core.api.Assertions.assertThatThrownBy -import static org.mockito.Matchers.anyString +import static org.mockito.ArgumentMatchers.anyString import static org.mockito.Mockito.verify import static org.mockito.Mockito.when import static org.mockito.Mockito.eq diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCustomDeleteE2EServiceInstanceV2Test.groovy b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCustomDeleteE2EServiceInstanceV2Test.groovy new file mode 100644 index 0000000000..6b3674d908 --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCustomDeleteE2EServiceInstanceV2Test.groovy @@ -0,0 +1,62 @@ +/*- + * ============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.infrastructure.scripts + +import org.junit.Before +import org.junit.Test +import org.mockito.Mockito +import org.mockito.Spy +import org.onap.aai.domain.yang.AllottedResource +import org.onap.so.bpmn.common.scripts.MsoGroovyTest +import org.onap.so.bpmn.mock.FileUtil +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 javax.ws.rs.core.UriBuilder +import static org.mockito.Mockito.times +import static org.mockito.Mockito.when + +class DoCustomDeleteE2EServiceInstanceV2Test extends MsoGroovyTest { + + @Spy + DoCustomDeleteE2EServiceInstanceV2 doCustomDeleteE2EServiceInstanceV2 + + @Before + void init(){ + super.init("DoCustomDeleteE2EServiceInstanceV2") + Mockito.when(doCustomDeleteE2EServiceInstanceV2.getAAIClient()).thenReturn(client) + } + + @Test + void testPrepareServiceDeleteResource(){ + when(mockExecution.getVariable("serviceInstance")).thenReturn(FileUtil.readResourceFile("__files/AAI/ServiceInstanceWithAR.json")) + def relink = "/aai/v11/business/customers/customer/testCustIdInfra/service-subscriptions/service-subscription/HNPORTAL/service-instances/service-instance/testServiceInstanceIdPortalPri/allotted-resources/allotted-resource/testAllottedResourceIdPortalPri" + AAIResourceUri uri = AAIUriFactory.createResourceFromExistingURI(AAIObjectType.ALLOTTED_RESOURCE, UriBuilder.fromPath(relink).build()) + AllottedResource ar = new AllottedResource(); + ar.setId("ar1") + ar.setType("ar") + ar.setRole("ar") + ar.setResourceVersion("1234") + when(client.get(AllottedResource.class,uri)).thenReturn(Optional.of(ar)) + doCustomDeleteE2EServiceInstanceV2.prepareServiceDeleteResource(mockExecution) + Mockito.verify(client, times(1)).get(AllottedResource.class,uri) + } +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteNetworkInstanceTest.groovy b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteNetworkInstanceTest.groovy index 7f55eb3dcb..a95a01912d 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteNetworkInstanceTest.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteNetworkInstanceTest.groovy @@ -20,35 +20,39 @@ package org.onap.so.bpmn.infrastructure.scripts - import static org.mockito.Mockito.* - -import static org.onap.so.bpmn.mock.StubResponseNetworkAdapter.MockNetworkAdapter; -import static org.onap.so.bpmn.mock.StubResponseAAI.MockGetNetworkByIdWithDepth; import static org.onap.so.bpmn.mock.StubResponseAAI.MockGetNetworkCloudRegion; import static org.onap.so.bpmn.mock.StubResponseAAI.MockGetNetworkCloudRegion_404; +import static org.onap.so.bpmn.mock.StubResponseNetworkAdapter.MockNetworkAdapter; + +import org.apache.commons.lang3.* 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.engine.delegate.DelegateExecution import org.junit.Before import org.junit.Ignore import org.junit.Rule import org.junit.Test -import org.junit.runner.RunWith import org.mockito.MockitoAnnotations -import org.mockito.runners.MockitoJUnitRunner +import org.onap.aai.domain.yang.L3Network +import org.onap.aai.domain.yang.Relationship +import org.onap.aai.domain.yang.RelationshipList +import org.onap.so.bpmn.common.scripts.MsoGroovyTest import org.onap.so.bpmn.common.scripts.MsoUtils import org.onap.so.bpmn.core.WorkflowException +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.constants.Defaults import com.github.tomakehurst.wiremock.client.WireMock import com.github.tomakehurst.wiremock.junit.WireMockRule -import org.apache.commons.lang3.* -@RunWith(MockitoJUnitRunner.class) -class DoDeleteNetworkInstanceTest { +class DoDeleteNetworkInstanceTest extends MsoGroovyTest{ @Rule public WireMockRule wireMockRule = new WireMockRule(8090); @@ -1117,11 +1121,11 @@ String sdncAdapterWorkflowFormattedResponse_404 = @Before public void init() { + super.init("DoDeleteNetworkInstance") MockitoAnnotations.initMocks(this) } @Test - //@Ignore public void preProcessRequest_Json() { println "************ preProcessRequest_Payload ************* " @@ -1183,7 +1187,7 @@ String sdncAdapterWorkflowFormattedResponse_404 = //@Ignore public void preProcessRequest_vPER() { - def networkModelInfo = """{"modelUuid": "sn5256d1-5a33-55df-13ab-12abad84e111", + String networkModelInfo = """{"modelUuid": "sn5256d1-5a33-55df-13ab-12abad84e111", "modelName": "CONTRAIL_EXTERNAL", "modelType": "CONTRAIL_EXTERNAL", "modelVersion": "1", @@ -1258,7 +1262,6 @@ String sdncAdapterWorkflowFormattedResponse_404 = verify(mockExecution).setVariable(Prefix + "networkInputs", "") verify(mockExecution).setVariable(Prefix + "tenantId", "") - verify(mockExecution).setVariable(Prefix + "queryAAIRequest","") verify(mockExecution).setVariable(Prefix + "queryAAIResponse", "") verify(mockExecution).setVariable(Prefix + "aaiReturnCode", "") verify(mockExecution).setVariable(Prefix + "isAAIGood", false) @@ -1351,7 +1354,7 @@ String sdncAdapterWorkflowFormattedResponse_404 = //@Ignore public void preProcessRequest_Json_MissingCloudRegion() { - def networkModelInfo = """{"modelVersionId": "sn5256d1-5a33-55df-13ab-12abad84e111", + String networkModelInfo = """{"modelVersionId": "sn5256d1-5a33-55df-13ab-12abad84e111", "modelName": "CONTRAIL_EXTERNAL", "modelType": "CONTRAIL_EXTERNAL", "modelVersion": "1", @@ -1583,13 +1586,10 @@ String sdncAdapterWorkflowFormattedResponse_404 = @Test - //@Ignore - public void callRESTQueryAAI_200() { - println "************ callRESTQueryAAI ************* " + public void callRESTQueryAAI_VfRelationshipExist() { - WireMock.reset(); - MockGetNetworkByIdWithDepth("bdc5efe8-404a-409b-85f6-0dcc9eebae30", "DeleteNetworkV2/deleteNetworkAAIResponse_Success.xml", "all"); + println "************ callRESTQueryAAI ************* " ExecutionEntity mockExecution = setupMock() when(mockExecution.getVariable(Prefix + "networkInputs")).thenReturn(expectedNetworkRequest) @@ -1602,89 +1602,113 @@ String sdncAdapterWorkflowFormattedResponse_404 = when(mockExecution.getVariable("mso.workflow.global.default.aai.namespace")).thenReturn('http://org.openecomp.aai.inventory/') when(mockExecution.getVariable("mso.msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7") when(mockExecution.getVariable("aai.auth")).thenReturn("757A94191D685FD2092AC1490730A4FC") - - DoDeleteNetworkInstance DoDeleteNetworkInstance = new DoDeleteNetworkInstance() - DoDeleteNetworkInstance.callRESTQueryAAI(mockExecution) + String networkId = "bdc5efe8-404a-409b-85f6-0dcc9eebae30" + DoDeleteNetworkInstance doDeleteNetworkInstance = spy(DoDeleteNetworkInstance.class) + when(doDeleteNetworkInstance.getAAIClient()).thenReturn(client) + L3Network l3Network = getL3Network() + Relationship relationship = new Relationship(); + relationship.setRelatedTo("vf-module") + l3Network.getRelationshipList().getRelationship().add(relationship) + AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.L3_NETWORK, networkId).depth(Depth.ALL) + when(client.get(L3Network.class,uri)).thenReturn(Optional.of(l3Network)) + + doDeleteNetworkInstance.callRESTQueryAAI(mockExecution) verify(mockExecution).setVariable("prefix", Prefix) - verify(mockExecution).setVariable(Prefix + "queryAAIRequest", "http://localhost:8090/aai/v9/network/l3-networks/l3-network/bdc5efe8-404a-409b-85f6-0dcc9eebae30"+"?depth=all") - verify(mockExecution).setVariable(Prefix + "aaiReturnCode", "200") + verify(mockExecution).setVariable(Prefix + "aaiReturnCode", 200) //verify(mockExecution).setVariable(Prefix + "queryAAIResponse", aaiResponse) verify(mockExecution).setVariable(Prefix + "isAAIGood", true) - verify(mockExecution).setVariable(Prefix + "isVfRelationshipExist", false) + verify(mockExecution).setVariable(Prefix + "isVfRelationshipExist", true) } @Test //@Ignore - public void callRESTQueryAAI_withRelationship_200() { + public void callRESTQueryAAI_200() { println "************ callRESTQueryAAI ************* " - - WireMock.reset(); - MockGetNetworkByIdWithDepth("bdc5efe8-404a-409b-85f6-0dcc9eebae30", "DeleteNetworkV2/deleteNetworkAAIResponse_withRelationship_Success.xml", "all"); - ExecutionEntity mockExecution = setupMock() when(mockExecution.getVariable(Prefix + "networkInputs")).thenReturn(expectedNetworkRequest) when(mockExecution.getVariable(Prefix + "messageId")).thenReturn("e8ebf6a0-f8ea-4dc0-8b99-fe98a87722d6") when(mockExecution.getVariable("aai.endpoint")).thenReturn("http://localhost:8090") when(mockExecution.getVariable("mso.workflow.default.aai.network.l3-network.uri")).thenReturn("") - // old: when(mockExecution.getVariable("mso.workflow.DoDeleteNetworkInstance.aai.network.l3-network.uri")).thenReturn("/aai/v8/network/l3-networks/l3-network") - when(mockExecution.getVariable("mso.workflow.DoDeleteNetworkInstance.aai.l3-network.uri")).thenReturn("/aai/v9/network/l3-networks/l3-network") + when(mockExecution.getVariable("mso.workflow.doDeleteNetworkInstance.aai.l3-network.uri")).thenReturn("/aai/v9/network/l3-networks/l3-network") when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") when(mockExecution.getVariable("mso.workflow.global.default.aai.namespace")).thenReturn('http://org.openecomp.aai.inventory/') when(mockExecution.getVariable("mso.msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7") when(mockExecution.getVariable("aai.auth")).thenReturn("757A94191D685FD2092AC1490730A4FC") - - DoDeleteNetworkInstance DoDeleteNetworkInstance = new DoDeleteNetworkInstance() - DoDeleteNetworkInstance.callRESTQueryAAI(mockExecution) + when(mockExecution.getVariable(Prefix + "lcpCloudRegion")).thenReturn(null) + String networkId = "bdc5efe8-404a-409b-85f6-0dcc9eebae30" + DoDeleteNetworkInstance doDeleteNetworkInstance = spy(DoDeleteNetworkInstance.class) + when(doDeleteNetworkInstance.getAAIClient()).thenReturn(client) + L3Network l3Network = getL3Network() + AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.L3_NETWORK, networkId).depth(Depth.ALL) + when(client.get(L3Network.class,uri)).thenReturn(Optional.of(l3Network)) + doDeleteNetworkInstance.callRESTQueryAAI(mockExecution) verify(mockExecution, atLeast(1)).setVariable("prefix", Prefix) - verify(mockExecution).setVariable(Prefix + "queryAAIRequest", "http://localhost:8090/aai/v9/network/l3-networks/l3-network/bdc5efe8-404a-409b-85f6-0dcc9eebae30"+"?depth=all") - verify(mockExecution).setVariable(Prefix + "aaiReturnCode", "200") - //verify(mockExecution).setVariable(Prefix + "queryAAIResponse", aaiResponseWithRelationship) + verify(mockExecution).setVariable(Prefix + "aaiReturnCode", 200) verify(mockExecution).setVariable(Prefix + "isAAIGood", true) - verify(mockExecution).setVariable(Prefix + "isVfRelationshipExist", true) - + verify(mockExecution).setVariable(Prefix + "queryAAIResponse", l3Network) } - @Test - //@Ignore - public void callRESTQueryAAI_200_DefaultUri() { - - println "************ callRESTQueryAAI ************* " - - WireMock.reset(); - MockGetNetworkByIdWithDepth("bdc5efe8-404a-409b-85f6-0dcc9eebae30", "DeleteNetworkV2/deleteNetworkAAIResponse_Success.xml", "all"); - - ExecutionEntity mockExecution = setupMock() - when(mockExecution.getVariable(Prefix + "networkInputs")).thenReturn(expectedNetworkRequest) - when(mockExecution.getVariable(Prefix + "messageId")).thenReturn("e8ebf6a0-f8ea-4dc0-8b99-fe98a87722d6") - when(mockExecution.getVariable("aai.endpoint")).thenReturn("http://localhost:8090") - // old: when(mockExecution.getVariable("mso.workflow.default.aai.network.l3-network.uri")).thenReturn("/aai/v8/network/l3-networks/l3-network") - when(mockExecution.getVariable("mso.workflow.global.default.aai.version")).thenReturn("8") - when(mockExecution.getVariable("mso.workflow.default.aai.v8.l3-network.uri")).thenReturn("/aai/v9/network/l3-networks/l3-network") - when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") - when(mockExecution.getVariable("mso.workflow.global.default.aai.namespace")).thenReturn('http://org.openecomp.aai.inventory/') - when(mockExecution.getVariable("mso.msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7") - when(mockExecution.getVariable("aai.auth")).thenReturn("757A94191D685FD2092AC1490730A4FC") - - DoDeleteNetworkInstance DoDeleteNetworkInstance = new DoDeleteNetworkInstance() - DoDeleteNetworkInstance.callRESTQueryAAI(mockExecution) - verify(mockExecution).setVariable("prefix", Prefix) - verify(mockExecution).setVariable(Prefix + "queryAAIRequest", "http://localhost:8090/aai/v9/network/l3-networks/l3-network/bdc5efe8-404a-409b-85f6-0dcc9eebae30"+ "?depth=all") - - verify(mockExecution).setVariable(Prefix + "aaiReturnCode", "200") - //verify(mockExecution).setVariable(Prefix + "queryAAIResponse", aaiResponse) - verify(mockExecution).setVariable(Prefix + "isAAIGood", true) + @Test + //@Ignore + public void callRESTQueryAAI_CloudRegionRelation() { + + println "************ callRESTQueryAAI ************* " + ExecutionEntity mockExecution = setupMock() + when(mockExecution.getVariable(Prefix + "networkInputs")).thenReturn(expectedNetworkRequest) + when(mockExecution.getVariable(Prefix + "messageId")).thenReturn("e8ebf6a0-f8ea-4dc0-8b99-fe98a87722d6") + when(mockExecution.getVariable("aai.endpoint")).thenReturn("http://localhost:8090") + when(mockExecution.getVariable("mso.workflow.default.aai.network.l3-network.uri")).thenReturn("") + when(mockExecution.getVariable("mso.workflow.doDeleteNetworkInstance.aai.l3-network.uri")).thenReturn("/aai/v9/network/l3-networks/l3-network") + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("mso.workflow.global.default.aai.namespace")).thenReturn('http://org.openecomp.aai.inventory/') + when(mockExecution.getVariable("mso.msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7") + when(mockExecution.getVariable("aai.auth")).thenReturn("757A94191D685FD2092AC1490730A4FC") + when(mockExecution.getVariable(Prefix + "lcpCloudRegion")).thenReturn(null) + String networkId = "bdc5efe8-404a-409b-85f6-0dcc9eebae30" + DoDeleteNetworkInstance doDeleteNetworkInstance = spy(DoDeleteNetworkInstance.class) + when(doDeleteNetworkInstance.getAAIClient()).thenReturn(client) + L3Network l3Network = new L3Network(); + RelationshipList relationshipList = new RelationshipList() + Relationship relationship = new Relationship(); + relationship.setRelatedTo("cloud-region") + relationship.setRelatedLink("http://localhost:18080/cloud-regions/cloud-region/" + Defaults.CLOUD_OWNER.toString() + "/lcpCloudRegion/") + relationshipList.getRelationship().add(relationship) + l3Network.setRelationshipList(relationshipList) + AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.L3_NETWORK, networkId).depth(Depth.ALL) + when(client.get(L3Network.class,uri)).thenReturn(Optional.of(l3Network)) + doDeleteNetworkInstance.callRESTQueryAAI(mockExecution) + + verify(mockExecution, atLeast(1)).setVariable("prefix", Prefix) + + verify(mockExecution).setVariable(Prefix + "aaiReturnCode", 200) + verify(mockExecution).setVariable(Prefix + "isAAIGood", true) + verify(mockExecution).setVariable(Prefix + "queryAAIResponse", l3Network) + } + + private L3Network getL3Network() { + L3Network l3Network = new L3Network(); + RelationshipList relationshipList = new RelationshipList() + Relationship relationship = new Relationship(); + relationship.setRelatedTo("cloud-region") + relationship.setRelatedLink("http://localhost:18080/cloud-regions/cloud-region/" + Defaults.CLOUD_OWNER.toString() + "/lcpCloudRegion/") + relationshipList.getRelationship().add(relationship) + relationship.setRelatedTo("tenant") + relationship.setRelatedLink("http://localhost:18080/cloud-regions/cloud-region/" + Defaults.CLOUD_OWNER.toString() + "/lcpCloudRegion/tenants/tenant/tenantId/") + relationshipList.getRelationship().add(relationship) + + l3Network.setRelationshipList(relationshipList) + l3Network + } - } @Test - //@Ignore public void callRESTQueryAAICloudRegion30_200() { println "************ callRESTQueryAAICloudRegion30_200 ************* " diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteVFCNetworkServiceInstanceTest.groovy b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteVFCNetworkServiceInstanceTest.groovy new file mode 100644 index 0000000000..c2113e2f28 --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteVFCNetworkServiceInstanceTest.groovy @@ -0,0 +1,73 @@ +/*- + * ============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.infrastructure.scripts + +import org.camunda.bpm.engine.delegate.BpmnError +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.rules.ExpectedException +import org.onap.aai.domain.yang.VolumeGroup +import org.onap.aai.domain.yang.VolumeGroups +import org.onap.so.bpmn.common.scripts.MsoGroovyTest +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.constants.Defaults + +import static org.mockito.ArgumentMatchers.isA +import static org.mockito.Mockito.doThrow +import static org.mockito.Mockito.spy +import static org.mockito.Mockito.when + +public class DoDeleteVFCNetworkServiceInstanceTest extends MsoGroovyTest { + + @Rule + public ExpectedException thrown = ExpectedException.none(); + + private DoDeleteVFCNetworkServiceInstance doDeleteVFCNetworkServiceInstance; + @Before + public void init(){ + super.init("DoDeleteVFCNetworkServiceInstance"); + doDeleteVFCNetworkServiceInstance = spy(DoDeleteVFCNetworkServiceInstance.class); + when(doDeleteVFCNetworkServiceInstance.getAAIClient()).thenReturn(client) + } + + @Test + void callRESTDeleteAAIVolumeGroupTest(){ + String resourceInstanceId = "resourceInstanceId" + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("resourceInstanceId")).thenReturn(resourceInstanceId) + doDeleteVFCNetworkServiceInstance.deleteNSRelationship(mockExecution) + } + + @Test + void callRESTDeleteAAIVolumeGroupTestException(){ + String resourceInstanceId = "resourceInstanceId" + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("resourceInstanceId")).thenReturn(resourceInstanceId) + doThrow(Exception.class).when(client).disconnect(isA(AAIResourceUri.class),isA(AAIResourceUri.class)) + thrown.expect(BpmnError.class) + doDeleteVFCNetworkServiceInstance.deleteNSRelationship(mockExecution) + } + +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteVfModuleFromVnfTest.groovy b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteVfModuleFromVnfTest.groovy index 447463a079..cfdeee2c32 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteVfModuleFromVnfTest.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteVfModuleFromVnfTest.groovy @@ -35,14 +35,24 @@ import org.mockito.ArgumentCaptor import org.mockito.Captor import org.mockito.Mockito import org.mockito.MockitoAnnotations +import org.mockito.Spy import org.mockito.runners.MockitoJUnitRunner +import org.onap.aai.domain.yang.GenericVnf +import org.onap.aai.domain.yang.NetworkPolicies +import org.onap.aai.domain.yang.NetworkPolicy +import org.onap.so.bpmn.common.scripts.MsoGroovyTest import org.onap.so.bpmn.core.WorkflowException +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 static com.github.tomakehurst.wiremock.client.WireMock.* import static org.mockito.Mockito.* @RunWith(MockitoJUnitRunner.class) -class DoDeleteVfModuleFromVnfTest { +class DoDeleteVfModuleFromVnfTest extends MsoGroovyTest { @Rule public WireMockRule wireMockRule = new WireMockRule(28090); @@ -50,9 +60,14 @@ class DoDeleteVfModuleFromVnfTest { @Captor static ArgumentCaptor<ExecutionEntity> captor = ArgumentCaptor.forClass(ExecutionEntity.class) + @Spy + DoDeleteVfModuleFromVnf deleteVfModuleFromVnf + @Before public void init() throws IOException { - MockitoAnnotations.initMocks(this); + super.init("DoDeleteVfModuleFromVnf") + MockitoAnnotations.initMocks(this) + when(deleteVfModuleFromVnf.getAAIClient()).thenReturn(client) } @Test @@ -89,40 +104,64 @@ class DoDeleteVfModuleFromVnfTest { @Test void testDeleteNetworkPoliciesFromAAI() { - ExecutionEntity mockExecution = setupMock() - when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") - when(mockExecution.getVariable("mso.workflow.DoDeleteVfModuleFromVnf.aai.network-policy.uri")).thenReturn("/aai/v8/network/network-policies/network-policy") - when(mockExecution.getVariable("mso.workflow.custom.DoDeleteVfModuleFromVnf.aai.version")).thenReturn("8") - when(mockExecution.getVariable("aai.endpoint")).thenReturn("http://localhost:28090") - when(mockExecution.getVariable("mso.workflow.global.default.aai.namespace")).thenReturn("http://org.openecomp.aai.inventory/") + List fqdnList = new ArrayList() fqdnList.add("test") when(mockExecution.getVariable("DDVFMV_contrailNetworkPolicyFqdnList")).thenReturn(fqdnList) - mockData() - DoDeleteVfModuleFromVnf obj = new DoDeleteVfModuleFromVnf() - obj.deleteNetworkPoliciesFromAAI(mockExecution) + AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectPlurals.NETWORK_POLICY) + uri.queryParam("network-policy-fqdn", "test") + NetworkPolicies networkPolicies = new NetworkPolicies(); + NetworkPolicy networkPolicy = new NetworkPolicy(); + networkPolicy.setNetworkPolicyId("NP1") + networkPolicies.getNetworkPolicy().add(networkPolicy) + when(client.get(NetworkPolicies.class, uri)).thenReturn(Optional.of(networkPolicies)) + + AAIResourceUri delUri = AAIUriFactory.createResourceUri(AAIObjectType.NETWORK_POLICY, networkPolicy.getNetworkPolicyId()) + doNothing().when(client).delete(delUri) + deleteVfModuleFromVnf.deleteNetworkPoliciesFromAAI(mockExecution) Mockito.verify(mockExecution).setVariable("prefix", 'DDVFMV_') Mockito.verify(mockExecution).setVariable("DCVFM_aaiQueryNetworkPolicyByFqdnReturnCode", 200) } + @Test + void testDeleteNetworkPoliciesFromAAINotFound() { + + List fqdnList = new ArrayList() + fqdnList.add("test") + when(mockExecution.getVariable("DDVFMV_contrailNetworkPolicyFqdnList")).thenReturn(fqdnList) + AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectPlurals.NETWORK_POLICY) + uri.queryParam("network-policy-fqdn", "test") + when(client.get(NetworkPolicies.class, uri)).thenReturn(Optional.empty()) + deleteVfModuleFromVnf.deleteNetworkPoliciesFromAAI(mockExecution) + + Mockito.verify(mockExecution).setVariable("prefix", 'DDVFMV_') + Mockito.verify(mockExecution).setVariable("DCVFM_aaiQueryNetworkPolicyByFqdnReturnCode", 404) + } + @Test void testQueryAAIForVfModule() { ExecutionEntity mockExecution = setupMock() - when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") when(mockExecution.getVariable("vnfId")).thenReturn("12345") - when(mockExecution.getVariable("aai.endpoint")).thenReturn("http://localhost:28090") - when(mockExecution.getVariable("mso.workflow.global.default.aai.namespace")).thenReturn("mso.workflow.global.default.aai.namespace") - when(mockExecution.getVariable("mso.workflow.default.aai.generic-vnf.version")).thenReturn("8") - when(mockExecution.getVariable("mso.msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7") - when(mockExecution.getVariable("aai.auth")).thenReturn("757A94191D685FD2092AC1490730A4FC") - - mockData() - DoDeleteVfModuleFromVnf obj = new DoDeleteVfModuleFromVnf() - obj.queryAAIForVfModule(mockExecution) + AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, "12345").depth(Depth.ONE) + GenericVnf genericVnf = new GenericVnf() + genericVnf.setVnfId("test1") + when(client.get(GenericVnf.class, uri)).thenReturn(Optional.of(genericVnf)) + deleteVfModuleFromVnf.queryAAIForVfModule(mockExecution) Mockito.verify(mockExecution, atLeastOnce()).setVariable("DDVMFV_getVnfResponseCode", 200) + Mockito.verify(mockExecution, atLeastOnce()).setVariable("DDVMFV_getVnfResponse", genericVnf) + } + + @Test + void testQueryAAIForVfModuleNotFound() { + ExecutionEntity mockExecution = setupMock() + when(mockExecution.getVariable("vnfId")).thenReturn("12345") + AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, "12345").depth(Depth.ONE) + when(client.get(GenericVnf.class, uri)).thenReturn(Optional.empty()) + deleteVfModuleFromVnf.queryAAIForVfModule(mockExecution) + Mockito.verify(mockExecution, atLeastOnce()).setVariable("DDVMFV_getVnfResponseCode", 404) } diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteVfModuleTest.groovy b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteVfModuleTest.groovy index 3390b1a6f0..7776ab3fe6 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteVfModuleTest.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteVfModuleTest.groovy @@ -27,6 +27,7 @@ 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 @@ -34,16 +35,31 @@ import org.mockito.ArgumentCaptor import org.mockito.Captor import org.mockito.Mockito import org.mockito.MockitoAnnotations +import org.mockito.Spy import org.mockito.runners.MockitoJUnitRunner +import org.onap.aai.domain.yang.NetworkPolicies +import org.onap.aai.domain.yang.NetworkPolicy +import org.onap.aai.domain.yang.VfModule +import org.onap.aai.domain.yang.VfModules +import org.onap.so.bpmn.common.scripts.MsoGroovyTest import org.onap.so.bpmn.common.scripts.utils.XmlComparator import org.onap.so.bpmn.core.WorkflowException 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.entities.uri.AAIResourceUri +import org.onap.so.client.aai.entities.uri.AAIUriFactory + +import javax.ws.rs.NotFoundException import static com.github.tomakehurst.wiremock.client.WireMock.* import static org.mockito.Mockito.* @RunWith(MockitoJUnitRunner.class) -class DoDeleteVfModuleTest { +class DoDeleteVfModuleTest extends MsoGroovyTest{ + + @Spy + DoDeleteVfModule doDeleteVfModule @Rule public WireMockRule wireMockRule = new WireMockRule(28090); @@ -53,7 +69,9 @@ class DoDeleteVfModuleTest { @Before public void init() throws IOException { + super.init("DoDeleteVfModule") MockitoAnnotations.initMocks(this); + when(doDeleteVfModule.getAAIClient()).thenReturn(client) } @Test @@ -82,38 +100,49 @@ class DoDeleteVfModuleTest { @Test void testDeleteNetworkPoliciesFromAAI() { - ExecutionEntity mockExecution = setupMock() - when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") - when(mockExecution.getVariable("mso.workflow.DoDeleteVfModule.aai.network-policy.uri")).thenReturn("/aai/v8/network/network-policies/network-policy") - when(mockExecution.getVariable("mso.workflow.custom.DoDeleteVfModule.aai.version")).thenReturn("8") - when(mockExecution.getVariable("aai.endpoint")).thenReturn("http://localhost:28090") - when(mockExecution.getVariable("mso.workflow.global.default.aai.namespace")).thenReturn("http://org.openecomp.aai.inventory/") List fqdnList = new ArrayList() fqdnList.add("test") when(mockExecution.getVariable("DoDVfMod_contrailNetworkPolicyFqdnList")).thenReturn(fqdnList) - mockData() - DoDeleteVfModule obj = new DoDeleteVfModule() - obj.deleteNetworkPoliciesFromAAI(mockExecution) - + NetworkPolicies networkPolicies = new NetworkPolicies() + NetworkPolicy networkPolicy = new NetworkPolicy() + networkPolicy.setNetworkPolicyId("NP1") + networkPolicies.getNetworkPolicy().add(networkPolicy) + AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectPlurals.NETWORK_POLICY) + uri.queryParam("network-policy-fqdn", "test") + when(client.get(NetworkPolicies.class, uri)).thenReturn(Optional.of(networkPolicies)) + doDeleteVfModule.deleteNetworkPoliciesFromAAI(mockExecution) Mockito.verify(mockExecution).setVariable("DCVFM_aaiQueryNetworkPolicyByFqdnReturnCode", 200) } + @Test + void testDeleteNetworkPoliciesFromAAIError() { + List fqdnList = new ArrayList() + fqdnList.add("test") + when(mockExecution.getVariable("DoDVfMod_contrailNetworkPolicyFqdnList")).thenReturn(fqdnList) + NetworkPolicies networkPolicies = new NetworkPolicies() + NetworkPolicy networkPolicy = new NetworkPolicy() + networkPolicy.setNetworkPolicyId("NP1") + networkPolicies.getNetworkPolicy().add(networkPolicy) + AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectPlurals.NETWORK_POLICY) + uri.queryParam("network-policy-fqdn", "test") + when(client.get(NetworkPolicies.class, uri)).thenReturn(Optional.of(networkPolicies)) + AAIResourceUri delUri = AAIUriFactory.createResourceUri(AAIObjectType.NETWORK_POLICY, "NP1") + doThrow(new NotFoundException(("Not Found !"))).when(client).delete(delUri) + doDeleteVfModule.deleteNetworkPoliciesFromAAI(mockExecution) + Mockito.verify(client).delete(delUri) + } @Test void testQueryAAIVfModuleForStatus() { - ExecutionEntity mockExecution = setupMock() when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") - when(mockExecution.getVariable("DCVFM_vnfId")).thenReturn("12345") - when(mockExecution.getVariable("DCVFM_vfModuleName")).thenReturn("module-0") - when(mockExecution.getVariable("mso.workflow.DoDeleteVfModule.aai.generic-vnf.uri")).thenReturn("/aai/v9/network/generic-vnfs/generic-vnf") - when(mockExecution.getVariable("aai.endpoint")).thenReturn("http://localhost:28090") - when(mockExecution.getVariable("mso.workflow.global.default.aai.namespace")).thenReturn("http://org.openecomp.aai.inventory/") - - mockData() - DoCreateVfModule obj = new DoCreateVfModule() - obj.queryAAIVfModuleForStatus(mockExecution) - - Mockito.verify(mockExecution).setVariable("DCVFM_queryAAIVfModuleForStatusResponseCode", 200) + when(mockExecution.getVariable("vnfId")).thenReturn("12345") + when(mockExecution.getVariable("vfModuleId")).thenReturn("module-0") + AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.VF_MODULE,"12345","module-0") + VfModule vfModule = new VfModule() + vfModule.setOrchestrationStatus("Created") + when(client.get(VfModule.class, uri)).thenReturn(Optional.of(vfModule)) + doDeleteVfModule.queryAAIVfModuleForStatus(mockExecution) + Mockito.verify(mockExecution).setVariable("DoDVfMod_queryAAIVfModuleForStatusResponseCode", 200) } diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteVfModuleVolumeV2Test.groovy b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteVfModuleVolumeV2Test.groovy index 730be14df0..94aec7a73f 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteVfModuleVolumeV2Test.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteVfModuleVolumeV2Test.groovy @@ -23,6 +23,7 @@ package org.onap.so.bpmn.infrastructure.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.delegate.BpmnError import org.camunda.bpm.engine.impl.persistence.entity.ExecutionEntity import org.camunda.bpm.engine.repository.ProcessDefinition import org.junit.Assert @@ -35,25 +36,41 @@ import org.mockito.ArgumentCaptor import org.mockito.Captor import org.mockito.Mockito import org.mockito.MockitoAnnotations +import org.mockito.Spy import org.mockito.runners.MockitoJUnitRunner +import org.onap.aai.domain.yang.VolumeGroup +import org.onap.so.bpmn.common.scripts.MsoGroovyTest import org.onap.so.bpmn.common.scripts.utils.XmlComparator import org.onap.so.bpmn.core.WorkflowException import org.onap.so.bpmn.mock.FileUtil +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.client.graphinventory.exceptions.GraphInventoryUriComputationException + +import javax.ws.rs.NotFoundException import static com.github.tomakehurst.wiremock.client.WireMock.* import static org.mockito.Mockito.* @RunWith(MockitoJUnitRunner.class) -class DoDeleteVfModuleVolumeV2Test { +class DoDeleteVfModuleVolumeV2Test extends MsoGroovyTest{ @Rule public WireMockRule wireMockRule = new WireMockRule(28090); @Captor static ArgumentCaptor<ExecutionEntity> captor = ArgumentCaptor.forClass(ExecutionEntity.class) + @Spy + DoDeleteVfModuleVolumeV2 deleteVfModuleVolumeV2; + @Before public void init() throws IOException { + super.init("DoDeleteVfModuleVolumeV2") MockitoAnnotations.initMocks(this); + when(deleteVfModuleVolumeV2.getAAIClient()).thenReturn(client) + } @Test @@ -118,6 +135,118 @@ class DoDeleteVfModuleVolumeV2Test { XmlComparator.assertXMLEquals(str, captor.getValue(),"messageId","notificationUrl") } + @Test + void testCallRESTQueryAAIForVolumeGroup(){ + when(mockExecution.getVariable("tenantId")).thenReturn("Tenant123") + when(mockExecution.getVariable("volumeGroupId")).thenReturn("VolumeGroup123") + when(mockExecution.getVariable("DDVMV_aicCloudRegion")).thenReturn("Region1") + AAIResourceUri resourceUri = AAIUriFactory.createResourceUri(AAIObjectType.VOLUME_GROUP,CLOUD_OWNER, "Region1","VolumeGroup123") + Optional<VolumeGroup> volumeGroup = getAAIObjectFromJson(VolumeGroup.class,"__files/aai/VolumeGroupWithTenant.json"); + when(client.get(VolumeGroup.class,resourceUri)).thenReturn(volumeGroup) + deleteVfModuleVolumeV2.callRESTQueryAAIForVolumeGroup(mockExecution,"true") + Mockito.verify(mockExecution).setVariable("DDVMV_queryAAIVolGrpResponse", volumeGroup.get()) + Mockito.verify(mockExecution).setVariable("DDVMV_volumeGroupHeatStackId", volumeGroup.get().getHeatStackId()) + } + + @Test + void testCallRESTQueryAAIForVolumeGroupNoTenant(){ + when(mockExecution.getVariable("tenantId")).thenReturn("Tenant123") + when(mockExecution.getVariable("volumeGroupId")).thenReturn("VolumeGroup123") + when(mockExecution.getVariable("DDVMV_aicCloudRegion")).thenReturn("Region1") + AAIResourceUri resourceUri = AAIUriFactory.createResourceUri(AAIObjectType.VOLUME_GROUP,CLOUD_OWNER, "Region1","VolumeGroup123") + Optional<VolumeGroup> volumeGroup = getAAIObjectFromJson(VolumeGroup.class,"__files/aai/VolumeGroup.json"); + when(client.get(VolumeGroup.class,resourceUri)).thenReturn(volumeGroup) + try { + deleteVfModuleVolumeV2.callRESTQueryAAIForVolumeGroup(mockExecution, "true") + }catch(BpmnError error) { + println " Test End - Handle catch-throw BpmnError()! " + } + } + + @Test + void testCallRESTQueryAAIForVolumeGroupDifferentTenant(){ + when(mockExecution.getVariable("tenantId")).thenReturn("Tenant12345") + when(mockExecution.getVariable("volumeGroupId")).thenReturn("VolumeGroup123") + when(mockExecution.getVariable("DDVMV_aicCloudRegion")).thenReturn("Region1") + AAIResourceUri resourceUri = AAIUriFactory.createResourceUri(AAIObjectType.VOLUME_GROUP,CLOUD_OWNER, "Region1","VolumeGroup123") + Optional<VolumeGroup> volumeGroup = getAAIObjectFromJson(VolumeGroup.class,"__files/aai/VolumeGroupWithTenant.json"); + when(client.get(VolumeGroup.class,resourceUri)).thenReturn(volumeGroup) + try { + deleteVfModuleVolumeV2.callRESTQueryAAIForVolumeGroup(mockExecution, "true") + }catch(BpmnError error) { + println " Test End - Handle catch-throw BpmnError()! " + } + } + + @Test + void testCallRESTQueryAAIForVolumeGroupNotFound(){ + when(mockExecution.getVariable("tenantId")).thenReturn("Tenant123") + when(mockExecution.getVariable("volumeGroupId")).thenReturn("VolumeGroup123") + when(mockExecution.getVariable("DDVMV_aicCloudRegion")).thenReturn("Region1") + AAIResourceUri resourceUri = AAIUriFactory.createResourceUri(AAIObjectType.VOLUME_GROUP,CLOUD_OWNER, "Region1","VolumeGroup123") + when(client.get(VolumeGroup.class,resourceUri)).thenReturn(Optional.empty()) + try { + deleteVfModuleVolumeV2.callRESTQueryAAIForVolumeGroup(mockExecution, "true") + }catch(BpmnError error) { + println " Test End - Handle catch-throw BpmnError()! " + } + } + + @Test + void testCallRESTQueryAAIForVolumeGroupWithVfModule(){ + when(mockExecution.getVariable("tenantId")).thenReturn("Tenant123") + when(mockExecution.getVariable("volumeGroupId")).thenReturn("VolumeGroup123") + when(mockExecution.getVariable("DDVMV_aicCloudRegion")).thenReturn("Region1") + AAIResourceUri resourceUri = AAIUriFactory.createResourceUri(AAIObjectType.VOLUME_GROUP,CLOUD_OWNER, "Region1","VolumeGroup123") + Optional<VolumeGroup> volumeGroup = getAAIObjectFromJson(VolumeGroup.class,"__files/aai/VolumeGroupWithVfModule.json"); + when(client.get(VolumeGroup.class,resourceUri)).thenReturn(volumeGroup) + try { + deleteVfModuleVolumeV2.callRESTQueryAAIForVolumeGroup(mockExecution, "true") + }catch(BpmnError error) { + println " Test End - Handle catch-throw BpmnError()! " + } + } + + @Test + void testCallRESTDeleteAAIVolumeGroup(){ + Optional<VolumeGroup> volumeGroup = getAAIObjectFromJson(VolumeGroup.class,"__files/aai/VolumeGroup.json"); + when(mockExecution.getVariable("DDVMV_queryAAIVolGrpResponse")).thenReturn(volumeGroup.get()) + when(mockExecution.getVariable("DDVMV_aicCloudRegion")).thenReturn("Region1") + AAIResourceUri resourceUri = AAIUriFactory.createResourceUri(AAIObjectType.VOLUME_GROUP,CLOUD_OWNER, "Region1","VolumeGroup123") + doNothing().when(client).delete(resourceUri) + deleteVfModuleVolumeV2.callRESTDeleteAAIVolumeGroup(mockExecution,"true") + } + + @Test + void testCallRESTDeleteAAIVolumeGroupAaiError(){ + Optional<VolumeGroup> volumeGroup = getAAIObjectFromJson(VolumeGroup.class,"__files/aai/VolumeGroupWithVfModule.json"); + when(mockExecution.getVariable("DDVMV_queryAAIVolGrpResponse")).thenReturn(volumeGroup.get()) + when(mockExecution.getVariable("DDVMV_aicCloudRegion")).thenReturn("Region1") + AAIResourceUri resourceUri = AAIUriFactory.createResourceUri(AAIObjectType.VOLUME_GROUP,CLOUD_OWNER, "Region1",volumeGroup.get().getVolumeGroupId()) + doThrow(new GraphInventoryUriComputationException("Error")).when(client).delete(resourceUri) + try { + deleteVfModuleVolumeV2.callRESTDeleteAAIVolumeGroup(mockExecution, "true") + } catch (BpmnError error) { + println " Test End - Handle catch-throw BpmnError()! " + } + } + + @Test + void testCallRESTDeleteAAIVolumeGroupNotFound(){ + Optional<VolumeGroup> volumeGroup = getAAIObjectFromJson(VolumeGroup.class,"__files/aai/VolumeGroup.json"); + when(mockExecution.getVariable("DDVMV_queryAAIVolGrpResponse")).thenReturn(volumeGroup.get()) + when(mockExecution.getVariable("DDVMV_aicCloudRegion")).thenReturn("Region1") + AAIResourceUri resourceUri = AAIUriFactory.createResourceUri(AAIObjectType.VOLUME_GROUP,CLOUD_OWNER, "Region1","VolumeGroup123") + doThrow(new NotFoundException("VolumeGroup Not found")).when(client).delete(resourceUri) + try { + deleteVfModuleVolumeV2.callRESTDeleteAAIVolumeGroup(mockExecution, "true") + } catch (BpmnError error) { + println " Test End - Handle catch-throw BpmnError()! " + } + } + + + private ExecutionEntity setupMock() { diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteVnfAndModulesTest.groovy b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteVnfAndModulesTest.groovy index 0b95ffc053..f98d454eb0 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteVnfAndModulesTest.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteVnfAndModulesTest.groovy @@ -27,7 +27,6 @@ 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 @@ -35,14 +34,21 @@ import org.mockito.ArgumentCaptor import org.mockito.Captor import org.mockito.Mockito import org.mockito.MockitoAnnotations +import org.mockito.Spy import org.mockito.runners.MockitoJUnitRunner +import org.onap.aai.domain.yang.GenericVnf +import org.onap.so.bpmn.common.scripts.MsoGroovyTest import org.onap.so.bpmn.core.WorkflowException - +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.client.graphinventory.exceptions.GraphInventoryUriComputationException import static com.github.tomakehurst.wiremock.client.WireMock.* import static org.mockito.Mockito.* @RunWith(MockitoJUnitRunner.class) -public class DoDeleteVnfAndModulesTest { +public class DoDeleteVnfAndModulesTest extends MsoGroovyTest{ @Rule public WireMockRule wireMockRule = new WireMockRule(28090); @@ -50,13 +56,18 @@ public class DoDeleteVnfAndModulesTest { @Captor static ArgumentCaptor<ExecutionEntity> captor = ArgumentCaptor.forClass(ExecutionEntity.class) + @Spy + DoDeleteVnfAndModules doDeleteVnfAndModules + String cloudConfiguration = "{ " + "\"lcpCloudRegionId\": \"mdt1\"," + "\"tenantId\": \"88a6ca3ee0394ade9403f075db23167e\"" + "}"; @Before public void init() throws IOException { + super.init("DoDeleteVnfAndModules") MockitoAnnotations.initMocks(this); + when(doDeleteVnfAndModules.getAAIClient()).thenReturn(client) } @Test @@ -90,40 +101,26 @@ public class DoDeleteVnfAndModulesTest { @Test public void testQueryAAIVfModuleNullEndPoint() { - ExecutionEntity mockExecution = setupMock() - when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") when(mockExecution.getVariable("vnfId")).thenReturn("12345") - when(mockExecution.getVariable("mso.workflow.DoDeleteVnfAndModules.aai.generic-vnf.uri")).thenReturn("/aai/v8/network/generic-vnfs/generic-vnf") - when(mockExecution.getVariable("aai.endpoint")).thenReturn(null) - when(mockExecution.getVariable("mso.workflow.global.default.aai.namespace")).thenReturn("http://org.openecomp.aai.inventory/") - - mockData() + AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, "12345").depth(Depth.ONE) + doThrow(new GraphInventoryUriComputationException("Error in AAI")).when(client).get(GenericVnf.class,uri) try { - DoDeleteVnfAndModules obj = new DoDeleteVnfAndModules() - obj.queryAAIVfModule(mockExecution) + doDeleteVnfAndModules.queryAAIVfModule(mockExecution) } catch (Exception ex) { println " Test End - Handle catch-throw BpmnError()! " } - Mockito.verify(mockExecution,atLeastOnce()).setVariable(captor.capture(),captor.capture()) WorkflowException workflowException = captor.getValue() - Assert.assertEquals("AAI GET Failed:null", workflowException.getErrorMessage()) + Assert.assertEquals("AAI GET Failed:Error in AAI", workflowException.getErrorMessage()) Assert.assertEquals(1002, workflowException.getErrorCode()) } @Test public void testQueryAAIVfModule() { ExecutionEntity mockExecution = setupMock() - when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") when(mockExecution.getVariable("vnfId")).thenReturn("12345") - when(mockExecution.getVariable("mso.workflow.DoDeleteVnfAndModules.aai.generic-vnf.uri")).thenReturn("/aai/v8/network/generic-vnfs/generic-vnf") - when(mockExecution.getVariable("aai.endpoint")).thenReturn("http://localhost:28090") - when(mockExecution.getVariable("mso.workflow.global.default.aai.namespace")).thenReturn("http://org.openecomp.aai.inventory/") - - mockData() - DoDeleteVnfAndModules obj = new DoDeleteVnfAndModules() - obj.queryAAIVfModule(mockExecution) - + mockAAIGenericVnf("12345","__files/AAI/GenericVnfVfModule.json") + doDeleteVnfAndModules.queryAAIVfModule(mockExecution) Mockito.verify(mockExecution).setVariable("DCVFM_queryAAIVfModuleResponseCode", 200) } diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoUpdateE2EServiceInstanceTest.groovy b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoUpdateE2EServiceInstanceTest.groovy new file mode 100644 index 0000000000..30df8eacc5 --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoUpdateE2EServiceInstanceTest.groovy @@ -0,0 +1,83 @@ +/*- + * ============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.infrastructure.scripts + +import org.camunda.bpm.engine.impl.persistence.entity.ExecutionEntity +import org.junit.Before +import org.junit.Test +import org.mockito.ArgumentCaptor +import org.mockito.Captor +import org.mockito.Mockito +import org.onap.aai.domain.yang.ServiceInstance +import org.onap.so.bpmn.common.scripts.MsoGroovyTest + +import static com.shazam.shazamcrest.MatcherAssert.assertThat +import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs +import static org.mockito.Mockito.times +import static org.mockito.Mockito.when + +/** + * @author sushilma + * @since January 10, 2018 + */ +class DoUpdateE2EServiceInstanceTest extends MsoGroovyTest{ + + + @Before + public void init() { + super.init("DoUpdateE2EServiceInstance") + } + @Captor + static ArgumentCaptor<ExecutionEntity> captor = ArgumentCaptor.forClass(ExecutionEntity.class) + @Test + public void testPreProcessRequest(){ + mockData() + ServiceInstance expectedServiceInstanceData = getExpectedServiceInstance() + DoUpdateE2EServiceInstance serviceInstance = new DoUpdateE2EServiceInstance() + serviceInstance.preProcessAAIPUT(mockExecution) + Mockito.verify(mockExecution, times(1)).setVariable(captor.capture(), captor.capture()) + assertThat(captor.getValue(), sameBeanAs(expectedServiceInstanceData)) + } + + private ServiceInstance getExpectedServiceInstance() { + ServiceInstance expectedServiceInstanceData = new ServiceInstance() + expectedServiceInstanceData.setServiceInstanceId("1234") + expectedServiceInstanceData.setServiceInstanceName("volte-service") + expectedServiceInstanceData.setServiceType("E2E Service") + expectedServiceInstanceData.setServiceRole("E2E Service") + return expectedServiceInstanceData + } + + private void mockData() { + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("globalSubscriberId")).thenReturn("12345") + when(mockExecution.getVariable("serviceType")).thenReturn("TRANSPORT") + when(mockExecution.getVariable("serviceInstanceId")).thenReturn("1234") + when(mockExecution.getVariable("serviceInstanceName")).thenReturn("volte-service") + when(mockExecution.getVariable("uuiRequest")).thenReturn("""{"service":{"serviceDefId":"c1d4305f-cdbd-4bbe-9069-a2f4978fd89e" , "templateId" : "d4df5c27-98a1-4812-a8aa-c17f055b7a3f"}}""") + when(mockExecution.getVariable("mso.workflow.sdncadapter.callback")).thenReturn("/mso/sdncadapter/") + when(mockExecution.getVariable("mso.workflow.global.default.aai.namespace")).thenReturn("http://org.openecomp.aai.inventory/") + when(mockExecution.getVariable("mso.workflow.default.aai.customer.version")).thenReturn("8") + when(mockExecution.getVariable("mso.workflow.default.aai.v8.customer.uri")).thenReturn('/aai/v8/business/customers/customer') + when(mockExecution.getVariable("URN_mso_workflow_sdncadapter_callback")).thenReturn('/testUrl') + } + +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoUpdateNetworkInstanceTest.groovy b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoUpdateNetworkInstanceTest.groovy index 14dd10fc49..68a9ed659e 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoUpdateNetworkInstanceTest.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoUpdateNetworkInstanceTest.groovy @@ -1795,7 +1795,7 @@ String rollbackNetworkRequest = //@Ignore public void preProcessRequest_vPERNetworkRequest() { - def networkModelInfo = """{"modelUuid": "sn5256d1-5a33-55df-13ab-12abad84e111", + String networkModelInfo = """{"modelUuid": "sn5256d1-5a33-55df-13ab-12abad84e111", "modelName": "CONTRAIL_EXTERNAL", "modelType": "CONTRAIL_EXTERNAL", "modelVersion": "1", diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoUpdateVfModuleTest.groovy b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoUpdateVfModuleTest.groovy index 6ed9dbd2bd..d635b2311a 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoUpdateVfModuleTest.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoUpdateVfModuleTest.groovy @@ -35,7 +35,9 @@ import org.mockito.ArgumentCaptor import org.mockito.Captor import org.mockito.Mockito import org.mockito.MockitoAnnotations +import org.mockito.Spy import org.mockito.runners.MockitoJUnitRunner +import org.onap.so.bpmn.common.scripts.MsoGroovyTest import org.onap.so.bpmn.common.scripts.VfModule import org.onap.so.bpmn.core.WorkflowException import org.onap.so.bpmn.mock.FileUtil @@ -45,7 +47,7 @@ import static org.mockito.Mockito.* import org.onap.so.bpmn.common.scripts.utils.XmlComparator @RunWith(MockitoJUnitRunner.class) -class DoUpdateVfModuleTest { +class DoUpdateVfModuleTest extends MsoGroovyTest{ def prefix = "DOUPVfMod_" String doUpdateVfModuleRequest = FileUtil.readResourceFile("__files/VfModularity/DoUpdateVfModuleRequest.xml"); @@ -56,11 +58,16 @@ class DoUpdateVfModuleTest { static ArgumentCaptor<ExecutionEntity> captor = ArgumentCaptor.forClass(ExecutionEntity.class) @Rule - public WireMockRule wireMockRule = new WireMockRule(28090); + public WireMockRule wireMockRule = new WireMockRule(28090) + + @Spy + DoUpdateVfModule doUpdateVfModule @Before public void init() { + super.init("DoUpdateVfModule") MockitoAnnotations.initMocks(this) + when(doUpdateVfModule.getAAIClient()).thenReturn(client) } @Test @@ -258,18 +265,15 @@ class DoUpdateVfModuleTest { @Test void testQueryAAIVfModule() { - ExecutionEntity mockExecution = setupMock() when(mockExecution.getVariable("prefix")).thenReturn(prefix) - when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") when(mockExecution.getVariable(prefix + "vnfId")).thenReturn("12345") - when(mockExecution.getVariable("mso.workflow.default.aai.generic-vnf.version")).thenReturn("8") - when(mockExecution.getVariable("aai.endpoint")).thenReturn("http://localhost:28090") - when(mockExecution.getVariable("mso.workflow.global.default.aai.namespace")).thenReturn("http://org.openecomp.aai.inventory/") - mockData() - DoUpdateVfModule obj = new DoUpdateVfModule() - obj.queryAAIVfModule(mockExecution) + mockAAIGenericVnf("12345","__files/AAI/GenericVnfVfModule.json") + doUpdateVfModule.queryAAIVfModule(mockExecution) Mockito.verify(mockExecution).setVariable(prefix + "queryAAIVfModuleResponseCode", 200) + Mockito.verify(mockExecution).setVariable("DOUPVfMod_baseVfModuleId", "lukewarm") + Mockito.verify(mockExecution).setVariable("DOUPVfMod_baseVfModuleHeatStackId", "fastburn") + } diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/UpdateVfModuleVolumeInfraV1Test.groovy b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/UpdateVfModuleVolumeInfraV1Test.groovy index 620b0b787d..06ae576307 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/UpdateVfModuleVolumeInfraV1Test.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/UpdateVfModuleVolumeInfraV1Test.groovy @@ -20,42 +20,48 @@ package org.onap.so.bpmn.infrastructure.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.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.rules.ExpectedException 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.common.scripts.utils.XmlComparator -import org.onap.so.bpmn.core.WorkflowException +import org.onap.aai.domain.yang.GenericVnf +import org.onap.aai.domain.yang.VfModule +import org.onap.aai.domain.yang.VolumeGroup +import org.onap.so.bpmn.common.scripts.MsoGroovyTest import org.onap.so.bpmn.mock.FileUtil +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 javax.ws.rs.core.UriBuilder -import static com.github.tomakehurst.wiremock.client.WireMock.* import static org.mockito.Mockito.* @RunWith(MockitoJUnitRunner.class) -class UpdateVfModuleVolumeInfraV1Test { +class UpdateVfModuleVolumeInfraV1Test extends MsoGroovyTest{ def prefix = "UPDVfModVol_" @Captor static ArgumentCaptor<ExecutionEntity> captor = ArgumentCaptor.forClass(ExecutionEntity.class) + + @Rule + public ExpectedException thrown = ExpectedException.none() - @Rule - public WireMockRule wireMockRule = new WireMockRule(28090); - + @Before - public void init() - { + public void init(){ + super.init("UpdateVfModuleVolumeInfraV1") MockitoAnnotations.initMocks(this) } @@ -69,66 +75,95 @@ class UpdateVfModuleVolumeInfraV1Test { when(mockExecution.getVariable("mso.msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7") when(mockExecution.getVariable("aai.auth")).thenReturn("757A94191D685FD2092AC1490730A4FC") - mockData() - UpdateVfModuleVolumeInfraV1 obj = new UpdateVfModuleVolumeInfraV1() + UpdateVfModuleVolumeInfraV1 obj = spy(UpdateVfModuleVolumeInfraV1.class) + when(obj.getAAIClient()).thenReturn(client) + AAIResourceUri uri = AAIUriFactory.createResourceFromExistingURI(AAIObjectType.VF_MODULE, UriBuilder.fromPath("/aai/v8/network/generic-vnfs/generic-vnf/12345/vf-modules/vf-module/12345").build()) + VfModule vfModule = new VfModule(); + vfModule.setVfModuleId("12345") + vfModule.setModelInvariantId("ff5256d2-5a33-55df-13ab-12abad84e7ff") + when(client.get(VfModule.class,uri)).thenReturn(Optional.of(vfModule)) obj.queryAAIForVfModule(mockExecution, "true") - Mockito.verify(mockExecution, atLeastOnce()).setVariable("UPDVfModVol_personaModelId", "ff5256d2-5a33-55df-13ab-12abad84e7ff") + verify(mockExecution, atLeastOnce()).setVariable("UPDVfModVol_personaModelId", "ff5256d2-5a33-55df-13ab-12abad84e7ff") + } + + @Test + void testQueryAAIForVolumeGroup() { + String aicCloudRegion = "aicCloudRegionId" + String volumeGroupId = "volumeGroupId" + when(mockExecution.getVariable("UPDVfModVol_volumeGroupId")).thenReturn(volumeGroupId) + when(mockExecution.getVariable("UPDVfModVol_aicCloudRegion")).thenReturn(aicCloudRegion) + + UpdateVfModuleVolumeInfraV1 obj = spy(UpdateVfModuleVolumeInfraV1.class) + when(obj.getAAIClient()).thenReturn(client) + AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.VOLUME_GROUP, Defaults.CLOUD_OWNER.toString(), aicCloudRegion, volumeGroupId) + VolumeGroup volumeGroup = new VolumeGroup(); + volumeGroup.setVolumeGroupId(volumeGroupId) + + AAIResultWrapper wrapper = new AAIResultWrapper(FileUtil.readResourceFile("__files/aai/VolumeGroupWithTenant.json")) + when(client.get(uri)).thenReturn(wrapper) + thrown.expect(BpmnError.class) + obj.queryAAIForVolumeGroup(mockExecution, "true") } - @Test + @Test + void testQueryAAIForGenericVnf() { + String vnfId = "vnfId" + when(mockExecution.getVariable("vnfId")).thenReturn(vnfId) + + UpdateVfModuleVolumeInfraV1 obj = spy(UpdateVfModuleVolumeInfraV1.class) + when(obj.getAAIClient()).thenReturn(client) + + AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId) + GenericVnf genericVnf = new GenericVnf() + genericVnf.setVnfId(vnfId) + genericVnf.setVnfName("testvnfName") + when(client.get(GenericVnf.class,uri)).thenReturn(Optional.of(genericVnf)) + obj.queryAAIForGenericVnf(mockExecution, "true") + verify(mockExecution).setVariable("UPDVfModVol_AAIQueryGenericVfnResponse", genericVnf) + } + + @Test + void testQueryAAIForGenericVnfNodata() { + String vnfId = "vnfId" + when(mockExecution.getVariable("vnfId")).thenReturn(vnfId) + + UpdateVfModuleVolumeInfraV1 obj = spy(UpdateVfModuleVolumeInfraV1.class) + when(obj.getAAIClient()).thenReturn(client) + + AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId) + when(client.get(GenericVnf.class,uri)).thenReturn(Optional.empty()) + thrown.expect(BpmnError.class) + obj.queryAAIForGenericVnf(mockExecution, "true") + verify(mockExecution).setVariable("UPDVfModVol_AAIQueryGenericVfnResponse", genericVnf) + } + + @Test void testPrepVnfAdapterRest() { - ExecutionEntity mockExecution = setupMock() when(mockExecution.getVariable("prefix")).thenReturn(prefix) when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") when(mockExecution.getVariable(prefix + "aicCloudRegion")).thenReturn("RDM2WAGPLCP") when(mockExecution.getVariable(prefix + "tenantId")).thenReturn("") - when(mockExecution.getVariable(prefix + "aaiVolumeGroupResponse")).thenReturn(FileUtil.readResourceFile("__files/UpdateVfModuleVolumeInfraV1/queryVolumeId_AAIResponse_Success.xml")) + VolumeGroup volumeGroup = new VolumeGroup(); + volumeGroup.setHeatStackId("heatStackId") + when(mockExecution.getVariable(prefix + "aaiVolumeGroupResponse")).thenReturn(volumeGroup) when(mockExecution.getVariable(prefix + "vnfType")).thenReturn("vnf1") when(mockExecution.getVariable(prefix + "vnfVersion")).thenReturn("1") - when(mockExecution.getVariable(prefix + "AAIQueryGenericVfnResponse")).thenReturn(FileUtil.readResourceFile("__files/GenericFlows/getGenericVnfByNameResponse.xml")) + GenericVnf genericVnf = new GenericVnf() + genericVnf.setVnfId("vnfId") + genericVnf.setVnfName("testvnfName") + when(mockExecution.getVariable(prefix + "AAIQueryGenericVfnResponse")).thenReturn(genericVnf) when(mockExecution.getVariable(prefix + "requestId")).thenReturn("12345") when(mockExecution.getVariable(prefix + "serviceId")).thenReturn("12345") when(mockExecution.getVariable("mso-request-id")).thenReturn("12345") when(mockExecution.getVariable("mso.workflow.message.endpoint")).thenReturn('http://localhost:28080/mso/WorkflowMessage') when(mockExecution.getVariable("mso.use.qualified.host")).thenReturn("true") - mockData() UpdateVfModuleVolumeInfraV1 obj = new UpdateVfModuleVolumeInfraV1() obj.prepVnfAdapterRest(mockExecution, "true") - Mockito.verify(mockExecution, times(1)).setVariable(captor.capture(), captor.capture()) - def updateVolumeGroupRequest = captor.getValue() - String expectedValue = FileUtil.readResourceFile("__files/UpdateVfModuleVolumeInfraV1/updateVolumeGroupRequest.xml") - XmlComparator.assertXMLEquals(expectedValue, updateVolumeGroupRequest, "messageId", "notificationUrl") - } - - - private static ExecutionEntity setupMock() { - ProcessDefinition mockProcessDefinition = mock(ProcessDefinition.class) - when(mockProcessDefinition.getKey()).thenReturn("UpdateVfModuleVolumeInfraV1") - RepositoryService mockRepositoryService = mock(RepositoryService.class) - when(mockRepositoryService.getProcessDefinition()).thenReturn(mockProcessDefinition) - when(mockRepositoryService.getProcessDefinition().getKey()).thenReturn("UpdateVfModuleVolumeInfraV1") - 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("UpdateVfModuleVolumeInfraV1") - when(mockExecution.getProcessInstanceId()).thenReturn("UpdateVfModuleVolumeInfraV1") - when(mockExecution.getProcessEngineServices()).thenReturn(mockProcessEngineServices) - when(mockExecution.getProcessEngineServices().getRepositoryService().getProcessDefinition(mockExecution.getProcessDefinitionId())).thenReturn(mockProcessDefinition) - - return mockExecution + verify(mockExecution, times(1)).setVariable(captor.capture(), captor.capture()) + String updateVolumeGroupRequest = captor.getValue() + Assert.assertTrue(updateVolumeGroupRequest.contains("testvnfName")) } - - private static void mockData() { - stubFor(get(urlMatching(".*/aai/v[0-9]+/network/generic-vnfs/generic-vnf/12345/vf-modules/vf-module/.*")) - .willReturn(aResponse() - .withStatus(200).withHeader("Content-Type", "text/xml") - .withBodyFile("UpdateVfModuleVolumeInfraV1/vf_module_aai_response.xml"))) - } } diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/UpdateVfModuleVolumeTest.groovy b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/UpdateVfModuleVolumeTest.groovy new file mode 100644 index 0000000000..6771476955 --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/UpdateVfModuleVolumeTest.groovy @@ -0,0 +1,106 @@ +/*- + * ============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.infrastructure.scripts + + +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.impl.persistence.entity.ExecutionEntity +import org.junit.Assert +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.rules.ExpectedException +import org.junit.runner.RunWith +import org.mockito.ArgumentCaptor +import org.mockito.Captor +import org.mockito.MockitoAnnotations +import org.mockito.runners.MockitoJUnitRunner +import org.onap.aai.domain.yang.GenericVnf +import org.onap.aai.domain.yang.VfModule +import org.onap.aai.domain.yang.VolumeGroup +import org.onap.so.bpmn.common.scripts.MsoGroovyTest +import org.onap.so.bpmn.mock.FileUtil +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 javax.ws.rs.core.UriBuilder + +import static org.mockito.Mockito.* + +@RunWith(MockitoJUnitRunner.class) +class UpdateVfModuleVolumeTest extends MsoGroovyTest{ + + def prefix = "UPDVfModVol_" + @Captor + static ArgumentCaptor<ExecutionEntity> captor = ArgumentCaptor.forClass(ExecutionEntity.class) + + @Rule + public ExpectedException thrown = ExpectedException.none() + + + @Before + public void init(){ + super.init("UpdateVfModuleVolume") + MockitoAnnotations.initMocks(this) + } + + + @Test + void testQueryAAIForVolumeGroup() { + String aicCloudRegion = "aicCloudRegionId" + String volumeGroupId = "volumeGroupId" + when(mockExecution.getVariable("UPDVfModVol_volumeGroupId")).thenReturn(volumeGroupId) + when(mockExecution.getVariable("UPDVfModVol_aicCloudRegion")).thenReturn(aicCloudRegion) + + UpdateVfModuleVolume obj = spy(UpdateVfModuleVolume.class) + when(obj.getAAIClient()).thenReturn(client) + AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.VOLUME_GROUP, Defaults.CLOUD_OWNER.toString(), aicCloudRegion, volumeGroupId) + VolumeGroup volumeGroup = new VolumeGroup(); + volumeGroup.setVolumeGroupId(volumeGroupId) + + AAIResultWrapper wrapper = new AAIResultWrapper(FileUtil.readResourceFile("__files/aai/VolumeGroupWithTenant.json")) + when(client.get(uri)).thenReturn(wrapper) + obj.queryAAIForVolumeGroup(mockExecution) + verify(mockExecution).setVariable("UPDVfModVol_volumeGroupHeatStackId","heatStackId") + } + + @Test + void testQueryAAIForVolumeGroupNoTenant() { + String aicCloudRegion = "aicCloudRegionId" + String volumeGroupId = "volumeGroupId" + when(mockExecution.getVariable("UPDVfModVol_volumeGroupId")).thenReturn(volumeGroupId) + when(mockExecution.getVariable("UPDVfModVol_aicCloudRegion")).thenReturn(aicCloudRegion) + + UpdateVfModuleVolume obj = spy(UpdateVfModuleVolume.class) + when(obj.getAAIClient()).thenReturn(client) + AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.VOLUME_GROUP, Defaults.CLOUD_OWNER.toString(), aicCloudRegion, volumeGroupId) + VolumeGroup volumeGroup = new VolumeGroup(); + volumeGroup.setVolumeGroupId(volumeGroupId) + + AAIResultWrapper wrapper = new AAIResultWrapper(FileUtil.readResourceFile("__files/aai/VolumeGroupWithTenant.json")) + when(client.get(uri)).thenThrow(Exception.class) + thrown.expect(BpmnError.class) + obj.queryAAIForVolumeGroup(mockExecution) + } +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/vcpe/scripts/DoCreateAllottedResourceBRGRollbackTest.groovy b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/vcpe/scripts/DoCreateAllottedResourceBRGRollbackTest.groovy index 1e8842e68f..7982e4dd4b 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/vcpe/scripts/DoCreateAllottedResourceBRGRollbackTest.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/vcpe/scripts/DoCreateAllottedResourceBRGRollbackTest.groovy @@ -617,7 +617,7 @@ class DoCreateAllottedResourceBRGRollbackTest extends GroovyTestBase { private initUpdateAaiAROrchStatus(ExecutionEntity mex) { when(mex.getVariable(DBGFLAG)).thenReturn("true") - when(mex.getVariable("aaiARPath")).thenReturn(aaiUriPfx + "/aai/v9/business/customers/customer/"+CUST+"/service-subscriptions/service-subscription/"+SVC+"/service-instances/service-instance/"+INST+"/allotted-resources/allotted-resource/"+ARID) + when(mex.getVariable("aaiARPath")).thenReturn("/business/customers/customer/"+CUST+"/service-subscriptions/service-subscription/"+SVC+"/service-instances/service-instance/"+INST+"/allotted-resources/allotted-resource/"+ARID) when(mex.getVariable("aai.endpoint")).thenReturn(aaiUriPfx) } @@ -634,7 +634,7 @@ class DoCreateAllottedResourceBRGRollbackTest extends GroovyTestBase { private initDeleteAaiAR(ExecutionEntity mex) { when(mex.getVariable(DBGFLAG)).thenReturn("true") when(mex.getVariable("aaiARResourceVersion")).thenReturn(VERS) - when(mex.getVariable("aaiARPath")).thenReturn(aaiUriPfx + "/aai/v9/business/customers/customer/"+CUST+"/service-subscriptions/service-subscription/"+SVC+"/service-instances/service-instance/"+INST+"/allotted-resources/allotted-resource/"+ARID) + when(mex.getVariable("aaiARPath")).thenReturn("/business/customers/customer/"+CUST+"/service-subscriptions/service-subscription/"+SVC+"/service-instances/service-instance/"+INST+"/allotted-resources/allotted-resource/"+ARID) when(mex.getVariable("aai.endpoint")).thenReturn(aaiUriPfx) } diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/vcpe/scripts/DoCreateAllottedResourceBRGTest.groovy b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/vcpe/scripts/DoCreateAllottedResourceBRGTest.groovy index 543bb1db05..f5e48a02e4 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/vcpe/scripts/DoCreateAllottedResourceBRGTest.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/vcpe/scripts/DoCreateAllottedResourceBRGTest.groovy @@ -21,11 +21,7 @@ package org.onap.so.bpmn.vcpe.scripts -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.camunda.bpm.engine.delegate.DelegateExecution import org.junit.Before import org.junit.BeforeClass import org.junit.Rule @@ -36,10 +32,14 @@ import org.camunda.bpm.engine.delegate.BpmnError import org.onap.so.bpmn.core.UrnPropertiesReader import org.onap.so.bpmn.core.WorkflowException import org.onap.so.bpmn.mock.FileUtil +import org.onap.so.client.aai.AAIObjectType +import org.onap.so.client.aai.AAIResourcesClient +import org.onap.so.client.aai.entities.uri.AAIUriFactory + +import javax.ws.rs.core.UriBuilder import static com.github.tomakehurst.wiremock.client.WireMock.aResponse import static com.github.tomakehurst.wiremock.client.WireMock.put -import static com.github.tomakehurst.wiremock.client.WireMock.stubFor import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching import static org.junit.Assert.*; import static org.mockito.Mockito.* @@ -49,7 +49,6 @@ import static org.onap.so.bpmn.mock.StubResponseAAI.MockPutAllottedResource import static org.onap.so.bpmn.mock.StubResponseAAI.MockPutAllottedResource_500 import org.onap.so.bpmn.core.RollbackData -import org.onap.so.bpmn.vcpe.scripts.MapSetter import com.github.tomakehurst.wiremock.junit.WireMockRule @@ -62,7 +61,7 @@ class DoCreateAllottedResourceBRGTest extends GroovyTestBase { @BeforeClass public static void setUpBeforeClass() { - super.setUpBeforeClass() + aaiUriPfx = UrnPropertiesReader.getVariable("aai.endpoint") } @Before @@ -171,27 +170,18 @@ class DoCreateAllottedResourceBRGTest extends GroovyTestBase { // ***** createAaiAR ***** @Test - @Ignore public void createAaiAR() { - ExecutionEntity mex = setupMock() - def map = setupMap(mex) - initCreateAaiAr(mex) - - MockPutAllottedResource(CUST, SVC, INST, ARID) - - DoCreateAllottedResourceBRG DoCreateAllottedResourceBRG = new DoCreateAllottedResourceBRG() - DoCreateAllottedResourceBRG.createAaiAR(mex) - - def data = map.get("rollbackData") - assertNotNull(data) - assertTrue(data instanceof RollbackData) - - assertEquals("45", data.get(Prefix, "disableRollback")) - assertEquals("true", data.get(Prefix, "rollbackAAI")) - assertEquals(ARID, data.get(Prefix, "allottedResourceId")) - assertEquals("sii", data.get(Prefix, "serviceInstanceId")) - assertEquals("psii", data.get(Prefix, "parentServiceInstanceId")) - assertEquals(mex.getVariable("PSI_resourceLink")+"/allotted-resources/allotted-resource/"+ARID, data.get(Prefix, "aaiARPath")) + ExecutionEntity mockExecution = setupMock() + AAIResourcesClient client = mock(AAIResourcesClient.class) + when(mockExecution.getVariable("PSI_resourceLink")).thenReturn(AAIUriFactory.createResourceFromExistingURI(AAIObjectType.SERVICE_INSTANCE,UriBuilder.fromPath( "/aai/v9/business/customers/customer/"+CUST+"/service-subscriptions/service-subscription/"+SVC+"/service-instances/service-instance/"+INST).build())) + when(mockExecution.getVariable("CSI_resourceLink")).thenReturn("/aai/v9/business/customers/customer/"+CUST+"/service-subscriptions/service-subscription/"+SVC+"/service-instances/service-instance/"+INST) + when(mockExecution.getVariable("allottedResourceModelInfo")).thenReturn("{\n" + + " \"modelInvariantUuid\":\"modelInvariantUuid\",\n" + + " \"modelUuid\" : \"modelUuid\"\n" + + "}") + DoCreateAllottedResourceBRG doCreateAllottedResourceBRG = spy(DoCreateAllottedResourceBRG.class) + when(doCreateAllottedResourceBRG.getAAIClient()).thenReturn(client) + doCreateAllottedResourceBRG.createAaiAR(mockExecution) } @Test @@ -225,7 +215,6 @@ class DoCreateAllottedResourceBRGTest extends GroovyTestBase { } @Test -// @Ignore public void createAaiAR_MissingPsiLink() { ExecutionEntity mex = setupMock() initCreateAaiAr(mex) @@ -240,7 +229,6 @@ class DoCreateAllottedResourceBRGTest extends GroovyTestBase { } @Test -// @Ignore public void createAaiAR_HttpFailed() { ExecutionEntity mex = setupMock() initCreateAaiAr(mex) @@ -253,7 +241,6 @@ class DoCreateAllottedResourceBRGTest extends GroovyTestBase { } @Test -// @Ignore public void createAaiAR_BpmnError() { ExecutionEntity mex = setupMock() initCreateAaiAr(mex) @@ -268,7 +255,6 @@ class DoCreateAllottedResourceBRGTest extends GroovyTestBase { } @Test -// @Ignore public void createAaiAR_Ex() { ExecutionEntity mex = setupMock() initCreateAaiAr(mex) @@ -921,7 +907,7 @@ class DoCreateAllottedResourceBRGTest extends GroovyTestBase { when(mex.getVariable("allottedResourceId")).thenReturn(ARID) when(mex.getVariable("aai.endpoint")).thenReturn(aaiUriPfx) when(mex.getVariable("mso.workflow.global.default.aai.namespace")).thenReturn(UrnPropertiesReader.getVariable("mso.workflow.global.default.aai.namespace")) - when(mex.getVariable("PSI_resourceLink")).thenReturn(aaiUriPfx + "/aai/v9/business/customers/customer/"+CUST+"/service-subscriptions/service-subscription/"+SVC+"/service-instances/service-instance/"+INST) + when(mex.getVariable("PSI_resourceLink")).thenReturn(AAIUriFactory.createResourceFromExistingURI(AAIObjectType.SERVICE_INSTANCE, UriBuilder.fromPath( "/business/customers/customer/"+CUST+"/service-subscriptions/service-subscription/"+SVC+"/service-instances/service-instance/"+INST).build())) when(mex.getVariable("allottedResourceType")).thenReturn("BRGt") when(mex.getVariable("allottedResourceRole")).thenReturn("BRGr") when(mex.getVariable("CSI_resourceLink")).thenReturn(aaiUriPfx+"/aai/v9/mycsi") @@ -993,7 +979,7 @@ class DoCreateAllottedResourceBRGTest extends GroovyTestBase { private initUpdateAaiAROrchStatus(ExecutionEntity mex) { when(mex.getVariable(DBGFLAG)).thenReturn("true") - when(mex.getVariable("aaiARPath")).thenReturn(aaiUriPfx + "/aai/v9/business/customers/customer/"+CUST+"/service-subscriptions/service-subscription/"+SVC+"/service-instances/service-instance/"+INST+"/allotted-resources/allotted-resource/"+ARID) + when(mex.getVariable("aaiARPath")).thenReturn("/business/customers/customer/"+CUST+"/service-subscriptions/service-subscription/"+SVC+"/service-instances/service-instance/"+INST+"/allotted-resources/allotted-resource/"+ARID) } } diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/vcpe/scripts/DoCreateAllottedResourceTXCRollbackTest.groovy b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/vcpe/scripts/DoCreateAllottedResourceTXCRollbackTest.groovy index 66cfdb635d..50ce46e4a3 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/vcpe/scripts/DoCreateAllottedResourceTXCRollbackTest.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/vcpe/scripts/DoCreateAllottedResourceTXCRollbackTest.groovy @@ -617,7 +617,7 @@ class DoCreateAllottedResourceTXCRollbackTest extends GroovyTestBase { private initUpdateAaiAROrchStatus(ExecutionEntity mex) { when(mex.getVariable(DBGFLAG)).thenReturn("true") - when(mex.getVariable("aaiARPath")).thenReturn(aaiUriPfx + "/aai/v9/business/customers/customer/"+CUST+"/service-subscriptions/service-subscription/"+SVC+"/service-instances/service-instance/"+INST+"/allotted-resources/allotted-resource/"+ARID) + when(mex.getVariable("aaiARPath")).thenReturn("/business/customers/customer/"+CUST+"/service-subscriptions/service-subscription/"+SVC+"/service-instances/service-instance/"+INST+"/allotted-resources/allotted-resource/"+ARID) when(mex.getVariable("aai.endpoint")).thenReturn(aaiUriPfx) } @@ -634,7 +634,7 @@ class DoCreateAllottedResourceTXCRollbackTest extends GroovyTestBase { private initDeleteAaiAR(ExecutionEntity mex) { when(mex.getVariable(DBGFLAG)).thenReturn("true") when(mex.getVariable("aaiARResourceVersion")).thenReturn(VERS) - when(mex.getVariable("aaiARPath")).thenReturn(aaiUriPfx + "/aai/v9/business/customers/customer/"+CUST+"/service-subscriptions/service-subscription/"+SVC+"/service-instances/service-instance/"+INST+"/allotted-resources/allotted-resource/"+ARID) + when(mex.getVariable("aaiARPath")).thenReturn("/business/customers/customer/"+CUST+"/service-subscriptions/service-subscription/"+SVC+"/service-instances/service-instance/"+INST+"/allotted-resources/allotted-resource/"+ARID) when(mex.getVariable("aai.endpoint")).thenReturn(aaiUriPfx) } diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/vcpe/scripts/DoCreateAllottedResourceTXCTest.groovy b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/vcpe/scripts/DoCreateAllottedResourceTXCTest.groovy index fa40c17e63..b759ca1c20 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/vcpe/scripts/DoCreateAllottedResourceTXCTest.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/vcpe/scripts/DoCreateAllottedResourceTXCTest.groovy @@ -21,11 +21,7 @@ package org.onap.so.bpmn.vcpe.scripts -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.camunda.bpm.engine.delegate.DelegateExecution import org.junit.Before import org.junit.BeforeClass import org.junit.Rule @@ -36,15 +32,12 @@ import org.camunda.bpm.engine.delegate.BpmnError import org.onap.so.bpmn.core.UrnPropertiesReader import org.onap.so.bpmn.core.WorkflowException import org.onap.so.bpmn.mock.FileUtil -import org.springframework.beans.factory.config.YamlPropertiesFactoryBean -import org.springframework.core.io.ClassPathResource -import org.springframework.core.io.FileSystemResource -import org.springframework.core.io.Resource +import org.onap.so.client.aai.AAIObjectType +import org.onap.so.client.aai.AAIResourcesClient +import org.onap.so.client.aai.entities.uri.AAIUriFactory + +import javax.ws.rs.core.UriBuilder -import static com.github.tomakehurst.wiremock.client.WireMock.aResponse -import static com.github.tomakehurst.wiremock.client.WireMock.put -import static com.github.tomakehurst.wiremock.client.WireMock.stubFor -import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching import static org.junit.Assert.*; import static org.mockito.Mockito.* import static org.onap.so.bpmn.mock.StubResponseAAI.MockGetAllottedResource @@ -52,10 +45,7 @@ import static org.onap.so.bpmn.mock.StubResponseAAI.MockPatchAllottedResource import static org.onap.so.bpmn.mock.StubResponseAAI.MockPutAllottedResource import static org.onap.so.bpmn.mock.StubResponseAAI.MockPutAllottedResource_500 -import java.util.Map - import org.onap.so.bpmn.core.RollbackData -import org.onap.so.bpmn.vcpe.scripts.MapSetter import com.github.tomakehurst.wiremock.junit.WireMockRule @@ -85,7 +75,7 @@ class DoCreateAllottedResourceTXCTest extends GroovyTestBase { // ***** preProcessRequest ***** @Test - // @Ignore + public void preProcessRequest() { ExecutionEntity mex = setupMock() initPreProcess(mex) @@ -124,7 +114,7 @@ class DoCreateAllottedResourceTXCTest extends GroovyTestBase { } @Test - // @Ignore + public void getAaiAR_Duplicate() { MockGetAllottedResource(CUST, SVC, INST, ARID, "VCPE/DoCreateAllottedResourceTXC/getArTxc.xml") @@ -140,7 +130,7 @@ class DoCreateAllottedResourceTXCTest extends GroovyTestBase { } @Test - // @Ignore + public void getAaiAR_NotActive() { MockGetAllottedResource(CUST, SVC, INST, ARID, "VCPE/DoCreateAllottedResourceTXC/getArTxc.xml") @@ -175,61 +165,23 @@ class DoCreateAllottedResourceTXCTest extends GroovyTestBase { // ***** createAaiAR ***** @Test - @Ignore public void createAaiAR() { ExecutionEntity mex = setupMock() - def map = setupMap(mex) - initCreateAaiAr(mex) - - MockPutAllottedResource(CUST, SVC, INST, ARID) - - DoCreateAllottedResourceTXC DoCreateAllottedResourceTXC = new DoCreateAllottedResourceTXC() - DoCreateAllottedResourceTXC.createAaiAR(mex) - - def data = map.get("rollbackData") - assertNotNull(data) - assertTrue(data instanceof RollbackData) - - assertEquals("45", data.get(Prefix, "disableRollback")) - assertEquals("true", data.get(Prefix, "rollbackAAI")) - assertEquals(ARID, data.get(Prefix, "allottedResourceId")) - assertEquals("sii", data.get(Prefix, "serviceInstanceId")) - assertEquals("psii", data.get(Prefix, "parentServiceInstanceId")) - assertEquals(mex.getVariable("PSI_resourceLink")+"/allotted-resources/allotted-resource/"+ARID, data.get(Prefix, "aaiARPath")) - } - - @Test - @Ignore - public void createAaiAR_NoArid_NoModelUuids() { - ExecutionEntity mex = setupMock() - def map = setupMap(mex) initCreateAaiAr(mex) - - // no allottedResourceId - will be generated - - when(mex.getVariable("allottedResourceId")).thenReturn(null) - - wireMockRule - .stubFor(put(urlMatching("/aai/.*/allotted-resource/.*")) - .willReturn(aResponse() - .withStatus(200))) - - DoCreateAllottedResourceTXC DoCreateAllottedResourceTXC = new DoCreateAllottedResourceTXC() - DoCreateAllottedResourceTXC.createAaiAR(mex) - - def arid = map.get("allottedResourceId") - assertNotNull(arid) - assertFalse(arid.isEmpty()) - - def data = map.get("rollbackData") - assertNotNull(data) - assertTrue(data instanceof RollbackData) - - assertEquals(arid, data.get(Prefix, "allottedResourceId")) + when(mex.getVariable("PSI_resourceLink")).thenReturn(AAIUriFactory.createResourceFromExistingURI(AAIObjectType.SERVICE_INSTANCE, UriBuilder.fromPath( "/aai/v9/business/customers/customer/"+CUST+"/service-subscriptions/service-subscription/"+SVC+"/service-instances/service-instance/"+INST).build())) + when(mex.getVariable("CSI_resourceLink")).thenReturn("/aai/v9/business/customers/customer/"+CUST+"/service-subscriptions/service-subscription/"+SVC+"/service-instances/service-instance/"+INST) + when(mex.getVariable("allottedResourceModelInfo")).thenReturn("{\n" + + " \"modelInvariantUuid\":\"modelInvariantUuid\",\n" + + " \"modelUuid\" : \"modelUuid\"\n" + + "}") + AAIResourcesClient client = mock(AAIResourcesClient.class) + DoCreateAllottedResourceTXC doCreateAllottedResourceTXC = spy(DoCreateAllottedResourceTXC.class) + when(doCreateAllottedResourceTXC.getAAIClient()).thenReturn(client) + doCreateAllottedResourceTXC.createAaiAR(mex) } + @Test - // @Ignore public void createAaiAR_MissingPsiLink() { ExecutionEntity mex = setupMock() initCreateAaiAr(mex) @@ -244,7 +196,7 @@ class DoCreateAllottedResourceTXCTest extends GroovyTestBase { } @Test - // @Ignore + public void createAaiAR_HttpFailed() { ExecutionEntity mex = setupMock() initCreateAaiAr(mex) @@ -257,7 +209,7 @@ class DoCreateAllottedResourceTXCTest extends GroovyTestBase { } @Test - // @Ignore + public void createAaiAR_BpmnError() { ExecutionEntity mex = setupMock() initCreateAaiAr(mex) @@ -272,7 +224,7 @@ class DoCreateAllottedResourceTXCTest extends GroovyTestBase { } @Test - // @Ignore + public void createAaiAR_Ex() { ExecutionEntity mex = setupMock() initCreateAaiAr(mex) @@ -290,7 +242,7 @@ class DoCreateAllottedResourceTXCTest extends GroovyTestBase { // ***** buildSDNCRequest ***** @Test - // @Ignore + public void buildSDNCRequest() { ExecutionEntity mex = setupMock() initBuildSDNCRequest(mex) @@ -317,7 +269,7 @@ class DoCreateAllottedResourceTXCTest extends GroovyTestBase { } @Test - // @Ignore + public void buildSDNCRequest_Ex() { ExecutionEntity mex = setupMock() initBuildSDNCRequest(mex) @@ -333,7 +285,7 @@ class DoCreateAllottedResourceTXCTest extends GroovyTestBase { // ***** preProcessSDNCAssign ***** @Test - // @Ignore + public void preProcessSDNCAssign() { ExecutionEntity mex = setupMock() def map = setupMap(mex) @@ -359,7 +311,7 @@ class DoCreateAllottedResourceTXCTest extends GroovyTestBase { } @Test - // @Ignore + public void preProcessSDNCAssign_BpmnError() { ExecutionEntity mex = setupMock() initPreProcessSDNC(mex) @@ -372,7 +324,7 @@ class DoCreateAllottedResourceTXCTest extends GroovyTestBase { } @Test - // @Ignore + public void preProcessSDNCAssign_Ex() { ExecutionEntity mex = setupMock() initPreProcessSDNC(mex) @@ -388,7 +340,7 @@ class DoCreateAllottedResourceTXCTest extends GroovyTestBase { // ***** preProcessSDNCCreate ***** @Test - // @Ignore + public void preProcessSDNCCreate() { ExecutionEntity mex = setupMock() def map = setupMap(mex) @@ -415,7 +367,7 @@ class DoCreateAllottedResourceTXCTest extends GroovyTestBase { } @Test - // @Ignore + public void preProcessSDNCCreate_BpmnError() { ExecutionEntity mex = setupMock() initPreProcessSDNC(mex) @@ -428,7 +380,7 @@ class DoCreateAllottedResourceTXCTest extends GroovyTestBase { } @Test - // @Ignore + public void preProcessSDNCCreate_Ex() { ExecutionEntity mex = setupMock() initPreProcessSDNC(mex) @@ -444,7 +396,7 @@ class DoCreateAllottedResourceTXCTest extends GroovyTestBase { // ***** preProcessSDNCActivate ***** @Test - // @Ignore + public void preProcessSDNCActivate() { ExecutionEntity mex = setupMock() def map = setupMap(mex) @@ -471,7 +423,7 @@ class DoCreateAllottedResourceTXCTest extends GroovyTestBase { } @Test - // @Ignore + public void preProcessSDNCActivate_BpmnError() { ExecutionEntity mex = setupMock() initPreProcessSDNC(mex) @@ -484,7 +436,7 @@ class DoCreateAllottedResourceTXCTest extends GroovyTestBase { } @Test - // @Ignore + public void preProcessSDNCActivate_Ex() { ExecutionEntity mex = setupMock() initPreProcessSDNC(mex) @@ -500,7 +452,7 @@ class DoCreateAllottedResourceTXCTest extends GroovyTestBase { // ***** validateSDNCResp ***** @Test - // @Ignore + public void validateSDNCResp() { ExecutionEntity mex = setupMock() def map = setupMap(mex) @@ -524,7 +476,7 @@ class DoCreateAllottedResourceTXCTest extends GroovyTestBase { } @Test - // @Ignore + public void validateSDNCResp_Get() { ExecutionEntity mex = setupMock() def data = initValidateSDNCResp(mex) @@ -543,7 +495,7 @@ class DoCreateAllottedResourceTXCTest extends GroovyTestBase { } @Test - // @Ignore + public void validateSDNCResp_Unsuccessful() { ExecutionEntity mex = setupMock() initValidateSDNCResp(mex) @@ -558,7 +510,7 @@ class DoCreateAllottedResourceTXCTest extends GroovyTestBase { } @Test - // @Ignore + public void validateSDNCResp_BpmnError() { ExecutionEntity mex = setupMock() initValidateSDNCResp(mex) @@ -572,7 +524,7 @@ class DoCreateAllottedResourceTXCTest extends GroovyTestBase { } @Test - // @Ignore + public void validateSDNCResp_Ex() { ExecutionEntity mex = setupMock() initValidateSDNCResp(mex) @@ -589,7 +541,7 @@ class DoCreateAllottedResourceTXCTest extends GroovyTestBase { // ***** preProcessSDNCGet ***** @Test - // @Ignore + public void preProcessSDNCGet_FoundAR() { ExecutionEntity mex = setupMock() def map = setupMap(mex) @@ -608,7 +560,7 @@ class DoCreateAllottedResourceTXCTest extends GroovyTestBase { } @Test - // @Ignore + public void preProcessSDNCGet_NotFoundAR() { ExecutionEntity mex = setupMock() def map = setupMap(mex) @@ -629,7 +581,7 @@ class DoCreateAllottedResourceTXCTest extends GroovyTestBase { } @Test - // @Ignore + public void preProcessSDNCGet_Ex() { ExecutionEntity mex = setupMock() initPreProcessSDNCGet(mex) @@ -660,7 +612,7 @@ class DoCreateAllottedResourceTXCTest extends GroovyTestBase { // ***** generateOutputs ***** @Test - // @Ignore + public void generateOutputs() { ExecutionEntity mex = setupMock() def txctop = FileUtil.readResourceFile("__files/VCPE/DoCreateAllottedResourceTXC/SDNCTopologyQueryCallback.xml") @@ -679,7 +631,7 @@ class DoCreateAllottedResourceTXCTest extends GroovyTestBase { } @Test - // @Ignore + public void generateOutputs_BadXml() { ExecutionEntity mex = setupMock() @@ -694,7 +646,7 @@ class DoCreateAllottedResourceTXCTest extends GroovyTestBase { } @Test - // @Ignore + public void generateOutputs_BpmnError() { ExecutionEntity mex = setupMock() @@ -709,7 +661,7 @@ class DoCreateAllottedResourceTXCTest extends GroovyTestBase { } @Test - // @Ignore + public void generateOutputs_Ex() { ExecutionEntity mex = setupMock() @@ -727,7 +679,7 @@ class DoCreateAllottedResourceTXCTest extends GroovyTestBase { // ***** preProcessRollback ***** @Test - // @Ignore + public void preProcessRollback() { ExecutionEntity mex = setupMock() WorkflowException wfe = mock(WorkflowException.class) @@ -743,7 +695,7 @@ class DoCreateAllottedResourceTXCTest extends GroovyTestBase { } @Test - // @Ignore + public void preProcessRollback_NotWFE() { ExecutionEntity mex = setupMock() @@ -758,7 +710,7 @@ class DoCreateAllottedResourceTXCTest extends GroovyTestBase { } @Test - // @Ignore + public void preProcessRollback_BpmnError() { ExecutionEntity mex = setupMock() @@ -772,7 +724,7 @@ class DoCreateAllottedResourceTXCTest extends GroovyTestBase { } @Test - // @Ignore + public void preProcessRollback_Ex() { ExecutionEntity mex = setupMock() @@ -789,7 +741,7 @@ class DoCreateAllottedResourceTXCTest extends GroovyTestBase { // ***** postProcessRollback ***** @Test - // @Ignore + public void postProcessRollback() { ExecutionEntity mex = setupMock() WorkflowException wfe = mock(WorkflowException.class) @@ -806,7 +758,7 @@ class DoCreateAllottedResourceTXCTest extends GroovyTestBase { } @Test - // @Ignore + public void postProcessRollback_NotWFE() { ExecutionEntity mex = setupMock() @@ -822,7 +774,7 @@ class DoCreateAllottedResourceTXCTest extends GroovyTestBase { } @Test - // @Ignore + public void postProcessRollback_BpmnError() { ExecutionEntity mex = setupMock() @@ -837,7 +789,7 @@ class DoCreateAllottedResourceTXCTest extends GroovyTestBase { } @Test - // @Ignore + public void postProcessRollback_Ex() { ExecutionEntity mex = setupMock() @@ -891,7 +843,7 @@ class DoCreateAllottedResourceTXCTest extends GroovyTestBase { when(mex.getVariable("allottedResourceId")).thenReturn(ARID) when(mex.getVariable("aai.endpoint")).thenReturn(aaiUriPfx) when(mex.getVariable("mso.workflow.global.default.aai.namespace")).thenReturn(UrnPropertiesReader.getVariable("mso.workflow.global.default.aai.namespace")) - when(mex.getVariable("PSI_resourceLink")).thenReturn(aaiUriPfx + "/aai/v9/business/customers/customer/"+CUST+"/service-subscriptions/service-subscription/"+SVC+"/service-instances/service-instance/"+INST) + when(mex.getVariable("PSI_resourceLink")).thenReturn(AAIUriFactory.createResourceFromExistingURI(AAIObjectType.SERVICE_INSTANCE, UriBuilder.fromPath( "/business/customers/customer/"+CUST+"/service-subscriptions/service-subscription/"+SVC+"/service-instances/service-instance/"+INST).build())) when(mex.getVariable("allottedResourceType")).thenReturn("TXCt") when(mex.getVariable("allottedResourceRole")).thenReturn("TXCr") when(mex.getVariable("CSI_resourceLink")).thenReturn(aaiUriPfx+"/aai/v9/mycsi") @@ -951,7 +903,7 @@ class DoCreateAllottedResourceTXCTest extends GroovyTestBase { private initUpdateAaiAROrchStatus(ExecutionEntity mex) { when(mex.getVariable(DBGFLAG)).thenReturn("true") - when(mex.getVariable("aaiARPath")).thenReturn(aaiUriPfx + "/aai/v9/business/customers/customer/"+CUST+"/service-subscriptions/service-subscription/"+SVC+"/service-instances/service-instance/"+INST+"/allotted-resources/allotted-resource/"+ARID) + when(mex.getVariable("aaiARPath")).thenReturn("/business/customers/customer/"+CUST+"/service-subscriptions/service-subscription/"+SVC+"/service-instances/service-instance/"+INST+"/allotted-resources/allotted-resource/"+ARID) } } diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/vcpe/scripts/DoDeleteAllottedResourceBRGTest.groovy b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/vcpe/scripts/DoDeleteAllottedResourceBRGTest.groovy index e8004d3d2b..0528529819 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/vcpe/scripts/DoDeleteAllottedResourceBRGTest.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/vcpe/scripts/DoDeleteAllottedResourceBRGTest.groovy @@ -20,12 +20,7 @@ package org.onap.so.bpmn.vcpe.scripts - -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.camunda.bpm.engine.delegate.DelegateExecution import org.junit.Before import org.junit.BeforeClass import org.junit.Rule @@ -33,33 +28,19 @@ import org.junit.Test import org.junit.Ignore import org.mockito.MockitoAnnotations import org.camunda.bpm.engine.delegate.BpmnError +import org.mockito.Spy import org.onap.so.bpmn.core.UrnPropertiesReader -import org.onap.so.bpmn.core.WorkflowException import org.onap.so.bpmn.mock.FileUtil - -import static com.github.tomakehurst.wiremock.client.WireMock.aResponse -import static com.github.tomakehurst.wiremock.client.WireMock.delete -import static com.github.tomakehurst.wiremock.client.WireMock.get -import static com.github.tomakehurst.wiremock.client.WireMock.patch -import static com.github.tomakehurst.wiremock.client.WireMock.put -import static com.github.tomakehurst.wiremock.client.WireMock.stubFor -import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching +import org.onap.so.client.aai.entities.uri.AAIResourceUri import static org.junit.Assert.*; import static org.mockito.Mockito.* import static org.onap.so.bpmn.mock.StubResponseAAI.MockDeleteAllottedResource import static org.onap.so.bpmn.mock.StubResponseAAI.MockGetAllottedResource import static org.onap.so.bpmn.mock.StubResponseAAI.MockPatchAllottedResource -import static org.onap.so.bpmn.mock.StubResponseAAI.MockQueryAllottedResourceById - -import java.util.Map - -import org.onap.so.bpmn.core.RollbackData -import org.onap.so.bpmn.vcpe.scripts.MapSetter - import com.github.tomakehurst.wiremock.junit.WireMockRule class DoDeleteAllottedResourceBRGTest extends GroovyTestBase { - + @Rule public WireMockRule wireMockRule = new WireMockRule(PORT) @@ -69,11 +50,16 @@ class DoDeleteAllottedResourceBRGTest extends GroovyTestBase { public static void setUpBeforeClass() { super.setUpBeforeClass() } + + @Spy + DoDeleteAllottedResourceBRG doDeleteAllottedResourceBRG @Before public void init() { MockitoAnnotations.initMocks(this) + super.init() + when(doDeleteAllottedResourceBRG.getAllottedResourceUtils()).thenReturn(allottedResourceUtils_MOCK) } public DoDeleteAllottedResourceBRGTest() { @@ -131,40 +117,21 @@ class DoDeleteAllottedResourceBRGTest extends GroovyTestBase { // ***** getAaiAR ***** @Test - @Ignore + @Ignore public void getAaiAR() { - MockQueryAllottedResourceById(ARID, "GenericFlows/getARUrlById.xml") - MockGetAllottedResource(CUST, SVC, INST, ARID, "VCPE/DoDeleteAllottedResourceBRG/arGetById.xml") - ExecutionEntity mex = setupMock() initGetAaiAR(mex) - - DoDeleteAllottedResourceBRG DoDeleteAllottedResourceBRG = new DoDeleteAllottedResourceBRG() - DoDeleteAllottedResourceBRG.getAaiAR(mex) - + when(client_MOCK.exists(any(AAIResourceUri.class))).thenReturn(true) + doDeleteAllottedResourceBRG.getAaiAR(mex) verify(mex).setVariable("parentServiceInstanceId", INST) } @Test -// @Ignore public void getAaiAR_EmptyResponse() { - - // note: empty result-link - wireMockRule - .stubFor(get(urlMatching("/aai/.*/search/.*")) - .willReturn(aResponse() - .withStatus(200) - .withHeader("Content-Type", "text/xml") - .withBody("<result-data></result-data>"))) - - MockGetAllottedResource(CUST, SVC, INST, ARID, "VCPE/DoDeleteAllottedResourceBRG/arGetById.xml") - ExecutionEntity mex = setupMock() initGetAaiAR(mex) - - DoDeleteAllottedResourceBRG DoDeleteAllottedResourceBRG = new DoDeleteAllottedResourceBRG() - - assertTrue(doBpmnError( { _ -> DoDeleteAllottedResourceBRG.getAaiAR(mex) })) + when(client_MOCK.exists(any(AAIResourceUri.class))).thenReturn(false) + assertTrue(doBpmnError( { _ -> doDeleteAllottedResourceBRG.getAaiAR(mex) })) } @@ -562,13 +529,13 @@ class DoDeleteAllottedResourceBRGTest extends GroovyTestBase { when(mex.getVariable("mso.workflow.global.default.aai.version")).thenReturn(UrnPropertiesReader.getVariable("mso.workflow.global.default.aai.version")) when(mex.getVariable("mso.workflow.default.aai.v8.nodes.query.uri")).thenReturn(UrnPropertiesReader.getVariable("mso.workflow.default.aai.v8.nodes-query.uri")) when(mex.getVariable("aai.endpoint")).thenReturn(aaiUriPfx) - when(mex.getVariable("aaiARPath")).thenReturn(aaiUriPfx + "/aai/v9/business/customers/customer/"+CUST+"/service-subscriptions/service-subscription/"+SVC+"/service-instances/service-instance/"+INST+"/allotted-resources/allotted-resource/"+ARID) + when(mex.getVariable("aaiARPath")).thenReturn("/business/customers/customer/"+CUST+"/service-subscriptions/service-subscription/"+SVC+"/service-instances/service-instance/"+INST+"/allotted-resources/allotted-resource/"+ARID) when(mex.getVariable("aaiAROrchStatus")).thenReturn("Active") } private initUpdateAaiAROrchStatus(ExecutionEntity mex) { when(mex.getVariable(DBGFLAG)).thenReturn("true") - when(mex.getVariable("aaiARPath")).thenReturn(aaiUriPfx + "/aai/v9/business/customers/customer/"+CUST+"/service-subscriptions/service-subscription/"+SVC+"/service-instances/service-instance/"+INST+"/allotted-resources/allotted-resource/"+ARID) + when(mex.getVariable("aaiARPath")).thenReturn("/business/customers/customer/"+CUST+"/service-subscriptions/service-subscription/"+SVC+"/service-instances/service-instance/"+INST+"/allotted-resources/allotted-resource/"+ARID) } private initBuildSDNCRequest(ExecutionEntity mex) { @@ -598,7 +565,7 @@ class DoDeleteAllottedResourceBRGTest extends GroovyTestBase { private initDeleteAaiAR(ExecutionEntity mex) { when(mex.getVariable(DBGFLAG)).thenReturn("true") - when(mex.getVariable("aaiARPath")).thenReturn(aaiUriPfx + "/aai/v9/business/customers/customer/"+CUST+"/service-subscriptions/service-subscription/"+SVC+"/service-instances/service-instance/"+INST+"/allotted-resources/allotted-resource/"+ARID) + when(mex.getVariable("aaiARPath")).thenReturn("/business/customers/customer/"+CUST+"/service-subscriptions/service-subscription/"+SVC+"/service-instances/service-instance/"+INST+"/allotted-resources/allotted-resource/"+ARID) when(mex.getVariable("aaiARResourceVersion")).thenReturn("myvers") when(mex.getVariable("aai.endpoint")).thenReturn(aaiUriPfx) } diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/vcpe/scripts/DoDeleteAllottedResourceTXCTest.groovy b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/vcpe/scripts/DoDeleteAllottedResourceTXCTest.groovy index 6719be17a1..ad9b3d4f88 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/vcpe/scripts/DoDeleteAllottedResourceTXCTest.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/vcpe/scripts/DoDeleteAllottedResourceTXCTest.groovy @@ -20,12 +20,7 @@ package org.onap.so.bpmn.vcpe.scripts - -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.camunda.bpm.engine.delegate.DelegateExecution import org.junit.Before import org.junit.BeforeClass import org.junit.Rule @@ -33,30 +28,15 @@ import org.junit.Test import org.junit.Ignore import org.mockito.MockitoAnnotations import org.camunda.bpm.engine.delegate.BpmnError +import org.mockito.Spy import org.onap.so.bpmn.core.UrnPropertiesReader -import org.onap.so.bpmn.core.WorkflowException import org.onap.so.bpmn.mock.FileUtil - -import static com.github.tomakehurst.wiremock.client.WireMock.aResponse -import static com.github.tomakehurst.wiremock.client.WireMock.delete -import static com.github.tomakehurst.wiremock.client.WireMock.get -import static com.github.tomakehurst.wiremock.client.WireMock.patch -import static com.github.tomakehurst.wiremock.client.WireMock.put -import static com.github.tomakehurst.wiremock.client.WireMock.stubFor -import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching +import org.onap.so.client.aai.entities.uri.AAIResourceUri import static org.junit.Assert.*; import static org.mockito.Mockito.* import static org.onap.so.bpmn.mock.StubResponseAAI.MockDeleteAllottedResource import static org.onap.so.bpmn.mock.StubResponseAAI.MockGetAllottedResource import static org.onap.so.bpmn.mock.StubResponseAAI.MockPatchAllottedResource -import static org.onap.so.bpmn.mock.StubResponseAAI.MockQueryAllottedResourceById - - -import java.util.Map - -import org.onap.so.bpmn.core.RollbackData -import org.onap.so.bpmn.vcpe.scripts.MapSetter - import com.github.tomakehurst.wiremock.junit.WireMockRule class DoDeleteAllottedResourceTXCTest extends GroovyTestBase { @@ -66,6 +46,9 @@ class DoDeleteAllottedResourceTXCTest extends GroovyTestBase { String Prefix = "DDARTXC_" + @Spy + DoDeleteAllottedResourceTXC doDeleteAllottedResourceTXC + @BeforeClass public static void setUpBeforeClass() { super.setUpBeforeClass() @@ -74,7 +57,9 @@ class DoDeleteAllottedResourceTXCTest extends GroovyTestBase { @Before public void init() { - MockitoAnnotations.initMocks(this) + MockitoAnnotations.initMocks(this) + super.init() + when(doDeleteAllottedResourceTXC.getAllottedResourceUtils()).thenReturn(allottedResourceUtils_MOCK) } public DoDeleteAllottedResourceTXCTest() { @@ -130,42 +115,23 @@ class DoDeleteAllottedResourceTXCTest extends GroovyTestBase { // ***** getAaiAR ***** - @Test - @Ignore + @Ignore public void getAaiAR() { - MockQueryAllottedResourceById(ARID, "GenericFlows/getARUrlById.xml") - MockGetAllottedResource(CUST, SVC, INST, ARID, "VCPE/DoDeleteAllottedResourceTXC/arGetById.xml") - + ExecutionEntity mex = setupMock() initGetAaiAR(mex) - - DoDeleteAllottedResourceTXC DoDeleteAllottedResourceTXC = new DoDeleteAllottedResourceTXC() - DoDeleteAllottedResourceTXC.getAaiAR(mex) - + when(client_MOCK.exists(any(AAIResourceUri.class))).thenReturn(true) + doDeleteAllottedResourceTXC.getAaiAR(mex) verify(mex).setVariable("parentServiceInstanceId", INST) } - + @Test -// @Ignore public void getAaiAR_EmptyResponse() { - - // note: empty result-link - wireMockRule - .stubFor(get(urlMatching("/aai/.*/search/.*")) - .willReturn(aResponse() - .withStatus(200) - .withHeader("Content-Type", "text/xml") - .withBody("<result-data></result-data>"))) - - MockGetAllottedResource(CUST, SVC, INST, ARID, "VCPE/DoDeleteAllottedResourceTXC/arGetById.xml") - ExecutionEntity mex = setupMock() initGetAaiAR(mex) - - DoDeleteAllottedResourceTXC DoDeleteAllottedResourceTXC = new DoDeleteAllottedResourceTXC() - - assertTrue(doBpmnError( { _ -> DoDeleteAllottedResourceTXC.getAaiAR(mex) })) + when(client_MOCK.exists(any(AAIResourceUri.class))).thenReturn(false) + assertTrue(doBpmnError( { _ -> doDeleteAllottedResourceTXC.getAaiAR(mex) })) } @@ -563,13 +529,13 @@ class DoDeleteAllottedResourceTXCTest extends GroovyTestBase { when(mex.getVariable("mso.workflow.global.default.aai.version")).thenReturn(UrnPropertiesReader.getVariable("mso.workflow.global.default.aai.version")) when(mex.getVariable("mso.workflow.default.aai.v8.nodes.query.uri")).thenReturn(UrnPropertiesReader.getVariable("mso.workflow.default.aai.v8.nodes-query.uri")) when(mex.getVariable("aai.endpoint")).thenReturn(aaiUriPfx) - when(mex.getVariable("aaiARPath")).thenReturn(aaiUriPfx + "/aai/v9/business/customers/customer/"+CUST+"/service-subscriptions/service-subscription/"+SVC+"/service-instances/service-instance/"+INST+"/allotted-resources/allotted-resource/"+ARID) + when(mex.getVariable("aaiARPath")).thenReturn("/business/customers/customer/"+CUST+"/service-subscriptions/service-subscription/"+SVC+"/service-instances/service-instance/"+INST+"/allotted-resources/allotted-resource/"+ARID) when(mex.getVariable("aaiAROrchStatus")).thenReturn("Active") } private initUpdateAaiAROrchStatus(ExecutionEntity mex) { when(mex.getVariable(DBGFLAG)).thenReturn("true") - when(mex.getVariable("aaiARPath")).thenReturn(aaiUriPfx + "/aai/v9/business/customers/customer/"+CUST+"/service-subscriptions/service-subscription/"+SVC+"/service-instances/service-instance/"+INST+"/allotted-resources/allotted-resource/"+ARID) + when(mex.getVariable("aaiARPath")).thenReturn("/business/customers/customer/"+CUST+"/service-subscriptions/service-subscription/"+SVC+"/service-instances/service-instance/"+INST+"/allotted-resources/allotted-resource/"+ARID) } private initBuildSDNCRequest(ExecutionEntity mex) { @@ -599,7 +565,7 @@ class DoDeleteAllottedResourceTXCTest extends GroovyTestBase { private initDeleteAaiAR(ExecutionEntity mex) { when(mex.getVariable(DBGFLAG)).thenReturn("true") - when(mex.getVariable("aaiARPath")).thenReturn(aaiUriPfx + "/aai/v9/business/customers/customer/"+CUST+"/service-subscriptions/service-subscription/"+SVC+"/service-instances/service-instance/"+INST+"/allotted-resources/allotted-resource/"+ARID) + when(mex.getVariable("aaiARPath")).thenReturn("/business/customers/customer/"+CUST+"/service-subscriptions/service-subscription/"+SVC+"/service-instances/service-instance/"+INST+"/allotted-resources/allotted-resource/"+ARID) when(mex.getVariable("aaiARResourceVersion")).thenReturn("myvers") when(mex.getVariable("aai.endpoint")).thenReturn(aaiUriPfx) } diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/vcpe/scripts/GroovyTestBase.groovy b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/vcpe/scripts/GroovyTestBase.groovy index 764e6244d4..8ce3bdb6c3 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/vcpe/scripts/GroovyTestBase.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/vcpe/scripts/GroovyTestBase.groovy @@ -25,35 +25,17 @@ 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.camunda.bpm.engine.delegate.DelegateExecution -import org.junit.Before -import org.junit.BeforeClass -import org.junit.Rule -import org.junit.Test -import org.junit.Ignore -import org.mockito.MockitoAnnotations +import org.junit.runner.RunWith +import org.mockito.Mock import org.camunda.bpm.engine.delegate.BpmnError +import org.mockito.runners.MockitoJUnitRunner +import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor +import org.onap.so.bpmn.common.scripts.AllottedResourceUtils import org.onap.so.bpmn.core.UrnPropertiesReader -import org.onap.so.bpmn.core.WorkflowException -import org.onap.so.bpmn.mock.FileUtil -import org.springframework.beans.factory.config.YamlPropertiesFactoryBean -import org.springframework.core.io.ClassPathResource -import org.springframework.core.io.Resource - -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.patch -import static com.github.tomakehurst.wiremock.client.WireMock.put -import static com.github.tomakehurst.wiremock.client.WireMock.stubFor -import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching -import static org.junit.Assert.*; +import org.onap.so.client.aai.AAIResourcesClient import static org.mockito.Mockito.* -import static org.onap.so.bpmn.mock.StubResponseAAI.MockGetAllottedResource -import org.onap.so.bpmn.core.RollbackData -import org.onap.so.bpmn.vcpe.scripts.MapSetter - -import com.github.tomakehurst.wiremock.junit.WireMockRule +@RunWith(MockitoJUnitRunner.class) class GroovyTestBase { static final int PORT = 28090 @@ -71,6 +53,11 @@ class GroovyTestBase { String processName + AllottedResourceUtils allottedResourceUtils_MOCK + + @Mock + AAIResourcesClient client_MOCK + public static void setUpBeforeClass() { aaiUriPfx = UrnPropertiesReader.getVariable("aai.endpoint") } @@ -120,5 +107,10 @@ class GroovyTestBase { doAnswer(mapset).when(mex).setVariable(any(), any()) return mapset.getMap(); } - + + void init(){ + allottedResourceUtils_MOCK = spy(new AllottedResourceUtils(mock(AbstractServiceTaskProcessor.class))) + when(allottedResourceUtils_MOCK.getAAIClient()).thenReturn(client_MOCK) + } + } diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/aai/AAICreateResourcesTest.java b/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/aai/AAICreateResourcesTest.java index 7d3d298c68..2e588b7078 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/aai/AAICreateResourcesTest.java +++ b/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/aai/AAICreateResourcesTest.java @@ -22,7 +22,7 @@ package org.onap.so.bpmn.infrastructure.aai; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; -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.doThrow; @@ -38,7 +38,7 @@ import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.mockito.Spy; -import org.mockito.runners.MockitoJUnitRunner; +import org.mockito.junit.MockitoJUnitRunner; import org.onap.so.bpmn.servicedecomposition.bbobjects.GenericVnf; import org.onap.so.client.aai.AAIObjectType; import org.onap.so.client.aai.AAIResourcesClient; @@ -86,7 +86,7 @@ public class AAICreateResourcesTest { public void createAAIProjectTest() { doReturn(aaiResourcesClient).when(aaiResourcesClient).createIfNotExists(isA(AAIResourceUri.class), isA(Optional.class)); doNothing().when(aaiResourcesClient).connect(isA(AAIResourceUri.class), isA(AAIResourceUri.class)); - doNothing().when(aaiResourcesClient).connect(isA(AAIResourceUri.class), isA(AAIResourceUri.class)); + aaiCreateResources.createAAIProject(projectName, serviceInstanceId); @@ -185,7 +185,7 @@ public class AAICreateResourcesTest { @Test public void getVnfInstanceExceptionTest() { - doThrow(Exception.class).when(aaiResourcesClient).get(isA(AAIResourceUri.class)); + doThrow(RuntimeException.class).when(aaiResourcesClient).get(isA(AAIResourceUri.class)); Optional<GenericVnf> actualVnf = aaiCreateResources.getVnfInstance(vnfId); diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/aai/AAIDeleteServiceInstanceTest.java b/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/aai/AAIDeleteServiceInstanceTest.java index 5808a330a3..a540a6d2cc 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/aai/AAIDeleteServiceInstanceTest.java +++ b/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/aai/AAIDeleteServiceInstanceTest.java @@ -20,7 +20,7 @@ package org.onap.so.bpmn.infrastructure.aai; -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.doThrow; @@ -77,7 +77,7 @@ public class AAIDeleteServiceInstanceTest { doReturn("testProcessKey").when(execution).getVariable("testProcessKey"); doReturn("serviceInstanceId").when(execution).getVariable("serviceInstanceId"); - doThrow(Exception.class).when(aaiResourcesClient).delete(isA(AAIResourceUri.class)); + doThrow(RuntimeException.class).when(aaiResourcesClient).delete(isA(AAIResourceUri.class)); aaiDeleteServiceInstance.execute(execution); } diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/CancelDmaapSubscriptionTest.java b/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/CancelDmaapSubscriptionTest.java index 4282b0f2bb..8507d9c092 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/CancelDmaapSubscriptionTest.java +++ b/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/CancelDmaapSubscriptionTest.java @@ -24,7 +24,7 @@ import org.camunda.bpm.engine.delegate.DelegateExecution; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Matchers.eq; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/CheckAaiForCorrelationIdDelegateTest.java b/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/CheckAaiForCorrelationIdDelegateTest.java index 3eb3bd8796..eeda355f80 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/CheckAaiForCorrelationIdDelegateTest.java +++ b/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/CheckAaiForCorrelationIdDelegateTest.java @@ -20,9 +20,8 @@ package org.onap.so.bpmn.infrastructure.pnf.delegate; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.eq; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -34,8 +33,10 @@ import static org.onap.so.bpmn.infrastructure.pnf.delegate.ExecutionVariableName import org.camunda.bpm.engine.delegate.BpmnError; import org.camunda.bpm.engine.delegate.DelegateExecution; import org.junit.Before; +import org.junit.Rule; import org.junit.Test; import org.junit.experimental.runners.Enclosed; +import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.onap.so.bpmn.core.WorkflowException; @@ -45,6 +46,9 @@ public class CheckAaiForCorrelationIdDelegateTest { public static class ConnectionOkTests { private CheckAaiForCorrelationIdDelegate delegate; + + @Rule + public ExpectedException expectedException = ExpectedException.none(); @Before public void setUp() { @@ -53,13 +57,14 @@ public class CheckAaiForCorrelationIdDelegateTest { } @Test - public void shouldThrowExceptionWhenCorrelationIdIsNotSet() { + public void shouldThrowExceptionWhenCorrelationIdIsNotSet() throws Exception { // given DelegateExecution execution = mock(DelegateExecution.class); when(execution.getVariable(CORRELATION_ID)).thenReturn(null); when(execution.getVariable("testProcessKey")).thenReturn("testProcessKeyValue"); // when, then - assertThatThrownBy(() -> delegate.execute(execution)).isInstanceOf(BpmnError.class); + expectedException.expect(BpmnError.class); + delegate.execute(execution); verify(execution).setVariable(eq("WorkflowException"), any(WorkflowException.class)); } @@ -89,6 +94,9 @@ public class CheckAaiForCorrelationIdDelegateTest { public static class NoConnectionTests { private CheckAaiForCorrelationIdDelegate delegate; + + @Rule + public ExpectedException expectedException = ExpectedException.none(); @Before public void setUp() { @@ -97,13 +105,14 @@ public class CheckAaiForCorrelationIdDelegateTest { } @Test - public void shouldThrowExceptionWhenIoExceptionOnConnectionToAai() { + public void shouldThrowExceptionWhenIoExceptionOnConnectionToAai() throws Exception { // given DelegateExecution execution = mock(DelegateExecution.class); when(execution.getVariable(CORRELATION_ID)).thenReturn(ID_WITH_ENTRY); when(execution.getVariable("testProcessKey")).thenReturn("testProcessKey"); // when, then - assertThatThrownBy(() -> delegate.execute(execution)).isInstanceOf(BpmnError.class); + expectedException.expect(BpmnError.class); + delegate.execute(execution); verify(execution).setVariable(eq("WorkflowException"), any(WorkflowException.class)); } } diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/CreatePnfEntryInAaiDelegateTest.java b/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/CreatePnfEntryInAaiDelegateTest.java index ce6b766fa2..c487125ea6 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/CreatePnfEntryInAaiDelegateTest.java +++ b/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/CreatePnfEntryInAaiDelegateTest.java @@ -23,7 +23,7 @@ package org.onap.so.bpmn.infrastructure.pnf.delegate; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; -import static org.mockito.Matchers.eq; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.onap.so.bpmn.infrastructure.pnf.delegate.ExecutionVariableNames.CORRELATION_ID; import static org.onap.so.bpmn.infrastructure.pnf.delegate.ExecutionVariableNames.PNF_UUID; @@ -51,6 +51,6 @@ public class CreatePnfEntryInAaiDelegateTest { Pnf createdEntry = aaiConnection.getCreated().get("testCorrelationId"); assertThat(createdEntry.getPnfId()).isEqualTo(pnfUuid); assertThat(createdEntry.getPnfName()).isEqualTo("testCorrelationId"); - assertThat(createdEntry.isInMaint()).isTrue(); + assertThat(createdEntry.isInMaint()).isNull(); } -}
\ No newline at end of file +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/GeneratePnfUuidDelegateTest.java b/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/GeneratePnfUuidDelegateTest.java index c351706aff..8a1cdfa4c0 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/GeneratePnfUuidDelegateTest.java +++ b/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/GeneratePnfUuidDelegateTest.java @@ -38,4 +38,4 @@ public class GeneratePnfUuidDelegateTest { // then assertThat((String) execution.getVariable(PNF_UUID)).matches(PnfCheckInputs.UUID_REGEX); } -}
\ No newline at end of file +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/InformDmaapClientTest.java b/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/InformDmaapClientTest.java index ddf33a1d77..23c82229fe 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/InformDmaapClientTest.java +++ b/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/InformDmaapClientTest.java @@ -29,8 +29,8 @@ import org.junit.Test; import org.mockito.InOrder; import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.eq; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.*; public class InformDmaapClientTest { diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/PnfCheckInputsTest.java b/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/PnfCheckInputsTest.java index 3e146be3c2..1888831e2e 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/PnfCheckInputsTest.java +++ b/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/PnfCheckInputsTest.java @@ -105,4 +105,4 @@ public class PnfCheckInputsTest { delegateExecution.setVariable(PNF_UUID, uuid); return testedObject; } -}
\ No newline at end of file +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/dmaap/PnfEventReadyDmaapClientTest.java b/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/dmaap/PnfEventReadyDmaapClientTest.java index 1b0169d6d3..b30239d9c0 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/dmaap/PnfEventReadyDmaapClientTest.java +++ b/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/dmaap/PnfEventReadyDmaapClientTest.java @@ -22,9 +22,10 @@ package org.onap.so.bpmn.infrastructure.pnf.dmaap; -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.eq; + +import static org.junit.Assert.*; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyZeroInteractions; @@ -49,7 +50,7 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Mock; -import org.mockito.runners.MockitoJUnitRunner; +import org.mockito.junit.MockitoJUnitRunner; import org.onap.so.bpmn.infrastructure.pnf.dmaap.PnfEventReadyDmaapClient.DmaapTopicListenerThread; import org.springframework.core.env.Environment; @RunWith(MockitoJUnitRunner.class) @@ -113,10 +114,13 @@ public class PnfEventReadyDmaapClientTest { thenReturn(createResponse(String.format(JSON_EXAMPLE_WITH_CORRELATION_ID, CORRELATION_ID))); testedObjectInnerClassThread.run(); ArgumentCaptor<HttpGet> captor1 = ArgumentCaptor.forClass(HttpGet.class); - verify(httpClientMock).execute(captor1.capture()); - assertThat(captor1.getValue().getURI()).hasHost(HOST).hasPort(PORT).hasScheme(PROTOCOL) - .hasPath( - "/" + URI_PATH_PREFIX + "/" + EVENT_TOPIC_TEST + "/" + CONSUMER_GROUP + "/" + CONSUMER_ID + ""); + verify(httpClientMock).execute(captor1.capture()); + + assertEquals(captor1.getValue().getURI().getHost(),HOST); + assertEquals(captor1.getValue().getURI().getPort(),PORT); + assertEquals(captor1.getValue().getURI().getScheme(),PROTOCOL); + assertEquals(captor1.getValue().getURI().getPath(),"/" + URI_PATH_PREFIX + "/" + EVENT_TOPIC_TEST + "/" + CONSUMER_GROUP + "/" + CONSUMER_ID + ""); + verify(threadMockToNotifyCamundaFlow).run(); verify(executorMock).shutdown(); } diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/resources/__files/AAI/GenericVnfVfModule.json b/bpmn/so-bpmn-infrastructure-common/src/test/resources/__files/AAI/GenericVnfVfModule.json new file mode 100644 index 0000000000..488865c326 --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/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/so-bpmn-infrastructure-common/src/test/resources/__files/AAI/ServiceInstanceWithAR.json b/bpmn/so-bpmn-infrastructure-common/src/test/resources/__files/AAI/ServiceInstanceWithAR.json new file mode 100644 index 0000000000..1a2f5b8aa4 --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/test/resources/__files/AAI/ServiceInstanceWithAR.json @@ -0,0 +1,36 @@ +{"service-instance":{ + "service-instance-id": "serviceInstanceId", + "service-instance-name": "serviceInstanceName", + "orchestration-status": "CREATED", + "owning-entity": null, + "project": null, + "relationship-list": { + "relationship": [ + { + "related-to": "allotted-resource", + "related-link": "/aai/v11/business/customers/customer/testCustIdInfra/service-subscriptions/service-subscription/HNPORTAL/service-instances/service-instance/testServiceInstanceIdPortalPri/allotted-resources/allotted-resource/testAllottedResourceIdPortalPri", + "relationship-data": [ + { + "relationship-key": "cloud-region.cloud-owner", + "relationship-value": "CloudOwner" + }, + { + "relationship-key": "cloud-region.cloud-region-id", + "relationship-value": "mdt1" + }, + { + "relationship-key": "allotted-resource.id", + "relationship-value": "4a9184ac-5fad-44a1-b224-289bb490eaa9" + } + ] + } + ] + }, + "service-type": "serviceType", + "service-instance-location-id": "serviceInstanceLocId", + "selflink": "selfLink", + "metadata": null, + "configurations": [], + "model-info-service-instance": null +} +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/resources/__files/AAI/VolumeGroup.json b/bpmn/so-bpmn-infrastructure-common/src/test/resources/__files/AAI/VolumeGroup.json new file mode 100644 index 0000000000..4022ffe98a --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/test/resources/__files/AAI/VolumeGroup.json @@ -0,0 +1,10 @@ +{ + "volume-group-id":"volumeGroupId", + "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/so-bpmn-infrastructure-common/src/test/resources/__files/AAI/VolumeGroupWithTenant.json b/bpmn/so-bpmn-infrastructure-common/src/test/resources/__files/AAI/VolumeGroupWithTenant.json new file mode 100644 index 0000000000..e0fadfb78a --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/test/resources/__files/AAI/VolumeGroupWithTenant.json @@ -0,0 +1,29 @@ +{ + "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/cloud-infrastructure/cloud-regions/cloud-region/CloudOwner/mdt1/tenants/tenant/Tenant123", + "relationship-data": [ + { + "relationship-key": "cloud-region.cloud-owner", + "relationship-value": "CloudOwner" + }, + { + "relationship-key": "cloud-region.cloud-region-id", + "relationship-value": "mdt1" + }, + { + "relationship-key": "tenant.tenant-id", + "relationship-value": "Tenant123" + }] + }] + } +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/resources/__files/AAI/VolumeGroupWithVfModule.json b/bpmn/so-bpmn-infrastructure-common/src/test/resources/__files/AAI/VolumeGroupWithVfModule.json new file mode 100644 index 0000000000..9a47c44751 --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/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/so-bpmn-infrastructure-common/src/test/resources/application-test.yml b/bpmn/so-bpmn-infrastructure-common/src/test/resources/application-test.yml index 78ecd6ce88..5b36b65b43 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/test/resources/application-test.yml +++ b/bpmn/so-bpmn-infrastructure-common/src/test/resources/application-test.yml @@ -1,287 +1,287 @@ -aai:
- auth: 757A94191D685FD2092AC1490730A4FC
- dme2:
- timeout: '30000'
- endpoint: http://localhost:${wiremock.server.port}
-camunda:
- bpm:
- admin-user:
- id: admin
- password: admin
- database:
- type: h2
- history-level: FULL
- metrics:
- enabled: false
- db-reporter-activate: false
-canopi:
- auth: 757A94191D685FD2092AC1490730A4FC
-csi:
- aots:
- addincidentmanagement:
- endpoint: http://localhost:${wiremock.server.port}/AddIncidentManagementTicketRequest
- networkstatus:
- endpoint: http://localhost:${wiremock.server.port}/SendManagedNetworkStatusNotification
-entitymanager:
- packagesToScan: com
-mso:
- correlation:
- timeout: PT60S
- logPath: logs
- async:
- core-pool-size: 50
- max-pool-size: 50
- queue-capacity: 500
- adapters:
- completemsoprocess:
- endpoint: http://localhost:30253/CompleteMsoProcess
- db:
- auth: 757A94191D685FD2092AC1490730A4FC
- password: wLg4sjrAFUS8rfVfdvTXeQ==
- endpoint: http://localhost:${wiremock.server.port}/services/RequestsDbAdapter
- spring:
- endpoint: http://localhost:${wiremock.server.port}
- network:
- endpoint: http://localhost:30253/services/NetworkAdapter
- rest:
- endpoint: http://localhost:30253/services/rest/v1/networks
- openecomp:
- db:
- endpoint: http://localhost:${wiremock.server.port}/services/RequestsDbAdapter
- po:
- auth: 757A94191D685FD2092AC1490730A4FC
- password: 3141634BF7E070AA289CF2892C986C0B
- sdnc:
- endpoint: http://localhost:${wiremock.server.port}/adapters/SDNCAdapter
- rest:
- endpoint: http://localhost:${wiremock.server.port}/adapters/rest/v1/sdnc
- timeout: PT150S
- tenant:
- endpoint: http://localhost:30253/services/TenantAdapter
- vnf:
- endpoint: http://localhost:${wiremock.server.port}/services/VnfAdapter
- rest:
- endpoint: http://localhost:${wiremock.server.port}/services/rest/v1/vnfs
- volume-groups:
- rest:
- endpoint: http://localhost:30253/services/rest/v1/volume-groups
- vnf-async:
- endpoint: http://localhost:30253/services/VnfAdapterAsync
- adiod:
- vce:
- service:
- model:
- invariant:
- uuid: 1cc4e2e4-eb6e-404d-a66f-c8733cedcce8
- version: '5.0'
- bpmn:
- process:
- historyTimeToLive: '30'
- callbackRetryAttempts: '5'
- catalog:
- db:
- endpoint: http://localhost:${wiremock.server.port}/ecomp/mso/catalog
- spring:
- endpoint: http://localhost:30258
- csi:
- pwd: 4EA237303511EFBBC37F17A351562131
- sendmanagednetworkstatusnotification:
- applicationname: NetworkManagementEthernetOverFiber
- version: '212'
- usrname: mso
- db:
- auth: Basic YnBlbDptc28tZGItMTUwNyE=
- default:
- adapter:
- namespace: http://com.att.mso
- gateway:
- service:
- model:
- name: HNGWaaS for DHV Test
- healthcheck:
- log:
- debug: 'false'
- infra:
- customer:
- id: testCustIdInfra
- msoKey: 07a7159d3bf51a0e53be7a8f89699be7
- oam:
- network:
- role:
- gateway: HngwOamNetVto.OAM
- portal: HnportalOamNetVto.OAM
- po:
- timeout: PT60S
- portal:
- service:
- model:
- name: HNPortalaaS for DHV Test
- request:
- db:
- endpoint: http://localhost:${wiremock.server.port}/
- rollback: 'true'
- sdnc:
- firewall:
- yang:
- model:
- version: '2015-05-15'
- password: 3141634BF7E070AA289CF2892C986C0B
- timeout:
- firewall:
- minutes: '20'
- ucpe:
- async:
- hours: '120'
- minutes: '5'
- site-name: CamundaEngine
- sriov:
- network:
- role:
- gateway1: HngwSriovProviderNet.SR_IOV_Provider2_1
- gateway2: HngwSriovProviderNet.SR_IOV_Provider2_2
- portal1: HnportalSriovProviderNet3.SR_IOV_Provider2_1
- portal2: HnportalSriovProviderNet3.SR_IOV_Provider2_2
- workflow:
- sdnc:
- replication:
- delay: PT5S
- aai:
- distribution:
- delay: PT5S
- CreateGenericVNFV1:
- aai:
- volume-group:
- uri: /aai/v6/cloud-infrastructure/volume-groups/volume-group
- DHVCreateService:
- aai:
- customer:
- uri: /aai/v9/business/customers/customer
- createvce:
- delay:
- seconds: '1'
- default:
- aai:
- version: '8'
- cloud-region:
- version: '9'
- generic-vnf:
- version: '9'
- retry:
- attempts: '1'
- deleteCinderVolumeV1:
- aai:
- volume-group:
- uri: /aai/v6/cloud-infrastructure/volume-groups/volume-group
- global:
- default:
- aai:
- namespace: http://org.openecomp.aai.inventory/
- l3ToHigherLayerAddBonding:
- model:
- invariantid: 50359538-066f-4a8d-807f-f2bc8eaa79dc
- name: WAN Bonding v0.1
- version: '0.1'
- versionid: 52dbec20-47aa-42e4-936c-331d8e350d44
- message:
- endpoint: http://localhost:30252/mso/WorkflowMessage
- notification:
- name: GenericNotificationServiceATT
- sdncadapter:
- callback: http://localhost:${wiremock.server.port}/mso/SDNCAdapterCallbackService
- vnfadapter:
- create:
- callback: http://localhost:30253/mso/vnfAdapterNotify
- delete:
- callback: http://localhost:30253/mso/vnfAdapterNotify
- query:
- callback: http://localhost:30253/mso/vnfAdapterNotify
- rollback:
- callback: http://localhost:30253/mso/vnfAdapterNotify
-policy:
- auth: Basic dGVzdHBkcDphbHBoYTEyMw==
- client:
- auth: Basic bTAzNzQzOnBvbGljeVIwY2sk
- endpoint: https://localhost:8081/pdp/api/
- environment: TEST
-sdnc:
- auth: Basic YWRtaW46YWRtaW4=
- host: https://localhost:8443
- path: /restconf/operations/GENERIC-RESOURCE-API
-sdno:
- health-check:
- dmaap:
- password: eHQ1cUJrOUc
- publisher:
- topic: com.att.sdno.test-health-diagnostic-v02
- subscriber:
- topic: com.att.sdno.test-health-diagnostic-v02
- username: testuser
-pnf:
- dmaap:
- host:
- port:
-sniro:
- conductor:
- host: http://localhost:30253
- uri: /release
- manager:
- timeout: PT30M
- host: http://localhost:${wiremock.server.port}
- uri.v1: /sniro/api/v2/placement
- uri.v2: /sniro/api/placement/v2
- headers.auth: Basic dGVzdDp0ZXN0cHdk
- headers.patchVersion: 1
- headers.minorVersion: 1
- headers.latestVersion: 2
-server:
- port: 8080
- tomcat:
- max-threads: 50
- # ssl:
- # key-store: /app/msoClientKeyStore.jks
- # key-store-password: mso4you
- # key-store-type: JKS
- # trust-store: /app/msoTrustStore.jks
- # trust-store-password: mso_Domain2.0_4you
-spring:
- h2:
- console:
- enabled: true
- path: /h2
- datasource:
- url: jdbc:h2:mem:AZ;;DB_CLOSE_ON_EXIT=FALSE
- username: sa
- password: sa
- driverClassName: org.h2.Driver
- security:
- usercredentials:
- -
- username: test
- password: '$2a$12$Zi3AuYcZoZO/gBQyUtST2.F5N6HqcTtaNci2Et.ufsQhski56srIu'
- role: BPMN-Client
-# Hibernate
-hibernate:
- dialect: org.hibernate.dialect.MySQL5Dialect
- show_sql: false
-
-management:
- security:
- enabled: false
-
-security:
- basic:
- enabled: false
-
-appc:
- client:
- topic:
- read:
- name: APPC-TEST-AMDOCS2
- timeout: 360000
- write: APPC-TEST-AMDOCS1-IST
- response:
- timeout: 360000
- key: LSl8QKolmKcC0yJR
- secret: lgjXraD1HutKxv8jEN6tVouu
- service: ueb
- poolMembers: localhost:3904,localhost:3904,localhost:3904
\ No newline at end of file +aai: + auth: 5E12ACACBD552A415E081E29F2C4772F9835792A51C766CCFDD7433DB5220B59969CB2798C + dme2: + timeout: '30000' + endpoint: http://localhost:${wiremock.server.port} +camunda: + bpm: + admin-user: + id: admin + password: admin + database: + type: h2 + history-level: FULL + metrics: + enabled: false + db-reporter-activate: false +canopi: + auth: 5E12ACACBD552A415E081E29F2C4772F9835792A51C766CCFDD7433DB5220B59969CB2798C +csi: + aots: + addincidentmanagement: + endpoint: http://localhost:${wiremock.server.port}/AddIncidentManagementTicketRequest + networkstatus: + endpoint: http://localhost:${wiremock.server.port}/SendManagedNetworkStatusNotification +entitymanager: + packagesToScan: com +mso: + correlation: + timeout: PT60S + logPath: logs + async: + core-pool-size: 50 + max-pool-size: 50 + queue-capacity: 500 + adapters: + completemsoprocess: + endpoint: http://localhost:30253/CompleteMsoProcess + db: + auth: 5E12ACACBD552A415E081E29F2C4772F9835792A51C766CCFDD7433DB5220B59969CB2798C + password: wLg4sjrAFUS8rfVfdvTXeQ== + endpoint: http://localhost:${wiremock.server.port}/services/RequestsDbAdapter + spring: + endpoint: http://localhost:${wiremock.server.port} + network: + endpoint: http://localhost:30253/services/NetworkAdapter + rest: + endpoint: http://localhost:30253/services/rest/v1/networks + openecomp: + db: + endpoint: http://localhost:${wiremock.server.port}/services/RequestsDbAdapter + po: + auth: 5E12ACACBD552A415E081E29F2C4772F9835792A51C766CCFDD7433DB5220B59969CB2798C + password: 3141634BF7E070AA289CF2892C986C0B + sdnc: + endpoint: http://localhost:${wiremock.server.port}/adapters/SDNCAdapter + rest: + endpoint: http://localhost:${wiremock.server.port}/adapters/rest/v1/sdnc + timeout: PT150S + tenant: + endpoint: http://localhost:30253/services/TenantAdapter + vnf: + endpoint: http://localhost:${wiremock.server.port}/services/VnfAdapter + rest: + endpoint: http://localhost:${wiremock.server.port}/services/rest/v1/vnfs + volume-groups: + rest: + endpoint: http://localhost:30253/services/rest/v1/volume-groups + vnf-async: + endpoint: http://localhost:30253/services/VnfAdapterAsync + adiod: + vce: + service: + model: + invariant: + uuid: 1cc4e2e4-eb6e-404d-a66f-c8733cedcce8 + version: '5.0' + bpmn: + process: + historyTimeToLive: '30' + callbackRetryAttempts: '5' + catalog: + db: + endpoint: http://localhost:${wiremock.server.port}/ecomp/mso/catalog + spring: + endpoint: http://localhost:30258 + csi: + pwd: E684FA9977AF5DFB50F5ADC5B7425FDFA0CEBFF2E138E0477549879AEC8A9CE2DB7563 + sendmanagednetworkstatusnotification: + applicationname: NetworkManagementEthernetOverFiber + version: '212' + usrname: mso + db: + auth: Basic YnBlbDptc28tZGItMTUwNyE= + default: + adapter: + namespace: http://com.att.mso + gateway: + service: + model: + name: HNGWaaS for DHV Test + healthcheck: + log: + debug: 'false' + infra: + customer: + id: testCustIdInfra + msoKey: 07a7159d3bf51a0e53be7a8f89699be7 + oam: + network: + role: + gateway: HngwOamNetVto.OAM + portal: HnportalOamNetVto.OAM + po: + timeout: PT60S + portal: + service: + model: + name: HNPortalaaS for DHV Test + request: + db: + endpoint: http://localhost:${wiremock.server.port}/ + rollback: 'true' + sdnc: + firewall: + yang: + model: + version: '2015-05-15' + password: 3141634BF7E070AA289CF2892C986C0B + timeout: + firewall: + minutes: '20' + ucpe: + async: + hours: '120' + minutes: '5' + site-name: CamundaEngine + sriov: + network: + role: + gateway1: HngwSriovProviderNet.SR_IOV_Provider2_1 + gateway2: HngwSriovProviderNet.SR_IOV_Provider2_2 + portal1: HnportalSriovProviderNet3.SR_IOV_Provider2_1 + portal2: HnportalSriovProviderNet3.SR_IOV_Provider2_2 + workflow: + sdnc: + replication: + delay: PT5S + aai: + distribution: + delay: PT5S + CreateGenericVNFV1: + aai: + volume-group: + uri: /aai/v6/cloud-infrastructure/volume-groups/volume-group + DHVCreateService: + aai: + customer: + uri: /aai/v9/business/customers/customer + createvce: + delay: + seconds: '1' + default: + aai: + version: '8' + cloud-region: + version: '9' + generic-vnf: + version: '9' + retry: + attempts: '1' + deleteCinderVolumeV1: + aai: + volume-group: + uri: /aai/v6/cloud-infrastructure/volume-groups/volume-group + global: + default: + aai: + namespace: http://org.openecomp.aai.inventory/ + l3ToHigherLayerAddBonding: + model: + invariantid: 50359538-066f-4a8d-807f-f2bc8eaa79dc + name: WAN Bonding v0.1 + version: '0.1' + versionid: 52dbec20-47aa-42e4-936c-331d8e350d44 + message: + endpoint: http://localhost:30252/mso/WorkflowMessage + notification: + name: GenericNotificationServiceATT + sdncadapter: + callback: http://localhost:${wiremock.server.port}/mso/SDNCAdapterCallbackService + vnfadapter: + create: + callback: http://localhost:30253/mso/vnfAdapterNotify + delete: + callback: http://localhost:30253/mso/vnfAdapterNotify + query: + callback: http://localhost:30253/mso/vnfAdapterNotify + rollback: + callback: http://localhost:30253/mso/vnfAdapterNotify +policy: + auth: Basic dGVzdHBkcDphbHBoYTEyMw== + client: + auth: Basic bTAzNzQzOnBvbGljeVIwY2sk + endpoint: https://localhost:8081/pdp/api/ + environment: TEST +sdnc: + auth: Basic YWRtaW46YWRtaW4= + host: https://localhost:8443 + path: /restconf/operations/GENERIC-RESOURCE-API +sdno: + health-check: + dmaap: + password: eHQ1cUJrOUc + publisher: + topic: com.att.sdno.test-health-diagnostic-v02 + subscriber: + topic: com.att.sdno.test-health-diagnostic-v02 + username: testuser +pnf: + dmaap: + host: + port: +sniro: + conductor: + host: http://localhost:30253 + uri: /release + manager: + timeout: PT30M + host: http://localhost:${wiremock.server.port} + uri.v1: /sniro/api/v2/placement + uri.v2: /sniro/api/placement/v2 + headers.auth: Basic dGVzdDp0ZXN0cHdk + headers.patchVersion: 1 + headers.minorVersion: 1 + headers.latestVersion: 2 +server: + port: 8080 + tomcat: + max-threads: 50 + # ssl: + # key-store: /app/msoClientKeyStore.jks + # key-store-password: mso4you + # key-store-type: JKS + # trust-store: /app/msoTrustStore.jks + # trust-store-password: mso_Domain2.0_4you +spring: + h2: + console: + enabled: true + path: /h2 + datasource: + url: jdbc:h2:mem:AZ;;DB_CLOSE_ON_EXIT=FALSE + username: sa + password: sa + driverClassName: org.h2.Driver + security: + usercredentials: + - + username: test + password: '$2a$12$Zi3AuYcZoZO/gBQyUtST2.F5N6HqcTtaNci2Et.ufsQhski56srIu' + role: BPMN-Client +# Hibernate +hibernate: + dialect: org.hibernate.dialect.MySQL5Dialect + show_sql: false + +management: + security: + enabled: false + +security: + basic: + enabled: false + +appc: + client: + topic: + read: + name: APPC-TEST-AMDOCS2 + timeout: 360000 + write: APPC-TEST-AMDOCS1-IST + response: + timeout: 360000 + key: LSl8QKolmKcC0yJR + secret: lgjXraD1HutKxv8jEN6tVouu + service: ueb + poolMembers: localhost:3904,localhost:3904,localhost:3904 |