diff options
Diffstat (limited to 'bpmn/so-bpmn-infrastructure-common')
90 files changed, 4406 insertions, 4810 deletions
diff --git a/bpmn/so-bpmn-infrastructure-common/pom.xml b/bpmn/so-bpmn-infrastructure-common/pom.xml index 55d5d9244e..b29017ea8d 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,7 +305,7 @@ <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> </dependencies> 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 cd583f77ef..a0f0e279f6 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 @@ -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. @@ -31,16 +31,21 @@ import org.onap.so.bpmn.common.scripts.ExceptionUtil import org.onap.so.bpmn.common.scripts.ExternalAPIUtil import org.onap.so.bpmn.common.scripts.AaiUtil import org.onap.so.bpmn.common.scripts.MsoUtils +import org.onap.aai.domain.yang.SpPartner import org.onap.so.bpmn.common.recipe.ResourceInput import org.onap.so.bpmn.common.resource.ResourceRequestBuilder import org.onap.so.bpmn.core.WorkflowException import org.onap.so.bpmn.core.json.JsonUtils import org.onap.so.bpmn.infrastructure.workflow.serviceTask.client.builder.AbstractBuilder -import org.onap.so.rest.APIResponse +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.bpmn.common.scripts.SDNCAdapterUtils import org.onap.so.bpmn.infrastructure.workflow.service.ServicePluginFactory import java.util.Map import java.util.UUID +import javax.ws.rs.core.Response import org.onap.so.logger.MsoLogger import org.camunda.bpm.engine.runtime.Execution @@ -49,12 +54,10 @@ 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 -import org.onap.so.rest.RESTClient -import org.onap.so.rest.RESTConfig /** * This groovy class supports the <class>Create3rdONAPE2EServiceInstance.bpmn</class> process. - * flow for Create E2EServiceInstance in 3rdONAP + * flow for Create E2EServiceInstance in 3rdONAP */ public class Create3rdONAPE2EServiceInstance extends AbstractServiceTaskProcessor { @@ -82,10 +85,10 @@ public class Create3rdONAPE2EServiceInstance extends AbstractServiceTaskProcesso String resourceInputPrameters = resourceInputObj.getResourceParameters() String inputParametersJson = JsonUtils.getJsonValue(resourceInputPrameters, "requestInputs") JSONObject inputParameters = new JSONObject(inputParametersJson) - + // set local resourceInput execution.setVariable(Prefix + "ResourceInput", resourceInputObj) - + boolean is3rdONAPExist = false if(inputParameters.has("sppartner_url")) @@ -123,7 +126,7 @@ public class Create3rdONAPE2EServiceInstance extends AbstractServiceTaskProcesso String msg = "sppartner providingServiceInvarianteUuid is blank." msoLogger.debug(msg) } - + if(inputParameters.has("sppartner_handoverMode")) { String handoverMode = inputParameters.get("sppartner_handoverMode") @@ -153,9 +156,9 @@ public class Create3rdONAPE2EServiceInstance extends AbstractServiceTaskProcesso public void checkLocallCall (DelegateExecution execution) { msoLogger.info(" ***** Started checkLocallCall *****") try { - + //Get ResourceInput Object - ResourceInput resourceInputObj = execution.getVariable(Prefix + "ResourceInput") + ResourceInput resourceInputObj = execution.getVariable(Prefix + "ResourceInput") //uuiRequest String incomingRequest = resourceInputObj.getRequestsInputs() @@ -163,7 +166,7 @@ public class Create3rdONAPE2EServiceInstance extends AbstractServiceTaskProcesso String requestInputs = JsonUtils.getJsonValue(serviceParameters, "requestInputs") JSONObject inputParameters = new JSONObject(requestInputs) execution.setVariable(Prefix + "ServiceParameters", inputParameters) - + // CallSource is added only when ONAP SO calling 3rdONAP(External API) SO(Remote call) boolean isLocalCall = true String callSource = "UUI" @@ -174,11 +177,11 @@ public class Create3rdONAPE2EServiceInstance extends AbstractServiceTaskProcesso String sppartnerId = inputParameters.get("SppartnerServiceId") execution.setVariable(Prefix + "SppartnerServiceId", sppartnerId) isLocalCall = false - } + } } execution.setVariable(Prefix + "CallSource", callSource) msoLogger.debug("callSource is: " + callSource ) - + execution.setVariable("IsLocalCall", isLocalCall) } catch (Exception ex){ @@ -211,7 +214,7 @@ public class Create3rdONAPE2EServiceInstance extends AbstractServiceTaskProcesso } execution.setVariable("serviceType", serviceType) msoLogger.info("serviceType:" + serviceType) - + String resourceName = resourceInputObj.getResourceInstanceName() if (isBlank(resourceName)) { msg = "Input resourceName is null" @@ -219,11 +222,11 @@ public class Create3rdONAPE2EServiceInstance extends AbstractServiceTaskProcesso } execution.setVariable("resourceName", resourceName) msoLogger.info("resourceName:" + resourceName) - + int beginIndex = resourceName.indexOf("_") + 1 String serviceInstanceName = resourceName.substring(beginIndex) execution.setVariable("serviceInstanceName", serviceInstanceName) - + String serviceInstanceId = resourceInputObj.getServiceInstanceId() if (isBlank(serviceInstanceId)) { msg = "Input serviceInstanceId is null" @@ -239,7 +242,7 @@ public class Create3rdONAPE2EServiceInstance extends AbstractServiceTaskProcesso } execution.setVariable(Prefix + "ResourceModelInvariantUuid", resourceModelInvariantUuid) msoLogger.info("resourceModelInvariantUuid:" + resourceModelInvariantUuid) - + String resourceModelUuid = resourceInputObj.getResourceModelInfo().getModelUuid() if (isBlank(resourceModelUuid)) { msg = "Input resourceModelUuid is null" @@ -247,7 +250,7 @@ public class Create3rdONAPE2EServiceInstance extends AbstractServiceTaskProcesso } execution.setVariable(Prefix + "ResourceModelUuid", resourceModelUuid) msoLogger.info("resourceModelUuid:" + resourceModelUuid) - + String resourceModelCustomizationUuid = resourceInputObj.getResourceModelInfo().getModelCustomizationUuid() if (isBlank(resourceModelCustomizationUuid)) { msg = "Input resourceModelCustomizationUuid is null" @@ -300,7 +303,7 @@ public class Create3rdONAPE2EServiceInstance extends AbstractServiceTaskProcesso public void allocateCrossONAPResource(DelegateExecution execution) { msoLogger.info(" ***** Started allocateCrossONAPResource *****") - + //get TP links from AAI for SOTN handoverMode only String handoverMode = execution.getVariable(Prefix + "HandoverMode") if("SOTN".equalsIgnoreCase(handoverMode)) { @@ -318,7 +321,7 @@ public class Create3rdONAPE2EServiceInstance extends AbstractServiceTaskProcesso crossTPs.put("remote-access-topology-id", inputParameters.get("local-access-topology-id")); crossTPs.put("remote-access-node-id", inputParameters.get("local-access-node-id")); crossTPs.put("remote-access-ltp-id", inputParameters.get("local-access-ltp-id")); - + inputParameters.put("local-access-provider-id", crossTPs.get("local-access-provider-id")); inputParameters.put("local-access-client-id", crossTPs.get("local-access-client-id")); inputParameters.put("local-access-topology-id", crossTPs.get("local-access-topology-id")); @@ -336,17 +339,17 @@ public class Create3rdONAPE2EServiceInstance extends AbstractServiceTaskProcesso msoLogger.error("No allocated CrossONAPResource found in ServiceParameters") } } - + msoLogger.info("Exit " + allocateCrossONAPResource) } public void prepare3rdONAPRequest(DelegateExecution execution) { msoLogger.info(" ***** Started prepare3rdONAPRequest *****") - + String sppartnerUrl = execution.getVariable(Prefix + "SppartnerUrl") String extAPIPath = sppartnerUrl + '/serviceOrder' execution.setVariable("ExternalAPIURL", extAPIPath) - + // ExternalAPI message format String externalId = execution.getVariable("resourceName") String category = "E2E Service" @@ -363,7 +366,7 @@ public class Create3rdONAPE2EServiceInstance extends AbstractServiceTaskProcesso String serviceState = "active" String serviceName = execution.getVariable("serviceInstanceName") String serviceUuId = execution.getVariable(Prefix + "SppartnerUUID") - + Map<String, String> valueMap = new HashMap<>() valueMap.put("externalId", '"' + externalId + '"') valueMap.put("category", '"' + category + '"') @@ -381,30 +384,30 @@ public class Create3rdONAPE2EServiceInstance extends AbstractServiceTaskProcesso valueMap.put("serviceId", "null") //null for add valueMap.put("serviceName", '"' + serviceName + '"') valueMap.put("serviceUuId", '"' + serviceUuId + '"') - + ExternalAPIUtil externalAPIUtil = new ExternalAPIUtil() - - // insert CallSource='ExternalAPI' to uuiRequest + + // insert CallSource='ExternalAPI' to uuiRequest Map<String, String> requestInputsMap = new HashMap<>() requestInputsMap.put("inputName", '"CallSource"') requestInputsMap.put("inputValue", '"ExternalAPI"') String _requestInputs_ = externalAPIUtil.setTemplate(ExternalAPIUtil.RequestInputsTemplate, requestInputsMap) - + requestInputsMap.clear() String serviceInstanceId = execution.getVariable(Prefix + "ServiceInstanceId") requestInputsMap.put("inputName", '"SppartnerServiceId"') requestInputsMap.put("inputValue", '"' + serviceInstanceId + '"') _requestInputs_ += ",\n" + externalAPIUtil.setTemplate(ExternalAPIUtil.RequestInputsTemplate, requestInputsMap) - + requestInputsMap.clear() String serviceType = execution.getVariable("serviceType") requestInputsMap.put("inputName", '"serviceType"') requestInputsMap.put("inputValue", '"' + serviceType + '"') _requestInputs_ += ",\n" + externalAPIUtil.setTemplate(ExternalAPIUtil.RequestInputsTemplate, requestInputsMap) - + // Transfer all uuiRequest incomeParameters to ExternalAPI format JSONObject inputParameters = execution.getVariable(Prefix + "ServiceParameters") - for(String key : inputParameters.keySet()) { + for(String key : inputParameters.keySet()) { String inputName = key String inputValue = inputParameters.opt(key) requestInputsMap.clear() @@ -413,7 +416,7 @@ public class Create3rdONAPE2EServiceInstance extends AbstractServiceTaskProcesso _requestInputs_ += ",\n" + externalAPIUtil.setTemplate(ExternalAPIUtil.RequestInputsTemplate, requestInputsMap) } valueMap.put("_requestInputs_", _requestInputs_) - + String payload = externalAPIUtil.setTemplate(ExternalAPIUtil.PostServiceOrderRequestsTemplate, valueMap) execution.setVariable(Prefix + "Payload", payload) msoLogger.info("Exit " + prepare3rdONAPRequest) @@ -421,26 +424,26 @@ public class Create3rdONAPE2EServiceInstance extends AbstractServiceTaskProcesso public void doCreateE2ESIin3rdONAP(DelegateExecution execution) { msoLogger.info(" ***** Started doCreateE2ESIin3rdONAP *****") - + String extAPIPath = execution.getVariable("ExternalAPIURL") String payload = execution.getVariable(Prefix + "Payload") msoLogger.debug("doCreateE2ESIin3rdONAP externalAPIURL is: " + extAPIPath) msoLogger.debug("doCreateE2ESIin3rdONAP payload is: " + payload) - + ExternalAPIUtil externalAPIUtil = new ExternalAPIUtil() - APIResponse response = externalAPIUtil.executeExternalAPIPostCall(execution, extAPIPath, payload) + Response response = externalAPIUtil.executeExternalAPIPostCall(execution, extAPIPath, payload) - int responseCode = response.getStatusCode() + int responseCode = response.getStatus() execution.setVariable(Prefix + "PostServiceOrderResponseCode", responseCode) msoLogger.debug("Post ServiceOrder response code is: " + responseCode) - String extApiResponse = response.getResponseBodyAsString() + String extApiResponse = response.readEntity(String.class) JSONObject responseObj = new JSONObject(extApiResponse) execution.setVariable(Prefix + "PostServiceOrderResponse", extApiResponse) - + msoLogger.debug("doCreateE2ESIin3rdONAP response body is: " + extApiResponse) - + //Process Response if(responseCode == 200 || responseCode == 201 || responseCode == 202 ) //200 OK 201 CREATED 202 ACCEPTED @@ -455,32 +458,32 @@ public class Create3rdONAPE2EServiceInstance extends AbstractServiceTaskProcesso msoLogger.error("Post ServiceOrder Received a Bad Response Code. Response Code is: " + responseCode) // exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Post ServiceOrder Received a bad response from 3rdONAP External API") } - + msoLogger.info("Exit " + doCreateE2ESIin3rdONAP) } - + public void getE2ESIProgressin3rdONAP(DelegateExecution execution) { msoLogger.info(" ***** Started getE2ESIProgressin3rdONAP *****") - + String extAPIPath = execution.getVariable("ExternalAPIURL") extAPIPath += "/" + execution.getVariable("ServiceOrderId") utils.log("DEBUG", "getE2ESIProgressin3rdONAP create externalAPIURL is: " + extAPIPath, isDebugEnabled) - + ExternalAPIUtil externalAPIUtil = new ExternalAPIUtil() - APIResponse response = externalAPIUtil.executeExternalAPIGetCall(execution, extAPIPath) + Response response = externalAPIUtil.executeExternalAPIGetCall(execution, extAPIPath) - int responseCode = response.getStatusCode() + int responseCode = response.getStatus() execution.setVariable(Prefix + "GetServiceOrderResponseCode", responseCode) msoLogger.debug("Get ServiceOrder response code is: " + responseCode) - String extApiResponse = response.getResponseBodyAsString() + String extApiResponse = response.readEntity(String.class) JSONObject responseObj = new JSONObject(extApiResponse) execution.setVariable(Prefix + "GetServiceOrderResponse", extApiResponse) - + msoLogger.debug("getE2ESIProgressin3rdONAP create response body is: " + extApiResponse) - + //Process Response //200 OK 201 CREATED 202 ACCEPTED if(responseCode == 200 || responseCode == 201 || responseCode == 202 ) { @@ -511,7 +514,7 @@ public class Create3rdONAPE2EServiceInstance extends AbstractServiceTaskProcesso String serviceOrderState = item.get("state") execution.setVariable(Prefix + "SuccessIndicator", true) execution.setVariable("ServiceOrderState", serviceOrderState) - + // Get serviceOrder State and process progress if("ACKNOWLEDGED".equalsIgnoreCase(serviceOrderState)) { execution.setVariable("progress", 15) @@ -539,17 +542,17 @@ public class Create3rdONAPE2EServiceInstance extends AbstractServiceTaskProcesso execution.setVariable("statusDescription", "Create Service Order Status is unknown") } } - else{ + else{ msoLogger.debug("Get ServiceOrder Received a Bad Response Code. Response Code is: " + responseCode) execution.setVariable("progress", 100) execution.setVariable("status", "error") execution.setVariable("statusDescription", "Get Create ServiceOrder Received a bad response") exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Get Create ServiceOrder Received a bad response from 3rdONAP External API") - } - + } + msoLogger.info("Exit " + getE2ESIProgressin3rdONAP) } - + /** * delay 5 sec */ @@ -562,8 +565,8 @@ public class Create3rdONAPE2EServiceInstance extends AbstractServiceTaskProcesso } public void saveSPPartnerInAAI(DelegateExecution execution) { - msoLogger.info(" ***** Started saveSPPartnerInAAI *****") - + msoLogger.info(" ***** Started saveSPPartnerInAAI *****") + String sppartnerId = execution.getVariable(Prefix + "SppartnerServiceId") String sppartnerUrl = execution.getVariable(Prefix + "SppartnerUrl") String callSource = execution.getVariable(Prefix + "CallSource") @@ -574,57 +577,21 @@ public class Create3rdONAPE2EServiceInstance extends AbstractServiceTaskProcesso String resourceModelUuid = execution.getVariable(Prefix + "ResourceModelUuid") String resourceModelCustomizationUuid = execution.getVariable(Prefix + "ResourceModelCustomizationUuid") - AaiUtil aaiUriUtil = new AaiUtil() - String aai_uri = aaiUriUtil.getBusinessSPPartnerUri(execution) - String namespace = aaiUriUtil.getNamespaceFromUri(aai_uri) - - String payload = - """<sp-partner xmlns=\"${namespace}\"> - <id>${sppartnerId}</id> - <url>${sppartnerUrl}</url> - <callsource>${callSource}</callsource> - <model-invariant-id>${resourceModelInvariantUuid}</model-invariant-id> - <model-version-id>${resourceModelUuid}</model-version-id> - <model-customization-id>${resourceModelCustomizationUuid}</model-customization-id> - <relationship-list> - <relationship> - <related-to>service-instance</related-to> - <related-link>/aai/v14/business/customers/customer/${globalSubscriberId}/service-subscriptions/service-subscription/${serviceType}/service-instances/service-instance/${serviceInstanceId}</related-link> - <relationship-data> - <relationship-key>service-instance.service-instance-id</relationship-key> - <relationship-value>${serviceInstanceId}</relationship-value> - </relationship-data> - </relationship> - </relationship-list> - </sp-partner>""".trim() - utils.logAudit(payload) - - String aai_endpoint = execution.getVariable("URN_aai_endpoint") - String serviceAaiPath = "${aai_endpoint}${aai_uri}/" + UriUtils.encode(sppartnerId,"UTF-8") - - APIResponse response = aaiUriUtil.executeAAIPutCall(execution, serviceAaiPath, payload) - int responseCode = response.getStatusCode() - execution.setVariable(Prefix + "PutSppartnerResponseCode", responseCode) - msoLogger.debug("Put sppartner response code is: " + responseCode) + SpPartner partner = new SpPartner() + partner.setSpPartnerId(sppartnerId) + partner.setUrl(sppartnerUrl) + partner.setCallsource(callSource) + partner.setModelInvariantId(resourceModelInvariantUuid) + partner.setModelVersionId(resourceModelUuid) + partner.setModelCustomizationId(resourceModelCustomizationUuid) - String aaiResponse = response.getResponseBodyAsString() - aaiResponse = StringEscapeUtils.unescapeXml(aaiResponse) - execution.setVariable(Prefix + "PutSppartnerResponse", aaiResponse) + AAIResourcesClient client = new AAIResourcesClient() + AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.SP_PARTNER, sppartnerId) + client.create(uri, partner) + + AAIResourceUri siUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, globalSubscriberId, serviceType, serviceInstanceId) + client.connect(uri, siUri) - //Process Response - if(responseCode == 200 || responseCode == 201 || responseCode == 202 ) - //200 OK 201 CREATED 202 ACCEPTED - { - msoLogger.debug("PUT sppartner Received a Good Response") - execution.setVariable(Prefix + "SuccessIndicator", true) - } - else - { - msoLogger.debug("Put sppartner Received a Bad Response Code. Response Code is: " + responseCode) - exceptionUtil.MapAAIExceptionToWorkflowExceptionGeneric(execution, aaiResponse, responseCode) - throw new BpmnError("MSOWorkflowException") - } - msoLogger.info("Exit " + saveSPPartnerInAAI) } @@ -632,7 +599,7 @@ public class Create3rdONAPE2EServiceInstance extends AbstractServiceTaskProcesso def dbAdapterEndpoint = execution.getVariable("URN_mso_adapters_openecomp_db_endpoint") execution.setVariable("CVFMI_dbAdapterEndpoint", dbAdapterEndpoint) execution.setVariable("CVFMI_updateResOperStatusRequest", body) - } + } public void postProcess(DelegateExecution execution){ msoLogger.info(" ***** Started postProcess *****") diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateDeviceResource.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateDeviceResource.groovy index 89a6239be7..8fc9ce0883 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateDeviceResource.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateDeviceResource.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. @@ -26,27 +26,23 @@ import org.json.XML; import static org.apache.commons.lang3.StringUtils.*; import groovy.xml.XmlUtil import groovy.json.* -import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor +import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor import org.onap.so.bpmn.common.scripts.ExceptionUtil import org.onap.so.bpmn.common.recipe.ResourceInput; -import org.onap.so.bpmn.common.resource.ResourceRequestBuilder -import org.onap.so.bpmn.core.WorkflowException +import org.onap.so.bpmn.common.resource.ResourceRequestBuilder +import org.onap.so.bpmn.core.WorkflowException import org.onap.so.bpmn.core.json.JsonUtils import org.onap.so.bpmn.infrastructure.workflow.serviceTask.client.builder.AbstractBuilder import org.onap.so.logger.MsoLogger -import org.onap.so.rest.APIResponse import org.onap.so.bpmn.common.scripts.SDNCAdapterUtils import java.util.UUID; -import org.camunda.bpm.engine.delegate.BpmnError +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 -import org.onap.so.rest.RESTClient -import org.onap.so.rest.RESTConfig -import org.onap.so.rest.APIResponse; +import org.springframework.web.util.UriUtils import org.onap.so.bpmn.common.scripts.AaiUtil /** @@ -56,18 +52,18 @@ import org.onap.so.bpmn.common.scripts.AaiUtil public class CreateDeviceResource extends AbstractServiceTaskProcessor { String Prefix="CREDEVRES_" - + ExceptionUtil exceptionUtil = new ExceptionUtil() JsonUtils jsonUtil = new JsonUtils() - + private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, CreateDeviceResource.class) public void preProcessRequest(DelegateExecution execution){ msoLogger.info(" ***** Started preProcessRequest *****") String msg = "" - try { - + try { + //get bpmn inputs from resource request. String requestId = execution.getVariable("mso-request-id") String requestAction = execution.getVariable("requestAction") @@ -90,10 +86,10 @@ public class CreateDeviceResource extends AbstractServiceTaskProcessor { // String requestInputs = JsonUtils.getJsonValue(serviceParameters, "requestInputs") // JSONObject serviceInputParameters = new JSONObject(requestInputs) // execution.setVariable(Prefix + "ServiceParameters", serviceInputParameters) - + //Deal with recipeParams String recipeParamsFromWf = execution.getVariable("recipeParamXsd") - String resourceName = resourceInputObj.getResourceInstanceName() + String resourceName = resourceInputObj.getResourceInstanceName() if (isBlank(resourceName)) { msg = "Input resourceName is null" msoLogger.error(msg) @@ -108,7 +104,7 @@ public class CreateDeviceResource extends AbstractServiceTaskProcessor { } execution.setVariable(Prefix + "ResourceModelInvariantUuid", resourceModelInvariantUuid) msoLogger.info("resourceModelInvariantUuid:" + resourceModelInvariantUuid) - + String resourceModelUuid = resourceInputObj.getResourceModelInfo().getModelUuid() if (isBlank(resourceModelUuid)) { msg = "Input resourceModelUuid is null" @@ -116,7 +112,7 @@ public class CreateDeviceResource extends AbstractServiceTaskProcessor { } execution.setVariable(Prefix + "ResourceModelUuid", resourceModelUuid) msoLogger.info("resourceModelUuid:" + resourceModelUuid) - + String resourceModelCustomizationUuid = resourceInputObj.getResourceModelInfo().getModelCustomizationUuid() if (isBlank(resourceModelCustomizationUuid)) { msg = "Input resourceModelCustomizationUuid is null" @@ -127,7 +123,7 @@ public class CreateDeviceResource extends AbstractServiceTaskProcessor { execution.setVariable(Prefix + "serviceInstanceId", resourceInputObj.getServiceInstanceId()) execution.setVariable("mso-request-id", requestId) - + } catch (BpmnError e) { throw e; } catch (Exception ex){ @@ -136,22 +132,22 @@ public class CreateDeviceResource extends AbstractServiceTaskProcessor { exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) } } - + public void checkDevType(DelegateExecution execution){ msoLogger.info(" ***** Started checkDevType *****") try { JSONObject resourceInputParameters = execution.getVariable(Prefix + "ResourceRequestInputs") String devType = resourceInputParameters.get("device_class") - + if(StringUtils.isBlank(devType)) { devType = "OTHER" } - // support VNF as PNF, to modify + // support VNF as PNF, to modify else if(StringUtils.equalsIgnoreCase(devType, "VNF")) { devType = "PNF" - } - + } + execution.setVariable("device_class", devType) } catch (Exception ex){ @@ -160,13 +156,13 @@ public class CreateDeviceResource extends AbstractServiceTaskProcessor { exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) } } - + private void setProgressUpdateVariables(DelegateExecution execution, String body) { def dbAdapterEndpoint = execution.getVariable("URN_mso_adapters_openecomp_db_endpoint") execution.setVariable("CVFMI_dbAdapterEndpoint", dbAdapterEndpoint) execution.setVariable("CVFMI_updateResOperStatusRequest", body) } - + public void prepareUpdateProgress(DelegateExecution execution) { msoLogger.info(" ***** Started prepareUpdateProgress *****") ResourceInput resourceInputObj = execution.getVariable(Prefix + "ResourceInput") @@ -199,7 +195,7 @@ public class CreateDeviceResource extends AbstractServiceTaskProcessor { setProgressUpdateVariables(execution, body) msoLogger.info(" ***** Exit prepareUpdateProgress *****") } - + public void getVNFTemplatefromSDC(DelegateExecution execution){ msoLogger.info(" ***** Started getVNFTemplatefromSDC *****") try { @@ -212,7 +208,7 @@ public class CreateDeviceResource extends AbstractServiceTaskProcessor { exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) } } - + public void postVNFInfoProcess(DelegateExecution execution){ msoLogger.info(" ***** Started postVNFInfoProcess *****") try { @@ -225,7 +221,7 @@ public class CreateDeviceResource extends AbstractServiceTaskProcessor { exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) } } - + public void sendSyncResponse (DelegateExecution execution) { msoLogger.debug(" *** sendSyncResponse *** ") diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateSDNCNetworkResource.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateSDNCNetworkResource.groovy index 47b3cc351f..4b5737c776 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateSDNCNetworkResource.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateSDNCNetworkResource.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. @@ -25,14 +25,19 @@ import org.camunda.bpm.engine.delegate.BpmnError import org.camunda.bpm.engine.delegate.DelegateExecution import org.json.JSONObject import org.json.XML +import org.onap.aai.domain.yang.ServiceInstance +import org.onap.aai.domain.yang.ServiceInstances import org.onap.so.bpmn.common.recipe.ResourceInput import org.onap.so.bpmn.common.resource.ResourceRequestBuilder 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.core.json.JsonUtils +import org.onap.so.client.aai.AAIObjectPlurals +import org.onap.so.client.aai.AAIResourcesClient +import org.onap.so.client.aai.entities.uri.AAIResourceUri +import org.onap.so.client.aai.entities.uri.AAIUriFactory import org.onap.so.logger.MsoLogger -import org.onap.so.rest.APIResponse import static org.apache.commons.lang3.StringUtils.* @@ -50,7 +55,7 @@ public class CreateSDNCNetworkResource extends AbstractServiceTaskProcessor { JsonUtils jsonUtil = new JsonUtils() public void preProcessRequest(DelegateExecution execution){ - + msoLogger.info(" ***** Started preProcessRequest *****") try { @@ -208,27 +213,20 @@ public class CreateSDNCNetworkResource extends AbstractServiceTaskProcessor { def vpnName = StringUtils.containsIgnoreCase(modelName, "sotnvpnattachment") ? "sotnvpnattachmentvf_sotncondition_sotnVpnName" : "sdwanvpnattachmentvf_sdwancondition_sdwanVpnName" String parentServiceName = jsonUtil.getJsonValueForKey(resourceInputObj.getRequestsInputs(), vpnName) - AaiUtil aaiUtil = new AaiUtil(this) - String aai_endpoint = execution.getVariable("URN_aai_endpoint") - String customerUri = aaiUtil.getBusinessCustomerUri(execution) + "/" + customer - String aai_service_query_url = aai_endpoint + customerUri + "/service-subscriptions/service-subscription/" + serviceType + "/service-instances?service-instance-name=" + parentServiceName + AAIResourcesClient client = new AAIResourcesClient() + AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectPlurals.SERVICE_INSTANCE, customer, serviceType).queryParam("service-instance-name", parentServiceName) + ServiceInstances sis = client.get(uri).asBean(ServiceInstances.class).get() + ServiceInstance si = sis.getServiceInstance().get(0) - APIResponse aaiResponse = aaiUtil.executeAAIGetCall(execution, aai_service_query_url) - def parentServiceInstanceId = getParentServiceInstnaceId(aaiResponse) - execution.setVariable("parentServiceInstanceId", parentServiceInstanceId) - break + def parentServiceInstanceId = si.getServiceInstanceId() + execution.setVariable("parentServiceInstanceId", parentServiceInstanceId) + break default: break } } - private String getParentServiceInstnaceId(APIResponse aaiResponse) { - String response = aaiResponse.getResponseBodyAsString() - def xmlResp = new XmlParser().parseText(response) - return "${xmlResp?."service-instance"[0]?."service-instance-id"[0]?.text()}" - } - /** * Pre Process the BPMN Flow Request * Includes: @@ -388,7 +386,7 @@ public class CreateSDNCNetworkResource extends AbstractServiceTaskProcessor { // for SDWANConnectivity and SOTNConnectivity: default: sdncTopologyCreateRequest = """<aetgt:SDNCAdapterWorkflowRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1" - xmlns:sdncadapter="http://org.onap.so/workflow/sdnc/adapter/schema/v1" + xmlns:sdncadapter="http://org.onap.so/workflow/sdnc/adapter/schema/v1" xmlns:sdncadapterworkflow="http://org.onap/so/workflow/schema/v1"> <sdncadapter:RequestHeader> <sdncadapter:RequestId>${hdrRequestId}</sdncadapter:RequestId> 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 26f12831bd..e3702f1014 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 @@ -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,24 +18,23 @@ * ============LICENSE_END========================================================= */ -package org.onap.so.bpmn.infrastructure.scripts; +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.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.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.ExceptionUtil -import org.onap.so.bpmn.common.scripts.MsoUtils -import org.onap.so.bpmn.core.json.JsonUtils +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.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 groovy.json.* +import javax.ws.rs.core.Response +import org.onap.so.utils.TargetEntity /** * This groovy class supports the <class>DoCreateVFCNetworkServiceInstance.bpmn</class> process. @@ -46,9 +45,9 @@ public class CreateVFCNSResource extends AbstractServiceTaskProcessor { String vfcUrl = "/vfc/rest/v1/vfcadapter" - + String host = "http://mso.mso.testlab.openecomp.org:8080" - + ExceptionUtil exceptionUtil = new ExceptionUtil() JsonUtils jsonUtil = new JsonUtils() @@ -116,7 +115,7 @@ public class CreateVFCNSResource extends AbstractServiceTaskProcessor { execution.setVariable("nsOperationKey", nsOperationKey); execution.setVariable("nsParameters", nsParameters) execution.setVariable("nsServiceModelUUID", nsServiceModelUUID); - + } catch (BpmnError e) { throw e; @@ -150,9 +149,9 @@ public class CreateVFCNSResource extends AbstractServiceTaskProcessor { "additionalParamForNs":${requestInputs} } }""" - APIResponse apiResponse = postRequest(execution, host + vfcUrl + "/ns", reqBody) - String returnCode = apiResponse.getStatusCode() - String aaiResponseAsString = apiResponse.getResponseBodyAsString() + Response apiResponse = postRequest(execution, host + vfcUrl + "/ns", reqBody) + String returnCode = apiResponse.getStatus() + String aaiResponseAsString = apiResponse.readEntity(String.class) String nsInstanceId = ""; if(returnCode== "200" || returnCode == "201"){ nsInstanceId = jsonUtil.getJsonValue(aaiResponseAsString, "nsInstanceId") @@ -178,9 +177,9 @@ public class CreateVFCNSResource extends AbstractServiceTaskProcessor { }""" String nsInstanceId = execution.getVariable("nsInstanceId") String url = host + vfcUrl + "/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") @@ -197,9 +196,9 @@ public class CreateVFCNSResource extends AbstractServiceTaskProcessor { String jobId = execution.getVariable("jobId") String nsOperationKey = execution.getVariable("nsOperationKey"); String url = host + vfcUrl + "/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") @@ -209,12 +208,12 @@ public class CreateVFCNSResource extends AbstractServiceTaskProcessor { } /** - * delay 5 sec + * delay 5 sec */ public void timeDelay(DelegateExecution execution) { try { Thread.sleep(5000); - } catch(InterruptedException e) { + } catch(InterruptedException e) { msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Time Delay exception" + e , "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, ""); } } @@ -232,53 +231,17 @@ public class CreateVFCNSResource extends AbstractServiceTaskProcessor { String globalSubscriberId = execution.getVariable("globalSubscriberId") String serviceType = execution.getVariable("serviceType") String serviceId = execution.getVariable("serviceInstanceId") - String addRelationPayload = """<relationship xmlns="http://org.openecomp.aai.inventory/v11"> - <related-to>service-instance</related-to> - <related-link>/aai/v11/business/customers/customer/${globalSubscriberId}/service-subscriptions/service-subscription/${serviceType}/service-instances/service-instance/${nsInstanceId}</related-link> - <relationship-data> - <relationship-key>customer.global-customer-id</relationship-key> - <relationship-value>${MsoUtils.xmlEscape(globalSubscriberId)}</relationship-value> - </relationship-data> - <relationship-data> - <relationship-key>service-subscription.service-type</relationship-key> - <relationship-value>${MsoUtils.xmlEscape(serviceType)}</relationship-value> - </relationship-data> - <relationship-data> - <relationship-key>service-instance.service-instance-id</relationship-key> - <relationship-value>${MsoUtils.xmlEscape(nsInstanceId)}</relationship-value> - </relationship-data> - </relationship>""" - String endpoint = execution.getVariable("URN_aai_endpoint") - msoLogger.info("Add Relationship req:\n" + addRelationPayload) - String url = endpoint + "/aai/v11/business/customers/customer/" + globalSubscriberId + "/service-subscriptions/service-subscription/" + serviceType + "/service-instances/service-instance/" + serviceId + "/relationship-list/relationship" - APIResponse aaiRsp = executeAAIPutCall(execution, url, addRelationPayload) - msoLogger.info("aai response status code:" + aaiRsp.getStatusCode()) - msoLogger.info("aai response content:" + aaiRsp.getResponseBodyAsString()) - msoLogger.info(" *****Exit addNSRelationship *****") - } - - public APIResponse executeAAIPutCall(DelegateExecution execution, String url, String payload){ - msoLogger.trace("Started Execute AAI Put Process ") - APIResponse apiResponse = null + + AAIResourceUri nsUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE,globalSubscriberId,serviceType,nsInstanceId) + AAIResourceUri relatedServiceUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE,globalSubscriberId,serviceType,serviceId) + try{ - String uuid = utils.getRequestID() - msoLogger.info("Generated uuid is: " + uuid) - msoLogger.info("URL to be used is: " + url) - String userName = execution.getVariable("URN_aai_auth") - String password = execution.getVariable("URN_mso_msoKey") - String basicAuthCred = utils.getBasicAuth(userName,password) - RESTConfig config = new RESTConfig(url); - RESTClient client = new RESTClient(config).addHeader("X-FromAppId", "MSO").addHeader("X-TransactionId", uuid).addHeader("Content-Type", "application/xml").addHeader("Accept","application/xml"); - if (basicAuthCred != null && !"".equals(basicAuthCred)) { - client.addAuthorizationHeader(basicAuthCred) - } - apiResponse = client.httpPut(payload) - msoLogger.trace("Completed Execute AAI Put Process ") + getAAIClient().connect(nsUri,relatedServiceUri) + msoLogger.info("NS relationship to Service added successfully") }catch(Exception e){ - msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception occured while executing AAI Put Call.", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, e); + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception occured while Creating NS relationship.", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, e.getMessage(),e); throw new BpmnError("MSOWorkflowException") } - return apiResponse } /** @@ -286,23 +249,29 @@ public class CreateVFCNSResource extends AbstractServiceTaskProcessor { * url: the url of the request * requestBody: the body of the request */ - private APIResponse postRequest(DelegateExecution execution, String url, String requestBody){ + private Response postRequest(DelegateExecution execution, String urlString, String requestBody){ msoLogger.trace("Started Execute VFC adapter Post Process ") msoLogger.info("url:"+url +"\nrequestBody:"+ requestBody) - APIResponse apiResponse = null + Response apiResponse = null try{ - RESTConfig config = new RESTConfig(url); - RESTClient client = new RESTClient(config).addHeader("Content-Type", "application/json").addHeader("Accept","application/json").addHeader("Authorization","Basic QlBFTENsaWVudDpwYXNzd29yZDEk"); - apiResponse = client.httpPost(requestBody) - msoLogger.info("response code:"+ apiResponse.getStatusCode() +"\nresponse body:"+ apiResponse.getResponseBodyAsString()) + + URL url = new URL(urlString); + + HttpClient httpClient = new HttpClient(url, "application/json", TargetEntity.VNF_ADAPTER) + httpClient.addAdditionalHeader("Accept", "application/json") + httpClient.addAdditionalHeader("Authorization", "Basic QlBFTENsaWVudDpwYXNzd29yZDEk") + + apiResponse = httpClient.post(requestBody) + + msoLogger.info("response code:"+ apiResponse.getStatus() +"\nresponse body:"+ apiResponse.readEntity(String.class)) msoLogger.trace("Completed Execute VF-C adapter Post Process ") }catch(Exception e){ msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception occured while executing AAI Post Call.", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, e); throw new BpmnError("MSOWorkflowException") - } + } return apiResponse } - + public void sendSyncResponse (DelegateExecution execution) { def isDebugEnabled=execution.getVariable("isDebugLogEnabled") utils.log("DEBUG", " *** sendSyncResponse *** ", isDebugEnabled) 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/Delete3rdONAPE2EServiceInstance.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/Delete3rdONAPE2EServiceInstance.groovy index 56e5be04a5..46c0c4bfa0 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 @@ -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,39 +20,31 @@ package org.onap.so.bpmn.infrastructure.scripts +import javax.ws.rs.NotFoundException +import javax.ws.rs.core.Response + +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.json.XML - -import static org.apache.commons.lang3.StringUtils.* -import groovy.xml.XmlUtil +import org.onap.aai.domain.yang.SpPartner +import org.onap.so.bpmn.common.recipe.ResourceInput +import org.onap.so.bpmn.common.resource.ResourceRequestBuilder +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.ExternalAPIUtil -import org.onap.so.bpmn.common.scripts.AaiUtil -import org.onap.so.bpmn.common.scripts.MsoUtils -import org.onap.so.bpmn.common.recipe.ResourceInput -import org.onap.so.bpmn.common.resource.ResourceRequestBuilder -import org.onap.so.bpmn.core.WorkflowException import org.onap.so.bpmn.core.json.JsonUtils -import org.onap.so.bpmn.infrastructure.workflow.serviceTask.client.builder.AbstractBuilder -import org.onap.so.rest.APIResponse -import org.onap.so.bpmn.infrastructure.workflow.service.ServicePluginFactory -import java.util.UUID +import org.onap.so.client.aai.AAIObjectType +import org.onap.so.client.aai.AAIResourcesClient +import org.onap.so.client.aai.entities.uri.AAIResourceUri +import org.onap.so.client.aai.entities.uri.AAIUriFactory import org.onap.so.logger.MsoLogger -import org.camunda.bpm.engine.runtime.Execution -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 -import org.onap.so.rest.RESTClient -import org.onap.so.rest.RESTConfig - /** * This groovy class supports the <class>Delete3rdONAPE2EServiceInstance.bpmn</class> process. - * flow for Delete 3rdONAPE2EServiceInstance in 3rdONAP + * flow for Delete 3rdONAPE2EServiceInstance in 3rdONAP */ public class Delete3rdONAPE2EServiceInstance extends AbstractServiceTaskProcessor { @@ -79,33 +71,31 @@ public class Delete3rdONAPE2EServiceInstance extends AbstractServiceTaskProcesso ResourceInput resourceInputObj = ResourceRequestBuilder.getJsonObject(resourceInput, ResourceInput.class) // set local resourceInput execution.setVariable(Prefix + "ResourceInput", resourceInputObj) - + String resourceInstanceId = resourceInputObj.getResourceInstancenUuid() String sppartnerId = resourceInstanceId execution.setVariable(Prefix + "SppartnerId", sppartnerId) - + // Get Sppartner from AAI - AaiUtil aaiUriUtil = new AaiUtil() - String aai_uri = aaiUriUtil.getBusinessSPPartnerUri(execution) - String namespace = aaiUriUtil.getNamespaceFromUri(aai_uri) - String aai_endpoint = execution.getVariable("URN_aai_endpoint") - String serviceAaiPath = "${aai_endpoint}${aai_uri}/" + UriUtils.encode(sppartnerId,"UTF-8") - execution.setVariable(Prefix + "ServiceAaiPath", serviceAaiPath) - + AaiUtil aaiUriUtil = new AaiUtil(this) + AAIResourceUri spPartner = AAIUriFactory.createResourceUri(AAIObjectType.SP_PARTNER, sppartnerId) + String spPartnerUri = aaiUriUtil.createAaiUri(spPartner) + execution.setVariable(Prefix + "ServiceAaiPath", spPartnerUri) + getSPPartnerInAAI(execution) - + String callSource = "UUI" String sppartnerUrl = "" if(execution.hasVariable(Prefix + "CallSource")) { callSource = execution.getVariable(Prefix + "CallSource") sppartnerUrl = execution.getVariable(Prefix + "SppartnerUrl") } - - boolean is3rdONAPExist = false - if(!isBlank(sppartnerUrl)) { + + boolean is3rdONAPExist = false + if(!isBlank(sppartnerUrl)) { is3rdONAPExist = true } - + execution.setVariable("Is3rdONAPExist", is3rdONAPExist) execution.setVariable(Prefix + "ServiceInstanceId", resourceInputObj.getServiceInstanceId()) execution.setVariable("mso-request-id", requestId) @@ -122,7 +112,7 @@ public class Delete3rdONAPE2EServiceInstance extends AbstractServiceTaskProcesso public void checkLocallCall (DelegateExecution execution) { msoLogger.info(" ***** Started checkLocallCall *****") - + boolean isLocalCall = true String callSource = execution.getVariable(Prefix + "CallSource") if("ExternalAPI".equalsIgnoreCase(callSource)) { @@ -136,7 +126,7 @@ public class Delete3rdONAPE2EServiceInstance extends AbstractServiceTaskProcesso String msg = "" try { - ResourceInput resourceInputObj = execution.getVariable(Prefix + "ResourceInput") + ResourceInput resourceInputObj = execution.getVariable(Prefix + "ResourceInput") String globalSubscriberId = resourceInputObj.getGlobalSubscriberId() if (isBlank(globalSubscriberId)) { @@ -154,15 +144,15 @@ public class Delete3rdONAPE2EServiceInstance extends AbstractServiceTaskProcesso } execution.setVariable("serviceType", serviceType) msoLogger.info( "serviceType:" + serviceType) - - String operationId = resourceInputObj.getOperationId() + + String operationId = resourceInputObj.getOperationId() if (isBlank(operationId)) { msg = "Input operationId is null" msoLogger.error( msg) } execution.setVariable("operationId", operationId) msoLogger.info( "operationId:" + operationId) - + String resourceName = resourceInputObj.getResourceInstanceName() if (isBlank(resourceName)) { msg = "Input resourceName is null" @@ -170,7 +160,7 @@ public class Delete3rdONAPE2EServiceInstance extends AbstractServiceTaskProcesso } execution.setVariable("resourceName", resourceName) msoLogger.info("resourceName:" + resourceName) - + String resourceTemplateId = resourceInputObj.getResourceModelInfo().getModelCustomizationUuid() if (isBlank(resourceTemplateId)) { msg = "Input resourceTemplateId is null" @@ -223,11 +213,11 @@ public class Delete3rdONAPE2EServiceInstance extends AbstractServiceTaskProcesso public void prepare3rdONAPRequest(DelegateExecution execution) { msoLogger.info(" ***** Started prepare3rdONAPRequest *****") - + String sppartnerUrl = execution.getVariable(Prefix + "SppartnerUrl") String extAPIPath = sppartnerUrl + '/serviceOrder' execution.setVariable("ExternalAPIURL", extAPIPath) - + // ExternalAPI message format String externalId = execution.getVariable("resourceName") String category = "E2E Service" @@ -245,10 +235,10 @@ public class Delete3rdONAPE2EServiceInstance extends AbstractServiceTaskProcesso String serviceName = "" String serviceType = execution.getVariable("serviceType") String serviceId = execution.getVariable(Prefix + "SppartnerId") - + queryServicefrom3rdONAP(execution) - String serviceSpecificationId = execution.getVariable(Prefix + "ServiceSpecificationId") - + String serviceSpecificationId = execution.getVariable(Prefix + "ServiceSpecificationId") + Map<String, String> valueMap = new HashMap<>() valueMap.put("externalId", '"' + externalId + '"') valueMap.put("category", '"' + category + '"') @@ -266,20 +256,20 @@ public class Delete3rdONAPE2EServiceInstance extends AbstractServiceTaskProcesso valueMap.put("serviceId", '"' + serviceId + '"') valueMap.put("serviceName", "null") valueMap.put("serviceUuId", '"' + serviceSpecificationId + '"') - + ExternalAPIUtil externalAPIUtil = new ExternalAPIUtil() - + valueMap.put("_requestInputs_", "") - + String payload = externalAPIUtil.setTemplate(ExternalAPIUtil.PostServiceOrderRequestsTemplate, valueMap) execution.setVariable(Prefix + "Payload", payload) msoLogger.info( "Exit " + prepare3rdONAPRequest) } - + private void queryServicefrom3rdONAP(DelegateExecution execution) { msoLogger.info(" ***** Started queryServicefrom3rdONAP *****") - + String globalSubscriberId = execution.getVariable("globalSubscriberId") String SppartnerServiceId = execution.getVariable(Prefix + "SppartnerId") @@ -290,17 +280,17 @@ public class Delete3rdONAPE2EServiceInstance extends AbstractServiceTaskProcesso ExternalAPIUtil externalAPIUtil = new ExternalAPIUtil() - APIResponse response = externalAPIUtil.executeExternalAPIGetCall(execution, extAPIPath) + Response response = externalAPIUtil.executeExternalAPIGetCall(execution, extAPIPath) - int responseCode = response.getStatusCode() + int responseCode = response.getStatus() execution.setVariable(Prefix + "GetServiceResponseCode", responseCode) msoLogger.debug("Get Service response code is: " + responseCode) - String extApiResponse = response.getResponseBodyAsString() + String extApiResponse = response.readEntity(String.class) - execution.setVariable(Prefix + "GetServiceResponse", extApiResponse) + execution.setVariable(Prefix + "GetServiceResponse", extApiResponse) msoLogger.debug("queryServicefrom3rdONAP response body is: " + extApiResponse) - + //Process Response //200 OK 201 CREATED 202 ACCEPTED if(responseCode == 200 || responseCode == 201 || responseCode == 202 ) { @@ -320,27 +310,27 @@ public class Delete3rdONAPE2EServiceInstance extends AbstractServiceTaskProcesso msoLogger.error("Get Service Received a Bad Response Code. Response Code is: " + responseCode) // exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Get Service Received a bad response from 3rdONAP External API") } - + msoLogger.info( "Exit " + queryServicefrom3rdONAP) } public void doDeleteE2ESIin3rdONAP(DelegateExecution execution) { msoLogger.info(" ***** Started doDeleteE2ESIin3rdONAP *****") - + String extAPIPath = execution.getVariable("ExternalAPIURL") String payload = execution.getVariable(Prefix + "Payload") msoLogger.debug("doDeleteE2ESIin3rdONAP externalAPIURL is: " + extAPIPath) msoLogger.debug("doDeleteE2ESIin3rdONAP payload is: " + payload) - + ExternalAPIUtil externalAPIUtil = new ExternalAPIUtil() - APIResponse response = externalAPIUtil.executeExternalAPIPostCall(execution, extAPIPath, payload) + Response response = externalAPIUtil.executeExternalAPIPostCall(execution, extAPIPath, payload) - int responseCode = response.getStatusCode() + int responseCode = response.getStatus() execution.setVariable(Prefix + "PostServiceOrderResponseCode", responseCode) msoLogger.debug("Post ServiceOrder response code is: " + responseCode) - String extApiResponse = response.getResponseBodyAsString() + String extApiResponse = response.readEntity(String.class) JSONObject responseObj = new JSONObject(extApiResponse) execution.setVariable(Prefix + "PostServiceOrderResponse", extApiResponse) @@ -360,31 +350,31 @@ public class Delete3rdONAPE2EServiceInstance extends AbstractServiceTaskProcesso msoLogger.error("Post ServiceOrder Received a Bad Response Code. Response Code is: " + responseCode) exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Post ServiceOrder Received a bad response from 3rdONAP External API") } - + msoLogger.info( "Exit " + doDeleteE2ESIin3rdONAP) } - + public void getE2ESIProgressin3rdONAP(DelegateExecution execution) { msoLogger.info(" ***** Started getE2ESIProgressin3rdONAP *****") - + String extAPIPath = execution.getVariable("ExternalAPIURL") extAPIPath += "/" + execution.getVariable("ServiceOrderId") msoLogger.debug("getE2ESIProgressin3rdONAP delete externalAPIURL is: " + extAPIPath) - + ExternalAPIUtil externalAPIUtil = new ExternalAPIUtil() - APIResponse response = externalAPIUtil.executeExternalAPIGetCall(execution, extAPIPath) + Response response = externalAPIUtil.executeExternalAPIGetCall(execution, extAPIPath) - int responseCode = response.getStatusCode() + int responseCode = response.getStatus() execution.setVariable(Prefix + "GetServiceOrderResponseCode", responseCode) msoLogger.debug("Get ServiceOrder response code is: " + responseCode) - String extApiResponse = response.getResponseBodyAsString() + String extApiResponse = response.readEntity(String.class) JSONObject responseObj = new JSONObject(extApiResponse) execution.setVariable(Prefix + "GetServiceOrderResponse", extApiResponse) - - utils.log("DEBUG", "getE2ESIProgressin3rdONAP delete response body is: " + extApiResponse, isDebugEnabled) + + utils.log("DEBUG", "getE2ESIProgressin3rdONAP delete response body is: " + extApiResponse) //Process Response //200 OK 201 CREATED 202 ACCEPTED if(responseCode == 200 || responseCode == 201 || responseCode == 202 ) @@ -443,17 +433,17 @@ public class Delete3rdONAPE2EServiceInstance extends AbstractServiceTaskProcesso execution.setVariable("statusDescription", "Delete Service Order Status is unknown") } } - else{ + else{ msoLogger.debug("Get ServiceOrder Received a Bad Response Code. Response Code is: " + responseCode) execution.setVariable("progress", 100) execution.setVariable("status", "error") execution.setVariable("statusDescription", "Get Delete ServiceOrder Received a bad response") exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Get Delete ServiceOrder Received a bad response from 3rdONAP External API") - } - + } + msoLogger.info( "Exit " + getE2ESIProgressin3rdONAP) } - + /** * delay 5 sec */ @@ -466,86 +456,53 @@ public class Delete3rdONAPE2EServiceInstance extends AbstractServiceTaskProcesso } private void getSPPartnerInAAI(DelegateExecution execution) { - msoLogger.info(" ***** Started getSPPartnerInAAI *****") - - AaiUtil aaiUriUtil = new AaiUtil() - String serviceAaiPath = execution.getVariable(Prefix + "ServiceAaiPath") - APIResponse response = aaiUriUtil.executeAAIGetCall(execution, serviceAaiPath) - int responseCode = response.getStatusCode() - execution.setVariable(Prefix + "GetSppartnerResponseCode", responseCode) - msoLogger.debug(" Get sppartner response code is: " + responseCode) - - String aaiResponse = response.getResponseBodyAsString() - aaiResponse = StringEscapeUtils.unescapeXml(aaiResponse) - aaiResponse = aaiResponse.replaceAll("&", "&") - execution.setVariable(Prefix + "GetSppartnerResponse", aaiResponse) + msoLogger.info(" ***** Started getSPPartnerInAAI *****") + String id = execution.getVariable(Prefix + "SppartnerId") + + AAIResourcesClient client = new AAIResourcesClient() + AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.SP_PARTNER, id) + SpPartner sp = client.get(uri).asBean(SpPartner.class).get() + + msoLogger.debug("GET sppartner Received a Good Response") + execution.setVariable(Prefix + "SuccessIndicator", true) + execution.setVariable(Prefix + "FoundIndicator", true) + + String sppartnerId = sp.getSpPartnerId() + execution.setVariable(Prefix + "SppartnerId", sppartnerId) + msoLogger.debug(" SppartnerId is: " + sppartnerId) + String sppartnerUrl = sp.getUrl() + execution.setVariable(Prefix + "SppartnerUrl", sppartnerUrl) + msoLogger.debug(" SppartnerUrl is: " + sppartnerUrl) + String callSource = sp.getCallsource() + execution.setVariable(Prefix + "CallSource", callSource) + msoLogger.debug(" CallSource is: " + callSource) + String sppartnerVersion = sp.getResourceVersion() + execution.setVariable(Prefix + "SppartnerVersion", sppartnerVersion) + msoLogger.debug(" Resource Version is: " + sppartnerVersion) + - //Process Response - if(responseCode == 200 || responseCode == 201 || responseCode == 202 ) - //200 OK 201 CREATED 202 ACCEPTED - { - msoLogger.debug("GET sppartner Received a Good Response") - execution.setVariable(Prefix + "SuccessIndicator", true) - execution.setVariable(Prefix + "FoundIndicator", true) - - String sppartnerId = utils.getNodeText1(aaiResponse, "sp-partner-id") - execution.setVariable(Prefix + "SppartnerId", sppartnerId) - msoLogger.debug(" SppartnerId is: " + sppartnerId) - String sppartnerUrl = utils.getNodeText1(aaiResponse, "url") - execution.setVariable(Prefix + "SppartnerUrl", sppartnerUrl) - msoLogger.debug(" SppartnerUrl is: " + sppartnerUrl) - String callSource = utils.getNodeText1(aaiResponse, "callsource") - execution.setVariable(Prefix + "CallSource", callSource) - msoLogger.debug(" CallSource is: " + callSource) - String sppartnerVersion = utils.getNodeText1(aaiResponse, "resource-version") - execution.setVariable(Prefix + "SppartnerVersion", sppartnerVersion) - msoLogger.debug(" Resource Version is: " + sppartnerVersion) - } - else - { - msoLogger.debug("Get sppartner Received a Bad Response Code. Response Code is: " + responseCode) -// exceptionUtil.MapAAIExceptionToWorkflowExceptionGeneric(execution, aaiResponse, responseCode) -// throw new BpmnError("MSOWorkflowException") - } - msoLogger.info( "Exit " + getSPPartnerInAAI) } - + public void deleteSPPartnerInAAI(DelegateExecution execution) { msoLogger.info(" ***** Started deleteSPPartnerInAAI *****") - + String sppartnerId = execution.getVariable(Prefix + "SppartnerId") String sppartnerUrl = execution.getVariable(Prefix + "SppartnerUrl") String sppartnerVersion = execution.getVariable(Prefix + "SppartnerVersion") - - AaiUtil aaiUriUtil = new AaiUtil() - String serviceAaiPath = execution.getVariable(Prefix + "ServiceAaiPath") + "?resource-version=${sppartnerVersion}" - APIResponse response = aaiUriUtil.executeAAIDeleteCall(execution, serviceAaiPath) - int responseCode = response.getStatusCode() - execution.setVariable(Prefix + "DeleteSppartnerResponseCode", responseCode) - msoLogger.debug(" Get sppartner response code is: " + responseCode) - - String aaiResponse = response.getResponseBodyAsString() - aaiResponse = StringEscapeUtils.unescapeXml(aaiResponse) - execution.setVariable(Prefix + "DeleteSppartnerResponse", aaiResponse) - //Process Response - if(responseCode == 200 || responseCode == 204 ) - { + AAIResourcesClient client = new AAIResourcesClient() + AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.SP_PARTNER, sppartnerId) + try { + client.delete(uri) msoLogger.debug("Delete sppartner Received a Good Response") execution.setVariable(Prefix + "SuccessIndicator", true) - } - else if(responseCode == 404){ + } catch (NotFoundException e) { msoLogger.debug(" Delete sppartner Received a Not Found (404) Response") execution.setVariable(Prefix + "FoundIndicator", false) } - else - { - msoLogger.debug("Delete sppartner Received a Bad Response Code. Response Code is: " + responseCode) -// exceptionUtil.MapAAIExceptionToWorkflowExceptionGeneric(execution, aaiResponse, responseCode) -// throw new BpmnError("MSOWorkflowException") - } - + msoLogger.debug("Delete sppartner Received a Good Response") + msoLogger.info( "Exit " + deleteSPPartnerInAAI) } @@ -553,7 +510,7 @@ public class Delete3rdONAPE2EServiceInstance extends AbstractServiceTaskProcesso def dbAdapterEndpoint = execution.getVariable("URN_mso_adapters_openecomp_db_endpoint") execution.setVariable("CVFMI_dbAdapterEndpoint", dbAdapterEndpoint) execution.setVariable("CVFMI_updateResOperStatusRequest", body) - } + } public void postProcess(DelegateExecution execution){ msoLogger.info(" ***** Started postProcess *****") diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteDeviceResource.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteDeviceResource.groovy index 71ce28d7d3..82be3e6a0c 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteDeviceResource.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteDeviceResource.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. @@ -29,23 +29,23 @@ import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor import org.onap.so.bpmn.common.scripts.ExceptionUtil import org.onap.so.bpmn.common.recipe.ResourceInput; import org.onap.so.bpmn.common.resource.ResourceRequestBuilder +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.bpmn.infrastructure.workflow.serviceTask.client.builder.AbstractBuilder +import org.onap.so.client.HttpClient import org.onap.so.logger.MsoLogger -import org.onap.so.rest.APIResponse import org.onap.so.bpmn.common.scripts.SDNCAdapterUtils import java.util.UUID; - +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 javax.ws.rs.core.MediaType import org.apache.commons.codec.binary.Base64; import org.springframework.web.util.UriUtils -import org.onap.so.rest.RESTClient -import org.onap.so.rest.RESTConfig -import org.onap.so.rest.APIResponse; +import org.onap.so.utils.TargetEntity import org.onap.so.bpmn.common.scripts.AaiUtil /** @@ -106,20 +106,29 @@ public class DeleteDeviceResource extends AbstractServiceTaskProcessor { private void getDeviceInAAI(DelegateExecution execution) { msoLogger.info(" ***** Started getDeviceInAAI *****") - + String deviceId = execution.getVariable(Prefix + "DeviceId") AaiUtil aaiUriUtil = new AaiUtil() String aai_uri = aaiUriUtil.getNetworkDeviceUri(execution) String aai_endpoint = execution.getVariable("URN_aai_endpoint") String serviceAaiPath = "${aai_endpoint}${aai_uri}/" + UriUtils.encode(deviceId,"UTF-8") execution.setVariable(Prefix + "ServiceAaiPath", serviceAaiPath) - - APIResponse response = aaiUriUtil.executeAAIGetCall(execution, serviceAaiPath) - int responseCode = response.getStatusCode() + + URL url = new URL(serviceAaiPath) + HttpClient client = new HttpClient(url, MediaType.APPLICATION_XML, TargetEntity.AAI) + client.addBasicAuthHeader(UrnPropertiesReader.getVariable("aai.auth", execution), UrnPropertiesReader.getVariable("mso.msoKey", execution)) + client.addAdditionalHeader("X-FromAppId", "MSO") + client.addAdditionalHeader("X-TransactionId", utils.getRequestID()) + client.addAdditionalHeader("Accept", MediaType.APPLICATION_XML) + Response response = client.get() + + + + int responseCode = response.getStatus() execution.setVariable(Prefix + "GetDeviceResponseCode", responseCode) msoLogger.debug(" Get device response code is: " + responseCode) - String aaiResponse = response.getResponseBodyAsString() + String aaiResponse = response.readEntity(String.class) aaiResponse = StringEscapeUtils.unescapeXml(aaiResponse) aaiResponse = aaiResponse.replaceAll("&", "&") execution.setVariable(Prefix + "GetDeviceResponse", aaiResponse) @@ -131,8 +140,8 @@ public class DeleteDeviceResource extends AbstractServiceTaskProcessor { msoLogger.debug("GET Device Received a Good Response") execution.setVariable(Prefix + "SuccessIndicator", true) execution.setVariable(Prefix + "FoundIndicator", true) - - String devClass = utils.getNodeText1(aaiResponse, "device_class") + + String devClass = utils.getNodeText(aaiResponse, "device_class") execution.setVariable(Prefix + "DeviceClass", devClass) msoLogger.debug(" DeviceClass is: " + devClass) 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 98605fea8b..9c9ed933e0 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. @@ -40,9 +40,6 @@ 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 org.onap.so.rest.APIResponse; -import org.onap.so.rest.RESTClient -import org.onap.so.rest.RESTConfig import java.util.List; import java.util.UUID; @@ -88,48 +85,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){ @@ -139,7 +136,7 @@ public class DoCompareModelVersions extends AbstractServiceTaskProcessor { } utils.log("INFO"," ***** Exit preProcessRequest *****", isDebugEnabled) } - + public void prepareDecomposeService_Target(DelegateExecution execution) { def isDebugEnabled=execution.getVariable("isDebugLogEnabled") @@ -153,7 +150,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) @@ -166,8 +163,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) @@ -177,7 +174,7 @@ public class DoCompareModelVersions extends AbstractServiceTaskProcessor { exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) } } - + public void prepareDecomposeService_Original(DelegateExecution execution) { def isDebugEnabled=execution.getVariable("isDebugLogEnabled") @@ -191,7 +188,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) @@ -204,8 +201,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) @@ -214,45 +211,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 ebd622ca51..5b7d38dfb6 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 @@ -28,7 +28,6 @@ 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.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 @@ -38,6 +37,7 @@ 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.json.JsonUtils +import org.onap.so.bpmn.infrastructure.workflow.service.ServicePluginFactory import org.onap.so.client.aai.AAIObjectType import org.onap.so.client.aai.AAIResourcesClient import org.onap.so.client.aai.entities.AAIResultWrapper @@ -46,7 +46,7 @@ import org.onap.so.bpmn.infrastructure.workflow.service.ServicePluginFactory 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 org.onap.so.bpmn.core.UrnPropertiesReader @@ -461,10 +461,10 @@ public class DoCreateE2EServiceInstance extends AbstractServiceTaskProcessor { uuiRequest = ServicePluginFactory.getInstance().doProcessSiteLocation(serviceDecomposition, uuiRequest); execution.setVariable("uuiRequest", uuiRequest) execution.setVariable("serviceDecomposition", serviceDecomposition) - + msoLogger.trace("======== COMPLETED doProcessSiteLocation Process ======== ") } - + // Allocate cross link TPs(terminal points) for sotn network only public void doTPResourcesAllocation(DelegateExecution execution){ msoLogger.trace("======== Start doTPResourcesAllocation Process ======== ") diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateE2EServiceInstanceRollback.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateE2EServiceInstanceRollback.groovy index 82355beed2..4f00a64ecb 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateE2EServiceInstanceRollback.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateE2EServiceInstanceRollback.groovy @@ -32,9 +32,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 import org.onap.so.bpmn.common.scripts.ExceptionUtil; 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..c9497165c4 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,27 @@ 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") - 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 +560,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 +632,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 +698,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() @@ -978,75 +769,86 @@ public class DoCreateNetworkInstance extends AbstractServiceTaskProcessor { try { // get variables String networkId = execution.getVariable(Prefix + "networkId") - networkId = UriUtils.encode(networkId,"UTF-8") String requeryIdAAIResponse = execution.getVariable(Prefix + "requeryIdAAIResponse") String createNetworkResponse = execution.getVariable(Prefix + "createNetworkResponse") - // Prepare url - AaiUtil aaiUriUtil = new AaiUtil(this) - - 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) + L3Network l3Network = new L3Network() + if (utils.nodeExists(requeryIdAAIResponse, 'heat-stack-id')) { + } else { + if (utils.nodeExists(createNetworkResponse, 'networkStackId')) { + l3Network.setHeatStackId(utils.getNodeText(createNetworkResponse, 'networkStackId')) } - msoLogger.debug(Prefix + "isPONR" + ": " + execution.getVariable(Prefix + "isPONR")) + } + if (utils.nodeExists(requeryIdAAIResponse, 'neutron-network-id')) { } 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(createNetworkResponse, 'neutronNetworkId')) { + l3Network.setNeutronNetworkId(utils.getNodeText(createNetworkResponse, 'neutronNetworkId')) + } + } + if (utils.nodeExists(requeryIdAAIResponse, 'contrail-network-fqdn')) { + } else { + if (utils.nodeExists(createNetworkResponse, 'networkFqdn')) { + l3Network.setContrailNetworkFqdn(utils.getNodeText(createNetworkResponse, '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(createNetworkResponse, 'orchestration-status') + if(status.equals("pending-create") || status.equals("PendingCreate")){ + l3Network.setOperationalStatus("Created") + }else{ + l3Network.setOperationalStatus("Active") + } + + AAIResourcesClient client = new AAIResourcesClient() + AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.L3_NETWORK, networkId) + client.update(uri, l3Network) + + String subnetsXml = utils.getNodeXml(requeryIdAAIResponse, "subnets") + InputSource source = new InputSource(new StringReader(subnetsXml)); + DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); + docFactory.setNamespaceAware(true) + DocumentBuilder docBuilder = docFactory.newDocumentBuilder() + Document xml = docBuilder.parse(source) + NodeList nodeList = xml.getElementsByTagNameNS("*", "subnet") + for (int x = 0; x < nodeList.getLength(); x++) { + Node node = nodeList.item(x) + if (node.getNodeType() == Node.ELEMENT_NODE) { + Element eElement = (Element) node + String subnetOrchStatus = eElement.getElementsByTagNameNS("*", "orchestration-status").item(0).getTextContent() + String subnetId = eElement.getElementsByTagNameNS("*", "subnet-id").item(0).getTextContent() + Subnet subnet = new Subnet() + String neutronSubnetId = networkUtils.extractNeutSubId(createNetworkResponse, 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) } } + 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) { 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..1d75d399ee 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. @@ -25,6 +25,7 @@ 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.logger.MsoLogger import org.onap.so.logger.MessageEnum @@ -34,12 +35,10 @@ 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 org.onap.so.utils.TargetEntity import java.util.UUID; - +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.* @@ -61,7 +60,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 +72,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 +80,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 +102,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 +121,7 @@ public class DoCreateNetworkInstanceRollback extends AbstractServiceTaskProcesso if(rollbackData.containsKey("rollbackSDNCRequest")) { rollbackSDNCRequest = rollbackData["rollbackSDNCRequest"] } - + if(rollbackData.containsKey("rollbackNetworkRequest")) { rollbackNetworkRequest = rollbackData["rollbackNetworkRequest"] } @@ -130,14 +129,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 +146,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 +167,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 HttpClient(url, "application/xml", 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 +261,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 +294,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 +316,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 +327,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 +342,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 +361,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/DoCreateServiceInstance.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateServiceInstance.groovy index 6d41923bdf..4bda803da0 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 @@ -48,7 +48,7 @@ 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.* @@ -278,7 +278,7 @@ public class DoCreateServiceInstance extends AbstractServiceTaskProcessor { if (siParamsXml == null) siParamsXml = "" execution.setVariable("siParamsXml", siParamsXml) - + } catch (BpmnError e) { throw e; } catch (Exception ex){ @@ -291,70 +291,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,7 +323,7 @@ public class DoCreateServiceInstance extends AbstractServiceTaskProcessor { { oStatus = "Created" } - + //QUERY CATALOG DB AND GET WORKLOAD / ENVIRONMENT CONTEXT String environmentContext = "" String workloadContext ="" @@ -396,7 +345,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 +354,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 10f6acd403..a3c30dcb50 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 @@ -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,25 +18,24 @@ * ============LICENSE_END========================================================= */ -package org.onap.so.bpmn.infrastructure.scripts; +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.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.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.ExceptionUtil -import org.onap.so.bpmn.common.scripts.MsoUtils -import org.onap.so.bpmn.core.UrnPropertiesReader; -import org.onap.so.bpmn.core.json.JsonUtils +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.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 groovy.json.* +import javax.ws.rs.core.Response /** * This groovy class supports the <class>DoCreateVFCNetworkServiceInstance.bpmn</class> process. @@ -46,9 +45,9 @@ public class DoCreateVFCNetworkServiceInstance extends AbstractServiceTaskProces private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, DoCreateVFCNetworkServiceInstance.class); String vfcUrl = "/vfc/rest/v1/vfcadapter" - + String host = "http://mso.mso.testlab.openecomp.org:8080" - + ExceptionUtil exceptionUtil = new ExceptionUtil() JsonUtils jsonUtil = new JsonUtils() @@ -100,7 +99,7 @@ public class DoCreateVFCNetworkServiceInstance extends AbstractServiceTaskProces }""" execution.setVariable("nsOperationKey", nsOperationKey); execution.setVariable("nsParameters", nsParameters) - + } catch (BpmnError e) { throw e; @@ -127,9 +126,9 @@ public class DoCreateVFCNetworkServiceInstance extends AbstractServiceTaskProces "nsOperationKey":${nsOperationKey}, "nsParameters":${nsParameters} }""" - APIResponse apiResponse = postRequest(execution, host + vfcUrl + "/ns", reqBody) - String returnCode = apiResponse.getStatusCode() - String aaiResponseAsString = apiResponse.getResponseBodyAsString() + Response apiResponse = postRequest(execution, host + vfcUrl + "/ns", reqBody) + String returnCode = apiResponse.getStatus() + String aaiResponseAsString = apiResponse.readEntity(String.class) String nsInstanceId = ""; if(returnCode== "200" || returnCode == "201"){ nsInstanceId = jsonUtil.getJsonValue(aaiResponseAsString, "nsInstanceId") @@ -155,9 +154,9 @@ public class DoCreateVFCNetworkServiceInstance extends AbstractServiceTaskProces }""" String nsInstanceId = execution.getVariable("nsInstanceId") String url = host + vfcUrl + "/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") @@ -174,9 +173,9 @@ public class DoCreateVFCNetworkServiceInstance extends AbstractServiceTaskProces String jobId = execution.getVariable("jobId") String nsOperationKey = execution.getVariable("nsOperationKey"); String url = host + vfcUrl + "/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") @@ -186,12 +185,12 @@ public class DoCreateVFCNetworkServiceInstance extends AbstractServiceTaskProces } /** - * delay 5 sec + * delay 5 sec */ public void timeDelay(DelegateExecution execution) { try { Thread.sleep(5000); - } catch(InterruptedException e) { + } catch(InterruptedException e) { msoLogger.debug("Time Delay exception" + e ) } } @@ -209,53 +208,17 @@ public class DoCreateVFCNetworkServiceInstance extends AbstractServiceTaskProces String globalSubscriberId = execution.getVariable("globalSubscriberId") String serviceType = execution.getVariable("serviceType") String serviceId = execution.getVariable("serviceId") - String addRelationPayload = """<relationship xmlns="http://org.openecomp.aai.inventory/v11"> - <related-to>service-instance</related-to> - <related-link>/aai/v11/business/customers/customer/${globalSubscriberId}/service-subscriptions/service-subscription/${serviceType}/service-instances/service-instance/${nsInstanceId}</related-link> - <relationship-data> - <relationship-key>customer.global-customer-id</relationship-key> - <relationship-value>${MsoUtils.xmlEscape(globalSubscriberId)}</relationship-value> - </relationship-data> - <relationship-data> - <relationship-key>service-subscription.service-type</relationship-key> - <relationship-value>${MsoUtils.xmlEscape(serviceType)}</relationship-value> - </relationship-data> - <relationship-data> - <relationship-key>service-instance.service-instance-id</relationship-key> - <relationship-value>${MsoUtils.xmlEscape(nsInstanceId)}</relationship-value> - </relationship-data> - </relationship>""" - String endpoint = UrnPropertiesReader.getVariable("aai.endpoint", execution) - msoLogger.debug("Add Relationship req:\n" + addRelationPayload) - String url = endpoint + "/aai/v11/business/customers/customer/" + globalSubscriberId + "/service-subscriptions/service-subscription/" + serviceType + "/service-instances/service-instance/" + serviceId + "/relationship-list/relationship" - APIResponse aaiRsp = executeAAIPutCall(execution, url, addRelationPayload) - msoLogger.debug("aai response status code:" + aaiRsp.getStatusCode()) - msoLogger.debug("aai response content:" + aaiRsp.getResponseBodyAsString()) - msoLogger.trace("Exit addNSRelationship") - } - - public APIResponse executeAAIPutCall(DelegateExecution execution, String url, String payload){ - msoLogger.trace("Started Execute AAI Put Process") - APIResponse apiResponse = null + + AAIResourceUri nsUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE,globalSubscriberId,serviceType,nsInstanceId) + AAIResourceUri relatedServiceUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE,globalSubscriberId,serviceType,serviceId) + try{ - String uuid = utils.getRequestID() - msoLogger.debug("Generated uuid is: " + uuid) - msoLogger.debug("URL to be used is: " + url) - String userName = UrnPropertiesReader.getVariable("aai.auth", execution) - String password = UrnPropertiesReader.getVariable("mso.msoKey", execution) - String basicAuthCred = utils.getBasicAuth(userName,password) - RESTConfig config = new RESTConfig(url); - RESTClient client = new RESTClient(config).addHeader("X-FromAppId", "MSO").addHeader("X-TransactionId", uuid).addHeader("Content-Type", "application/xml").addHeader("Accept","application/xml"); - if (basicAuthCred != null && !"".equals(basicAuthCred)) { - client.addAuthorizationHeader(basicAuthCred) - } - apiResponse = client.httpPut(payload) - msoLogger.trace("Completed Execute AAI Put Process") + getAAIClient().connect(nsUri,relatedServiceUri) + msoLogger.info("NS relationship to Service added successfully") }catch(Exception e){ - msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception occured while executing AAI Put Call", "BPMN", MsoLogger.getServiceName(),MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception occured while executing AAI Put Call", "BPMN", MsoLogger.getServiceName(),MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); throw new BpmnError("MSOWorkflowException") } - return apiResponse } /** @@ -263,20 +226,26 @@ public class DoCreateVFCNetworkServiceInstance extends AbstractServiceTaskProces * url: the url of the request * requestBody: the body of the request */ - private APIResponse postRequest(DelegateExecution execution, String url, String requestBody){ + private Response postRequest(DelegateExecution execution, String urlString, String requestBody){ msoLogger.trace("Started Execute VFC adapter Post Process") - msoLogger.debug("url:"+url +"\nrequestBody:"+ requestBody) - APIResponse apiResponse = null + msoLogger.debug("url:"+urlString +"\nrequestBody:"+ requestBody) + Response apiResponse = null try{ - RESTConfig config = new RESTConfig(url); - RESTClient client = new RESTClient(config).addHeader("Content-Type", "application/json").addHeader("Accept","application/json").addHeader("Authorization","Basic QlBFTENsaWVudDpwYXNzd29yZDEk"); - apiResponse = client.httpPost(requestBody) - msoLogger.debug("response code:"+ apiResponse.getStatusCode() +"\nresponse body:"+ apiResponse.getResponseBodyAsString()) + + URL url = new URL(urlString); + + HttpClient httpClient = new HttpClient(url, "application/json", TargetEntity.VNF_ADAPTER) + httpClient.addAdditionalHeader("Accept", "application/json") + httpClient.addAdditionalHeader("Authorization", "Basic QlBFTENsaWVudDpwYXNzd29yZDEk") + + 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(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception occured while executing AAI Post Call", "BPMN", MsoLogger.getServiceName(),MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); 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 58b90a1bf2..50fe75e3df 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,6 +20,8 @@ package org.onap.so.bpmn.infrastructure.scripts +import javax.ws.rs.core.MediaType +import javax.ws.rs.core.Response import javax.xml.parsers.DocumentBuilder import javax.xml.parsers.DocumentBuilderFactory @@ -28,6 +30,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 @@ -38,11 +41,11 @@ 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.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 @@ -50,12 +53,12 @@ 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.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.springframework.web.util.UriUtils import org.w3c.dom.Document import org.w3c.dom.Element @@ -639,28 +642,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 = new HttpClient(new URL(endPoint), MediaType.APPLICATION_XML, 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) { @@ -723,31 +724,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 = new HttpClient(new URL(endPoint), MediaType.APPLICATION_XML, 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) { @@ -1861,50 +1862,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 @@ -1917,7 +1885,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) 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..93379c72be 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,35 @@ 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.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 +154,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 +214,22 @@ 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<VolumeGroup> volumeGroup = getAAIClient().get(VolumeGroup.class,uri) + if(volumeGroup.isPresent()){ + execution.setVariable(prefix+'AaiReturnCode', 200) + execution.setVariable("queriedVolumeGroupId",volumeGroup.get().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 +274,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 +282,43 @@ 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) 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 +349,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> @@ -539,54 +496,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 +532,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/DoCustomDeleteE2EServiceInstanceV2.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCustomDeleteE2EServiceInstanceV2.groovy index 21bf0f2c5c..eab6fe05e7 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCustomDeleteE2EServiceInstanceV2.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCustomDeleteE2EServiceInstanceV2.groovy @@ -20,27 +20,28 @@ */ package org.onap.so.bpmn.infrastructure.scripts +import org.onap.aai.domain.yang.AllottedResource + +import javax.ws.rs.core.UriBuilder + 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.json.JSONArray; -import org.json.JSONObject; 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.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.springframework.web.util.UriUtils; 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.json.JSONObject @@ -371,19 +372,15 @@ public class DoCustomDeleteE2EServiceInstanceV2 extends AbstractServiceTaskProce if (StringUtils.equalsIgnoreCase(relatedTo, "allotted-resource")) { msoLogger.info("allotted-resource exists ") - String aaiArRsp = getAaiAr(execution, relatedLink) + Optional<AllottedResource> aaiArRsp = getAaiAr(execution, relatedLink) msoLogger.info("aaiArRsp: " + aaiArRsp) - if (! isBlank(aaiArRsp)) { - def type = utils.getNodeText(aaiArRsp, "type") - def id = utils.getNodeText(aaiArRsp, "id") - def role = utils.getNodeText(aaiArRsp, "role") - def resourceVersion = utils.getNodeText(aaiArRsp, "resource-version") + if (aaiArRsp.isPresent()) { JSONObject jObject = new JSONObject() - jObject.put("resourceType", type) - jObject.put("resourceInstanceId", id) - jObject.put("resourceRole", role) - jObject.put("resourceVersion", resourceVersion) + jObject.put("resourceType", aaiArRsp.get().getType()) + jObject.put("resourceInstanceId", aaiArRsp.get().getId()) + jObject.put("resourceRole", aaiArRsp.get().getRole()) + jObject.put("resourceVersion", aaiArRsp.get().getResourceVersion()) allResources.put(jObject) msoLogger.info("allResources: " + allResources) @@ -577,27 +574,11 @@ public class DoCustomDeleteE2EServiceInstanceV2 extends AbstractServiceTaskProce msoLogger.info("Exited " + method) } - private String getAaiAr(DelegateExecution execution, String relink) { + private Optional<AllottedResource> getAaiAr(DelegateExecution execution, String relink) { def method = getClass().getSimpleName() + '.getAaiAr(' +'execution=' + execution.getId() +')' msoLogger.info("Entered " + method) - AaiUtil aaiUtil = new AaiUtil(this) - String aaiEndpoint = execution.getVariable("URN_aai_endpoint") + relink - - msoLogger.debug("get AR info " + aaiEndpoint) - APIResponse response = aaiUtil.executeAAIGetCall(execution, aaiEndpoint) - - int responseCode = response.getStatusCode() - msoLogger.debug("get AR info responseCode:" + responseCode) - - String aaiResponse = response.getResponseBodyAsString() - msoLogger.debug("get AR info " + aaiResponse) - - if(responseCode < 200 || responseCode >= 300 || isBlank(aaiResponse)) { - return null - } - - msoLogger.info("Exited " + method) - return aaiResponse + AAIResourceUri uri = AAIUriFactory.createResourceFromExistingURI(AAIObjectType.ALLOTTED_RESOURCE, UriBuilder.fromPath(relink).build()) + return getAAIClient().get(AllottedResource.class,uri) } /** * prepare Decompose next resource to create request 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 66bd1ece90..3630df00f4 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 @@ -21,6 +21,7 @@ package org.onap.so.bpmn.infrastructure.scripts import static org.apache.commons.lang3.StringUtils.*; +import javax.ws.rs.core.Response import javax.xml.parsers.DocumentBuilder import javax.xml.parsers.DocumentBuilderFactory @@ -36,8 +37,10 @@ import org.onap.so.bpmn.common.scripts.MsoUtils 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.rest.APIResponse + +import org.onap.so.utils.TargetEntity import org.onap.so.bpmn.core.json.JsonUtils +import org.onap.so.client.HttpClient import org.springframework.web.util.UriUtils; import org.w3c.dom.Document import org.w3c.dom.Element @@ -207,7 +210,7 @@ public class DoDeleteE2EServiceInstance extends AbstractServiceTaskProcessor { } execution.setVariable("serviceRelationShip", jArray.toString()) - + // //test(siData) // NodeList nodeList = serviceXml.getElementsByTagName("relationship") // JSONArray jArray = new JSONArray() @@ -276,8 +279,8 @@ public class DoDeleteE2EServiceInstance extends AbstractServiceTaskProcessor { // } // // for SP-Partner // }else if (e.equals("sp-partner")){ -// -// } +// +// } // } // } // execution.setVariable("serviceRelationShip", jArray.toString()) @@ -311,16 +314,16 @@ public class DoDeleteE2EServiceInstance extends AbstractServiceTaskProcessor { } utils.log("INFO"," *** Exit postProcessAAIGET *** ", isDebugEnabled) } - + private JSONObject getRelationShipData(node, isDebugEnabled){ JSONObject jObj = new JSONObject() - + def relation = utils.nodeToString(node) def rt = utils.getNodeText(relation, "related-to") - + def rl = utils.getNodeText(relation, "related-link") utils.log("INFO", "ServiceInstance Related NS/Configuration :" + rl, isDebugEnabled) - + def rl_datas = utils.getIdenticalChildren(node, "relationship-data") for(def rl_data : rl_datas) { def eKey = utils.getChildNodeText(rl_data, "relationship-key") @@ -398,7 +401,7 @@ public class DoDeleteE2EServiceInstance extends AbstractServiceTaskProcessor { } private void generateRelatedResourceInfo(String response, JSONObject jObj){ - + def xml = new XmlSlurper().parseText(response) def rtn = xml.childNodes() while (rtn.hasNext()) { @@ -408,26 +411,29 @@ public class DoDeleteE2EServiceInstance extends AbstractServiceTaskProcessor { jObj.put(key, value) } } - + private JSONObject getRelatedResourceInAAI (DelegateExecution execution, JSONObject jObj) { def isDebugEnabled = execution.getVariable("isDebugLogEnabled") - utils.log("INFO"," ***** Started getRelatedResourceInAAI *****", isDebugEnabled) - + utils.log("INFO"," ***** Started getRelatedResourceInAAI *****", isDebugEnabled) + AaiUtil aaiUriUtil = new AaiUtil() String aai_endpoint = execution.getVariable("URN_aai_endpoint") String urlLink = jObj.get("resourceLinkUrl") String serviceAaiPath = "${aai_endpoint}${urlLink}" - APIResponse response = aaiUriUtil.executeAAIGetCall(execution, serviceAaiPath) - int responseCode = response.getStatusCode() + + URL url = new URL(serviceAaiPath) + HttpClient client = new HttpClient(url, "application/xml", TargetEntity.AAI) + + + Response response = client.get() + int responseCode = response.getStatus() execution.setVariable(Prefix + "GeRelatedResourceResponseCode", responseCode) utils.log("DEBUG", " Get RelatedResource code is: " + responseCode, isDebugEnabled) - String aaiResponse = response.getResponseBodyAsString() - aaiResponse = StringEscapeUtils.unescapeXml(aaiResponse) - aaiResponse = aaiResponse.replaceAll("&", "&") + String aaiResponse = response.readEntity(String.class) execution.setVariable(Prefix + "GetRelatedResourceResponse", aaiResponse) - + //Process Response if(responseCode == 200 || responseCode == 201 || responseCode == 202 ) //200 OK 201 CREATED 202 ACCEPTED @@ -435,9 +441,9 @@ public class DoDeleteE2EServiceInstance extends AbstractServiceTaskProcessor { utils.log("DEBUG", "GET RelatedResource Received a Good Response", isDebugEnabled) execution.setVariable(Prefix + "SuccessIndicator", true) execution.setVariable(Prefix + "FoundIndicator", true) - + generateRelatedResourceInfo(aaiResponse, jObj) - + //get model-invariant-uuid and model-uuid String modelInvariantId = "" String modelUuid = "" @@ -447,19 +453,19 @@ public class DoDeleteE2EServiceInstance extends AbstractServiceTaskProcessor { modelUuid = jObj.get("model-version-id") modelCustomizationId = jObj.get("model-customization-id") } - - jObj.put("modelInvariantId", modelInvariantId) - jObj.put("modelVersionId", modelUuid) + + jObj.put("modelInvariantId", modelInvariantId) + jObj.put("modelVersionId", modelUuid) jObj.put("modelCustomizationId", modelCustomizationId) } else { - utils.log("ERROR", "Get RelatedResource Received a Bad Response Code. Response Code is: " + responseCode, isDebugEnabled) + utils.log("ERROR", "Get RelatedResource Received a Bad Response Code. Response Code is: " + responseCode, isDebugEnabled) } - + utils.log("INFO", " ***** Exit getRelatedResourceInAAI *****", isDebugEnabled) - return jObj; - + return jObj; + } public void postDecomposeService(DelegateExecution execution) { @@ -491,7 +497,7 @@ public class DoDeleteE2EServiceInstance extends AbstractServiceTaskProcessor { relationShipList.each { JSONObject obj = getRelatedResourceInAAI(execution, (JSONObject)it) - + for (Resource resource : deleteResourceList) { String modelName = resource.getModelInfo().getModelName() @@ -508,7 +514,7 @@ public class DoDeleteE2EServiceInstance extends AbstractServiceTaskProcessor { } } } - } + } // only delete real existing resources execution.setVariable("deleteResourceList", deleteRealResourceList) 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..ca4643dea0 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,22 @@ 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.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 +74,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 +248,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 +361,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 +448,13 @@ 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; + URL url = new URL(vnfAdapterUrl) + HttpClient httpClient = new HttpClient(url, "application/xml", TargetEntity.OPENSTACK_ADAPTER) + httpClient.addAdditionalHeader("Authorization", execution.getVariable("BasicAuthHeaderValuePO")) + Response response = httpClient.delete(vnfAdapterRequest) - response = client.httpDelete(vnfAdapterRequest) - execution.setVariable(Prefix + "networkReturnCode", response.getStatusCode()) - execution.setVariable(Prefix + "deleteNetworkResponse", response.getResponseBodyAsString()) + execution.setVariable(Prefix + "networkReturnCode", response.getStatus()) } catch (Exception ex) { // caught exception @@ -531,7 +495,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 +970,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/DoDeleteVFCNetworkServiceInstance.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteVFCNetworkServiceInstance.groovy index 0069bf4f0a..d855479694 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 @@ -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,25 +18,22 @@ * ============LICENSE_END========================================================= */ -package org.onap.so.bpmn.infrastructure.scripts; +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.BpmnError 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.common.scripts.MsoUtils -import org.onap.so.bpmn.core.json.JsonUtils +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.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 groovy.json.* +import org.onap.so.utils.TargetEntity +import javax.ws.rs.core.Response /** * This groovy class supports the <class>DoDeleteVFCNetworkServiceInstance.bpmn</class> process. * flow for E2E ServiceInstance Delete @@ -44,11 +41,11 @@ import groovy.json.* public class DoDeleteVFCNetworkServiceInstance extends AbstractServiceTaskProcessor { private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, DoDeleteVFCNetworkServiceInstance.class); - + String vfcUrl = "/vfc/rest/v1/vfcadapter" - + String host = "http://mso.mso.testlab.openecomp.org:8080" - + ExceptionUtil exceptionUtil = new ExceptionUtil() JsonUtils jsonUtil = new JsonUtils() @@ -110,55 +107,14 @@ public class DoDeleteVFCNetworkServiceInstance extends AbstractServiceTaskProces String globalSubscriberId = execution.getVariable("globalSubscriberId") String serviceType = execution.getVariable("serviceType") String serviceId = execution.getVariable("serviceId") - String deleteRelationPayload = """<relationship xmlns="http://org.openecomp.aai.inventory/v11"> - <related-to>service-instance</related-to> - <related-link>/aai/v11/business/customers/customer/${globalSubscriberId}/service-subscriptions/service-subscription/${serviceType}/service-instances/service-instance/${nsInstanceId}</related-link> - <relationship-data> - <relationship-key>customer.global-customer-id</relationship-key> - <relationship-value>${MsoUtils.xmlEscape(globalSubscriberId)}</relationship-value> - </relationship-data> - <relationship-data> - <relationship-key>service-subscription.service-type</relationship-key> - <relationship-value>${MsoUtils.xmlEscape(serviceType)}</relationship-value> - </relationship-data> - <relationship-data> - <relationship-key>service-instance.service-instance-id</relationship-key> - <relationship-value>${MsoUtils.xmlEscape(nsInstanceId)}</relationship-value> - </relationship-data> - </relationship>""" - String endpoint = execution.getVariable("URN_aai_endpoint") - utils.log("INFO","Delete Relationship req:\n" + deleteRelationPayload, isDebugEnabled) - String url = endpoint + "/aai/v11/business/customers/customer/" + globalSubscriberId + "/service-subscriptions/service-subscription/" + serviceType + "/service-instances/service-instance/" + serviceId + "/relationship-list/relationship" - - APIResponse aaiRsp = executeAAIDeleteCall(execution, url, deleteRelationPayload) - utils.log("INFO","aai response status code:" + aaiRsp.getStatusCode(), isDebugEnabled) - utils.log("INFO","aai response content:" + aaiRsp.getResponseBodyAsString(), isDebugEnabled) - utils.log("INFO"," *****Exit deleteNSRelationship *****", isDebugEnabled) - } - - public APIResponse executeAAIDeleteCall(DelegateExecution execution, String url, String payload){ - def isDebugEnabled = execution.getVariable("isDebugLogEnabled") - utils.log("INFO", " ======== Started Execute AAI Delete Process ======== ", isDebugEnabled) - APIResponse apiResponse = null - try{ - String uuid = utils.getRequestID() - utils.log("INFO","Generated uuid is: " + uuid, isDebugEnabled) - utils.log("INFO","URL to be used is: " + url, isDebugEnabled) - String userName = execution.getVariable("URN_aai_auth") - String password = execution.getVariable("URN_mso_msoKey") - String basicAuthCred = utils.getBasicAuth(userName,password) - RESTConfig config = new RESTConfig(url); - RESTClient client = new RESTClient(config).addHeader("X-FromAppId", "MSO").addHeader("X-TransactionId", uuid).addHeader("Content-Type", "application/xml").addHeader("Accept","application/xml"); - if (basicAuthCred != null && !"".equals(basicAuthCred)) { - client.addAuthorizationHeader(basicAuthCred) - } - apiResponse = client.httpDelete(payload) - utils.log("INFO","======== Completed Execute AAI Delete Process ======== ", isDebugEnabled) + AAIResourceUri serviceInstanceUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, globalSubscriberId, serviceType, serviceId) + AAIResourceUri nsServiceInstanceUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, globalSubscriberId, serviceType, nsInstanceId) + try { + getAAIClient().disconnect(serviceInstanceUri, nsServiceInstanceUri) }catch(Exception e){ - utils.log("ERROR","Exception occured while executing AAI Put Call. Exception is: \n" + e, isDebugEnabled) - throw new BpmnError("MSOWorkflowException") + exceptionUtil.buildAndThrowWorkflowException(execution,25000,"Exception occured while NS disconnect call: " + e.getMessage()) } - return apiResponse + utils.log("INFO"," *****Exit deleteNSRelationship *****", isDebugEnabled) } /** @@ -168,16 +124,15 @@ public class DoDeleteVFCNetworkServiceInstance extends AbstractServiceTaskProces msoLogger.trace("deleteNetworkService start ") String nsOperationKey = execution.getVariable("nsOperationKey"); - String url = host + vfcUrl + "/ns/" + execution.getVariable("nsInstanceId") - APIResponse apiResponse = deleteRequest(execution, url, nsOperationKey) - String returnCode = apiResponse.getStatusCode() - String apiResponseAsString = apiResponse.getResponseBodyAsString() + String url = host + vfcUrl + "/ns/" + execution.getVariable("nsInstanceId") + Response apiResponse = deleteRequest(execution, url, nsOperationKey) + String returnCode = apiResponse.getStatus() String operationStatus = "error"; if(returnCode== "200" || returnCode== "202"){ operationStatus = "finished" } execution.setVariable("operationStatus", operationStatus) - + msoLogger.trace("deleteNetworkService end ") } @@ -187,16 +142,16 @@ public class DoDeleteVFCNetworkServiceInstance extends AbstractServiceTaskProces public void terminateNetworkService(DelegateExecution execution) { msoLogger.trace("terminateNetworkService start ") - String nsOperationKey = execution.getVariable("nsOperationKey") + String nsOperationKey = execution.getVariable("nsOperationKey") String url = host + vfcUrl + "/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") } - execution.setVariable("jobId", jobId) + execution.setVariable("jobId", jobId) msoLogger.trace("terminateNetworkService end ") } @@ -208,10 +163,10 @@ public class DoDeleteVFCNetworkServiceInstance extends AbstractServiceTaskProces msoLogger.trace("queryNSProgress start ") String jobId = execution.getVariable("jobId") String nsOperationKey = execution.getVariable("nsOperationKey"); - String url = host + vfcUrl + "/jobs/" + execution.getVariable("jobId") - APIResponse apiResponse = postRequest(execution, url, nsOperationKey) - String returnCode = apiResponse.getStatusCode() - String apiResponseAsString = apiResponse.getResponseBodyAsString() + String url = host + vfcUrl + "/jobs/" + execution.getVariable("jobId") + 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") @@ -221,12 +176,12 @@ public class DoDeleteVFCNetworkServiceInstance extends AbstractServiceTaskProces } /** - * delay 5 sec + * delay 5 sec */ public void timeDelay(DelegateExecution execution) { try { Thread.sleep(5000); - } catch(InterruptedException e) { + } catch(InterruptedException e) { msoLogger.info("Time Delay exception" + e) } } @@ -243,21 +198,27 @@ public class DoDeleteVFCNetworkServiceInstance extends AbstractServiceTaskProces * url: the url of the request * requestBody: the body of the request */ - private APIResponse postRequest(DelegateExecution execution, String url, String requestBody){ + private Response postRequest(DelegateExecution execution, String urlString, String requestBody){ - msoLogger.trace("Started Execute VFC adapter Post Process ") - msoLogger.info("url:"+url +"\nrequestBody:"+ requestBody) - APIResponse apiResponse = null - try{ - RESTConfig config = new RESTConfig(url); - RESTClient client = new RESTClient(config).addHeader("Content-Type", "application/json").addHeader("Accept","application/json").addHeader("Authorization","Basic QlBFTENsaWVudDpwYXNzd29yZDEk");; - apiResponse = client.httpPost(requestBody) - msoLogger.info("response code:"+ apiResponse.getStatusCode() +"\nresponse body:"+ apiResponse.getResponseBodyAsString()) - msoLogger.trace("Completed Execute VF-C adapter Post Process ") - }catch(Exception e){ + msoLogger.trace("Started Execute VFC adapter Post Process ") + msoLogger.info("url:"+urlString +"\nrequestBody:"+ requestBody) + Response apiResponse = null + try{ + URL url = new URL(urlString); + + HttpClient httpClient = new HttpClient(url, "application/json", TargetEntity.VNF_ADAPTER) + httpClient.addAdditionalHeader("Accept", "application/json") + httpClient.addAdditionalHeader("Authorization", "Basic QlBFTENsaWVudDpwYXNzd29yZDEk") + + 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(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception occured while executing VF-C Post Call. Exception is: \n" + e, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); throw new BpmnError("MSOWorkflowException") - } + } return apiResponse } /** @@ -265,21 +226,24 @@ 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.trace("Started Execute VFC adapter Delete Process ") msoLogger.info("url:"+url +"\nrequestBody:"+ requestBody) - APIResponse apiResponse = null + Response r try{ - RESTConfig config = new RESTConfig(url); - RESTClient client = new RESTClient(config).addHeader("Content-Type", "application/json").addHeader("Accept","application/json").addHeader("Authorization","Basic QlBFTENsaWVudDpwYXNzd29yZDEk"); - apiResponse = client.httpDelete(requestBody) - msoLogger.info("response code:"+ apiResponse.getStatusCode() +"\nresponse body:"+ apiResponse.getResponseBodyAsString()) - msoLogger.trace("Completed Execute VF-C adapter Delete Process ") + + URL Url = new URL(url) + HttpClient httpClient = new HttpClient(Url, "application/json", TargetEntity.VNF_ADAPTER) + httpClient.addAdditionalHeader("Accept", "application/json") + httpClient.addAdditionalHeader("Authorization", "Basic QlBFTENsaWVudDpwYXNzd29yZDEk") + r = httpClient.delete(requestBody) + + msoLogger.trace("Completed Execute VF-C adapter Delete Process ") }catch(Exception e){ - msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception occured while executing VF-C Post Call. Exception is: \n" + e, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception occured while executing VF-C Post Call. Exception is: \n" + e, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); throw new BpmnError("MSOWorkflowException") - } - return apiResponse + } + 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 e06e5238c6..a99f6e993e 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 @@ -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. @@ -31,12 +31,10 @@ 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.rest.RESTClient -import org.onap.so.rest.RESTConfig -import org.onap.so.rest.APIResponse; +import javax.ws.rs.core.Response import org.onap.so.bpmn.infrastructure.vfcmodel.ScaleResource +import org.onap.so.client.HttpClient import org.onap.so.bpmn.infrastructure.vfcmodel.ScaleNsByStepsData import org.onap.so.bpmn.infrastructure.vfcmodel.ScaleNsData @@ -47,6 +45,7 @@ import org.onap.so.bpmn.infrastructure.vfcmodel.NsParameters import org.onap.so.bpmn.infrastructure.vfcmodel.LocationConstraint import org.onap.so.logger.MessageEnum import org.onap.so.logger.MsoLogger +import org.onap.so.utils.TargetEntity @@ -114,10 +113,10 @@ public class DoScaleVFCNetworkServiceInstance extends AbstractServiceTaskProcess String url = host + scaleUrl.replaceAll("\\{nsInstanceId\\}", nsInstanceId) - APIResponse apiResponse = postRequest(execution, url, reqBody) + Response apiResponse = postRequest(execution, url, reqBody) - String returnCode = apiResponse.getStatusCode() - String aaiResponseAsString = apiResponse.getResponseBodyAsString() + String returnCode = apiResponse.getStatus() + String aaiResponseAsString = apiResponse.readEntity(String.class) String jobId = "" if (returnCode == "200" || returnCode == "202") { jobId = jsonUtil.getJsonValue(aaiResponseAsString, "jobId") @@ -156,10 +155,10 @@ public class DoScaleVFCNetworkServiceInstance extends AbstractServiceTaskProcess nsOperationKey.setOperationId(execution.getVariable("operationId")) String queryReqBody = objectToJsonStr(nsOperationKey) - APIResponse apiResponse = postRequest(execution,url, queryReqBody) + Response apiResponse = postRequest(execution,url, queryReqBody) - String returnCode = apiResponse.getStatusCode() - String aaiResponseAsString = apiResponse.getResponseBodyAsString() + String returnCode = apiResponse.getStatus() + String aaiResponseAsString = apiResponse.readEntity(String.class) String operationStatus = "error" @@ -195,16 +194,19 @@ public class DoScaleVFCNetworkServiceInstance extends AbstractServiceTaskProcess * url: the url of the request * requestBody: the body of the request */ - private APIResponse postRequest(DelegateExecution execution, String url, String requestBody){ + private Response postRequest(DelegateExecution execution, String urlString, String requestBody){ msoLogger.trace("Started Execute VFC adapter Post Process ") - msoLogger.info("url:"+url +"\nrequestBody:"+ requestBody) - APIResponse apiResponse = null + msoLogger.info("url:"+urlString +"\nrequestBody:"+ requestBody) + Response apiResponse = null try{ - RESTConfig config = new RESTConfig(url) - RESTClient client = new RESTClient(config).addHeader("Content-Type", "application/json").addHeader("Authorization","Basic QlBFTENsaWVudDpwYXNzd29yZDEk") -// RESTClient client = new RESTClient(config).addHeader("Content-Type", "application/json").addHeader("Accept","application/json").addHeader("Authorization","Basic QlBFTENsaWVudDpwYXNzd29yZDEk") - apiResponse = client.httpPost(requestBody) - msoLogger.info("response code:"+ apiResponse.getStatusCode() +"\nresponse body:"+ apiResponse.getResponseBodyAsString()) + URL url = new URL(urlString); + + HttpClient httpClient = new HttpClient(url, "application/json", TargetEntity.VNF_ADAPTER) + httpClient.addAdditionalHeader("Authorization", "Basic QlBFTENsaWVudDpwYXNzd29yZDEk") + + apiResponse = httpClient.post(requestBody) + + msoLogger.info("response code:"+ apiResponse.getStatus() +"\nresponse body:"+ apiResponse.readEntity(String.class)) msoLogger.trace("Completed Execute VF-C adapter Post Process ") }catch(Exception e){ msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception occured while executing VFC Post Call.", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, e); 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 5b7fdb2c22..58ee260c25 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 @@ -17,14 +17,16 @@ * limitations under the License. * ============LICENSE_END========================================================= */ -package org.onap.so.bpmn.infrastructure.scripts; +package org.onap.so.bpmn.infrastructure.scripts +import org.onap.so.client.aai.AAIResourcesClient +import org.onap.so.client.aai.entities.uri.AAIResourceUri; 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.so.bpmn.common.scripts.AaiUtil +import org.onap.aai.domain.yang.ServiceInstance; import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor import org.onap.so.bpmn.common.scripts.ExceptionUtil import org.onap.so.bpmn.common.scripts.MsoUtils @@ -308,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..cc301db4cd 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.setOperationalStatus("Created") + }else{ + l3Network.setOperationalStatus("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..f6a8a1558c 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,6 +22,7 @@ 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.ExceptionUtil @@ -44,7 +45,7 @@ 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 { @@ -982,55 +983,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..7fdbb5cb89 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. @@ -22,6 +22,8 @@ package org.onap.so.bpmn.infrastructure.scripts import static org.apache.commons.lang3.StringUtils.*; +import javax.ws.rs.core.MediaType +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 @@ -34,15 +36,14 @@ 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.HttpClient import org.onap.so.client.aai.AAIObjectType; import org.onap.so.client.aai.AAIResourcesClient import org.onap.so.client.aai.entities.uri.AAIResourceUri import org.onap.so.client.aai.entities.uri.AAIUriFactory; import org.onap.so.logger.MessageEnum import org.onap.so.logger.MsoLogger -import org.onap.so.rest.APIResponse -import org.onap.so.rest.RESTClient -import org.onap.so.rest.RESTConfig +import org.onap.so.utils.TargetEntity import org.springframework.web.util.UriUtils; /** @@ -54,14 +55,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 +70,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 +139,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 +156,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 HttpClient(new URL(endPoint), MediaType.APPLICATION_XML, 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 +205,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 +217,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 +239,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 +277,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 +322,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 +345,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 +378,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 +395,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 +405,7 @@ class DoUpdateVnfAndModules extends AbstractServiceTaskProcessor { exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in prepUpdateAAIGenericVnf(): ' + e.getMessage()) } } - + /** * APP-C Call - placeholder. * @@ -415,6 +416,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/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/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/vcpe/scripts/DeleteVcpeResCustService.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/vcpe/scripts/DeleteVcpeResCustService.groovy index 8a3dcbab5d..7a6fd72a7d 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 @@ -32,7 +32,7 @@ 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 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 1be4989490..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,83 +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) - execution.setVariable("aaiARPath", arUtils.createARUrl(execution, siResourceLink, allottedResourceId)) - msoLogger.debug("GET 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 @@ -357,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 48eb1c85f9..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,18 +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) - execution.setVariable("aaiARPath", arUtils.createARUrl(execution, siResourceLink, allottedResourceId)) - msoLogger.debug("GET 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") @@ -217,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 @@ -286,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/delegate/CheckAaiForCorrelationIdDelegate.java b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/delegate/CheckAaiForCorrelationIdDelegate.java index b49c4211b1..469069e136 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,13 +24,11 @@ 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.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @@ -41,14 +39,10 @@ import org.springframework.stereotype.Component; * - correlationId - String * * Outputs: - * - AAI_CONTAINS_INFO_ABOUT_PNF - local Boolean - * - aaiContainsInfoAboutIp - local Boolean + * - 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 AaiConnection aaiConnection; @Autowired @@ -57,18 +51,15 @@ 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(); + 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/PnfCheckInputs.java b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/delegate/PnfCheckInputs.java index 164f51f579..94fb6a8674 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/delegate/PnfCheckInputs.java +++ b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/delegate/PnfCheckInputs.java @@ -23,6 +23,7 @@ package org.onap.so.bpmn.infrastructure.pnf.delegate; import static org.onap.so.bpmn.infrastructure.pnf.delegate.ExecutionVariableNames.CORRELATION_ID; import static org.onap.so.bpmn.infrastructure.pnf.delegate.ExecutionVariableNames.TIMEOUT_FOR_NOTIFICATION; +import com.google.common.base.Strings; import org.camunda.bpm.engine.delegate.DelegateExecution; import org.camunda.bpm.engine.delegate.JavaDelegate; import org.onap.so.bpmn.common.scripts.ExceptionUtil; @@ -46,11 +47,11 @@ public class PnfCheckInputs implements JavaDelegate { @Override public void execute(DelegateExecution execution) { String correlationId = (String) execution.getVariable(CORRELATION_ID); - if (correlationId == null) { + if (Strings.isNullOrEmpty(correlationId)) { new ExceptionUtil().buildAndThrowWorkflowException(execution, 9999, "correlationId variable not defined"); } String timeout = (String) execution.getVariable(TIMEOUT_FOR_NOTIFICATION); - if (timeout == null) { + if (Strings.isNullOrEmpty(timeout)) { LOGGER.debug("timeoutForPnfEntryNotification variable not found, setting default"); if (defaultTimeout == null) { new ExceptionUtil().buildAndThrowWorkflowException(execution, 9999, 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 e753f79ebd..7f1c2fd9b1 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) { 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..2eb4c9c408 --- /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.Matchers.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..161075f66e 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,22 +20,33 @@ 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 { + @Rule + public ExpectedException thrown = ExpectedException.none(); + def jsonRequest = """ { "requestDetails": { @@ -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..6ed5bfe89a 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,20 +21,50 @@ 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.Matchers.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 { + @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) + } + def deleteVnfAdapterRequestXml = """<deleteVolumeGroupRequest> <cloudSiteId>RDM2WAGPLCP</cloudSiteId> <tenantId>fba1bd1e195a404cacb9ce17a9b2b421</tenantId> @@ -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/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..52b54a48e8 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.Matchers.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..26d3ab8d9d 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,26 +20,42 @@ 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.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.Matchers.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) @@ -86,6 +102,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 +136,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 +152,126 @@ 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) + VolumeGroup volumeGroup = new VolumeGroup() + volumeGroup.setVolumeGroupId("volumeGroupId") + when(client.get(VolumeGroup.class,uri)).thenReturn(Optional.of(volumeGroup)) + 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) + } + + @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/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..f6efe1d7d1 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 ************* " @@ -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) @@ -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..764ceb256a --- /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.Matchers.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/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/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/InformDmaapClientTest.java b/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/InformDmaapClientTest.java index ddf33a1d77..7a31ae1a67 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,7 +29,7 @@ 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.ArgumentMatchers.any; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.*; 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 2e8fb4be78..ab8d206a62 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 @@ -20,8 +20,7 @@ package org.onap.so.bpmn.infrastructure.pnf.delegate; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.mockito.Matchers.eq; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -30,12 +29,17 @@ 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.Rule; import org.junit.Test; +import org.junit.rules.ExpectedException; public class PnfCheckInputsTest { private static final String DEFAULT_TIMEOUT = "P1D"; + @Rule + public ExpectedException expectedException = ExpectedException.none(); + private DelegateExecution mockDelegateExecution() { new PnfCheckInputs(DEFAULT_TIMEOUT); DelegateExecution delegateExecution = mock(DelegateExecution.class); @@ -49,7 +53,19 @@ public class PnfCheckInputsTest { PnfCheckInputs testedObject = new PnfCheckInputs(DEFAULT_TIMEOUT); DelegateExecution delegateExecution = mockDelegateExecution(); // when, then - assertThatThrownBy(() -> testedObject.execute(delegateExecution)).isInstanceOf(BpmnError.class); + expectedException.expect(BpmnError.class); + testedObject.execute(delegateExecution); + } + + @Test + public void shouldThrowException_whenPnfIdIsEmptyString() throws Exception { + // given + PnfCheckInputs testedObject = new PnfCheckInputs(DEFAULT_TIMEOUT); + DelegateExecution delegateExecution = mockDelegateExecution(); + when(delegateExecution.getVariable(CORRELATION_ID)).thenReturn(""); + // when, then + expectedException.expect(BpmnError.class); + testedObject.execute(delegateExecution); } private DelegateExecution mockDelegateExecutionWithCorrelationId() { @@ -65,7 +81,19 @@ public class PnfCheckInputsTest { PnfCheckInputs testedObject = new PnfCheckInputs(null); DelegateExecution delegateExecution = mockDelegateExecutionWithCorrelationId(); // when, then - assertThatThrownBy(() -> testedObject.execute(delegateExecution)).isInstanceOf(BpmnError.class); + expectedException.expect(BpmnError.class); + testedObject.execute(delegateExecution); + } + + @Test + public void shouldThrowException_whenTimeoutIsEmptyStringAndDefaultIsNotDefined() throws Exception { + // given + PnfCheckInputs testedObject = new PnfCheckInputs(null); + DelegateExecution delegateExecution = mockDelegateExecutionWithCorrelationId(); + when(delegateExecution.getVariable(TIMEOUT_FOR_NOTIFICATION)).thenReturn(""); + // when, then + expectedException.expect(BpmnError.class); + testedObject.execute(delegateExecution); } @Test @@ -78,4 +106,4 @@ public class PnfCheckInputsTest { // then verify(delegateExecution).setVariable(eq(TIMEOUT_FOR_NOTIFICATION), eq(DEFAULT_TIMEOUT)); } -}
\ 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..33b4689629 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,8 +22,9 @@ 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.junit.Assert.*; +import static org.mockito.ArgumentMatchers.any; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -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 |