diff options
Diffstat (limited to 'bpmn/MSOCommonBPMN/src/main/groovy')
33 files changed, 935 insertions, 3488 deletions
diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/AaiUtil.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/AaiUtil.groovy index 2f4e70c893..8a8e41247c 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/AaiUtil.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/AaiUtil.groovy @@ -19,22 +19,27 @@ */ package org.onap.so.bpmn.common.scripts + +import org.onap.so.client.HttpClientFactory + import java.util.regex.Matcher import java.util.regex.Pattern +import javax.ws.rs.core.MediaType +import javax.ws.rs.core.Response import javax.ws.rs.core.UriBuilder import org.camunda.bpm.engine.delegate.BpmnError import org.camunda.bpm.engine.delegate.DelegateExecution +import org.onap.aai.domain.yang.GenericVnf import org.onap.so.bpmn.core.UrnPropertiesReader; +import org.onap.so.client.HttpClient import org.onap.so.client.aai.AAIVersion import org.onap.so.client.aai.entities.uri.AAIUri import org.onap.so.logger.MessageEnum import org.onap.so.logger.MsoLogger import org.onap.so.openpojo.rules.HasToStringRule -import org.onap.so.rest.APIResponse; -import org.onap.so.rest.RESTClient -import org.onap.so.rest.RESTConfig +import org.onap.so.utils.TargetEntity @Deprecated class AaiUtil { @@ -53,37 +58,6 @@ class AaiUtil { this.taskProcessor = taskProcessor } - public String getBusinessSPPartnerUri(DelegateExecution execution) { - def uri = getUri(execution, 'sp-partner') - msoLogger.debug('AaiUtil.getBusinessSPPartnerUri() - AAI URI: ' + uri) - return uri - } - - public String getVersion(DelegateExecution execution, resourceName, processKey) { - def versionWithResourceKey = "mso.workflow.default.aai.${resourceName}.version" - def versionWithProcessKey = "mso.workflow.custom.${processKey}.aai.version" - - def version = UrnPropertiesReader.getVariable(versionWithProcessKey, execution) - if (version) { - msoLogger.debug("AaiUtil.getVersion() - using flow specific ${versionWithProcessKey}=${version}") - return version - } - - version = UrnPropertiesReader.getVariable(versionWithResourceKey, execution) - if (version) { - msoLogger.debug("AaiUtil.getVersion() - using resource specific ${versionWithResourceKey}=${version}") - return version - } - - version = UrnPropertiesReader.getVariable(DEFAULT_VERSION_KEY, execution) - if (version) { - msoLogger.debug("AaiUtil.getVersion() - using default version ${DEFAULT_VERSION_KEY}=${version}") - return version - } - - (new ExceptionUtil()).buildAndThrowWorkflowException(execution, 9999, "Internal Error: One of the following should be defined in MSO URN properties file: ${versionWithResourceKey}, ${versionWithProcessKey}, ${DEFAULT_VERSION_KEY}") - } - public String createAaiUri(AAIUri uri) { return createAaiUri(AAIVersion.valueOf('V' + UrnPropertiesReader.getVariable(DEFAULT_VERSION_KEY)), uri) } @@ -93,14 +67,6 @@ class AaiUtil { return UriBuilder.fromUri(result + uri.build().toString()).build().toString() } - public String setNamespace(DelegateExecution execution) { - def key = AAI_NAMESPACE_STRING_KEY - aaiNamespace = UrnPropertiesReader.getVariable(key, execution) - if (aaiNamespace == null ) { - (new ExceptionUtil()).buildAndThrowWorkflowException(execution, 9999, 'Internal Error: AAI URI entry for ' + key + ' not defined in the MSO URN properties file') - } - } - public String getNamespace() { return getNamespace(AAIVersion.valueOf('V' + UrnPropertiesReader.getVariable(DEFAULT_VERSION_KEY))) } @@ -113,330 +79,6 @@ class AaiUtil { return namespace + version } - /** - * This method can be used for getting the building namespace out of uri. - * NOTE: A getUri() method needs to be invoked first. - * Alternative method is the getNamespaceFromUri(DelegateExecution execution, String uri) - * return namespace (plus version from uri) - * - * @param url - * - * @return namespace - */ - public String getNamespaceFromUri(String uri) { - String namespace = UrnPropertiesReader.getVariable(AAI_NAMESPACE_STRING_KEY) - if (namespace == null) { - throw new Exception('Internal Error: AAI Namespace has not been set yet. A getUri() method needs to be invoked first.') - } - if(uri!=null){ - String version = getVersionFromUri(uri) - return namespace + "v"+version - }else{ - return namespace - } - } - - /** - * This method can be used for building namespace with aai version out of uri. - * NOTE: 2 arguments: DelegateExecution execution & String uri - * @param execution - * @param url - * - * @return namespace - */ - public String getNamespaceFromUri(DelegateExecution execution, String uri) { - String namespace = UrnPropertiesReader.getVariable(AAI_NAMESPACE_STRING_KEY, execution) - if (namespace == null ) { - (new ExceptionUtil()).buildAndThrowWorkflowException(execution, 9999, 'Internal Error: AAI URI entry for ' + AAI_NAMESPACE_STRING_KEY + ' not defined in the MSO URN properties file') - } - if(uri!=null){ - String version = getVersionFromUri(uri) - return namespace + "v"+version - }else{ - return namespace - } - } - - /** - * This is used to extract the version from uri. - * - * @param uri - * - * @return version - */ - private String getVersionFromUri(String uri) { - - Matcher versionRegEx = Pattern.compile("/v(\\d+)").matcher(uri) - if (versionRegEx.find()) { - return versionRegEx.group(1); - } - - return ""; - } - - - /** - * This reusable method can be used for making AAI Get Calls. The url should - * be passed as a parameter along with the execution. The method will - * return an APIResponse. - * - * @param execution - * @param url - * - * @return APIResponse - * - */ - public APIResponse executeAAIGetCall(DelegateExecution execution, String url){ - msoLogger.trace("STARTED Execute AAI Get Process ") - APIResponse apiResponse = null - try{ - String uuid = utils.getRequestID() - msoLogger.debug("Generated uuid is: " + uuid) - msoLogger.debug("URL to be used is: " + url) - - String basicAuthCred = utils.getBasicAuth(UrnPropertiesReader.getVariable("aai.auth", execution),UrnPropertiesReader.getVariable("mso.msoKey", execution)) - - RESTConfig config = new RESTConfig(url); - RESTClient client = new RESTClient(config).addHeader("X-FromAppId", "MSO").addHeader("X-TransactionId", uuid).addHeader("Accept","application/xml"); - - if (basicAuthCred != null && !"".equals(basicAuthCred)) { - client.addAuthorizationHeader(basicAuthCred) - } - apiResponse = client.httpGet() - - msoLogger.trace("COMPLETED Execute AAI Get Process ") - }catch(Exception e){ - msoLogger.debug("Exception occured while executing AAI Get Call. Exception is: \n" + e) - (new ExceptionUtil()).buildAndThrowWorkflowException(execution, 9999, e.getMessage()) - } - return apiResponse - } - - - /** - * This reusable method can be used for making AAI httpPut Calls. The url should - * be passed as a parameter along with the execution and payload. The method will - * return an APIResponse. - * - * @param execution - * @param url - * @param payload - * - * @return APIResponse - * - */ - public APIResponse executeAAIPutCall(DelegateExecution execution, String url, String payload){ - msoLogger.trace("Started Execute AAI Put Process ") - APIResponse apiResponse = null - try{ - String uuid = utils.getRequestID() - msoLogger.debug("Generated uuid is: " + uuid) - msoLogger.debug("URL to be used is: " + url) - - String basicAuthCred = utils.getBasicAuth(UrnPropertiesReader.getVariable("aai.auth", execution),UrnPropertiesReader.getVariable("mso.msoKey", execution)) - - 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 ") - }catch(Exception e){ - msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception occured while executing AAI Put Call.", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, e); - (new ExceptionUtil()).buildAndThrowWorkflowException(execution, 9999, e.getMessage()) - } - return apiResponse - } - - /** - * This reusable method can be used for making AAI httpPatch Calls. The url should - * be passed as a parameter along with the execution and payload. The method will - * return an APIResponse. - * - * @param execution - * @param url - * @param payload - * - * @return APIResponse - * - */ - public APIResponse executeAAIPatchCall(DelegateExecution execution, String url, String payload){ - msoLogger.trace("Started Execute AAI Patch Process ") - APIResponse apiResponse = null - try{ - String uuid = utils.getRequestID() - msoLogger.debug("Generated uuid is: " + uuid) - - msoLogger.debug("URL to be used is: " + url) - - String basicAuthCred = utils.getBasicAuth(UrnPropertiesReader.getVariable("aai.auth", execution),UrnPropertiesReader.getVariable("mso.msoKey", execution)) - - RESTConfig config = new RESTConfig(url); - RESTClient client = new RESTClient(config).addHeader("X-FromAppId", "MSO").addHeader("X-TransactionId", uuid).addHeader("Content-Type", "application/merge-patch+json").addHeader("Accept","application/json"); - if (basicAuthCred != null && !"".equals(basicAuthCred)) { - client.addAuthorizationHeader(basicAuthCred) - } - apiResponse = client.httpPatch(payload) - - msoLogger.trace("Completed Execute AAI Patch Process ") - }catch(Exception e){ - msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception occured while executing AAI Patch Call.", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, e); - (new ExceptionUtil()).buildAndThrowWorkflowException(execution, 9999, e.getMessage()) - } - return apiResponse - } - - - /** - * This reusable method can be used for making AAI Delete Calls. The url should - * be passed as a parameter along with the execution. The method will - * return an APIResponse. - * - * @param execution - * @param url - * - * @return APIResponse - * - */ - public APIResponse executeAAIDeleteCall(DelegateExecution execution, String url){ - msoLogger.trace("Started Execute AAI Delete Process ") - APIResponse apiResponse = null - try{ - String uuid = utils.getRequestID() - msoLogger.debug("Generated uuid is: " + uuid) - msoLogger.debug("URL to be used is: " + url) - - String basicAuthCred = utils.getBasicAuth(UrnPropertiesReader.getVariable("aai.auth", execution),UrnPropertiesReader.getVariable("mso.msoKey", execution)) - - RESTConfig config = new RESTConfig(url); - RESTClient client = new RESTClient(config).addHeader("X-FromAppId", "MSO").addHeader("X-TransactionId", uuid).addHeader("Accept","application/xml"); - if (basicAuthCred != null && !"".equals(basicAuthCred)) { - client.addAuthorizationHeader(basicAuthCred) - } - apiResponse = client.delete() - - msoLogger.trace("Completed Execute AAI Delete Process ") - }catch(Exception e){ - msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception occured while executing AAI Delete Call.", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, e); - (new ExceptionUtil()).buildAndThrowWorkflowException(execution, 9999, e.getMessage()) - } - return apiResponse - } - - /** - * This reusable method can be used for making AAI Delete Calls. The url should - * be passed as a parameter along with the execution. The method will - * return an APIResponse. - * - * @param execution - * @param url - * @param payload - * - * @return APIResponse - * - */ - public APIResponse executeAAIDeleteCall(DelegateExecution execution, String url, String payload, String authHeader){ - msoLogger.trace("Started Execute AAI Delete Process ") - APIResponse apiResponse = null - try{ - String uuid = utils.getRequestID() - msoLogger.debug("Generated uuid is: " + uuid) - - msoLogger.debug("URL to be used is: " + url) - - String basicAuthCred = utils.getBasicAuth(UrnPropertiesReader.getVariable("aai.auth", execution),UrnPropertiesReader.getVariable("mso.msoKey", execution)) - RESTConfig config = new RESTConfig(url); - RESTClient client = new RESTClient(config).addHeader("X-FromAppId", "MSO").addHeader("X-TransactionId", uuid).addHeader("Accept","application/xml").addAuthorizationHeader(authHeader); - if (basicAuthCred != null && !"".equals(basicAuthCred)) { - client.addAuthorizationHeader(basicAuthCred) - } - apiResponse = client.httpDelete(payload) - - msoLogger.trace("Completed Execute AAI Delete Process ") - }catch(Exception e){ - msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception occured while executing AAI Delete Call.", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, e); - (new ExceptionUtil()).buildAndThrowWorkflowException(execution, 9999, e.getMessage()) - } - return apiResponse - } - - /** - * This reusable method can be used for making AAI Post Calls. The url - * and payload should be passed as a parameters along with the execution. - * The method will return an APIResponse. - * - * @param execution - * @param url - * @param payload - * - * @return APIResponse - * - */ - public APIResponse executeAAIPostCall(DelegateExecution execution, String url, String payload){ - msoLogger.trace("Started Execute AAI Post Process ") - APIResponse apiResponse = null - try{ - String uuid = utils.getRequestID() - msoLogger.debug("Generated uuid is: " + uuid) - msoLogger.debug("URL to be used is: " + url) - - String basicAuthCred = utils.getBasicAuth(UrnPropertiesReader.getVariable("aai.auth", execution),UrnPropertiesReader.getVariable("mso.msoKey", execution)) - RESTConfig config = new RESTConfig(url); - RESTClient client = new RESTClient(config).addHeader("X-FromAppId", "MSO").addHeader("X-TransactionId", uuid).addHeader("Accept","application/xml"); - - if (basicAuthCred != null && !"".equals(basicAuthCred)) { - client.addAuthorizationHeader(basicAuthCred) - } - apiResponse = client.httpPost(payload) - - msoLogger.trace("Completed Execute AAI 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); - (new ExceptionUtil()).buildAndThrowWorkflowException(execution, 9999, e.getMessage()) - } - return apiResponse - } - - /** - * This reusable method can be used for making AAI Post Calls. The url - * and payload should be passed as a parameters along with the execution. - * The method will return an APIResponse. - * - * @param execution - * @param url - * @param payload - * @param authenticationHeader - addAuthenticationHeader value - * @param headerName - name of header you want to add, i.e. addHeader(headerName, headerValue) - * @param headerValue - the header's value, i.e. addHeader(headerName, headerValue) - * - * @return APIResponse - * - */ - public APIResponse executeAAIPostCall(DelegateExecution execution, String url, String payload, String authenticationHeaderValue, String headerName, String headerValue){ - msoLogger.trace("Started Execute AAI Post Process ") - APIResponse apiResponse = null - try{ - msoLogger.debug("URL to be used is: " + url) - - String basicAuthCred = utils.getBasicAuth(UrnPropertiesReader.getVariable("aai.auth", execution),UrnPropertiesReader.getVariable("mso.msoKey", execution)) - - RESTConfig config = new RESTConfig(url); - RESTClient client = new RESTClient(config).addAuthorizationHeader(authenticationHeaderValue).addHeader(headerName, headerValue) - if (basicAuthCred != null && !"".equals(basicAuthCred)) { - client.addAuthorizationHeader(basicAuthCred) - } - apiResponse = client.httpPost(payload) - - msoLogger.trace("Completed Execute AAI 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); - (new ExceptionUtil()).buildAndThrowWorkflowException(execution, 9999, e.getMessage()) - } - return apiResponse - } - /* Utility to get the Cloud Region from AAI * Returns String cloud region id, (ie, cloud-region-id) @@ -448,9 +90,17 @@ class AaiUtil { public String getAAICloudReqion(DelegateExecution execution, String url, String backend, inputCloudRegion){ String regionId = "" try{ - APIResponse apiResponse = executeAAIGetCall(execution, url) - String returnCode = apiResponse.getStatusCode() - String aaiResponseAsString = apiResponse.getResponseBodyAsString() + URL Url = new URL(url) + HttpClient client = new HttpClientFactory().newXmlClient(Url, 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 apiResponse = client.get() + + String returnCode = apiResponse.getStatus() + String aaiResponseAsString = apiResponse.readEntity(String.class) msoLogger.debug("Call AAI Cloud Region Return code: " + returnCode) execution.setVariable(execution.getVariable("prefix")+"queryCloudRegionReturnCode", returnCode) @@ -490,19 +140,6 @@ class AaiUtil { return regionId } - /* returns xml Node with service-type of searchValue */ - def searchServiceType(xmlInput, searchValue){ - def fxml= new XmlSlurper().parseText(xmlInput) - def ret = fxml.'**'.find {it.'service-type' == searchValue} - return ret - } - - /* returns xml Node with service-instance-id of searchValue */ - def searchServiceInstanceId(xmlInput, searchValue){ - def ret = xmlInput.'**'.find {it.'service-instance-id' == searchValue} - return ret - } - /** * Get the lowest unused VF Module index from AAI response for a given module type. The criteria for * determining module type is specified by "key" parameter (for example, "persona-model-id"), @@ -516,10 +153,10 @@ class AaiUtil { * @return moduleIndex * */ - public int getLowestUnusedVfModuleIndexFromAAIVnfResponse(DelegateExecution execution, String aaiVnfResponse, String key, String value) { + public int getLowestUnusedVfModuleIndexFromAAIVnfResponse(DelegateExecution execution, GenericVnf aaiVnfResponse, String key, String value) { if (aaiVnfResponse != null) { String vfModulesText = taskProcessor.utils.getNodeXml(aaiVnfResponse, "vf-modules") - if (vfModulesText == null || vfModulesText.isEmpty()) { + if (aaiVnfResponse.getVfModules() == null || aaiVnfResponse.getVfModules().getVfModule().isEmpty()) { msoLogger.debug("There are no VF modules in this VNF yet") return 0 } @@ -549,4 +186,3 @@ class AaiUtil { } } } - diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/AbstractServiceTaskProcessor.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/AbstractServiceTaskProcessor.groovy index 9e71313e09..57af763ed5 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/AbstractServiceTaskProcessor.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/AbstractServiceTaskProcessor.groovy @@ -20,8 +20,6 @@ package org.onap.so.bpmn.common.scripts; -import groovy.json.JsonSlurper - import org.camunda.bpm.engine.delegate.BpmnError import org.camunda.bpm.engine.delegate.DelegateExecution import org.camunda.bpm.engine.variable.VariableMap @@ -30,11 +28,13 @@ import org.camunda.bpm.engine.variable.Variables.SerializationDataFormats import org.camunda.bpm.engine.variable.impl.value.ObjectValueImpl import org.onap.so.bpmn.common.workflow.context.WorkflowCallbackResponse import org.onap.so.bpmn.common.workflow.context.WorkflowContextHolder -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.client.aai.AAIResourcesClient import org.springframework.web.util.UriUtils +import groovy.json.JsonSlurper + public abstract class AbstractServiceTaskProcessor implements ServiceTaskProcessor { public MsoUtils utils = new MsoUtils() @@ -767,4 +767,4 @@ public abstract class AbstractServiceTaskProcessor implements ServiceTaskProcess public AAIResourcesClient getAAIClient(){ return new AAIResourcesClient(); } -}
\ No newline at end of file +} diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/AllottedResourceUtils.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/AllottedResourceUtils.groovy index c337a21987..a43a2b1f89 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/AllottedResourceUtils.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/AllottedResourceUtils.groovy @@ -20,22 +20,25 @@ package org.onap.so.bpmn.common.scripts -import static org.apache.commons.lang3.StringUtils.*; +import org.onap.so.client.aai.entities.AAIResultWrapper + +import static org.apache.commons.lang3.StringUtils.isBlank; import javax.ws.rs.NotFoundException +import javax.ws.rs.core.UriBuilder -import org.apache.commons.lang3.* +import org.apache.commons.lang.StringUtils import org.camunda.bpm.engine.delegate.BpmnError -import org.camunda.bpm.engine.delegate.DelegateExecution; -import org.onap.so.bpmn.core.UrnPropertiesReader +import org.camunda.bpm.engine.delegate.DelegateExecution +import org.onap.aai.domain.yang.AllottedResource import org.onap.so.bpmn.core.WorkflowException -import org.onap.so.client.aai.AAIObjectType; +import org.onap.so.client.PreconditionFailedException +import org.onap.so.client.aai.AAIObjectType import org.onap.so.client.aai.AAIResourcesClient import org.onap.so.client.aai.entities.uri.AAIResourceUri import org.onap.so.client.aai.entities.uri.AAIUriFactory import org.onap.so.logger.MessageEnum import org.onap.so.logger.MsoLogger -import org.onap.so.rest.APIResponse; @@ -68,7 +71,6 @@ class AllottedResourceUtils { String arType = execution.getVariable("allottedResourceType") String arRole = execution.getVariable("allottedResourceRole") String siXml = execution.getVariable("CSI_service") - String ar = null String orchStatus = null XmlParser xmlParser = new XmlParser() msoLogger.debug("getAROrchStatus siXml:" + siXml) @@ -84,9 +86,8 @@ class AllottedResourceUtils { msoLogger.debug("getARORchStatus AR found") def groovy.util.Node relatedLink = utils.getChildNode(relationship, 'related-link') if (relatedLink != null){ - ar = getARbyLink(execution, relatedLink.text(), arRole) - if (!isBlank(ar)) - { + Optional<AllottedResource> ar = getARbyLink(execution, relatedLink.text(), arRole) + if (ar.isPresent()){ orchStatus = execution.getVariable("aaiAROrchStatus") break } @@ -106,16 +107,21 @@ class AllottedResourceUtils { // get Allotted Resource by AllottedResourceId // used on Delete - called from doDeleteAR // setsVariable aaiARGetResponse - public String getARbyId (DelegateExecution execution, String allottedResourceId) { - msoLogger.trace("getARbyId ") - AAIResourceUri arLink = getARLinkbyId(execution, allottedResourceId) - String ar = null - if (!isBlank(arLink)) - { - ar = getARbyLink(execution, arLink, "") + public boolean ifExistsAR(DelegateExecution execution, String allottedResourceId) { + msoLogger.trace("ifExistsAR ") + try { + AAIResourceUri resourceUri = AAIUriFactory.createResourceUri(AAIObjectType.ALLOTTED_RESOURCE, allottedResourceId) + AAIResultWrapper wrapper = getAAIClient().get(resourceUri) + Optional<AllottedResource> allottedResource = wrapper.asBean(AllottedResource.class) + if(allottedResource.isPresent()) { + setExecutionVariables(execution , allottedResource.get(),resourceUri) + return true + }else { + return false + } + }catch(Exception e){ + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error in ifExistsAR" + e.getMessage()) } - msoLogger.trace(" Exit GetARbyId - AR:" + ar) - return ar; } public String getPSIFmARLink(DelegateExecution execution, String arLink) @@ -125,144 +131,65 @@ class AllottedResourceUtils { String[] split = arLink.split("/service-instance/") String[] splitB = split[1].split("/allotted-resources/") String siId = splitB[0] - msoLogger.trace(" Exit getARLinkbyId - parentServiceInstanceId:" + siId ) + msoLogger.trace(" Exit getPSIFmARLink - parentServiceInstanceId:" + siId ) return siId } - - // get Allotted Resource Link by AllottedResourceId using Nodes Query - // used on Delete - called from getARbyId - public String getARLinkbyId (DelegateExecution execution, String allottedResourceId) { - msoLogger.trace("getARLinkbyId ") - String arLink = null - try { - AAIResourcesClient client = new AAIResourcesClient() - AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.ALLOTTED_RESOURCE, allottedResourceId) - AaiUtil aaiUtil = new AaiUtil(taskProcessor) - arLink = aaiUtil.createAaiUri(uri) - } catch (NotFoundException e) { - msoLogger.debug("GET AR received a Not Found (404) Response") - } catch(Exception e){ - msoLogger.debug(" Error encountered within GetAaiAR" + e.getMessage()) - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error in GetARbyId" + e.getMessage()) - } - msoLogger.debug(" ***** Exit GetARLinkbyId ***** Link:" + arLink) - return arLink - } - + // get Allotted resource using Link // used on Create called from getARORchStatus - // used on Delete called from getARbyId + // used on Delete called from ifExistsAR // setsVariable aaiARPath - used for Patch in create - public String getARbyLink (DelegateExecution execution, String link, String role) { + + public Optional<AllottedResource> getARbyLink (DelegateExecution execution, String link, String role) { msoLogger.trace("getARbyLink ") - String ar = null - String arUrl = null + Optional<AllottedResource> allottedResource = Optional.empty() try { - AaiUtil aaiUriUtil = new AaiUtil(taskProcessor) - String aai_endpoint = UrnPropertiesReader.getVariable("aai.endpoint", execution) - String arEndpoint = "" - - if(!isBlank(link)) { - msoLogger.debug("Incoming AR Resource Link is: " + link) - String[] split = link.split("/aai/") - arEndpoint = "/aai/" + split[1] - } - - arUrl = "${aai_endpoint}" + arEndpoint - - msoLogger.debug("GET AR Aai Path is: \n" + arUrl) - - APIResponse response = aaiUriUtil.executeAAIGetCall(execution, arUrl) - int responseCode = response.getStatusCode() - msoLogger.debug(" GET AR response code is: " + responseCode) - - String aaiResponse = response.getResponseBodyAsString() - msoLogger.debug("GET AR:" + aaiResponse) - if(responseCode == 200 || responseCode == 202){ - msoLogger.debug("GET AR Received a Good Response Code") - if(utils.nodeExists(aaiResponse, "allotted-resource")){ - if (!isBlank(role)) - { - if (utils.nodeExists(aaiResponse, "role") && role.equals(utils.getNodeText(aaiResponse, "role"))) { - ar = aaiResponse - }else{ - msoLogger.debug("AAI AR does not match input role:" + role) - } + msoLogger.debug("GET AR Aai Path is: \n" + link) + AAIResourceUri uri = AAIUriFactory.createResourceFromExistingURI(AAIObjectType.ALLOTTED_RESOURCE, UriBuilder.fromPath(link).build()) + allottedResource = getAAIClient().get(AllottedResource.class,uri); + if(allottedResource.isPresent()) { + if (!isBlank(role)) { + if (role == allottedResource.get().getRole()) { + setExecutionVariables(execution,allottedResource.get(),uri) + } else { + msoLogger.debug("AAI AR does not match input role:" + role) } - else - { - ar = aaiResponse - } - } - else - { - msoLogger.debug("GET AR Does NOT Contain Data" ) + } else { + setExecutionVariables(execution,allottedResource.get(),uri) } - }else if(responseCode == 404){ + }else{ msoLogger.debug("GET AR received a Not Found (404) Response") } - else{ - msoLogger.debug(" GET AR received a Bad Response: \n" + aaiResponse) - buildAAIErrorResponse(execution, aaiResponse, "Error retrieving AR from AAI") - } }catch(Exception e){ msoLogger.debug(" Error encountered within GetAaiAR" + e.getMessage()) exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error in GetAaiAR" + e.getMessage()) } - if (!isBlank(ar)) - { - execution.setVariable("aaiARGetResponse", ar) - execution.setVariable("aaiARPath", arUrl) - - String resourceVersion = null - if (utils.nodeExists(ar, "resource-version")) { - resourceVersion = utils.getNodeText(ar, "resource-version") - execution.setVariable("aaiARResourceVersion", resourceVersion) - } + return allottedResource + } - String orchStatus = null - if (utils.nodeExists(ar, "orchestration-status")) { - orchStatus= utils.getNodeText(ar, "orchestration-status") - } - else - { - orchStatus = " " - } - execution.setVariable("aaiAROrchStatus", orchStatus) + public void setExecutionVariables(DelegateExecution execution, AllottedResource ar, AAIResourceUri arUrl) { + execution.setVariable("aaiARGetResponse", ar) + execution.setVariable("aaiARPath", arUrl.build().toString()) + execution.setVariable("aaiARResourceVersion", ar.getResourceVersion()) + if (StringUtils.isNotEmpty(ar.getOrchestrationStatus())) { + execution.setVariable("aaiAROrchStatus", ar.getOrchestrationStatus()) + } + else + { + execution.setVariable("aaiAROrchStatus", " ") } - msoLogger.trace(" Exit GetARbyLink - AR:" + ar) - return ar } public void updateAROrchStatus(DelegateExecution execution, String status, String aaiARPath){ msoLogger.trace("updaAROrchStatus ") try{ - String updateReq = """ - { - "orchestration-status": "${status}" - } - """ - + AllottedResource allottedResource = new AllottedResource(); + allottedResource.setOrchestrationStatus(status) msoLogger.debug('AAI AR URI: ' + aaiARPath) - AaiUtil aaiUriUtil = new AaiUtil(taskProcessor) - APIResponse apiResponse = aaiUriUtil.executeAAIPatchCall(execution, aaiARPath, updateReq) - def aaiResponse = apiResponse.getResponseBodyAsString() - def responseCode = apiResponse.getStatusCode() - - msoLogger.debug("AAI Response Code: " + responseCode) - msoLogger.debug("AAI Response: " + aaiResponse) - if(responseCode == 200){ - msoLogger.debug("UpdateAR Good REST Response is: " + "\n" + aaiResponse) - }else{ - msoLogger.debug("UpdateAROrchStatus Bad REST Response!") - buildAAIErrorResponse(execution, aaiResponse, "Error updating AR OrchStatus in AAI") - } - - }catch(BpmnError b){ - msoLogger.debug("Rethrowing MSOWorkflowException ") - throw b + AAIResourceUri uri = AAIUriFactory.createResourceFromExistingURI(AAIObjectType.ALLOTTED_RESOURCE, UriBuilder.fromPath(aaiARPath).build()) + getAAIClient().update(uri,allottedResource) }catch(Exception e){ msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception in updateAR.", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, e.getMessage()); exceptionUtil.buildAndThrowWorkflowException(execution, 500, 'Internal Error in updateAROrchStatus.' + e.getMessage()) @@ -274,39 +201,20 @@ class AllottedResourceUtils { public void deleteAR(DelegateExecution execution, String aaiARPath){ msoLogger.trace(" deleteAR - aaiARPath:" + aaiARPath) try { - AaiUtil aaiUriUtil = new AaiUtil(taskProcessor) - APIResponse response = aaiUriUtil.executeAAIDeleteCall(execution, aaiARPath) - int responseCode = response.getStatusCode() - execution.setVariable("deleteARResponseCode", responseCode) - msoLogger.debug(" Delete AR response code:" + responseCode) - - String aaiResponse = response.getResponseBodyAsString() - execution.setVariable("aaiARDeleteResponse", aaiResponse) - - msoLogger.debug("Delete AR Response:" + aaiResponse) - - //Process Response - if(responseCode == 204){ - msoLogger.debug(" Delete AR Received a Good Response") - execution.setVariable("wasDeleted", "true") - }else if(responseCode == 404){ - msoLogger.debug(" Delete AR Received a Not Found (404) Response") - }else if(responseCode == 412){ - msoLogger.debug("Delete AR Received a Resource Version Mismatch Error: \n" + aaiResponse) - exceptionUtil.buildAndThrowWorkflowException(execution, 412, "DeleteAR Received a resource-version Mismatch Error Response from AAI") - }else{ - msoLogger.debug("Delete AR Received a BAD REST Response: \n" + aaiResponse) - buildAAIErrorResponse(execution, aaiResponse, "Error deleting AR in AAI") - exceptionUtil.MapAAIExceptionToWorkflowExceptionGeneric(execution, aaiResponse, responseCode) - } - }catch(BpmnError b){ - msoLogger.debug("Rethrowing MSOWorkflowException") - throw b + AAIResourceUri uri = AAIUriFactory.createResourceFromExistingURI(AAIObjectType.ALLOTTED_RESOURCE, UriBuilder.fromPath(aaiARPath).build()) + getAAIClient().delete(uri); + }catch(NotFoundException ex){ + msoLogger.debug(" Delete AR Received a Not Found (404) Response") + }catch(PreconditionFailedException ex){ + msoLogger.debug("Delete AR Received a Resource Version Mismatch Error: \n") + exceptionUtil.buildAndThrowWorkflowException(execution, 412, "DeleteAR Received a resource-version Mismatch Error Response from AAI") }catch(Exception e){ msoLogger.debug(" Error encountered in deleteAR!" + e) exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured During Delete AR") } + msoLogger.debug(" Delete AR Received a Good Response") + execution.setVariable("wasDeleted", "true") msoLogger.trace("Exit deleteAR ") } @@ -324,24 +232,8 @@ class AllottedResourceUtils { throw new BpmnError("MSOWorkflowException") } - public String createARUrl(DelegateExecution execution, AAIResourceUri uri, String allottedResourceId) { - AaiUtil aaiUriUtil = new AaiUtil(taskProcessor) - AAIResourceUri siResourceLink= uri - - String siUri = "" - - if(siResourceLink != null) { - msoLogger.debug("Incoming PSI Resource Link is: " + siResourceLink.build().toString()) - } - else - { - String msg = "Parent Service Link in AAI is null" - msoLogger.debug(msg) - exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) - } - AAIResourceUri arUri = AAIUriFactory.createResourceFromParentURI(siResourceLink, AAIObjectType.ALLOTTED_RESOURCE, allottedResourceId) - - return aaiUriUtil.createAaiUri(arUri) + public AAIResourcesClient getAAIClient(){ + return new AAIResourcesClient() } } diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/CatalogDbUtils.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/CatalogDbUtils.groovy index 9ce29dedb8..df0dfaee60 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/CatalogDbUtils.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/CatalogDbUtils.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,29 +20,22 @@ package org.onap.so.bpmn.common.scripts -import org.json.JSONObject; -import org.json.JSONArray; -import org.json.XML -import org.onap.so.bpmn.core.UrnPropertiesReader; -import org.springframework.web.util.UriUtils; - -import org.onap.so.bpmn.core.json.JsonUtils - - -import groovy.json.JsonBuilder -import groovy.json.JsonSlurper -import groovy.util.slurpersupport.GPathResult -import groovy.xml.QName; - +import org.apache.commons.lang3.StringUtils import org.camunda.bpm.engine.delegate.DelegateExecution - -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.json.JSONArray +import org.json.JSONObject +import org.onap.logging.ref.slf4j.ONAPLogConstants +import org.onap.so.bpmn.core.UrnPropertiesReader +import org.onap.so.bpmn.core.json.JsonUtils +import org.onap.so.client.HttpClient +import org.onap.so.client.HttpClientFactory import org.onap.so.logger.MessageEnum +import org.onap.so.logger.MsoLogger +import org.onap.so.utils.TargetEntity +import org.springframework.web.util.UriUtils - +import javax.ws.rs.core.MediaType +import javax.ws.rs.core.Response /*** * Utilities for accessing Catalog DB Adapter to retrieve Networks, VNF/VFModules, AllottedResources and complete ServiceResources information @@ -52,415 +45,15 @@ import org.onap.so.logger.MessageEnum class CatalogDbUtils { private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, CatalogDbUtils.class); - - MsoUtils utils = new MsoUtils() - JsonUtils jsonUtils = new JsonUtils() + private HttpClientFactory httpClientFactory + private MsoUtils msoUtils + private JsonUtils jsonUtils static private String defaultDbAdapterVersion = "v2" - public JSONArray getAllNetworksByServiceModelUuid(DelegateExecution execution, String serviceModelUuid) { - JSONArray networksList = null - String endPoint = "/serviceNetworks?serviceModelUuid=" + UriUtils.encode(serviceModelUuid, "UTF-8") - try { - String catalogDbResponse = getResponseFromCatalogDb(execution, endPoint) - - if (catalogDbResponse != null) { - networksList = parseNetworksJson(catalogDbResponse, "serviceNetworks", "v1") - } - - } - catch (Exception e) { - msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception in Querying Catalog DB", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, e.message); - throw e - } - - return networksList - } - - public JSONArray getAllNetworksByServiceModelUuid(DelegateExecution execution, String serviceModelUuid, String catalogUtilsVersion) { - JSONArray networksList = null - String endPoint = "/serviceNetworks?serviceModelUuid=" + UriUtils.encode(serviceModelUuid, "UTF-8") - try { - String catalogDbResponse = getResponseFromCatalogDb(execution, endPoint) - - if (catalogDbResponse != null) { - if (!catalogUtilsVersion.equals("v1")) { - JSONObject responseJson = new JSONObject(catalogDbResponse) - networksList = responseJson.getJSONArray("serviceNetworks") - } - else { - networksList = parseNetworksJson(catalogDbResponse, "serviceNetworks", catalogUtilsVersion) - } - } - - } - catch (Exception e) { - msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception in Querying Catalog DB", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, e.message); - throw e - } - - return networksList - } - - public JSONArray getAllNetworksByServiceModelInvariantUuid(DelegateExecution execution, String serviceModelInvariantUuid) { - JSONArray networksList = null - String endPoint = "/serviceNetworks?serviceModelInvariantUuid=" + UriUtils.encode(serviceModelInvariantUuid, "UTF-8") - try { - String catalogDbResponse = getResponseFromCatalogDb(execution, endPoint) - - if (catalogDbResponse != null) { - networksList = parseNetworksJson(catalogDbResponse, "serviceNetworks", "v1") - } - - } - catch (Exception e) { - msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception in Querying Catalog DB", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, e.message); - throw e - } - - return networksList - } - - public JSONArray getAllNetworksByServiceModelInvariantUuid(DelegateExecution execution, String serviceModelInvariantUuid, String catalogUtilsVersion) { - JSONArray networksList = null - String endPoint = "/serviceNetworks?serviceModelInvariantUuid=" + UriUtils.encode(serviceModelInvariantUuid, "UTF-8") - try { - String catalogDbResponse = getResponseFromCatalogDb(execution, endPoint) - - if (catalogDbResponse != null) { - if (!catalogUtilsVersion.equals("v1")) { - JSONObject responseJson = new JSONObject(catalogDbResponse) - networksList = responseJson.getJSONArray("serviceNetworks") - } - else { - networksList = parseNetworksJson(catalogDbResponse, "serviceNetworks", catalogUtilsVersion) - } - } - - } - catch (Exception e) { - msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception in Querying Catalog DB", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, e.message); - throw e - } - - return networksList - } - - public JSONArray getAllNetworksByServiceModelInvariantUuidAndServiceModelVersion(DelegateExecution execution, String serviceModelInvariantUuid, String serviceModelVersion) { - JSONArray networksList = null - String endPoint = "/serviceNetworks?serviceModelInvariantUuid=" + UriUtils.encode(serviceModelInvariantUuid, "UTF-8") + "&serviceModelVersion=" + UriUtils.encode(serviceModelVersion, "UTF-8") - try { - String catalogDbResponse = getResponseFromCatalogDb(execution, endPoint) - - if (catalogDbResponse != null) { - networksList = parseNetworksJson(catalogDbResponse, "serviceNetworks", "v1") - } - - } - catch (Exception e) { - msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception in Querying Catalog DB", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, e.message); - throw e - } - - return networksList - } - - public JSONArray getAllNetworksByServiceModelInvariantUuidAndServiceModelVersion(DelegateExecution execution, String serviceModelInvariantUuid, String serviceModelVersion, String catalogUtilsVersion) { - JSONArray networksList = null - String endPoint = "/serviceNetworks?serviceModelInvariantUuid=" + UriUtils.encode(serviceModelInvariantUuid, "UTF-8") + "&serviceModelVersion=" + UriUtils.encode(serviceModelVersion, "UTF-8") - try { - String catalogDbResponse = getResponseFromCatalogDb(execution, endPoint) - - if (catalogDbResponse != null) { - if (!catalogUtilsVersion.equals("v1")) { - JSONObject responseJson = new JSONObject(catalogDbResponse) - networksList = responseJson.getJSONArray("serviceNetworks") - } - else { - networksList = parseNetworksJson(catalogDbResponse, "serviceNetworks", catalogUtilsVersion) - } - } - - } - catch (Exception e) { - msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception in Querying Catalog DB", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, e.message); - throw e - } - - return networksList - } - - public JSONArray getAllNetworksByNetworkModelCustomizationUuid(DelegateExecution execution, String networkModelCustomizationUuid) { - JSONArray networksList = null - String endPoint = "/serviceNetworks?networkModelCustomizationUuid=" + UriUtils.encode(networkModelCustomizationUuid, "UTF-8") - try { - String catalogDbResponse = getResponseFromCatalogDb(execution, endPoint) - - if (catalogDbResponse != null) { - networksList = parseNetworksJson(catalogDbResponse, "serviceNetworks", "v1") - } - - } - catch (Exception e) { - msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception in Querying Catalog DB", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, e.message); - throw e - } - - return networksList - } - - public JSONArray getAllNetworksByNetworkModelCustomizationUuid(DelegateExecution execution, String networkModelCustomizationUuid, String catalogUtilsVersion) { - JSONArray networksList = null - String endPoint = "/serviceNetworks?networkModelCustomizationUuid=" + UriUtils.encode(networkModelCustomizationUuid, "UTF-8") - try { - String catalogDbResponse = getResponseFromCatalogDb(execution, endPoint) - - if (catalogDbResponse != null) { - if (!catalogUtilsVersion.equals("v1")) { - JSONObject responseJson = new JSONObject(catalogDbResponse) - networksList = responseJson.getJSONArray("serviceNetworks") - } - else { - networksList = parseNetworksJson(catalogDbResponse, "serviceNetworks", catalogUtilsVersion) - } - } - - } - catch (Exception e) { - msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception in Querying Catalog DB", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, e.message); - throw e - } - - return networksList - } - - public JSONArray getAllNetworksByNetworkType(DelegateExecution execution, String networkType) { - JSONArray networksList = null - String endPoint = "/serviceNetworks?networkType=" + UriUtils.encode(networkType, "UTF-8") - try { - String catalogDbResponse = getResponseFromCatalogDb(execution, endPoint) - - if (catalogDbResponse != null) { - networksList = parseNetworksJson(catalogDbResponse, "serviceNetworks", "v1") - } - - } - catch (Exception e) { - msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception in Querying Catalog DB", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, e.message); - throw e - } - - return networksList - } - - public JSONArray getAllNetworksByNetworkType(DelegateExecution execution, String networkType, String catalogUtilsVersion) { - JSONArray networksList = null - String endPoint = "/serviceNetworks?networkType=" + UriUtils.encode(networkType, "UTF-8") - try { - String catalogDbResponse = getResponseFromCatalogDb(execution, endPoint) - - if (catalogDbResponse != null) { - if (!catalogUtilsVersion.equals("v1")) { - JSONObject responseJson = new JSONObject(catalogDbResponse) - networksList = responseJson.getJSONArray("serviceNetworks") - } - else { - networksList = parseNetworksJson(catalogDbResponse, "serviceNetworks", catalogUtilsVersion) - } - } - - } - catch (Exception e) { - msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception in Querying Catalog DB", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, e.message); - throw e - } - - return networksList - } - - - public JSONArray getAllVnfsByServiceModelUuid(DelegateExecution execution, String serviceModelUuid) { - JSONArray vnfsList = null - String endPoint = "/serviceVnfs?serviceModelUuid=" + UriUtils.encode(serviceModelUuid, "UTF-8") - try { - msoLogger.debug("ENDPOINT: " + endPoint) - String catalogDbResponse = getResponseFromCatalogDb(execution, endPoint) - - if (catalogDbResponse != null) { - vnfsList = parseVnfsJson(catalogDbResponse, "serviceVnfs", "v1") - } - - } - catch (Exception e) { - msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception in Querying Catalog DB", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, e.message); - throw e - } - - return vnfsList - } - - public JSONArray getAllVnfsByServiceModelUuid(DelegateExecution execution, String serviceModelUuid, String catalogUtilsVersion) { - JSONArray vnfsList = null - String endPoint = "/serviceVnfs?serviceModelUuid=" + UriUtils.encode(serviceModelUuid, "UTF-8") - try { - msoLogger.debug("ENDPOINT: " + endPoint) - String catalogDbResponse = getResponseFromCatalogDb(execution, endPoint) - - if (catalogDbResponse != null) { - if (!catalogUtilsVersion.equals("v1")) { - JSONObject responseJson = new JSONObject(catalogDbResponse) - vnfsList = responseJson.getJSONArray("serviceVnfs") - } - else { - vnfsList = parseVnfsJson(catalogDbResponse, "serviceVnfs", catalogUtilsVersion) - } - } - - } - catch (Exception e) { - msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception in Querying Catalog DB", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, e.message); - throw e - } - - return vnfsList - } - - public JSONArray getAllVnfsByServiceModelInvariantUuid(DelegateExecution execution, String serviceModelInvariantUuid) { - JSONArray vnfsList = null - String endPoint ="/serviceVnfs?serviceModelInvariantUuid=" + UriUtils.encode(serviceModelInvariantUuid, "UTF-8") - try { - msoLogger.debug("ENDPOINT: " + endPoint) - String catalogDbResponse = getResponseFromCatalogDb(execution, endPoint) - - if (catalogDbResponse != null) { - vnfsList = parseVnfsJson(catalogDbResponse, "serviceVnfs", "v1") - } - - } - catch (Exception e) { - msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception in Querying Catalog DB", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, e.message); - throw e - } - - return vnfsList - } - - public JSONArray getAllVnfsByServiceModelInvariantUuid(DelegateExecution execution, String serviceModelInvariantUuid, String catalogUtilsVersion) { - JSONArray vnfsList = null - String endPoint = "/serviceVnfs?serviceModelInvariantUuid=" + UriUtils.encode(serviceModelInvariantUuid, "UTF-8") - try { - msoLogger.debug("ENDPOINT: " + endPoint) - String catalogDbResponse = getResponseFromCatalogDb(execution, endPoint) - - if (catalogDbResponse != null) { - if (!catalogUtilsVersion.equals("v1")) { - JSONObject responseJson = new JSONObject(catalogDbResponse) - vnfsList = responseJson.getJSONArray("serviceVnfs") - } - else { - vnfsList = parseVnfsJson(catalogDbResponse, "serviceVnfs", catalogUtilsVersion) - } - } - - } - catch (Exception e) { - msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception in Querying Catalog DB", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, e.message); - throw e - } - - return vnfsList - } - - public JSONArray getAllVnfsByServiceModelInvariantUuidAndServiceModelVersion(DelegateExecution execution, String serviceModelInvariantUuid, String serviceModelVersion) { - JSONArray vnfsList = null - String endPoint = "/serviceVnfs?serviceModelInvariantUuid=" + UriUtils.encode(serviceModelInvariantUuid, "UTF-8") + "&serviceModelVersion=" + UriUtils.encode(serviceModelVersion, "UTF-8") - try { - msoLogger.debug("ENDPOINT: " + endPoint) - String catalogDbResponse = getResponseFromCatalogDb(execution, endPoint) - - if (catalogDbResponse != null) { - vnfsList = parseVnfsJson(catalogDbResponse, "serviceVnfs", "v1") - } - - } - catch (Exception e) { - msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception in Querying Catalog DB", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, e.message); - throw e - } - - return vnfsList - } - - public JSONArray getAllVnfsByServiceModelInvariantUuidAndServiceModelVersion(DelegateExecution execution, String serviceModelInvariantUuid, String serviceModelVersion, String catalogUtilsVersion) { - JSONArray vnfsList = null - String endPoint = "/serviceVnfs?serviceModelInvariantUuid=" + UriUtils.encode(serviceModelInvariantUuid, "UTF-8") + "&serviceModelVersion=" + UriUtils.encode(serviceModelVersion, "UTF-8") - try { - msoLogger.debug("ENDPOINT: " + endPoint) - String catalogDbResponse = getResponseFromCatalogDb(execution, endPoint) - - if (catalogDbResponse != null) { - if (!catalogUtilsVersion.equals("v1")) { - JSONObject responseJson = new JSONObject(catalogDbResponse) - vnfsList = responseJson.getJSONArray("serviceVnfs") - } - else { - vnfsList = parseVnfsJson(catalogDbResponse, "serviceVnfs", catalogUtilsVersion) - } - } - - } - catch (Exception e) { - msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception in Querying Catalog DB", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, e.message); - throw e - } - - return vnfsList - } - - public JSONArray getAllVnfsByVnfModelCustomizationUuid(DelegateExecution execution, String vnfModelCustomizationUuid) { - JSONArray vnfsList = null - String endPoint = "/serviceVnfs?vnfModelCustomizationUuid=" + UriUtils.encode(vnfModelCustomizationUuid, "UTF-8") - try { - msoLogger.debug("ENDPOINT: " + endPoint) - String catalogDbResponse = getResponseFromCatalogDb(execution, endPoint) - - if (catalogDbResponse != null) { - vnfsList = parseVnfsJson(catalogDbResponse, "serviceVnfs", "v1") - } - - } - catch (Exception e) { - msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception in Querying Catalog DB", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, e.message); - throw e - } - - return vnfsList - } - - /** - * This method gets a all vnfs for a particular - * service from the catalog database using the - * service model's model name. - * - * @param catalogDbEndpoint - * @param serviceModelModelName - * @return vnfsList * - * - */ - public JSONArray getAllVnfsByServiceModelModelName(DelegateExecution execution, String serviceModelModelName) { - JSONArray vnfsList = null - String endPoint = "/serviceVnfs?serviceModelName=" + UriUtils.encode(serviceModelModelName, "UTF-8") - try { - msoLogger.debug("ENDPOINT: " + endPoint) - String catalogDbResponse = getResponseFromCatalogDb(execution, endPoint) - - if (catalogDbResponse != null) { - vnfsList = parseVnfsJson(catalogDbResponse, "serviceVnfs", defaultDbAdapterVersion) - } - }catch (Exception e) { - msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception in Querying Catalog DB", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, e.message); - throw e - } - return vnfsList + CatalogDbUtils(HttpClientFactory httpClientFactory, MsoUtils msoUtils, JsonUtils jsonUtils) { + this.httpClientFactory = httpClientFactory + this.msoUtils = msoUtils + this.jsonUtils = jsonUtils } public JSONArray getAllVnfsByVnfModelCustomizationUuid(DelegateExecution execution, String vnfModelCustomizationUuid, String catalogUtilsVersion) { @@ -489,263 +82,6 @@ class CatalogDbUtils { return vnfsList } - /** - * This method gets a single vf module from - * the catalog database using the vf module's - * model name. It returns that vf module as - * a JSONObject - * - * @param catalogDbEndpoint - * @param vfModuleModelName - * @return vfModule - */ - public JSONObject getVfModuleByVfModuleModelName(DelegateExecution execution, String vfModuleModelName) { - JSONObject vfModule = null - String endPoint = "/vfModules?vfModuleModelName=" + UriUtils.encode(vfModuleModelName, "UTF-8") - try{ - msoLogger.debug("Get VfModule By VfModule ModelName Endpoint is: " + endPoint) - String catalogDbResponse = getResponseFromCatalogDb(execution, endPoint) - - if (catalogDbResponse != null) { - vfModule = parseVfModuleJson(catalogDbResponse, "vfModules", "v1") - } - } - catch(Exception e){ - msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception in Querying Catalog DB", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, e.message); - throw e - } - - return vfModule - } - - /** - * This method gets a single vf module from - * the catalog database using the vf module's - * model name. It returns that vf module as - * a JSONObject - * - * @param catalogDbEndpoint - * @param vfModuleModelName - * @param catalogUtilsVersion - * @return vfModules - */ - public JSONObject getVfModuleByVfModuleModelName(DelegateExecution execution, String vfModuleModelName, String catalogUtilsVersion) { - JSONObject vfModule = null - String endPoint = "/vfModules?vfModuleModelName=" + UriUtils.encode(vfModuleModelName, "UTF-8") - try{ - msoLogger.debug("Get VfModule By VfModule ModelName Endpoint is: " + endPoint) - String catalogDbResponse = getResponseFromCatalogDb(execution, endPoint) - - if (catalogDbResponse != null) { - vfModule = parseVfModuleJson(catalogDbResponse, "vfModules", "v1") - } - } - catch(Exception e){ - msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception in Querying Catalog DB", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, e.message); - throw e - } - - return vfModule - } - - - public JSONArray getAllottedResourcesByServiceModelUuid(DelegateExecution execution, String serviceModelUuid) { - JSONArray vnfsList = null - String endPoint = "/ServiceAllottedResources?serviceModelUuid=" + UriUtils.encode(serviceModelUuid, "UTF-8") - try { - String catalogDbResponse = getResponseFromCatalogDb(execution, endPoint) - - if (catalogDbResponse != null) { - vnfsList = parseAllottedResourcesJson(catalogDbResponse, "serviceAllottedResources", "v1") - } - - } - catch (Exception e) { - msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception in Querying Catalog DB", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, e.message); - throw e - } - - return vnfsList - } - - public JSONArray getAllottedResourcesByServiceModelUuid(DelegateExecution execution, String serviceModelUuid, String catalogUtilsVersion) { - JSONArray vnfsList = null - String endPoint = "/ServiceAllottedResources?serviceModelUuid=" + UriUtils.encode(serviceModelUuid, "UTF-8") - try { - String catalogDbResponse = getResponseFromCatalogDb(execution, endPoint) - - if (catalogDbResponse != null) { - if (!catalogUtilsVersion.equals("v1")) { - JSONObject responseJson = new JSONObject(catalogDbResponse) - vnfsList = responseJson.getJSONArray("serviceAllottedResources") - } - else { - vnfsList = parseAllottedResourcesJson(catalogDbResponse, "serviceAllottedResources", catalogUtilsVersion) - } - } - - } - catch (Exception e) { - msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception in Querying Catalog DB", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, e.message); - throw e - } - - return vnfsList - } - - public JSONArray getAllottedResourcesByServiceModelInvariantUuid(DelegateExecution execution, String serviceModelInvariantUuid) { - JSONArray vnfsList = null - String endPoint = "/serviceAllottedResources?serviceModelInvariantUuid=" + UriUtils.encode(serviceModelInvariantUuid, "UTF-8") - try { - String catalogDbResponse = getResponseFromCatalogDb(execution, endPoint) - - if (catalogDbResponse != null) { - vnfsList = parseAllottedResourcesJson(catalogDbResponse, "serviceAllottedResources", "v1") - } - - } - catch (Exception e) { - msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception in Querying Catalog DB", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, e.message); - throw e - } - - return vnfsList - } - - public JSONArray getAllottedResourcesByServiceModelInvariantUuid(DelegateExecution execution, String serviceModelInvariantUuid, String catalogUtilsVersion) { - JSONArray vnfsList = null - String endPoint = "/serviceAllottedResources?serviceModelInvariantUuid=" + UriUtils.encode(serviceModelInvariantUuid, "UTF-8") - try { - String catalogDbResponse = getResponseFromCatalogDb(execution, endPoint) - - if (catalogDbResponse != null) { - if (!catalogUtilsVersion.equals("v1")) { - JSONObject responseJson = new JSONObject(catalogDbResponse) - vnfsList = responseJson.getJSONArray() - } - else { - vnfsList = parseAllottedResourcesJson(catalogDbResponse, "serviceAllottedResources", catalogUtilsVersion) - } - } - - } - catch (Exception e) { - msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception in Querying Catalog DB", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, e.getStackTrace()); - throw e - } - - return vnfsList - } - - public JSONArray getAllottedResourcesByServiceModelInvariantUuidAndServiceModelVersion(DelegateExecution execution, String serviceModelInvariantUuid, String serviceModelVersion) { - JSONArray vnfsList = null - String endPoint = "/serviceAllottedResources?serviceModelInvariantUuid=" + UriUtils.encode(serviceModelInvariantUuid, "UTF-8") + "&serviceModelVersion=" + UriUtils.encode(serviceModelVersion, "UTF-8") - try { - String catalogDbResponse = getResponseFromCatalogDb(execution, endPoint) - - if (catalogDbResponse != null) { - vnfsList = parseAllottedResourcesJson(catalogDbResponse, "serviceAllottedResources", "v1") - } - - } - catch (Exception e) { - msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception in Querying Catalog DB", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, e.message); - throw e - } - - return vnfsList - } - - public JSONArray getAllottedResourcesByServiceModelInvariantUuidAndServiceModelVersion(DelegateExecution execution, String serviceModelInvariantUuid, String serviceModelVersion, String catalogUtilsVersion) { - JSONArray vnfsList = null - String endPoint = "/serviceAllottedResources?serviceModelInvariantUuid=" + UriUtils.encode(serviceModelInvariantUuid, "UTF-8") + "&serviceModelVersion=" + UriUtils.encode(serviceModelVersion, "UTF-8") - try { - String catalogDbResponse = getResponseFromCatalogDb(execution, endPoint) - - if (catalogDbResponse != null) { - if (!catalogUtilsVersion.equals("v1")) { - JSONObject responseJson = new JSONObject(catalogDbResponse) - vnfsList = responseJson.getJSONArray("serviceAllottedResources") - } - else { - vnfsList = parseAllottedResourcesJson(catalogDbResponse, "serviceAllottedResources", catalogUtilsVersion) - } - } - - } - catch (Exception e) { - msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception in Querying Catalog DB", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, e.message); - throw e - } - - return vnfsList - } - - - public JSONArray getAllottedResourcesByArModelCustomizationUuid(DelegateExecution execution, String arModelCustomizationUuid) { - JSONArray vnfsList = null - String endPoint = "/serviceAllottedResources?serviceModelCustomizationUuid=" + UriUtils.encode(arModelCustomizationUuid, "UTF-8") - try { - String catalogDbResponse = getResponseFromCatalogDb(execution, endPoint) - - if (catalogDbResponse != null) { - vnfsList = parseAllottedResourcesJson(catalogDbResponse, "serviceAllottedResources", "v1") - } - - } - catch (Exception e) { - msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception in Querying Catalog DB", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, e.message); - throw e - } - - return vnfsList - } - - public JSONArray getAllottedResourcesByArModelCustomizationUuid(DelegateExecution execution, String arModelCustomizationUuid, String catalogUtilsVersion) { - JSONArray vnfsList = null - String endPoint = "/serviceAllottedResources?serviceModelCustomizationUuid=" + UriUtils.encode(arModelCustomizationUuid, "UTF-8") - try { - String catalogDbResponse = getResponseFromCatalogDb(execution, endPoint) - - if (catalogDbResponse != null) { - if (!catalogUtilsVersion.equals("v1")) { - JSONObject responseJson = new JSONObject(catalogDbResponse) - vnfsList = responseJson.getJSONArray("serviceAllottedResources") - } - else { - vnfsList = parseAllottedResourcesJson(catalogDbResponse, "serviceAllottedResources", catalogUtilsVersion) - } - } - - } - catch (Exception e) { - msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception in Querying Catalog DB", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, e.message); - throw e - } - - return vnfsList - } - - public JSONObject getServiceResourcesByServiceModelUuid(DelegateExecution execution, String serviceModelUuid) { - JSONObject resources = null - String endPoint = "/serviceResources?serviceModelUuid=" + UriUtils.encode(serviceModelUuid, "UTF-8") - try { - String catalogDbResponse = getResponseFromCatalogDb(execution, endPoint) - - if (catalogDbResponse != null) { - - resources = parseServiceResourcesJson(catalogDbResponse, "v1") - } - - } - catch (Exception e) { - utils.log("ERROR", "Exception in Querying Catalog DB: " + e.message) - throw e - } - - return resources - } - public JSONObject getServiceResourcesByServiceModelUuid(DelegateExecution execution, String serviceModelUuid, String catalogUtilsVersion) { JSONObject resources = null String endPoint = "/serviceResources?serviceModelUuid=" + UriUtils.encode(serviceModelUuid, "UTF-8") @@ -762,27 +98,7 @@ class CatalogDbUtils { } } catch (Exception e) { - utils.log("ERROR", "Exception in Querying Catalog DB: " + e.message) - throw e - } - - return resources - } - - public JSONObject getServiceResourcesByServiceModelInvariantUuid(DelegateExecution execution, String serviceModelInvariantUuid) { - JSONObject resources = null - String endPoint = "/serviceResources?serviceModelInvariantUuid=" + UriUtils.encode(serviceModelInvariantUuid, "UTF-8") - try { - String catalogDbResponse = getResponseFromCatalogDb(execution, endPoint) - - if (catalogDbResponse != null) { - - resources = parseServiceResourcesJson(catalogDbResponse, "v1") - } - - } - catch (Exception e) { - msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception in Querying Catalog DB", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, e.message); + msoUtils.log("ERROR", "Exception in Querying Catalog DB: " + e.message) throw e } @@ -790,23 +106,14 @@ class CatalogDbUtils { } public String getServiceResourcesByServiceModelInvariantUuidString(DelegateExecution execution, String serviceModelInvariantUuid) { - String resources = null String endPoint = "/serviceResources?serviceModelInvariantUuid=" + UriUtils.encode(serviceModelInvariantUuid, "UTF-8") try { - String catalogDbResponse = getResponseFromCatalogDb(execution, endPoint) - - if (catalogDbResponse != null) { - - resources = catalogDbResponse - } - + return getResponseFromCatalogDb(execution, endPoint) } catch (Exception e) { msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception in Querying Catalog DB", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, e.message); throw e } - - return resources } public JSONObject getServiceResourcesByServiceModelInvariantUuid(DelegateExecution execution, String serviceModelInvariantUuid, String catalogUtilsVersion) { @@ -833,27 +140,6 @@ class CatalogDbUtils { return resources } - - public JSONObject getServiceResourcesByServiceModelInvariantUuidAndServiceModelVersion(DelegateExecution execution, String serviceModelInvariantUuid, String serviceModelVersion) { - JSONObject resources = null - String endPoint = "/serviceResources?serviceModelInvariantUuid=" + UriUtils.encode(serviceModelInvariantUuid, "UTF-8") + "&serviceModelVersion=" + UriUtils.encode(serviceModelVersion, "UTF-8") - try { - String catalogDbResponse = getResponseFromCatalogDb(execution, endPoint) - - if (catalogDbResponse != null) { - //TODO this is wrong - resources = parseServiceResourcesJson(catalogDbResponse) - } - - } - catch (Exception e) { - msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception in Querying Catalog DB", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, e.message); - throw e - } - - return resources - } - public JSONObject getServiceResourcesByServiceModelInvariantUuidAndServiceModelVersion(DelegateExecution execution, String serviceModelInvariantUuid, String serviceModelVersion, String catalogUtilsVersion) { JSONObject resources = null String endPoint = "/serviceResources?serviceModelInvariantUuid=" + UriUtils.encode(serviceModelInvariantUuid, "UTF-8") + "&serviceModelVersion=" + UriUtils.encode(serviceModelVersion, "UTF-8") @@ -878,8 +164,6 @@ class CatalogDbUtils { return resources } - - private JSONArray parseNetworksJson (String catalogDbResponse, String arrayName, String catalogUtilsVersion) { JSONArray modelInfos = null @@ -982,22 +266,7 @@ class CatalogDbUtils { vfModuleModelJson.put("modelInfo", vfModuleModelInfo) String vfModuleType = jsonUtils.getJsonValueForKey(vfModule, "type") vfModuleModelJson.put("vfModuleType", vfModuleType) - switch(catalogUtilsVersion) { - case "v1": - //TODO this does not work, isBase is not a integer. - Integer isBase = jsonUtils.getJsonIntValueForKey(vfModule, "isBase") - if (isBase.intValue() == 1) { - vfModuleModelJson.put("isBase", "true") - } - else { - vfModuleModelJson.put("isBase", "false") - } - break - default: - boolean isBase = jsonUtils.getJsonBooleanValueForKey(vfModule, "isBase") - vfModuleModelJson.put("isBase", isBase) - break - } + vfModuleModelJson.put("isBase", jsonUtils.getJsonBooleanValueForKey(vfModule, "isBase")) String vfModuleLabel = jsonUtils.getJsonValueForKey(vfModule, "label") vfModuleModelJson.put("vfModuleLabel", vfModuleLabel) Integer initialCount = jsonUtils.getJsonIntValueForKey(vfModule, "initialCount") @@ -1019,58 +288,6 @@ class CatalogDbUtils { return modelInfos } - /** - * This method parses a Vf Module from the - * Vf Modules array - * - * @param catalogDbResponse - * @param arrayName - * @param catalogUtilsVersion - * @return vfModulelJson - */ - private JSONObject parseVfModuleJson (String catalogDbResponse, String arrayName, String catalogUtilsVersion) { - JSONObject vfModulelJson = new JSONObject() - msoLogger.debug("Started Parse Vf Module Json") - try { - JSONObject responseJson = new JSONObject(catalogDbResponse) - JSONArray vfModules = responseJson.getJSONArray(arrayName) - if(vfModules != null){ - JSONObject vfModuleInfo = new JSONObject() - for (int i = 0; i < vfModules.length(); i++) { - JSONObject vfModule = vfModules.getJSONObject(i) - JSONObject vfModuleModelInfo = buildModelInfo("vfModule", vfModule, catalogUtilsVersion) - vfModulelJson.put("modelInfo", vfModuleModelInfo) - String vfModuleType = jsonUtils.getJsonValueForKey(vfModule, "type") - vfModulelJson.put("vfModuleType", vfModuleType) - switch(catalogUtilsVersion) { - case "v1": - Integer isBase = jsonUtils.getJsonIntValueForKey(vfModule, "isBase") - if (isBase.intValue() == 1) { - vfModulelJson.put("isBase", "true") - } - else { - vfModulelJson.put("isBase", "false") - } - break - default: - boolean isBase = jsonUtils.getJsonBooleanValueForKey(vfModule, "isBase") - vfModulelJson.put("isBase", isBase) - break - } - String vfModuleLabel = jsonUtils.getJsonValueForKey(vfModule, "label") - vfModulelJson.put("vfModuleLabel", vfModuleLabel) - Integer initialCount = jsonUtils.getJsonIntValueForKey(vfModule, "initialCount") - vfModulelJson.put("initialCount", initialCount.intValue()) - } - } - msoLogger.debug("Completed Parsing Vf Module: " + vfModulelJson.toString()) - }catch (Exception e){ - msoLogger.debug("Exception while parsing Vf Modules from Catalog DB Response: " + e.message) - } - - return vfModulelJson - } - private JSONArray parseAllottedResourcesJson (String catalogDbResponse, String arrayName, String catalogUtilsVersion) { JSONArray modelInfos = null @@ -1123,37 +340,9 @@ class CatalogDbUtils { return modelInfos } - //TODO this is wrong - private JSONObject parseServiceResourcesJson (String catalogDbResponse) { - JSONObject serviceResources = new JSONObject() - String catalogUtilsVersion = "v1" - - try { - // Create array of jsons - - JSONObject responseJson = new JSONObject(catalogDbResponse) - JSONObject serviceResourcesRoot = responseJson.getJSONObject("serviceResources") - JSONArray vnfsArray = parseVnfsJson(serviceResourcesRoot.toString(), "vnfResources", catalogUtilsVersion) - serviceResources.put("vnfs", vnfsArray) - JSONArray networksArray = parseNetworksJson(serviceResourcesRoot.toString(), "networkResourceCustomization", catalogUtilsVersion) - serviceResources.put("networks", networksArray) - JSONArray allottedResourcesArray = parseAllottedResourcesJson(serviceResourcesRoot.toString(), "allottedResourceCustomization", catalogUtilsVersion) - serviceResources.put("allottedResources", allottedResourcesArray) - - String serviceResourcesString = serviceResources.toString() - msoLogger.debug("Returning serviceResources JSON: " + serviceResourcesString) - - } catch (Exception e) { - msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception in parsing Catalog DB Response", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, e.message); - } - - return serviceResources - } - private JSONObject parseServiceResourcesJson (String catalogDbResponse, String catalogUtilsVersion) { JSONObject serviceResources = new JSONObject() JSONObject serviceResourcesObject = new JSONObject() - String serviceResourcesString = "" try { // Create array of jsons @@ -1169,9 +358,7 @@ class CatalogDbUtils { JSONArray allottedResourcesArray = parseAllottedResourcesJson(serviceResourcesRoot.toString(), "serviceAllottedResources", catalogUtilsVersion) serviceResources.put("serviceAllottedResources", allottedResourcesArray) serviceResourcesObject.put("serviceResources", serviceResources) - - serviceResourcesString = serviceResourcesObject.toString() - msoLogger.debug("Returning serviceResources JSON: " + serviceResourcesString) + msoLogger.debug("Returning serviceResources JSON: " + serviceResourcesObject.toString()) } catch (Exception e) { msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception in parsing Catalog DB Response", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, e.message); @@ -1230,32 +417,25 @@ class CatalogDbUtils { String catalogDbEndpoint = UrnPropertiesReader.getVariable("mso.catalog.db.endpoint",execution) String queryEndpoint = catalogDbEndpoint + "/" + defaultDbAdapterVersion + endPoint - RESTConfig config = new RESTConfig(queryEndpoint); def responseData = '' - def bpmnRequestId = UUID.randomUUID().toString() - RESTClient client = new RESTClient(config). - addHeader('X-TransactionId', bpmnRequestId). - addHeader('X-FromAppId', 'BPMN'). - addHeader('Content-Type', 'application/json'). - addHeader('Accept','application/json'); - + HttpClient client = httpClientFactory.newJsonClient(new URL(queryEndpoint), TargetEntity.CATALOG_DB) + client.addAdditionalHeader(ONAPLogConstants.Headers.REQUEST_ID, UUID.randomUUID().toString()) + client.addAdditionalHeader('X-FromAppId', "BPMN") + client.addAdditionalHeader('Accept', MediaType.APPLICATION_JSON) String basicAuthCred = execution.getVariable("BasicAuthHeaderValueDB") - if (basicAuthCred != null && !"".equals(basicAuthCred)) { - client.addAuthorizationHeader(basicAuthCred) - }else { - client.addAuthorizationHeader(getBasicDBAuthHeader(execution)) - } + client.addAdditionalHeader("Authorization", StringUtils.defaultIfEmpty(basicAuthCred, getBasicDBAuthHeader(execution))) + msoLogger.debug('sending GET to Catalog DB endpoint: ' + endPoint) - APIResponse response = client.httpGet() + Response response = client.get() - responseData = response.getResponseBodyAsString() + responseData = response.readEntity(String.class) if (responseData != null) { msoLogger.debug("Received data from Catalog DB: " + 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 response as needed return responseData } @@ -1285,27 +465,27 @@ class CatalogDbUtils { } } catch (Exception e) { - utils.log("ERROR", "Exception in Querying Catalog DB: " + e.message) + msoUtils.log("ERROR", "Exception in Querying Catalog DB: " + e.message) throw e } return responseJson } - + private String getBasicDBAuthHeader(DelegateExecution execution) { - + String encodedString = null try { String basicAuthValueDB = UrnPropertiesReader.getVariable("mso.adapters.db.auth", execution) - utils.log("DEBUG", " Obtained BasicAuth userid password for Catalog DB adapter: " + basicAuthValueDB) - - encodedString = utils.getBasicAuth(basicAuthValueDB, UrnPropertiesReader.getVariable("mso.msoKey", execution)) + msoUtils.log("DEBUG", " Obtained BasicAuth userid password for Catalog DB adapter: " + basicAuthValueDB) + + encodedString = msoUtils.getBasicAuth(basicAuthValueDB, UrnPropertiesReader.getVariable("mso.msoKey", execution)) execution.setVariable("BasicAuthHeaderValueDB",encodedString) } catch (IOException ex) { String dataErrorMessage = " Unable to encode Catalog DB user/password string - " + ex.getMessage() - utils.log("ERROR", dataErrorMessage) + msoUtils.log("ERROR", dataErrorMessage) } return encodedString } - + }
\ No newline at end of file diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/CatalogDbUtilsFactory.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/CatalogDbUtilsFactory.groovy new file mode 100644 index 0000000000..faa0037169 --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/CatalogDbUtilsFactory.groovy @@ -0,0 +1,31 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2018 NOKIA. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.common.scripts + +import org.onap.so.bpmn.core.json.JsonUtils +import org.onap.so.client.HttpClientFactory + +public class CatalogDbUtilsFactory { + + CatalogDbUtils create() { + return new CatalogDbUtils(new HttpClientFactory(), new MsoUtils(), new JsonUtils()) + } +} diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/CompleteMsoProcess.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/CompleteMsoProcess.groovy index c19851d223..865b9ee8a7 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/CompleteMsoProcess.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/CompleteMsoProcess.groovy @@ -243,7 +243,7 @@ public class CompleteMsoProcess extends AbstractServiceTaskProcessor { msoLogger.trace('Entered ' + method) try { - def msoCompletionResponse = """ + String msoCompletionResponse = """ <sdncadapterworkflow:MsoCompletionResponse xmlns:sdncadapterworkflow="http://org.onap/so/workflow/schema/v1"> <sdncadapterworkflow:out>BPEL ${execution.getVariable("CMSO_mso-bpel-name")} FAILED</sdncadapterworkflow:out> </sdncadapterworkflow:MsoCompletionResponse> @@ -275,7 +275,7 @@ public class CompleteMsoProcess extends AbstractServiceTaskProcessor { // msoLogger.trace("Started CompleteMsoProcess PostProcessRequest Method "); try { - def msoCompletionResponse = """ + String msoCompletionResponse = """ <sdncadapterworkflow:MsoCompletionResponse xmlns:sdncadapterworkflow="http://ecomp.com/mso/workflow/schema/v1"> <sdncadapterworkflow:out>BPEL ${execution.getVariable("CMSO_mso-bpel-name")} completed</sdncadapterworkflow:out> </sdncadapterworkflow:MsoCompletionResponse> diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/ConfirmVolumeGroupName.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/ConfirmVolumeGroupName.groovy index c309c3bb68..f4e7926c8e 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/ConfirmVolumeGroupName.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/ConfirmVolumeGroupName.groovy @@ -4,6 +4,8 @@ * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright 2018 Nokia + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -19,6 +21,11 @@ */ package org.onap.so.bpmn.common.scripts + +import joptsimple.internal.Strings +import org.onap.so.bpmn.common.scripts.ExceptionUtil +import org.springframework.http.HttpStatus + import javax.ws.rs.core.UriBuilder import org.camunda.bpm.engine.delegate.DelegateExecution @@ -33,8 +40,12 @@ import org.onap.so.logger.MsoLogger public class ConfirmVolumeGroupName extends AbstractServiceTaskProcessor{ private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, ConfirmVolumeGroupName.class); - def Prefix="CVGN_" - ExceptionUtil exceptionUtil = new ExceptionUtil() + def static final Prefix = "CVGN_" + private final ExceptionUtil exceptionUtil + + ConfirmVolumeGroupName(ExceptionUtil exceptionUtil) { + this.exceptionUtil = exceptionUtil + } public void initProcessVariables(DelegateExecution execution) { execution.setVariable("prefix",Prefix) @@ -74,40 +85,39 @@ public class ConfirmVolumeGroupName extends AbstractServiceTaskProcessor{ try { Optional<VolumeGroup> volumeGroupOp = getAAIClient().get(VolumeGroup.class, resourceUri) if(volumeGroupOp.isPresent()){ - execution.setVariable("CVGN_queryVolumeGroupResponseCode", 200) + execution.setVariable("CVGN_queryVolumeGroupResponseCode", HttpStatus.OK.value()) execution.setVariable("CVGN_queryVolumeGroupResponse", volumeGroupOp.get()) }else{ - execution.setVariable("CVGN_queryVolumeGroupResponseCode", 404) + execution.setVariable("CVGN_queryVolumeGroupResponseCode", HttpStatus.NOT_FOUND.value()) execution.setVariable("CVGN_queryVolumeGroupResponse", "Volume Group not Found!") } } catch (Exception ex) { msoLogger.debug("Exception occurred while executing AAI GET:" + ex.getMessage()) - execution.setVariable("CVGN_queryVolumeGroupResponseCode", 500) + execution.setVariable("CVGN_queryVolumeGroupResponseCode", HttpStatus.INTERNAL_SERVER_ERROR.value()) execution.setVariable("CVGN_queryVolumeGroupResponse", "AAI GET Failed:" + ex.getMessage()) - exceptionUtil.buildAndThrowWorkflowException(execution, 500, "AAI GET Failed") + exceptionUtil.buildAndThrowWorkflowException(execution, HttpStatus.INTERNAL_SERVER_ERROR.value(), "AAI GET Failed") } } // process the result from queryAAIVolumeGroupId() public void checkAAIQueryResult(DelegateExecution execution) { - def result = execution.getVariable("CVGN_queryVolumeGroupResponse") - def actualVolumeGroupName = "" - if (execution.getVariable("CVGN_queryVolumeGroupResponseCode") == 404) { + if (execution.getVariable("CVGN_queryVolumeGroupResponseCode") == HttpStatus.NOT_FOUND.value()) { msoLogger.debug('volumeGroupId does not exist in AAI') } - else if (execution.getVariable("CVGN_queryVolumeGroupResponseCode") == 200) { + else if (execution.getVariable("CVGN_queryVolumeGroupResponseCode") == HttpStatus.OK.value()) { VolumeGroup volumeGroup = execution.getVariable("CVGN_queryVolumeGroupResponse") - if(volumeGroup.getVolumeGroupName()!=null){ + + if (!Strings.isNullOrEmpty(volumeGroup.getVolumeGroupName())) { actualVolumeGroupName = volumeGroup.getVolumeGroupName() - } - msoLogger.debug("volumeGroupId exists in AAI") + msoLogger.debug("volumeGroupId exists in AAI") + } } execution.setVariable("CVGN_volumeGroupNameMatches", false) def volumeGroupName = execution.getVariable("CVGN_volumeGroupName") - if (volumeGroupName.equals(actualVolumeGroupName)) { + if (!actualVolumeGroupName.isEmpty() && volumeGroupName.equals(actualVolumeGroupName)) { msoLogger.debug('Volume Group Name Matches AAI records') execution.setVariable("CVGN_volumeGroupNameMatches", true) } @@ -121,8 +131,8 @@ public class ConfirmVolumeGroupName extends AbstractServiceTaskProcessor{ // generates a WorkflowException if the volume group name does not match AAI record for this volume group public void handleVolumeGroupNameNoMatch(DelegateExecution execution) { - def errorNotAssociated = "Error occurred - volume group id " + execution.getVariable("CVGN_volumeGroupId") + - " is not associated with " + execution.getVariable("CVGN_volumeGroupName") + def errorNotAssociated = "Error occurred - volume group id ${execution.getVariable('CVGN_volumeGroupId')} " + + "is not associated with ${execution.getVariable('CVGN_volumeGroupName')}" msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, errorNotAssociated, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, ""); exceptionUtil.buildAndThrowWorkflowException(execution, 1002, errorNotAssociated) } diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/ConfirmVolumeGroupNameFactory.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/ConfirmVolumeGroupNameFactory.groovy new file mode 100644 index 0000000000..f032d640d5 --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/ConfirmVolumeGroupNameFactory.groovy @@ -0,0 +1,31 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2018 Nokia. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.common.scripts + +import org.onap.so.bpmn.common.scripts.ConfirmVolumeGroupName +import org.onap.so.bpmn.common.scripts.ExceptionUtil + +public class ConfirmVolumeGroupNameFactory { + + ConfirmVolumeGroupName create() { + return new ConfirmVolumeGroupName(new ExceptionUtil()); + } +} diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/ConfirmVolumeGroupTenant.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/ConfirmVolumeGroupTenant.groovy index 13904c372d..47a4612672 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/ConfirmVolumeGroupTenant.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/ConfirmVolumeGroupTenant.groovy @@ -20,27 +20,17 @@ package org.onap.so.bpmn.common.scripts -import org.onap.so.bpmn.core.UrnPropertiesReader - -import javax.xml.parsers.DocumentBuilder -import javax.xml.parsers.DocumentBuilderFactory - -import org.apache.commons.lang3.* import org.camunda.bpm.engine.delegate.BpmnError import org.camunda.bpm.engine.delegate.DelegateExecution -import org.onap.so.bpmn.core.WorkflowException -import org.onap.so.rest.APIResponse -import org.w3c.dom.Document -import org.w3c.dom.Element -import org.w3c.dom.Node -import org.w3c.dom.NodeList -import org.xml.sax.InputSource -import org.onap.so.logger.MessageEnum -import org.onap.so.logger.MsoLogger +import org.onap.aai.domain.yang.VolumeGroup import org.onap.so.client.aai.AAIObjectType +import org.onap.so.client.aai.entities.AAIResultWrapper +import org.onap.so.client.aai.entities.Relationships import org.onap.so.client.aai.entities.uri.AAIResourceUri import org.onap.so.client.aai.entities.uri.AAIUriFactory import org.onap.so.constants.Defaults +import org.onap.so.logger.MessageEnum +import org.onap.so.logger.MsoLogger /** * Vnf Module Subflow for confirming the volume group belongs @@ -59,60 +49,26 @@ class ConfirmVolumeGroupTenant extends AbstractServiceTaskProcessor{ public void preProcessRequest(DelegateExecution execution){ execution.setVariable("prefix", Prefix) msoLogger.trace("STARTED Confirm Volume Group Tenant Subflow ") - String processKey = getProcessKey(execution); try{ msoLogger.trace("Started QueryAAIForVolumeGroup Process ") String volumeGroupId = execution.getVariable("volumeGroupId") String incomingGroupName = execution.getVariable("volumeGroupName") String incomingTenantId = execution.getVariable("tenantId") - def aicCloudRegion = execution.getVariable("aicCloudRegion") - - AaiUtil aaiUriUtil = new AaiUtil(this) + String aicCloudRegion = execution.getVariable("aicCloudRegion") AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.VOLUME_GROUP, Defaults.CLOUD_OWNER.toString(), aicCloudRegion, volumeGroupId) - String path = aaiUriUtil.createAaiUri(uri) - - APIResponse queryAAIForVolumeGroupResponse = aaiUriUtil.executeAAIGetCall(execution, path) - - def responseCode = queryAAIForVolumeGroupResponse.getStatusCode() - execution.setVariable("queryVolumeGroupResponseCode", responseCode) - String response = queryAAIForVolumeGroupResponse.getResponseBodyAsString() - - msoLogger.debug("ConfirmVolumeGroup Response: " + response) - msoLogger.debug("ConfirmVolumeGroup Response Code: " + responseCode) - - if(responseCode == 200 && response != null){ - execution.setVariable("queryAAIVolumeGroupResponse", response) - msoLogger.debug("QueryAAIForVolumeGroup Received a Good REST Response is: \n" + response) - + AAIResultWrapper wrapper = getAAIClient().get(uri); + Optional<VolumeGroup> volumeGroup = wrapper.asBean(VolumeGroup.class) + Optional<Relationships> relationships = wrapper.getRelationships() + if(volumeGroup.isPresent()){ + execution.setVariable("queryAAIVolumeGroupResponse", volumeGroup.get()) String volumeGroupTenantId = "" - InputSource source = new InputSource(new StringReader(response)); - DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); - docFactory.setNamespaceAware(true) - DocumentBuilder docBuilder = docFactory.newDocumentBuilder() - Document createVCERequestXml = docBuilder.parse(source) - NodeList nodeList = createVCERequestXml.getElementsByTagNameNS("*", "relationship") - for (int x = 0; x < nodeList.getLength(); x++) { - Node node = nodeList.item(x) - if (node.getNodeType() == Node.ELEMENT_NODE) { - Element eElement = (Element) node - String e = eElement.getElementsByTagNameNS("*", "related-to").item(0).getTextContent() - if(e.equals("tenant")){ - NodeList relationDataList = eElement.getElementsByTagNameNS("*", "relationship-data") - for (int d = 0; d < relationDataList.getLength(); d++) { - Node dataNode = relationDataList.item(d) - if (dataNode.getNodeType() == Node.ELEMENT_NODE) { - Element dElement = (Element) dataNode - String key = dElement.getElementsByTagNameNS("*", "relationship-key").item(0).getTextContent() - if(key.equals("tenant.tenant-id")){ - volumeGroupTenantId = dElement.getElementsByTagNameNS("*", "relationship-value").item(0).getTextContent() - } - } - } - } + if(relationships.isPresent()){ + List<AAIResourceUri> tenantUris = relationships.get().getRelatedAAIUris(AAIObjectType.TENANT) + for (AAIResourceUri tenantURI: tenantUris){ + volumeGroupTenantId = tenantURI.getURIKeys().get("tenant-id") } } - //Determine if Tenant Ids match if(incomingTenantId.equals(volumeGroupTenantId)){ msoLogger.debug("Tenant Ids Match") @@ -123,7 +79,7 @@ class ConfirmVolumeGroupTenant extends AbstractServiceTaskProcessor{ } //Determine if Volume Group Names match - String volumeGroupName = utils.getNodeText(response, "volume-group-name") + String volumeGroupName = volumeGroup.get().getVolumeGroupName() if(incomingGroupName == null || incomingGroupName.length() < 1){ msoLogger.debug("Incoming Volume Group Name is NOT Provided.") execution.setVariable("groupNamesMatch", true) @@ -145,7 +101,7 @@ class ConfirmVolumeGroupTenant extends AbstractServiceTaskProcessor{ }catch(BpmnError b){ throw b }catch(Exception e){ - msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception Occured Processing queryAAIForVolumeGroup.", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, e); + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception Occured Processing queryAAIForVolumeGroup.", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, e.getMessage()); exceptionUtil.buildAndThrowWorkflowException(execution, 5000, "Internal Error - Occured in preProcessRequest.") } msoLogger.trace("COMPLETED queryAAIForVolumeGroup Process ") @@ -156,8 +112,8 @@ class ConfirmVolumeGroupTenant extends AbstractServiceTaskProcessor{ try{ msoLogger.trace("Started assignVolumeHeatId Process ") - String response = execution.getVariable("queryAAIVolumeGroupResponse") - String heatStackId = utils.getNodeText(response, "heat-stack-id") + VolumeGroup volumeGroup = execution.getVariable("queryAAIVolumeGroupResponse") + String heatStackId = volumeGroup.getHeatStackId() execution.setVariable("volumeHeatStackId", heatStackId) execution.setVariable("ConfirmVolumeGroupTenantResponse", heatStackId) // TODO: Should deprecate use of processKey+Response variable for the response. Will use "WorkflowResponse" instead diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/CreateAAIVfModule.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/CreateAAIVfModule.groovy index 3bbc4bd110..370600755b 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/CreateAAIVfModule.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/CreateAAIVfModule.groovy @@ -19,25 +19,27 @@ */ package org.onap.so.bpmn.common.scripts + +import org.apache.commons.lang.StringUtils import org.camunda.bpm.engine.delegate.DelegateExecution +import org.onap.aai.domain.yang.GenericVnf import org.onap.so.bpmn.core.RollbackData -import org.onap.so.bpmn.core.UrnPropertiesReader +import org.onap.so.client.aai.AAIObjectPlurals import org.onap.so.client.aai.AAIObjectType import org.onap.so.client.aai.entities.uri.AAIResourceUri import org.onap.so.client.aai.entities.uri.AAIUriFactory import org.onap.so.client.graphinventory.entities.uri.Depth +import org.onap.so.db.catalog.beans.OrchestrationStatus import org.onap.so.logger.MessageEnum import org.onap.so.logger.MsoLogger -import org.onap.so.rest.APIResponse -import org.springframework.web.util.UriUtils public class CreateAAIVfModule extends AbstractServiceTaskProcessor{ private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, CreateAAIVfModule.class); - def Prefix="CAAIVfMod_" + def prefix="CAAIVfMod_" ExceptionUtil exceptionUtil = new ExceptionUtil() public void initProcessVariables(DelegateExecution execution) { - execution.setVariable("prefix",Prefix) + execution.setVariable("prefix",prefix) execution.setVariable("CAAIVfMod_vnfId",null) execution.setVariable("CAAIVfMod_vnfName",null) execution.setVariable("CAAIVfMod_vnfType",null) @@ -94,55 +96,25 @@ public class CreateAAIVfModule extends AbstractServiceTaskProcessor{ execution.setVariable("CAAIVfMod_vnfName", vnfName) String vnfType = execution.getVariable("vnfType") - if (vnfType != null && !vnfType.isEmpty()) { - execution.setVariable("CAAIVfMod_vnfType", vnfType) - } else { - execution.setVariable("CAAIVfMod_vnfType","") - } + execution.setVariable("CAAIVfMod_vnfType", StringUtils.defaultString(vnfType)) execution.setVariable("CAAIVfMod_serviceId", execution.getVariable("serviceId")) String personaModelId = execution.getVariable("personaModelId") + execution.setVariable("CAAIVfMod_personaId",StringUtils.defaultString(personaModelId)) - if (personaModelId != null && !personaModelId.isEmpty()) { - execution.setVariable("CAAIVfMod_personaId",personaModelId) - } else { - execution.setVariable("CAAIVfMod_personaId","") - } - String personaModelVersion = execution.getVariable("personaModelVersion") + execution.setVariable("CAAIVfMod_personaVer", StringUtils.defaultString(personaModelVersion)) - if (personaModelVersion != null && !personaModelVersion.isEmpty()) { - execution.setVariable("CAAIVfMod_personaVer", personaModelVersion) - } else { - execution.setVariable("CAAIVfMod_personaVer","") - } - - String modelCustomizationId = execution.getVariable("modelCustomizationId") + execution.setVariable("CAAIVfMod_modelCustomizationId",StringUtils.defaultString(modelCustomizationId)) - if (modelCustomizationId != null && !modelCustomizationId.isEmpty()) { - execution.setVariable("CAAIVfMod_modelCustomizationId",modelCustomizationId) - } else { - execution.setVariable("CAAIVfMod_modelCustomizationId","") - } - String vnfPersonaModelId = execution.getVariable("vnfPersonaModelId") - - if (vnfPersonaModelId != null && !vnfPersonaModelId.isEmpty()) { - execution.setVariable("CAAIVfMod_vnfPersonaId",vnfPersonaModelId) - } else { - execution.setVariable("CAAIVfMod_vnfPersonaId","") - } - + execution.setVariable("CAAIVfMod_vnfPersonaId", StringUtils.defaultString(vnfPersonaModelId)) + String vnfPersonaModelVersion = execution.getVariable("vnfPersonaModelVersion") + execution.setVariable("CAAIVfMod_vnfPersonaVer", StringUtils.defaultString(vnfPersonaModelVersion)) - if (vnfPersonaModelVersion != null && !vnfPersonaModelVersion.isEmpty()) { - execution.setVariable("CAAIVfMod_vnfPersonaVer",vnfPersonaModelVersion) - } else { - execution.setVariable("CAAIVfMod_vnfPersonaVer","") - } - //isBaseVfModule Boolean isBaseVfModule = false String isBaseVfModuleString = execution.getVariable("isBaseVfModule") @@ -150,7 +122,7 @@ public class CreateAAIVfModule extends AbstractServiceTaskProcessor{ isBaseVfModule = true } execution.setVariable("CAAIVfMod_isBaseVfModule", isBaseVfModule) - + String isVidRequest = execution.getVariable("isVidRequest") if (isVidRequest != null && "true".equals(isVidRequest)) { msoLogger.debug("VID Request received") @@ -163,45 +135,33 @@ public class CreateAAIVfModule extends AbstractServiceTaskProcessor{ String aaiNamespace = aaiUriUtil.getNamespace() msoLogger.debug('AAI namespace is: ' + aaiNamespace) - execution.setVariable("CAAIVfMod_aaiNamespace","${aaiNamespace}") + execution.setVariable("CAAIVfMod_aaiNamespace",aaiNamespace) } - + // send a GET request to AA&I to retrieve the Generic VNF/VF Module information based on a Vnf Name // expect a 200 response with the information in the response body or a 404 if the Generic VNF does not exist public void queryAAIForGenericVnf(DelegateExecution execution) { - - AaiUtil aaiUtil = new AaiUtil(this) + AAIResourceUri uri - def vnfId = execution.getVariable("CAAIVfMod_vnfId") def vnfName = execution.getVariable("CAAIVfMod_vnfName") - if (vnfId == null || vnfId.isEmpty()) { - uri = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, "") + uri = AAIUriFactory.createResourceUri(AAIObjectPlurals.GENERIC_VNF) uri.queryParam("vnf-name", vnfName) } else { uri = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId) } - uri.depth(Depth.ONE) - String endPoint = aaiUtil.createAaiUri(uri) - try { - msoLogger.debug("queryAAIForGenericVnf() endpoint-" + endPoint) - msoLogger.debug("invoking GET call to AAI endpoint :"+System.lineSeparator()+endPoint) - msoLogger.debug("CreateAAIVfModule sending GET call to AAI Endpoint: " + endPoint) - - APIResponse response = aaiUtil.executeAAIGetCall(execution, endPoint) - def responseData = response.getResponseBodyAsString() - def statusCode = response.getStatusCode() - execution.setVariable("CAAIVfMod_queryGenericVnfResponseCode", statusCode) - execution.setVariable("CAAIVfMod_queryGenericVnfResponse", responseData) - - msoLogger.debug("CreateAAIVfModule Response Code: " + statusCode) - msoLogger.debug("CreateAAIVfModule Response data: " + responseData) - msoLogger.debug("Response code:" + statusCode) - msoLogger.debug("Response:" + System.lineSeparator()+responseData) + Optional<GenericVnf> genericVnfOp = getAAIClient().get(GenericVnf.class, uri) + if(genericVnfOp.isPresent()){ + execution.setVariable("CAAIVfMod_queryGenericVnfResponseCode", 200) + execution.setVariable("CAAIVfMod_queryGenericVnfResponse", genericVnfOp.get()) + }else{ + execution.setVariable("CAAIVfMod_queryGenericVnfResponseCode", 404) + execution.setVariable("CAAIVfMod_queryGenericVnfResponse", "Generic Vnf not Found!") + } } catch (Exception ex) { msoLogger.debug("Exception occurred while executing AAI GET:" + ex.getMessage()) exceptionUtil.buildAndThrowWorkflowException(execution, 5000, "Internal Error - Occured in queryAAIForGenericVnf.") @@ -212,8 +172,6 @@ public class CreateAAIVfModule extends AbstractServiceTaskProcessor{ // process the result from queryAAIForGenericVnf() // note: this method is primarily for logging as the actual decision logic is embedded in the bpmn flow public void processAAIGenericVnfQuery(DelegateExecution execution) { - def result = execution.getVariable("CAAIVfMod_queryGenericVnfResponse") - if (execution.getVariable("CAAIVfMod_queryGenericVnfResponseCode") == 404 && execution.getVariable("CAAIVfMod_vnfId").isEmpty()) { msoLogger.debug("New Generic VNF requested and it does not already exist") @@ -242,36 +200,20 @@ public class CreateAAIVfModule extends AbstractServiceTaskProcessor{ def newVnfId = UUID.randomUUID().toString() execution.setVariable("CAAIVfMod_vnfId",newVnfId) - String payload = """<generic-vnf xmlns="${execution.getVariable("CAAIVfMod_aaiNamespace")}"> - <vnf-id>${MsoUtils.xmlEscape(newVnfId)}</vnf-id> - <vnf-name>${MsoUtils.xmlEscape(execution.getVariable("CAAIVfMod_vnfName"))}</vnf-name> - <vnf-type>${MsoUtils.xmlEscape(execution.getVariable("CAAIVfMod_vnfType"))}</vnf-type> - <service-id>${MsoUtils.xmlEscape(execution.getVariable("CAAIVfMod_serviceId"))}</service-id> - <orchestration-status>Active</orchestration-status> - <model-invariant-id>${MsoUtils.xmlEscape(execution.getVariable("CAAIVfMod_vnfPersonaId"))}</model-invariant-id> - <model-version-id>${MsoUtils.xmlEscape(execution.getVariable("CAAIVfMod_vnfPersonaVer"))}</model-version-id> - </generic-vnf>""" as String - execution.setVariable("CAAIVfMod_createGenericVnfPayload", payload) + GenericVnf genericVnf = new GenericVnf() + genericVnf.setVnfId(newVnfId) + genericVnf.setVnfName(execution.getVariable("CAAIVfMod_vnfName")) + genericVnf.setVnfType(execution.getVariable("CAAIVfMod_vnfType")) + genericVnf.setServiceId(execution.getVariable("CAAIVfMod_serviceId")) + genericVnf.setOrchestrationStatus(OrchestrationStatus.ACTIVE.toString()) + genericVnf.setModelInvariantId(execution.getVariable("CAAIVfMod_vnfPersonaId")) + genericVnf.setModelVersionId(execution.getVariable("CAAIVfMod_vnfPersonaVer")) try { - AaiUtil aaiUtil = new AaiUtil(this) AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, newVnfId) - String endPoint = aaiUtil.createAaiUri(uri) - - msoLogger.debug("createGenericVnf() endpoint-" + endPoint) - msoLogger.debug("invoking PUT call to AAI with payload:"+System.lineSeparator()+payload) - msoLogger.debug("Sending PUT call to AAI with Endpoint /n" + endPoint + " with payload /n" + payload) - - APIResponse response = aaiUtil.executeAAIPutCall(execution, endPoint, payload); - def responseData = response.getResponseBodyAsString() - def responseStatusCode = response.getStatusCode() - execution.setVariable("CAAIVfMod_createGenericVnfResponseCode", responseStatusCode) - execution.setVariable("CAAIVfMod_createGenericVnfResponse", responseData) - - msoLogger.debug("Response Code: " + responseStatusCode) - msoLogger.debug("Response Data: " + responseData) - msoLogger.debug("Response code:" + responseStatusCode) - msoLogger.debug("Response:" + System.lineSeparator()+responseData) + getAAIClient().create(uri,genericVnf) + execution.setVariable("CAAIVfMod_createGenericVnfResponseCode", 201) + execution.setVariable("CAAIVfMod_createGenericVnfResponse", "Vnf Created") } catch (Exception ex) { ex.printStackTrace() msoLogger.debug("Exception occurred while executing AAI PUT:" + ex.getMessage()) @@ -293,24 +235,9 @@ public class CreateAAIVfModule extends AbstractServiceTaskProcessor{ int moduleIndex = 0 if (!isBaseModule) { - def aaiVnfResponse = execution.getVariable("CAAIVfMod_queryGenericVnfResponse") - AaiUtil aaiUtil = new AaiUtil(this) - def personaModelId = execution.getVariable("CAAIVfMod_personaId") - - // Check if the response includes model-invariant-id or persona-model-id - // note: getRequiredNodeText() throws an exception if the field is missing - // need to retun a null for the subsequent "either/or" logic to work properly -// def modelInvariantId = getRequiredNodeText(execution, aaiVnfResponse,'model-invariant-id') - def modelInvariantId = getNodeText(aaiVnfResponse,'model-invariant-id', null) - def fieldToCheck = 'model-invariant-id' - if (!modelInvariantId) { - fieldToCheck = 'persona-model-id' - } - - moduleIndex = aaiUtil.getLowestUnusedVfModuleIndexFromAAIVnfResponse(execution, aaiVnfResponse, - fieldToCheck, personaModelId) + GenericVnf aaiVnfResponse = execution.getVariable("CAAIVfMod_queryGenericVnfResponse") + moduleIndex = getLowestUnusedVfModuleIndexFromAAIVnfResponse(aaiVnfResponse,execution) } - def moduleIndexString = String.valueOf(moduleIndex) // if we get to this point, we may be about to create the Vf Module, // add rollback information about the Generic VNF for this base/add-on module @@ -323,38 +250,26 @@ public class CreateAAIVfModule extends AbstractServiceTaskProcessor{ rollbackData.put("VFMODULE", "isBaseModule", isBaseModule.toString()) execution.setVariable("RollbackData", rollbackData) msoLogger.debug("RollbackData:" + rollbackData) - String payload = """<vf-module xmlns="${execution.getVariable("CAAIVfMod_aaiNamespace")}"> - <vf-module-id>${MsoUtils.xmlEscape(newModuleId)}</vf-module-id> - <vf-module-name>${MsoUtils.xmlEscape(execution.getVariable("CAAIVfMod_moduleName"))}</vf-module-name> - <model-invariant-id>${MsoUtils.xmlEscape(execution.getVariable("CAAIVfMod_personaId"))}</model-invariant-id> - <model-version-id>${MsoUtils.xmlEscape(execution.getVariable("CAAIVfMod_personaVer"))}</model-version-id> - <model-customization-id>${MsoUtils.xmlEscape(execution.getVariable("CAAIVfMod_modelCustomizationId"))}</model-customization-id> - <is-base-vf-module>${MsoUtils.xmlEscape(isBaseModule)}</is-base-vf-module> - <orchestration-status>PendingCreate</orchestration-status> - <module-index>${MsoUtils.xmlEscape(moduleIndex)}</module-index> - </vf-module>""" as String - execution.setVariable("CAAIVfMod_createVfModulePayload", payload) + + org.onap.aai.domain.yang.VfModule vfModule = new org.onap.aai.domain.yang.VfModule() + vfModule.setVfModuleId(newModuleId) + vfModule.setVfModuleName(execution.getVariable("CAAIVfMod_moduleName")) + vfModule.setModelInvariantId(execution.getVariable("CAAIVfMod_personaId")) + vfModule.setModelVersionId(execution.getVariable("CAAIVfMod_personaVer")) + vfModule.setModelCustomizationId(execution.getVariable("CAAIVfMod_modelCustomizationId")) + vfModule.setIsBaseVfModule(isBaseModule) + vfModule.setOrchestrationStatus(OrchestrationStatus.PENDING_CREATE.toString()) + vfModule.setModuleIndex(moduleIndex) try { - - AaiUtil aaiUtil = new AaiUtil(this) + AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.VF_MODULE, vnfId, newModuleId) - String endPoint = aaiUtil.createAaiUri(uri) - - msoLogger.debug("createVfModule() endpoint-" + endPoint) - msoLogger.debug("invoking PUT call to AAI with payload:"+System.lineSeparator()+payload) - msoLogger.debug("CreateAAIVfModule sending PUT call to AAI with endpoint /n" + endPoint + " with payload /n " + payload) - - APIResponse response = aaiUtil.executeAAIPutCall(execution, endPoint, payload) - def responseData = response.getResponseBodyAsString() - def statusCode = response.getStatusCode() + getAAIClient().create(uri,vfModule) + def statusCode = 201 execution.setVariable("CAAIVfMod_createVfModuleResponseCode", statusCode) - execution.setVariable("CAAIVfMod_createVfModuleResponse", responseData) - - msoLogger.debug("Response code:" + statusCode) - msoLogger.debug("Response:" + System.lineSeparator()+responseData) - msoLogger.debug("Response Code: " + statusCode) - msoLogger.debug("Response data: " + responseData) + execution.setVariable("CAAIVfMod_createVfModuleResponse", "Vf Module Created") + + // the base or add-on VF Module was successfully created, // add the module name to the rollback data and the response if (isOneOf(statusCode, 200, 201)) { @@ -366,7 +281,7 @@ public class CreateAAIVfModule extends AbstractServiceTaskProcessor{ String responseOut = "" String isVidRequest = execution.getVariable("isVidRequest") - + def moduleIndexString = String.valueOf(moduleIndex) if (isBaseModule && (isVidRequest == null || "false".equals(isVidRequest))) { responseOut = """<CreateAAIVfModuleResponse> @@ -389,42 +304,69 @@ public class CreateAAIVfModule extends AbstractServiceTaskProcessor{ msoLogger.debug("CreateAAIVfModule Response /n " + responseOut) } } catch (Exception ex) { + execution.setVariable("CAAIVfMod_createVfModuleResponseCode", 500) + execution.setVariable("CAAIVfMod_createVfModuleResponse", ex.getMessage()) msoLogger.debug("Exception occurred while executing AAI PUT:" + ex.getMessage()) exceptionUtil.buildAndThrowWorkflowException(execution, 5000, "Internal Error - Occured in createVfModule.") } } - + + private int getLowestUnusedVfModuleIndexFromAAIVnfResponse(GenericVnf genericVnf,DelegateExecution execution){ + String personaModelId = execution.getVariable("CAAIVfMod_personaId") + if(genericVnf!=null && genericVnf.getVfModules()!= null && + !genericVnf.getVfModules().getVfModule().isEmpty()){ + Set<Integer> moduleIndices = new TreeSet<>() + for(org.onap.aai.domain.yang.VfModule vfModule in genericVnf.getVfModules().getVfModule()){ + if(genericVnf.getModelInvariantId()==null){ + if(vfModule.getPersonaModelVersion().equals(personaModelId) && vfModule.getModuleIndex()!=null) + moduleIndices.add(vfModule.getModuleIndex()) + }else{ + if(vfModule.getModelInvariantId().equals(personaModelId) && vfModule.getModuleIndex()!=null) + moduleIndices.add(vfModule.getModuleIndex()) + } + } + for(i in 0..moduleIndices.size()-1){ + if(moduleIndices.getAt(i) != i){ + return i; + } + } + return moduleIndices.size() + }else{ + return 0 + } + + } + // parses the output from the result from queryAAIForGenericVnf() to determine if the vf-module-name // requested for an Add-on VF Module does not already exist for the specified Generic VNF // also retrieves VNF name from AAI response for existing VNF public void parseForAddOnModule(DelegateExecution execution) { - def xml = execution.getVariable("CAAIVfMod_queryGenericVnfResponse") - def vnfNameFromAAI = utils.getNodeText(xml, "vnf-name") + GenericVnf genericVnf = execution.getVariable("CAAIVfMod_queryGenericVnfResponse") + def vnfNameFromAAI = genericVnf.getVnfName() execution.setVariable("CAAIVfMod_vnfNameFromAAI", vnfNameFromAAI) msoLogger.debug("Obtained vnf-name from AAI for existing VNF: " + vnfNameFromAAI) def newModuleName = execution.getVariable("CAAIVfMod_moduleName") msoLogger.debug("VF Module to be added: " + newModuleName) - def qryModuleNameList = utils.getMultNodes(xml, "vf-module-name") execution.setVariable("CAAIVfMod_moduleExists", false) - if (qryModuleNameList != null) { - msoLogger.debug("Existing VF Module List: " + qryModuleNameList) - for (String qryModuleName : qryModuleNameList) { + if (genericVnf !=null && genericVnf.getVfModules()!=null && !genericVnf.getVfModules().getVfModule().isEmpty()) { + def qryModuleList = genericVnf.getVfModules().getVfModule() + msoLogger.debug("Existing VF Module List: " + qryModuleList) + for (org.onap.aai.domain.yang.VfModule qryModule : qryModuleList) { + def qryModuleName = qryModule.getVfModuleName() if (newModuleName.equals(qryModuleName)) { // a module with the requested name already exists - failure - msoLogger.debug("VF Module " + qryModuleName + " already exists for Generic VNF " + execution.getVariable("CAAIVfMod_vnfNameFromAAI")) + msoLogger.debug("VF Module " + qryModuleName + " already exists for Generic VNF " + vnfNameFromAAI) execution.setVariable("CAAIVfMod_moduleExists", true) execution.setVariable("CAAIVfMod_parseModuleResponse", - "VF Module " + qryModuleName + " already exists for Generic VNF " + - execution.getVariable("CAAIVfMod_vnfNameFromAAI")) + "VF Module " + qryModuleName + " already exists for Generic VNF " + vnfNameFromAAI) break } } } if (execution.getVariable("CAAIVfMod_moduleExists") == false) { - msoLogger.debug("VF Module " + execution.getVariable("CAAIVfMod_moduleName") + " does not exist for Generic VNF " + execution.getVariable("CAAIVfMod_vnfNameFromAAI")) + msoLogger.debug("VF Module " + execution.getVariable("CAAIVfMod_moduleName") + " does not exist for Generic VNF " + vnfNameFromAAI) execution.setVariable("CAAIVfMod_parseModuleResponse", - "VF Module " + newModuleName + " does not exist for Generic VNF " + - execution.getVariable("CAAIVfMod_vnfNameFromAAI")) + "VF Module " + newModuleName + " does not exist for Generic VNF " + vnfNameFromAAI) } } @@ -432,49 +374,47 @@ public class CreateAAIVfModule extends AbstractServiceTaskProcessor{ // requested for an Add-on VF Module does not already exist for the specified Generic VNF; // also retrieves VNF name from AAI response for existing VNF public void parseForBaseModule(DelegateExecution execution) { - def xml = execution.getVariable("CAAIVfMod_queryGenericVnfResponse") - def vnfNameFromAAI = utils.getNodeText(xml, "vnf-name") + GenericVnf genericVnf = execution.getVariable("CAAIVfMod_queryGenericVnfResponse") + def vnfNameFromAAI = genericVnf.getVnfName() execution.setVariable("CAAIVfMod_vnfNameFromAAI", vnfNameFromAAI) msoLogger.debug("Obtained vnf-name from AAI for existing VNF: " + vnfNameFromAAI) def newModuleName = execution.getVariable("CAAIVfMod_moduleName") msoLogger.debug("VF Module to be added: " + newModuleName) - def qryModuleNameList = utils.getMultNodes(xml, "vf-module-name") + def qryModuleList = genericVnf !=null ? genericVnf.getVfModules():null; execution.setVariable("CAAIVfMod_moduleExists", false) - if (qryModuleNameList != null) { - msoLogger.debug("Existing VF Module List: " + qryModuleNameList) - for (String qryModuleName : qryModuleNameList) { - if (newModuleName.equals(qryModuleName)) { + if (qryModuleList != null && !qryModuleList.getVfModule().isEmpty()) { + def qryModules = qryModuleList.getVfModule() + msoLogger.debug("Existing VF Module List: " + qryModules) + for (org.onap.aai.domain.yang.VfModule qryModule : qryModules) { + if (newModuleName.equals(qryModule.getVfModuleName())) { // a module with the requested name already exists - failure - msoLogger.debug("VF Module " + qryModuleName + " already exists for Generic VNF " + execution.getVariable("CAAIVfMod_vnfNameFromAAI")) + msoLogger.debug("VF Module " + qryModule.getVfModuleName() + " already exists for Generic VNF " + vnfNameFromAAI) execution.setVariable("CAAIVfMod_baseModuleConflict", true) execution.setVariable("CAAIVfMod_parseModuleResponse", - "VF Module " + qryModuleName + " already exists for Generic VNF " + - execution.getVariable("CAAIVfMod_vnfNameFromAAI")) + "VF Module " + qryModule.getVfModuleName() + " already exists for Generic VNF " + vnfNameFromAAI) break } } } - def isBaseVfModuleList = utils.getMultNodes(xml, "is-base-vf-module") - if (isBaseVfModuleList != null && !execution.getVariable("CAAIVfMod_baseModuleConflict")) { - - for (String baseValue : isBaseVfModuleList) { - if (baseValue.equals("true")) { + + if (qryModuleList != null && !qryModuleList.getVfModule().isEmpty() && !execution.getVariable("CAAIVfMod_baseModuleConflict")) { + def qryModules = qryModuleList.getVfModule() + for (org.onap.aai.domain.yang.VfModule qryModule : qryModules) { + if (qryModule.isBaseVfModule) { // a base module already exists in this VNF - failure - msoLogger.debug("Base VF Module already exists for Generic VNF " + execution.getVariable("CAAIVfMod_vnfNameFromAAI")) + msoLogger.debug("Base VF Module already exists for Generic VNF " + vnfNameFromAAI) execution.setVariable("CAAIVfMod_baseModuleConflict", true) execution.setVariable("CAAIVfMod_parseModuleResponse", - "Base VF Module already exists for Generic VNF " + - execution.getVariable("CAAIVfMod_vnfNameFromAAI")) + "Base VF Module already exists for Generic VNF " + vnfNameFromAAI) break } } } - if (execution.getVariable("CAAIVfMod_moduleExists") == false && execution.getVariable("CAAIVfMod_baseModuleConflict") == false) { + if (execution.getVariable("CAAIVfMod_baseModuleConflict") == false) { msoLogger.debug("VF Module " + execution.getVariable("CAAIVfMod_moduleName") + " does not exist for Generic VNF " + execution.getVariable("CAAIVfMod_vnfNameFromAAI")) execution.setVariable("CAAIVfMod_parseModuleResponse", - "VF Module " + newModuleName + " does not exist for Generic VNF " + - execution.getVariable("CAAIVfMod_vnfNameFromAAI")) + "VF Module " + newModuleName + " does not exist for Generic VNF " + vnfNameFromAAI) } } @@ -534,73 +474,4 @@ public class CreateAAIVfModule extends AbstractServiceTaskProcessor{ exceptionUtil.buildAndThrowWorkflowException(execution, errorCode, errorResponse) msoLogger.debug("Workflow exception occurred in CreateAAIVfModule: " + errorResponse) } - - /** - * Performs a rollback. - * TBD: This method requires additional testing once integrated with the - * main CreateVfModule flow. - * @param execution the execution - */ - public void rollback(DelegateExecution execution) { - def method = getClass().getSimpleName() + ".rollback(" + - "execution=" + execution.getId() + - ")" - msoLogger.debug("Entered " + method) - - try { - RollbackData rollbackData = (RollbackData) execution.getVariable("RollbackData") - msoLogger.debug("RollbackData:" + rollbackData) - - AaiUtil aaiUriUtil = new AaiUtil(this) - - if (rollbackData != null) { - if (rollbackData.hasType("VFMODULE")) { - // use the DeleteAAIVfModule groovy methods for the rollback - def vnfId = rollbackData.get("VFMODULE", "vnfId") - def vfModuleId = rollbackData.get("VFMODULE", "vfModuleId") - def isBaseModule = rollbackData.get("VFMODULE", "isBaseModule") - execution.setVariable("DAAIVfMod_vnfId", vnfId) - execution.setVariable("DAAIVfMod_vfModuleId", vfModuleId) - - DeleteAAIVfModule dvm = new DeleteAAIVfModule() - // query A&AI to get the needed information for the delete(s) - dvm.queryAAIForGenericVnf(execution) - dvm.parseForVfModule(execution) - - // roll back the base or add-on module - dvm.deleteVfModule(execution) - def responseCode = execution.getVariable("DAAIVfMod_deleteVfModuleResponseCode") - def response = execution.getVariable("DAAIVfMod_deleteVfModuleResponseCode") - - if (isOneOf(responseCode, 200, 204)) { - msoLogger.debug("Received " + responseCode + " to VF Module rollback request") - } else { - msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Received " + responseCode + " to VF Module rollback request", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, rollbackData + System.lineSeparator() + "Response: " + response); - } - - // a new Generic VNF was created that needs to be rolled back - if (isBaseModule.equals("true")) { - dvm.queryAAIForGenericVnf(execution) - dvm.parseForResourceVersion(execution) - dvm.deleteGenericVnf(execution) - responseCode = execution.getVariable("DAAIVfMod_deleteGenericVnfResponseCode") - response = execution.getVariable("DAAIVfMod_deleteGenericVnfResponse") - - if (isOneOf(responseCode, 200, 204)) { - msoLogger.debug("Received " + responseCode + " to Generic VNF rollback request") - execution.setVariable("RollbackResult", "SUCCESS") - } else { - msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Received " + responseCode + " to Generic VNF rollback request", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, rollbackData + System.lineSeparator() + "Response: " + response); - } - } else { - execution.setVariable("RollbackResult", "SUCCESS") - } - } - } - - msoLogger.debug("Exited " + method) - } catch (Exception e) { - msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Caught exception in " + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); - } - } } diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/CreateAAIVfModuleVolumeGroup.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/CreateAAIVfModuleVolumeGroup.groovy index cc1be47029..075068513a 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/CreateAAIVfModuleVolumeGroup.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/CreateAAIVfModuleVolumeGroup.groovy @@ -22,12 +22,9 @@ package org.onap.so.bpmn.common.scripts import org.camunda.bpm.engine.delegate.BpmnError import org.camunda.bpm.engine.delegate.DelegateExecution -import org.onap.so.bpmn.core.UrnPropertiesReader import org.onap.so.client.aai.AAIObjectType import org.onap.so.client.aai.entities.uri.AAIResourceUri import org.onap.so.client.aai.entities.uri.AAIUriFactory -import org.onap.so.rest.APIResponse -import org.onap.so.logger.MessageEnum import org.onap.so.logger.MsoLogger public class CreateAAIVfModuleVolumeGroup extends AbstractServiceTaskProcessor { @@ -110,24 +107,17 @@ public class CreateAAIVfModuleVolumeGroup extends AbstractServiceTaskProcessor { try { def vnfId = execution.getVariable('CAAIVfModVG_vnfId') def vfModuleId = execution.getVariable('CAAIVfModVG_vfModuleId') - - AaiUtil aaiUtil = new AaiUtil(this) - AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.VF_MODULE, vnfId, vfModuleId) - String endPoint = aaiUtil.createAaiUri(uri) - try { - msoLogger.debug('sending GET to AAI endpoint \'' + endPoint + '\'') - msoLogger.debug("aaiResponse GET TO AAI Endpoint: " + endPoint) - APIResponse response = aaiUtil.executeAAIGetCall(execution, endPoint) - def responseData = response.getResponseBodyAsString() - execution.setVariable('CAAIVfModVG_getVfModuleResponseCode', response.getStatusCode()) - execution.setVariable('CAAIVfModVG_getVfModuleResponse', responseData) - - msoLogger.debug("CreateAAIVfModule Response Code: " + response.getStatusCode()) - msoLogger.debug("CreateAAIVfModule Response: " + response) - msoLogger.debug('Response code:' + response.getStatusCode()) - msoLogger.debug('Response:' + System.lineSeparator() + responseData) - } catch (Exception ex) { + AAIResourceUri resourceUri = AAIUriFactory.createResourceUri(AAIObjectType.VF_MODULE, vnfId, vfModuleId); + Optional<org.onap.aai.domain.yang.VfModule> vfModule = getAAIClient().get(org.onap.aai.domain.yang.VfModule.class, resourceUri) + if(vfModule.isPresent()){ + execution.setVariable('CAAIVfModVG_getVfModuleResponseCode', 200) + execution.setVariable('CAAIVfModVG_getVfModuleResponse', vfModule.get()) + }else{ + execution.setVariable('CAAIVfModVG_getVfModuleResponseCode', 404) + execution.setVariable('CAAIVfModVG_getVfModuleResponse', "VF-Module Not found!!") + } + }catch (Exception ex) { ex.printStackTrace() msoLogger.debug('Exception occurred while executing AAI GET:' + ex.getMessage()) execution.setVariable('CAAIVfModVG_getVfModuleResponseCode', 500) @@ -157,12 +147,10 @@ public class CreateAAIVfModuleVolumeGroup extends AbstractServiceTaskProcessor { try { def vnfId = execution.getVariable('CAAIVfModVG_vnfId') def vfModuleId = execution.getVariable('CAAIVfModVG_vfModuleId') - def vfModule = execution.getVariable('CAAIVfModVG_getVfModuleResponse') - def origRequest = execution.getVariable('CreateAAIVfModuleVolumeGroupRequest') - def Node vfModuleNode = xmlParser.parseText(vfModule) - + org.onap.aai.domain.yang.VfModule vfModule = execution.getVariable('CAAIVfModVG_getVfModuleResponse') + // Confirm resource-version is in retrieved VF Module - if (utils.getChildNode(vfModuleNode, 'resource-version') == null) { + if (vfModule.getResourceVersion() == null) { def msg = 'Can\'t update VF Module ' + vfModuleId + ' since \'resource-version\' is missing' msoLogger.error( msg); throw new Exception(msg) @@ -172,26 +160,16 @@ public class CreateAAIVfModuleVolumeGroup extends AbstractServiceTaskProcessor { def aicCloudRegion = execution.getVariable('CAAIVfModVG_aicCloudRegion') def cloudOwner = execution.getVariable('CAAIVfModVG_cloudOwner') def volumeGroupId = execution.getVariable('CAAIVfModVG_volumeGroupId') - def Node vgRelationshipNode = createVolumeGroupRelationshipNode(cloudOwner, aicCloudRegion, volumeGroupId) - insertVolumeGroupRelationshipNode(vfModuleNode, vgRelationshipNode) - def payload = utils.nodeToString(vfModuleNode) - AaiUtil aaiUtil = new AaiUtil(this) - AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.VF_MODULE, vnfId, vfModuleId) - String endPoint = aaiUtil.createAaiUri(uri) - try { - msoLogger.debug("CreateAAIVfModuleVolume Sendind PUT to AAI Endpoint \n " + endPoint + " with payload \n " + payload) - msoLogger.debug('sending PUT to AAI endpoint \'' + endPoint + '\'' + 'with payload \n' + payload) - APIResponse response = aaiUtil.executeAAIPutCall(execution, endPoint, payload) - def responseData = response.getResponseBodyAsString() - execution.setVariable('CAAIVfModVG_updateVfModuleResponseCode', response.getStatusCode()) - execution.setVariable('CAAIVfModVG_updateVfModuleResponse', responseData) - - msoLogger.debug("CreateAAIVfModule Response code: " + response.getStatusCode()) - msoLogger.debug("CreateAAIVfModule Response: " + responseData) - msoLogger.debug('Response code:' + response.getStatusCode()) - msoLogger.debug('Response:' + System.lineSeparator() + responseData) + AAIResourceUri vfModuleUri = AAIUriFactory.createResourceUri(AAIObjectType.VF_MODULE, vnfId,vfModuleId); + AAIResourceUri volumeGroupUri = AAIUriFactory.createResourceUri(AAIObjectType.VOLUME_GROUP, cloudOwner, aicCloudRegion,volumeGroupId); + msoLogger.debug("Creating relationship between Vf Module: " + vfModuleUri.build().toString() + " and Volume Group: " + volumeGroupUri.build().toString()) + getAAIClient().connect(vfModuleUri,volumeGroupUri) + execution.setVariable('CAAIVfModVG_updateVfModuleResponseCode', 200) + execution.setVariable('CAAIVfModVG_updateVfModuleResponse', "Success") + msoLogger.debug("CreateAAIVfModule Response code: " + 200) + msoLogger.debug("CreateAAIVfModule Response: " + "Success") } catch (Exception ex) { ex.printStackTrace() msoLogger.debug('Exception occurred while executing AAI PUT:' + ex.getMessage()) @@ -206,72 +184,6 @@ public class CreateAAIVfModuleVolumeGroup extends AbstractServiceTaskProcessor { exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in updateVfModule(): ' + e.getMessage()) } } - - /** - * Construct a Volume Group relationship Node with the given AIC Cloud Region and - * Volume Group ID for insertion into a VF Module. - * - * @param aicCloudRegion Cloud Region ID to use in the Volume Group relationship - * @param volumeGroupId Volume Group ID to use in the Volume Group relationship - * @return a Node representing the new Volume Group relationship - */ - private Node createVolumeGroupRelationshipNode(String cloudOwner, String aicCloudRegion, String volumeGroupId) { - - def Node relatedTo = new Node(null, 'related-to', 'volume-group') - - def Node relationshipKeyCO = new Node(null, 'relationship-key', 'cloud-region.cloud-owner') - def Node relationshipValueCO = new Node(null, 'relationship-value', cloudOwner) - def Node relationshipDataCO = new Node(null, 'relationship-data') - relationshipDataCO.append(relationshipKeyCO) - relationshipDataCO.append(relationshipValueCO) - - def Node relationshipKeyCRI = new Node(null, 'relationship-key', 'cloud-region.cloud-region-id') - def Node relationshipValueCRI = new Node(null, 'relationship-value', aicCloudRegion) - def Node relationshipDataCRI = new Node(null, 'relationship-data') - relationshipDataCRI.append(relationshipKeyCRI) - relationshipDataCRI.append(relationshipValueCRI) - - def Node relationshipKeyVGI = new Node(null, 'relationship-key', 'volume-group.volume-group-id') - def Node relationshipValueVGI = new Node(null, 'relationship-value', volumeGroupId) - def Node relationshipDataVGI = new Node(null, 'relationship-data') - relationshipDataVGI.append(relationshipKeyVGI) - relationshipDataVGI.append(relationshipValueVGI) - - def Node volumeGroupRelationship = new Node(null, 'relationship') - volumeGroupRelationship.append(relatedTo) - volumeGroupRelationship.append(relationshipDataCO) - volumeGroupRelationship.append(relationshipDataCRI) - volumeGroupRelationship.append(relationshipDataVGI) - - return volumeGroupRelationship; - } - - /** - * Insert the given Volume Group relationship Node into the given VF Module. - * If the VF Module does NOT contain a relationship list: - * - Create a relationship list containing the Volume Group relationship and insert it into the VF Module - * If the VF Module contains a relationship list but not a Volume Group relationship: - * - Insert the the Volume Group relationship into the relationship lsit - * If the VF Module contains a relationship list and has a Volume Group relationship: - * - Replace the existing Volume Group relationship with the new one - * @param vfModuleNode - * @param volumeGroupRelationshipNode - */ - private void insertVolumeGroupRelationshipNode(Node vfModuleNode, Node volumeGroupRelationshipNode) { - def Node relationshipList = utils.getChildNode(vfModuleNode, 'relationship-list') - if (relationshipList == null) { - relationshipList = new Node(null, 'relationship-list') - relationshipList.append(volumeGroupRelationshipNode) - vfModuleNode.append(relationshipList) - } else { - def Node currVolumeGroupRelationshipNode = getCurrVolumeGroupRelationshipNode(relationshipList) - if (currVolumeGroupRelationshipNode == null) { - relationshipList.append(volumeGroupRelationshipNode) - } else { - currVolumeGroupRelationshipNode.replaceNode(volumeGroupRelationshipNode) - } - } - } /** * Find and return the value of the Volume Group ID for the specified VF Module. If diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/DecomposeService.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/DecomposeService.groovy index 739bc4b7ed..1c1d5eb0e3 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/DecomposeService.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/DecomposeService.groovy @@ -20,9 +20,6 @@ package org.onap.so.bpmn.common.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.json.JSONObject; @@ -56,7 +53,7 @@ public class DecomposeService extends AbstractServiceTaskProcessor { String Prefix="DDS_" ExceptionUtil exceptionUtil = new ExceptionUtil() - CatalogDbUtils catalogDbUtils = new CatalogDbUtils() + CatalogDbUtils catalogDbUtils = new CatalogDbUtilsFactory().create() JsonUtils jsonUtils = new JsonUtils() public void preProcessRequest (DelegateExecution execution) { diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/DeleteAAIVfModule.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/DeleteAAIVfModule.groovy index 6da1f6d6ff..b8df241913 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/DeleteAAIVfModule.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/DeleteAAIVfModule.groovy @@ -20,15 +20,11 @@ package org.onap.so.bpmn.common.scripts import org.camunda.bpm.engine.delegate.DelegateExecution -import org.onap.so.bpmn.core.WorkflowException -import org.onap.so.bpmn.core.UrnPropertiesReader +import org.onap.aai.domain.yang.GenericVnf import org.onap.so.client.aai.AAIObjectType import org.onap.so.client.aai.entities.uri.AAIResourceUri import org.onap.so.client.aai.entities.uri.AAIUriFactory import org.onap.so.client.graphinventory.entities.uri.Depth -import org.onap.so.rest.APIResponse -import org.onap.so.rest.RESTClient; -import org.onap.so.rest.RESTConfig; import org.onap.so.logger.MessageEnum import org.onap.so.logger.MsoLogger @@ -83,15 +79,16 @@ public class DeleteAAIVfModule extends AbstractServiceTaskProcessor{ AaiUtil aaiUriUtil = new AaiUtil(this) AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId) uri.depth(Depth.ONE) - String endPoint = aaiUriUtil.createAaiUri(uri) - - APIResponse response = aaiUriUtil.executeAAIGetCall(execution, endPoint) - - msoLogger.debug('Response code:' + response.getStatusCode()) - msoLogger.debug('Response:' + response.getResponseBodyAsString()) + Optional<GenericVnf> genericVnf = getAAIClient().get(GenericVnf.class, uri) + + if(genericVnf.isPresent()) { + execution.setVariable("DAAIVfMod_queryGenericVnfResponseCode", 200) + execution.setVariable("DAAIVfMod_queryGenericVnfResponse", genericVnf.get()) - execution.setVariable("DAAIVfMod_queryGenericVnfResponseCode", response.getStatusCode()) - execution.setVariable("DAAIVfMod_queryGenericVnfResponse", response.getResponseBodyAsString()) + }else{ + execution.setVariable("DAAIVfMod_queryGenericVnfResponseCode", 404) + execution.setVariable("DAAIVfMod_queryGenericVnfResponse", "Vnf Not Found!") + } } catch (Exception ex) { msoLogger.debug("Exception occurred while executing AAI GET:" + ex.getMessage()) @@ -106,20 +103,10 @@ public class DeleteAAIVfModule extends AbstractServiceTaskProcessor{ try { String vnfId = execution.getVariable("DAAIVfMod_vnfId") - String resourceVersion = execution.getVariable("DAAIVfMod_genVnfRsrcVer") - - AaiUtil aaiUriUtil = new AaiUtil(this) AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId) - uri.resourceVersion(resourceVersion) - String endPoint = aaiUriUtil.createAaiUri(uri) - - APIResponse response = aaiUriUtil.executeAAIDeleteCall(execution, endPoint) - - def responseData = response.getResponseBodyAsString() - execution.setVariable("DAAIVfMod_deleteGenericVnfResponseCode", response.getStatusCode()) - execution.setVariable("DAAIVfMod_deleteGenericVnfResponse", responseData) - msoLogger.debug("Response code:" + response.getStatusCode()) - msoLogger.debug("Response:" + System.lineSeparator() + responseData) + getAAIClient().delete(uri) + execution.setVariable("DAAIVfMod_deleteGenericVnfResponseCode", 200) + execution.setVariable("DAAIVfMod_deleteGenericVnfResponse", "Vnf Deleted") } catch (Exception ex) { ex.printStackTrace() msoLogger.debug("Exception occurred while executing AAI DELETE:" + ex.getMessage()) @@ -133,22 +120,12 @@ public class DeleteAAIVfModule extends AbstractServiceTaskProcessor{ try { String vnfId = execution.getVariable("DAAIVfMod_vnfId") String vfModuleId = execution.getVariable("DAAIVfMod_vfModuleId") - String resourceVersion = execution.getVariable("DAAIVfMod_vfModRsrcVer") - AaiUtil aaiUriUtil = new AaiUtil(this) AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.VF_MODULE, vnfId, vfModuleId) - uri.resourceVersion(resourceVersion) - String endPoint = aaiUriUtil.createAaiUri(uri) - - APIResponse response = aaiUriUtil.executeAAIDeleteCall(execution, endPoint) - - responseData = response.getResponseBodyAsString() - execution.setVariable("DAAIVfMod_deleteVfModuleResponseCode", response.getStatusCode()) - execution.setVariable("DAAIVfMod_deleteVfModuleResponse", responseData) - msoLogger.debug("DeleteAAIVfModule - AAI Response" + responseData) - msoLogger.debug("Response code:" + response.getStatusCode()) - msoLogger.debug("Response:" + System.lineSeparator() + responseData) + getAAIClient().delete(uri) + execution.setVariable("DAAIVfMod_deleteVfModuleResponseCode", 200) + execution.setVariable("DAAIVfMod_deleteVfModuleResponse", "Vf Module Deleted") } catch (Exception ex) { ex.printStackTrace() msoLogger.debug("Exception occurred while executing AAI PUT:" + ex.getMessage()) @@ -160,88 +137,66 @@ public class DeleteAAIVfModule extends AbstractServiceTaskProcessor{ // to be deleted exists for the specified Generic Vnf and if it is the Base Module, // there are no Add-on Modules present public void parseForVfModule(DelegateExecution execution) { - def xml = execution.getVariable("DAAIVfMod_queryGenericVnfResponse") - msoLogger.debug("DeleteAAIVfModule - queryGenericVnfResponse" + xml) + GenericVnf genericVnf = execution.getVariable("DAAIVfMod_queryGenericVnfResponse") def delModuleId = execution.getVariable("DAAIVfMod_vfModuleId") msoLogger.debug("Vf Module to be deleted: " + delModuleId) - List <String> qryModuleIdList = utils.getMultNodes(xml, "vf-module-id") - List <String> qryBaseModuleList = utils.getMultNodes(xml, "is-base-vf-module") - List <String> qryResourceVerList = utils.getMultNodes(xml, "resource-version") - execution.setVariable("DAAIVfMod_moduleExists", false) - execution.setVariable("DAAIVfMod_isBaseModule", false) - execution.setVariable("DAAIVfMod_isLastModule", false) - // - def isBaseVfModule = "false" - // loop through the Vf Module Ids looking for a match - if (qryModuleIdList != null && !qryModuleIdList.empty) { - msoLogger.debug("Existing Vf Module Id List: " + qryModuleIdList) - msoLogger.debug("Existing Vf Module Resource Version List: " + qryResourceVerList) - def moduleCntr = 0 - // the Generic Vnf resource-version in the 1st entry in the query response - execution.setVariable("DAAIVfMod_genVnfRsrcVer", qryResourceVerList[moduleCntr]) - for (String qryModuleId : qryModuleIdList) { - if (delModuleId.equals(qryModuleId)) { - // a Vf Module with the requested Id exists - execution.setVariable("DAAIVfMod_moduleExists", true) - // find the corresponding value for the is-base-vf-module field - isBaseVfModule = qryBaseModuleList[moduleCntr] - // find the corresponding value for the resource-version field - // note: the Generic Vnf entry also has a resource-version field, so - // add 1 to the index to get the corresponding Vf Module value - execution.setVariable("DAAIVfMod_vfModRsrcVer", qryResourceVerList[moduleCntr+1]) - msoLogger.debug("Match found for Vf Module Id " + qryModuleId + " for Generic Vnf Id " + execution.getVariable("DAAIVfMod_vnfId") + ", Base Module is " + isBaseVfModule + ", Resource Version is " + execution.getVariable("vfModRsrcVer")) - break - } - moduleCntr++ - } - } - - // determine if the module to be deleted is a Base Module and/or the Last Module - if (execution.getVariable("DAAIVfMod_moduleExists") == true) { - if (isBaseVfModule.equals("true") && qryModuleIdList.size() != 1) { - execution.setVariable("DAAIVfMod_parseModuleResponse", - "Found Vf Module Id " + delModuleId + " for Generic Vnf Id " + - execution.getVariable("DAAIVfMod_vnfId") + ": is Base Module, not Last Module") - execution.setVariable("DAAIVfMod_isBaseModule", true) - } else { - if (isBaseVfModule.equals("true") && qryModuleIdList.size() == 1) { - execution.setVariable("DAAIVfMod_parseModuleResponse", - "Found Vf Module Id " + delModuleId + " for Generic Vnf Id " + - execution.getVariable("DAAIVfMod_vnfId") + ": is Base Module and Last Module") - execution.setVariable("DAAIVfMod_isBaseModule", true) - execution.setVariable("DAAIVfMod_isLastModule", true) - } else { - if (qryModuleIdList.size() == 1) { - execution.setVariable("DAAIVfMod_parseModuleResponse", - "Found Vf Module Id " + delModuleId + " for Generic Vnf Id " + - execution.getVariable("DAAIVfMod_vnfId") + ": is Not Base Module, is Last Module") - execution.setVariable("DAAIVfMod_isLastModule", true) - } else { - execution.setVariable("DAAIVfMod_parseModuleResponse", - "Found Vf Module Id " + delModuleId + " for Generic Vnf Id " + - execution.getVariable("DAAIVfMod_vnfId") + ": is Not Base Module and Not Last Module") - } - } - } - msoLogger.debug(execution.getVariable("DAAIVfMod_parseModuleResponse")) - } else { // (execution.getVariable("DAAIVfMod_moduleExists") == false) - msoLogger.debug("Vf Module Id " + delModuleId + " does not exist for Generic Vnf Id " + execution.getVariable("DAAIVfMod_vnfId")) - execution.setVariable("DAAIVfMod_parseModuleResponse", - "Vf Module Id " + delModuleId + " does not exist for Generic Vnf Id " + - execution.getVariable("DAAIVfMod_vnfName")) - } + + execution.setVariable("DAAIVfMod_genVnfRsrcVer", genericVnf.getResourceVersion()) + + execution.setVariable("DAAIVfMod_moduleExists", false) + execution.setVariable("DAAIVfMod_isBaseModule", false) + execution.setVariable("DAAIVfMod_isLastModule", false) + if(genericVnf.getVfModules()!= null && !genericVnf.getVfModules().getVfModule().isEmpty()){ + Optional<org.onap.aai.domain.yang.VfModule> vfModule = genericVnf.getVfModules().getVfModule().stream(). + filter{ v -> v.getVfModuleId().equals(delModuleId)}.findFirst() + if(vfModule.isPresent()){ + execution.setVariable("DAAIVfMod_moduleExists", true) + execution.setVariable("DAAIVfMod_vfModRsrcVer", vfModule.get().getResourceVersion()) + + if (vfModule.get().isBaseVfModule && genericVnf.getVfModules().getVfModule().size() != 1) { + execution.setVariable("DAAIVfMod_parseModuleResponse", + "Found Vf Module Id " + delModuleId + " for Generic Vnf Id " + + execution.getVariable("DAAIVfMod_vnfId") + ": is Base Module, not Last Module") + execution.setVariable("DAAIVfMod_isBaseModule", true) + } else { + if (vfModule.get().isBaseVfModule && genericVnf.getVfModules().getVfModule().size() == 1) { + execution.setVariable("DAAIVfMod_parseModuleResponse", + "Found Vf Module Id " + delModuleId + " for Generic Vnf Id " + + execution.getVariable("DAAIVfMod_vnfId") + ": is Base Module and Last Module") + execution.setVariable("DAAIVfMod_isBaseModule", true) + execution.setVariable("DAAIVfMod_isLastModule", true) + } else { + if (genericVnf.getVfModules().getVfModule().size() == 1) { + execution.setVariable("DAAIVfMod_parseModuleResponse", + "Found Vf Module Id " + delModuleId + " for Generic Vnf Id " + + execution.getVariable("DAAIVfMod_vnfId") + ": is Not Base Module, is Last Module") + execution.setVariable("DAAIVfMod_isLastModule", true) + } else { + execution.setVariable("DAAIVfMod_parseModuleResponse", + "Found Vf Module Id " + delModuleId + " for Generic Vnf Id " + + execution.getVariable("DAAIVfMod_vnfId") + ": is Not Base Module and Not Last Module") + } + } + } + msoLogger.debug(execution.getVariable("DAAIVfMod_parseModuleResponse")) + } + } + if (execution.getVariable("DAAIVfMod_moduleExists") == false) { // (execution.getVariable("DAAIVfMod_moduleExists") == false) + msoLogger.debug("Vf Module Id " + delModuleId + " does not exist for Generic Vnf Id " + execution.getVariable("DAAIVfMod_vnfId")) + execution.setVariable("DAAIVfMod_parseModuleResponse", + "Vf Module Id " + delModuleId + " does not exist for Generic Vnf Id " + + execution.getVariable("DAAIVfMod_vnfName")) + } } // parses the output from the result from queryAAIForGenericVnf() to determine if the Vf Module // to be deleted exists for the specified Generic Vnf and if it is the Base Module, // there are no Add-on Modules present public void parseForResourceVersion(DelegateExecution execution) { - def xml = execution.getVariable("DAAIVfMod_queryGenericVnfResponse") - msoLogger.debug("DeleteAAIVfModule - queryGenericVnfResponse" + xml) - String resourceVer = utils.getNodeText(xml, "resource-version") - execution.setVariable("DAAIVfMod_genVnfRsrcVer", resourceVer) - msoLogger.debug("Latest Generic VNF Resource Version: " + resourceVer) + GenericVnf genericVnf = execution.getVariable("DAAIVfMod_queryGenericVnfResponse") + execution.setVariable("DAAIVfMod_genVnfRsrcVer", genericVnf.getResourceVersion()) + msoLogger.debug("Latest Generic VNF Resource Version: " + genericVnf.getResourceVersion()) } @@ -303,4 +258,4 @@ public class DeleteAAIVfModule extends AbstractServiceTaskProcessor{ msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "AAI error occurred deleting the Generic Vnf", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, execution.getVariable("DAAIVfMod_deleteGenericVnfResponse")); exceptionUtil.buildAndThrowWorkflowException(execution, 5000, execution.getVariable("DAAIVfMod_deleteGenericVnfResponse")) } -}
\ No newline at end of file +} diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/ExceptionUtil.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/ExceptionUtil.groovy index 4b701e6a58..e132b411a5 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/ExceptionUtil.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/ExceptionUtil.groovy @@ -293,7 +293,7 @@ class ExceptionUtil extends AbstractServiceTaskProcessor { execution.setVariable("WorkflowException", exception); msoLogger.debug("Outgoing WorkflowException is " + exception) msoLogger.debug("Throwing MSOWorkflowException") - throw new BpmnError("MSOWorkflowException") + throw new BpmnError(errorCode.toString(), String.format("MSOWorkflowException: %s", errorMessage)) } /** diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/ExternalAPIUtil.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/ExternalAPIUtil.groovy index 3096bedda6..94c82f5a0c 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/ExternalAPIUtil.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/ExternalAPIUtil.groovy @@ -19,14 +19,17 @@ */ package org.onap.so.bpmn.common.scripts -import org.camunda.bpm.engine.delegate.BpmnError + + import org.camunda.bpm.engine.delegate.DelegateExecution -import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor; +import org.onap.logging.ref.slf4j.ONAPLogConstants +import org.onap.so.client.HttpClient +import org.onap.so.client.HttpClientFactory 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.apache.commons.lang3.StringEscapeUtils +import org.onap.so.utils.TargetEntity + +import javax.ws.rs.core.MediaType +import javax.ws.rs.core.Response import java.util.regex.Matcher import java.util.regex.Pattern @@ -34,12 +37,12 @@ class ExternalAPIUtil { String Prefix="EXTAPI_" - public MsoUtils utils = new MsoUtils() - - ExceptionUtil exceptionUtil = new ExceptionUtil() - private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, ExternalAPIUtil.class) + private final HttpClientFactory httpClientFactory; + private final MsoUtils utils; + private final ExceptionUtil exceptionUtil; + public static final String PostServiceOrderRequestsTemplate = "{\n" + "\t\"externalId\": <externalId>,\n" + @@ -83,7 +86,10 @@ class ExternalAPIUtil { "\t} \n" + "}" - public ExternalAPIUtil() { + ExternalAPIUtil(HttpClientFactory httpClientFactory, MsoUtils utils, ExceptionUtil exceptionUtil) { + this.httpClientFactory = httpClientFactory + this.utils = utils + this.exceptionUtil = exceptionUtil } // public String getUri(DelegateExecution execution, resourceName) { @@ -127,23 +133,21 @@ class ExternalAPIUtil { * @return APIResponse * */ - public APIResponse executeExternalAPIGetCall(DelegateExecution execution, String url){ + public Response executeExternalAPIGetCall(DelegateExecution execution, String url){ msoLogger.debug(" ======== STARTED Execute ExternalAPI Get Process ======== ") - APIResponse apiResponse = null + Response apiResponse = null try{ String uuid = utils.getRequestID() msoLogger.debug( "Generated uuid is: " + uuid) msoLogger.debug( "URL to be used is: " + url) - String basicAuthCred = utils.getBasicAuth(execution.getVariable("URN_externalapi_auth"),execution.getVariable("URN_mso_msoKey")) + HttpClient client = httpClientFactory.newJsonClient(new URL(url), TargetEntity.EXTERNAL) + client.addBasicAuthHeader(execution.getVariable("URN_externalapi_auth"), execution.getVariable("URN_mso_msoKey")) + client.addAdditionalHeader("X-FromAppId", "MSO") + client.addAdditionalHeader(ONAPLogConstants.Headers.REQUEST_ID, uuid) + client.addAdditionalHeader("Accept", MediaType.APPLICATION_JSON) - RESTConfig config = new RESTConfig(url); - RESTClient client = new RESTClient(config).addHeader("X-FromAppId", "MSO").addHeader("X-TransactionId", uuid).addHeader("Accept","application/json"); - - if (basicAuthCred != null && !"".equals(basicAuthCred)) { - client.addAuthorizationHeader(basicAuthCred) - } - apiResponse = client.httpGet() + apiResponse = client.get() msoLogger.debug( "======== COMPLETED Execute ExternalAPI Get Process ======== ") }catch(Exception e){ @@ -162,25 +166,23 @@ class ExternalAPIUtil { * @param url * @param payload * - * @return APIResponse + * @return Response * */ - public APIResponse executeExternalAPIPostCall(DelegateExecution execution, String url, String payload){ + public Response executeExternalAPIPostCall(DelegateExecution execution, String url, String payload){ msoLogger.debug( " ======== Started Execute ExternalAPI Post Process ======== ") - APIResponse apiResponse = null + Response apiResponse = null try{ String uuid = utils.getRequestID() msoLogger.debug( "Generated uuid is: " + uuid) msoLogger.debug( "URL to be used is: " + url) - String basicAuthCred = utils.getBasicAuth(execution.getVariable("URN_externalapi_auth"),execution.getVariable("URN_mso_msoKey")) - RESTConfig config = new RESTConfig(url); - RESTClient client = new RESTClient(config).addHeader("X-FromAppId", "MSO").addHeader("X-TransactionId", uuid).addHeader("Content-Type", "application/json").addHeader("Accept","application/json"); + HttpClient httpClient = httpClientFactory.newJsonClient(new URL(url), TargetEntity.AAI) + httpClient.addBasicAuthHeader(execution.getVariable("URN_externalapi_auth"), execution.getVariable("URN_mso_msoKey")) + httpClient.addAdditionalHeader("X-FromAppId", "MSO") + httpClient.addAdditionalHeader("X-TransactionId", uuid) - if (basicAuthCred != null && !"".equals(basicAuthCred)) { - client.addAuthorizationHeader(basicAuthCred) - } - apiResponse = client.httpPost(payload) + apiResponse = httpClient.post(payload) msoLogger.debug( "======== Completed Execute ExternalAPI Post Process ======== ") }catch(Exception e){ @@ -190,42 +192,6 @@ class ExternalAPIUtil { return apiResponse } - /** - * This reusable method can be used for making ExternalAPI Post Calls. The url - * and payload should be passed as a parameters along with the execution. - * The method will return an APIResponse. - * - * @param execution - * @param url - * @param payload - * @param authenticationHeader - addAuthenticationHeader value - * @param headerName - name of header you want to add, i.e. addHeader(headerName, headerValue) - * @param headerValue - the header's value, i.e. addHeader(headerName, headerValue) - * - * @return APIResponse - * - */ - public APIResponse executeExternalAPIPostCall(DelegateExecution execution, String url, String payload, String authenticationHeaderValue, String headerName, String headerValue){ - msoLogger.debug( " ======== Started Execute ExternalAPI Post Process ======== ") - APIResponse apiResponse = null - try{ - msoLogger.debug( "URL to be used is: " + url) - - String basicAuthCred = utils.getBasicAuth(execution.getVariable("URN_externalapi_auth"),execution.getVariable("URN_mso_msoKey")) - RESTConfig config = new RESTConfig(url); - RESTClient client = new RESTClient(config).addAuthorizationHeader(authenticationHeaderValue).addHeader(headerName, headerValue) - if (basicAuthCred != null && !"".equals(basicAuthCred)) { - client.addAuthorizationHeader(basicAuthCred) - } - apiResponse = client.httpPost(payload) - - msoLogger.debug( "======== Completed Execute ExternalAPI Post Process ======== ") - }catch(Exception e){ - msoLogger.error("Exception occured while executing ExternalAPI Post Call. Exception is: \n" + e) - exceptionUtil.buildAndThrowWorkflowException(execution, 9999, e.getMessage()) - } - return apiResponse - } }
\ No newline at end of file diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/ExternalAPIUtilFactory.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/ExternalAPIUtilFactory.groovy new file mode 100644 index 0000000000..e7f46464ee --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/ExternalAPIUtilFactory.groovy @@ -0,0 +1,29 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2018 Nokia. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.onap.so.bpmn.common.scripts + +import org.onap.so.client.HttpClientFactory + +class ExternalAPIUtilFactory { + + ExternalAPIUtil create() { + return new ExternalAPIUtil(new HttpClientFactory(), new MsoUtils(), new ExceptionUtil()) + } +} diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/FalloutHandler.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/FalloutHandler.groovy index 9732693f38..480dcd5e8f 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/FalloutHandler.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/FalloutHandler.groovy @@ -355,7 +355,7 @@ public class FalloutHandler extends AbstractServiceTaskProcessor { Boolean success = (Boolean) execution.getVariable("FH_success") String out = success ? "Fallout Handler Succeeded" : "Fallout Handler Failed"; - def falloutHandlerResponse = """ + String falloutHandlerResponse = """ <workflow:FalloutHandlerResponse xmlns:workflow="http://org.onap/so/workflow/schema/v1"> <workflow:out>${MsoUtils.xmlEscape(out)}</workflow:out> </workflow:FalloutHandlerResponse> diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/GenerateVfModuleName.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/GenerateVfModuleName.groovy index 78d147e819..1be24c4ce0 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/GenerateVfModuleName.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/GenerateVfModuleName.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,22 +21,24 @@ package org.onap.so.bpmn.common.scripts import org.onap.so.bpmn.core.UrnPropertiesReader +import org.onap.so.client.HttpClientFactory import java.io.Serializable; +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.springframework.web.util.UriUtils import org.onap.so.bpmn.core.json.JsonUtils import org.onap.so.bpmn.core.WorkflowException +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.client.graphinventory.entities.uri.Depth -import org.onap.so.rest.APIResponse; -import org.onap.so.rest.RESTClient -import org.onap.so.rest.RESTConfig +import org.onap.so.utils.TargetEntity import org.onap.so.logger.MessageEnum import org.onap.so.logger.MsoLogger @@ -46,8 +48,8 @@ public class GenerateVfModuleName extends AbstractServiceTaskProcessor{ def Prefix="GVFMN_" ExceptionUtil exceptionUtil = new ExceptionUtil() - - + + public void preProcessRequest(DelegateExecution execution) { try { def vnfId = execution.getVariable("vnfId") @@ -76,7 +78,7 @@ public class GenerateVfModuleName extends AbstractServiceTaskProcessor{ try { def vnfId = execution.getVariable('vnfId') def personaModelId = execution.getVariable('personaModelId') - + AaiUtil aaiUtil = new AaiUtil(this) AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId) uri.depth(Depth.ONE) @@ -85,34 +87,35 @@ public class GenerateVfModuleName extends AbstractServiceTaskProcessor{ msoLogger.debug("AAI endPoint: " + endPoint) try { - RESTConfig config = new RESTConfig(endPoint); + HttpClient client = new HttpClientFactory().newXmlClient(new URL(endPoint), TargetEntity.AAI) + + client.addAdditionalHeader('X-TransactionId', UUID.randomUUID().toString()) + client.addAdditionalHeader('X-FromAppId', 'MSO') + client.addAdditionalHeader('Content-Type', 'application/xml') + client.addAdditionalHeader('Accept','application/xml') + def responseData = '' - def aaiRequestId = UUID.randomUUID().toString() - RESTClient client = new RESTClient(config). - addHeader('X-TransactionId', aaiRequestId). - addHeader('X-FromAppId', 'MSO'). - addHeader('Content-Type', 'application/xml'). - addHeader('Accept','application/xml'); + msoLogger.debug('sending GET to AAI endpoint \'' + endPoint + '\'') - APIResponse response = client.httpGet() + Response response = client.get() msoLogger.debug("GenerateVfModuleName - invoking httpGet() to AAI") - responseData = response.getResponseBodyAsString() + responseData = response.readEntity(String.class) if (responseData != null) { msoLogger.debug("Received generic VNF data: " + responseData) } msoLogger.debug("GenerateVfModuleName - queryAAIVfModule Response: " + responseData) - msoLogger.debug("GenerateVfModuleName - queryAAIVfModule ResponseCode: " + response.getStatusCode()) + msoLogger.debug("GenerateVfModuleName - queryAAIVfModule ResponseCode: " + response.getStatus()) - execution.setVariable('GVFMN_queryAAIVfModuleResponseCode', response.getStatusCode()) + execution.setVariable('GVFMN_queryAAIVfModuleResponseCode', response.getStatus()) execution.setVariable('GVFMN_queryAAIVfModuleResponse', responseData) - msoLogger.debug('Response code:' + response.getStatusCode()) + msoLogger.debug('Response code:' + response.getStatus()) msoLogger.debug('Response:' + System.lineSeparator() + responseData) - if (response.getStatusCode() == 200) { - // Set the VfModuleXML - if (responseData != null) { + if (response.getStatus() == 200) { + // Set the VfModuleXML + if (responseData != null) { String vfModulesText = utils.getNodeXml(responseData, "vf-modules") if (vfModulesText == null || vfModulesText.isEmpty()) { msoLogger.debug("There are no VF modules in this VNF yet") @@ -131,18 +134,18 @@ public class GenerateVfModuleName extends AbstractServiceTaskProcessor{ def personaModelIdFromAAI = utils.getNodeText(vfModuleXml, "model-invariant-id") if (!personaModelIdFromAAI) { // check old attribute name - personaModelIdFromAAI = utils.getNodeText(vfModuleXml, "persona-model-id") + personaModelIdFromAAI = utils.getNodeText(vfModuleXml, "persona-model-id") } if (personaModelIdFromAAI != null && personaModelIdFromAAI.equals(personaModelId)) { matchingVfModules = matchingVfModules + utils.removeXmlPreamble(vfModuleXml) - } + } } matchingVfModules = matchingVfModules + "</vfModules>" - msoLogger.debug("Matching VF Modules: " + matchingVfModules) + msoLogger.debug("Matching VF Modules: " + matchingVfModules) execution.setVariable("GVFMN_vfModuleXml", matchingVfModules) } } - } + } } catch (Exception ex) { ex.printStackTrace() msoLogger.debug('Exception occurred while executing AAI GET:' + ex.getMessage()) @@ -155,18 +158,18 @@ public class GenerateVfModuleName extends AbstractServiceTaskProcessor{ 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 queryAAI(): ' + e.getMessage()) } - + } - + public void generateName (DelegateExecution execution) { def method = getClass().getSimpleName() + '.generateName() ' + 'execution=' + execution.getId() + ')' msoLogger.trace('Entered ' + method) - - String vfModuleXml = execution.getVariable("GVFMN_vfModuleXml") - - String moduleIndex = utils.getLowestUnusedIndex(vfModuleXml) + + String vfModuleXml = execution.getVariable("GVFMN_vfModuleXml") + + String moduleIndex = utils.getLowestUnusedIndex(vfModuleXml) msoLogger.debug("moduleIndex is: " + moduleIndex) def vnfName = execution.getVariable("vnfName") def vfModuleLabel = execution.getVariable("vfModuleLabel") diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/MsoUtils.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/MsoUtils.groovy index 9a3e1b7349..4f0b530a3b 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/MsoUtils.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/MsoUtils.groovy @@ -287,14 +287,6 @@ class MsoUtils { return null } } - def getRelationshipVal(node, name){ - try{ - return node.'**'.find {it.'relationship-key'.text() == name}.'relationship-value'.text() - }catch(Exception e){ - return null - } - } - def log(logmode,logtxt,isDebugLogEnabled="false"){ if ("INFO"==logmode) { diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/NetworkUtils.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/NetworkUtils.groovy index 1e8569c3e7..23231df6be 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/NetworkUtils.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/NetworkUtils.groovy @@ -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,38 +18,33 @@ * ============LICENSE_END========================================================= */ -package org.onap.so.bpmn.common.scripts; +package org.onap.so.bpmn.common.scripts -import javax.ws.rs.core.UriBuilder -import javax.xml.parsers.DocumentBuilder -import javax.xml.parsers.DocumentBuilderFactory -import javax.xml.transform.Transformer -import javax.xml.transform.TransformerFactory -import javax.xml.transform.dom.DOMSource -import javax.xml.transform.stream.StreamResult - -import org.apache.commons.lang3.* +import groovy.xml.XmlUtil import org.camunda.bpm.engine.delegate.DelegateExecution +import org.onap.aai.domain.yang.HostRoute +import org.onap.aai.domain.yang.L3Network +import org.onap.aai.domain.yang.SegmentationAssignment +import org.onap.aai.domain.yang.Subnet +import org.onap.aai.domain.yang.Subnets import org.onap.so.bpmn.core.UrnPropertiesReader -import org.onap.so.client.aai.AAIObjectType -import org.onap.so.client.aai.entities.uri.AAIResourceUri -import org.onap.so.client.aai.entities.uri.AAIUriFactory -import org.onap.so.logger.MsoLogger import org.w3c.dom.Document import org.w3c.dom.Element import org.w3c.dom.Node -import org.w3c.dom.NodeList; +import org.w3c.dom.NodeList import org.xml.sax.InputSource -import groovy.xml.XmlUtil - +import javax.xml.parsers.DocumentBuilder +import javax.xml.parsers.DocumentBuilderFactory +import javax.xml.transform.Transformer +import javax.xml.transform.TransformerFactory +import javax.xml.transform.dom.DOMSource +import javax.xml.transform.stream.StreamResult /** * This groovy class supports the any Network processes that need the methods defined here. */ class NetworkUtils { - private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, NetworkUtils.class); - public MsoUtils utils = new MsoUtils() private AbstractServiceTaskProcessor taskProcessor @@ -71,7 +66,7 @@ class NetworkUtils { * @param cloudRegionId the cloud-region-region * @return String request */ - def CreateNetworkRequestV2(execution, requestId, messageId, requestInput, queryIdResponse, routeCollection, policyFqdns, tableCollection, cloudRegionId, backoutOnFailure, source) { + def CreateNetworkRequestV2(execution, requestId, messageId, requestInput,L3Network queryIdResponse, routeCollection, policyFqdns, tableCollection, cloudRegionId, backoutOnFailure, source) { String createNetworkRequest = null if(requestInput!=null && queryIdResponse!=null) { String serviceInstanceId = "" @@ -79,8 +74,8 @@ class NetworkUtils { String externalValue = "" if (source == "VID") { - sharedValue = utils.getNodeText(queryIdResponse, "is-shared-network") != null ? utils.getNodeText(queryIdResponse, "is-shared-network") : "false" - externalValue = utils.getNodeText(queryIdResponse, "is-external-network") != null ? utils.getNodeText(queryIdResponse, "is-external-network") : "false" + sharedValue = queryIdResponse.isIsSharedNetwork() != null ? queryIdResponse.isIsSharedNetwork() : "false" + externalValue = queryIdResponse.isIsExternalNetwork() != null ? queryIdResponse.isIsExternalNetwork() : "false" serviceInstanceId = utils.getNodeText(requestInput, "service-instance-id") } else { // source = 'PORTAL' @@ -107,14 +102,14 @@ class NetworkUtils { networkType = utils.getNodeText(networkModelInfo, "modelName") modelCustomizationUuid = utils.getNodeText(networkModelInfo, "modelCustomizationUuid") } else { - networkType = utils.getNodeText(queryIdResponse, "network-type") + networkType = queryIdResponse.getNetworkType() modelCustomizationUuid = utils.getNodeText(requestInput, "modelCustomizationId") } // queryIdResponse - String networkName = utils.getNodeText(queryIdResponse, "network-name") - String networkId = utils.getNodeText(queryIdResponse, "network-id") - String networkTechnology = utils.getNodeText(queryIdResponse, "network-technology") + String networkName = queryIdResponse.getNetworkName() + String networkId = queryIdResponse.getNetworkId() + String networkTechnology = queryIdResponse.getNetworkTechnology() // contrailNetwork - networkTechnology = 'Contrail' vs. 'AIC_SR_IOV') String contrailNetwork = "" @@ -131,13 +126,12 @@ class NetworkUtils { // rebuild subnets String subnets = "" - if (utils.nodeExists(queryIdResponse, "subnets")) { - def subnetsGroup = utils.getNodeXml(queryIdResponse, "subnets", false) - subnets = buildSubnets(subnetsGroup) + if (queryIdResponse.getSubnets() != null) { + subnets = buildSubnets(queryIdResponse) } String physicalNetworkName = "" - physicalNetworkName = utils.getNodeText(queryIdResponse, "physical-network-name") + physicalNetworkName = queryIdResponse.getPhysicalNetworkName() String vlansCollection = buildVlans(queryIdResponse) @@ -188,7 +182,7 @@ class NetworkUtils { * @param cloudRegionId the cloud-region-region * @return String request */ - def UpdateNetworkRequestV2(execution, requestId, messageId, requestInput, queryIdResponse, routeCollection, policyFqdns, tableCollection, cloudRegionId, backoutOnFailure, source) { + def UpdateNetworkRequestV2(execution, requestId, messageId, requestInput, L3Network queryIdResponse, routeCollection, policyFqdns, tableCollection, cloudRegionId, backoutOnFailure, source) { String updateNetworkRequest = null if(requestInput!=null && queryIdResponse!=null) { String serviceInstanceId = "" @@ -196,8 +190,8 @@ class NetworkUtils { String externalValue = "" if (source == "VID") { - sharedValue = utils.getNodeText(queryIdResponse, "is-shared-network") != null ? utils.getNodeText(queryIdResponse, "is-shared-network") : "false" - externalValue = utils.getNodeText(queryIdResponse, "is-external-network") != null ? utils.getNodeText(queryIdResponse, "is-external-network") : "false" + sharedValue = queryIdResponse.isIsSharedNetwork() != null ? queryIdResponse.isIsSharedNetwork() : "false" + externalValue = queryIdResponse.isIsExternalNetwork() != null ? queryIdResponse.isIsExternalNetwork() : "false" serviceInstanceId = utils.getNodeText(requestInput, "service-instance-id") } else { // source = 'PORTAL' @@ -212,9 +206,9 @@ class NetworkUtils { String tenantId = utils.getNodeText(requestInput, "tenant-id") // queryIdResponse - String networkName = utils.getNodeText(queryIdResponse, "network-name") - String networkId = utils.getNodeText(queryIdResponse, "network-id") - + String networkName = queryIdResponse.getNetworkName() + String networkId = queryIdResponse.getNetworkId() + String networkType = "" String modelCustomizationUuid = "" if (utils.nodeExists(requestInput, "networkModelInfo")) { @@ -222,15 +216,14 @@ class NetworkUtils { networkType = utils.getNodeText(networkModelInfo, "modelName") modelCustomizationUuid = utils.getNodeText(networkModelInfo, "modelCustomizationUuid") } else { - networkType = utils.getNodeText(queryIdResponse, "network-type") + networkType = queryIdResponse.getNetworkType() modelCustomizationUuid = utils.getNodeText(requestInput, "modelCustomizationId") } // rebuild subnets String subnets = "" - if (utils.nodeExists(queryIdResponse, "subnets")) { - def subnetsGroup = utils.getNodeXml(queryIdResponse, "subnets", false) - subnets = buildSubnets(subnetsGroup) + if (queryIdResponse.getSubnets() != null) { + subnets = buildSubnets(queryIdResponse) } String networkParams = "" @@ -239,12 +232,12 @@ class NetworkUtils { networkParams = buildParams(netParams) } - String networkStackId = utils.getNodeText(queryIdResponse, "heat-stack-id") + String networkStackId = queryIdResponse.getHeatStackId() if (networkStackId == 'null' || networkStackId == "" || networkStackId == null) { networkStackId = "force_update" } - String physicalNetworkName = utils.getNodeText(queryIdResponse, "physical-network-name") + String physicalNetworkName = queryIdResponse.getPhysicalNetworkName() String vlansCollection = buildVlans(queryIdResponse) updateNetworkRequest = @@ -289,227 +282,6 @@ class NetworkUtils { } /** - * This method returns the string for Create Volume Request payload - * @param groupId the volume-group-id - * @param volumeName the volume-group-name - * @param vnfType the vnf-type - * @param tenantId the value of relationship-key 'tenant.tenant-id' - * @return String request payload - */ - def String CreateNetworkVolumeRequest(groupId, volumeName, vnfType, tenantId) { - - String requestPayload = - """<volume-group xmlns="http://org.onap.so/v6"> - <volume-group-id>${MsoUtils.xmlEscape(groupId)}</volume-group-id> - <volume-group-name>${MsoUtils.xmlEscape(volumeName)}</volume-group-name> - <heat-stack-id></heat-stack-id> - <vnf-type>${MsoUtils.xmlEscape(vnfType)}</vnf-type> - <orchestration-status>Pending</orchestration-status> - <relationship-list> - <relationship> - <related-to>tenant</related-to> - <relationship-data> - <relationship-key>tenant.tenant-id</relationship-key> - <relationship-value>${MsoUtils.xmlEscape(tenantId)}</relationship-value> - </relationship-data> - </relationship> - </relationship-list> - </volume-group>""" - - return requestPayload - } - - def String createCloudRegionVolumeRequest(groupId, volumeName, vnfType, vnfId, tenantId, cloudOwner, cloudRegion, namespace, modelCustomizationId) { - - String requestPayload = - """<volume-group xmlns="${namespace}"> - <volume-group-id>${MsoUtils.xmlEscape(groupId)}</volume-group-id> - <volume-group-name>${MsoUtils.xmlEscape(volumeName)}</volume-group-name> - <heat-stack-id></heat-stack-id> - <vnf-type>${MsoUtils.xmlEscape(vnfType)}</vnf-type> - <orchestration-status>Pending</orchestration-status> - <vf-module-model-customization-id>${MsoUtils.xmlEscape(modelCustomizationId)}</vf-module-model-customization-id> - <relationship-list> - <relationship> - <related-to>generic-vnf</related-to> - <relationship-data> - <relationship-key>generic-vnf.vnf-id</relationship-key> - <relationship-value>${MsoUtils.xmlEscape(vnfId)}</relationship-value> - </relationship-data> - </relationship> - <relationship> - <related-to>tenant</related-to> - <relationship-data> - <relationship-key>tenant.tenant-id</relationship-key> - <relationship-value>${MsoUtils.xmlEscape(tenantId)}</relationship-value> - </relationship-data> - <relationship-data> - <relationship-key>cloud-region.cloud-owner</relationship-key> - <relationship-value>${cloudOwner}</relationship-value> - </relationship-data> - <relationship-data> - <relationship-key>cloud-region.cloud-region-id</relationship-key> - <relationship-value>${MsoUtils.xmlEscape(cloudRegion)}</relationship-value> - </relationship-data> - </relationship> - </relationship-list> - </volume-group>""" - - return requestPayload - } - - - /** - * This method returns the string for Update Volume Request payload - * @param requeryAAIVolGrpNameResponse the response of query volume group name (in AAI) - * @param heatStackId the value of heat stack id - * @return String request payload - */ - def String updateCloudRegionVolumeRequest(requeryAAIVolGrpNameResponse, heatStackId, namespace, modelCustomizationId) { - String requestPayload = "" - if (requeryAAIVolGrpNameResponse != null) { - def groupId = utils.getNodeText(requeryAAIVolGrpNameResponse, "volume-group-id") - def volumeName = utils.getNodeText(requeryAAIVolGrpNameResponse, "volume-group-name") - def vnfType = utils.getNodeText(requeryAAIVolGrpNameResponse, "vnf-type") - def resourceVersion = utils.getNodeText(requeryAAIVolGrpNameResponse, "resource-version") - def relationshipList = "" - if (utils.nodeExists(requeryAAIVolGrpNameResponse, "relationship")) { - relationshipList = rebuildRelationship(requeryAAIVolGrpNameResponse) - } - - requestPayload = - """<volume-group xmlns="${namespace}"> - <volume-group-id>${MsoUtils.xmlEscape(groupId)}</volume-group-id> - <volume-group-name>${MsoUtils.xmlEscape(volumeName)}</volume-group-name> - <heat-stack-id>${MsoUtils.xmlEscape(heatStackId)}</heat-stack-id> - <vnf-type>${MsoUtils.xmlEscape(vnfType)}</vnf-type> - <orchestration-status>Active</orchestration-status> - <resource-version>${MsoUtils.xmlEscape(resourceVersion)}</resource-version> - <vf-module-model-customization-id>${MsoUtils.xmlEscape(modelCustomizationId)}</vf-module-model-customization-id> - ${relationshipList} - </volume-group>""" - } - - return requestPayload - } - - - /** - * This method returns the string for Update Volume Request payload - * @param requeryAAIVolGrpNameResponse the response of query volume group name (in AAI) - * @param heatStackId the value of heat stack id - * @return String request payload - */ - def String UpdateNetworkVolumeRequest(requeryAAIVolGrpNameResponse, heatStackId) { - String requestPayload = "" - if (requeryAAIVolGrpNameResponse != null) { - def groupId = utils.getNodeText(requeryAAIVolGrpNameResponse, "volume-group-id") - def volumeName = utils.getNodeText(requeryAAIVolGrpNameResponse, "volume-group-name") - def vnfType = utils.getNodeText(requeryAAIVolGrpNameResponse, "vnf-type") - def resourceVersion = utils.getNodeText(requeryAAIVolGrpNameResponse, "resource-version") - def relationshipList = "" - if (utils.nodeExists(requeryAAIVolGrpNameResponse, "relationship")) { - relationshipList = rebuildRelationship(requeryAAIVolGrpNameResponse) - } - - requestPayload = - """<volume-group xmlns="http://org.onap.so/v6"> - <volume-group-id>${MsoUtils.xmlEscape(groupId)}</volume-group-id> - <volume-group-name>${MsoUtils.xmlEscape(volumeName)}</volume-group-name> - <heat-stack-id>${MsoUtils.xmlEscape(heatStackId)}</heat-stack-id> - <vnf-type>${MsoUtils.xmlEscape(vnfType)}</vnf-type> - <orchestration-status>Active</orchestration-status> - <resource-version>${MsoUtils.xmlEscape(resourceVersion)}</resource-version> - ${relationshipList} - </volume-group>""" - } - - return requestPayload - } - - /** - * This method returns the string for Create Contrail Network payload - * @param requeryIdAAIResponse the response from AAI query by id - * @param createNetworkResponse the response of create network - * @return String contrailNetworkCreatedUpdate - */ - def ContrailNetworkCreatedUpdate(requeryIdAAIResponse, createNetworkResponse, schemaVersion) { - - String contrailNetworkCreatedUpdate = "" - if(requeryIdAAIResponse!=null && createNetworkResponse!=null) { - - def l3Network = utils.getNodeXml(requeryIdAAIResponse, "l3-network", false).replace("tag0:","").replace(":tag0","") - def createNetworkContrailResponse = "" - if (utils.nodeExists(createNetworkResponse, 'createNetworkResponse')) { - createNetworkContrailResponse = utils.getNodeXml(createNetworkResponse, "createNetworkResponse", false).replace("tag0:","").replace(":tag0","") - } else { - createNetworkContrailResponse = utils.getNodeXml(createNetworkResponse, "updateNetworkContrailResponse", false).replace("tag0:","").replace(":tag0","") - } - - // rebuild network - def networkList = ["network-id", "network-name", "network-type", "network-role", "network-technology", "neutron-network-id", "is-bound-to-vpn", "service-id", "network-role-instance", "resource-version", "resource-model-uuid", "orchestration-status", "heat-stack-id", "mso-catalog-key", "contrail-network-fqdn", - "physical-network-name", "is-provider-network", "is-shared-network", "is-external-network"] - String rebuildNetworkElements = buildNetworkElements(l3Network, createNetworkContrailResponse, networkList) - - // rebuild 'subnets' - def rebuildSubnetList = "" - if (utils.nodeExists(requeryIdAAIResponse, 'subnet')) { - rebuildSubnetList = buildSubnets(requeryIdAAIResponse, createNetworkResponse) - } - - // rebuild 'segmentation-assignments' - def rebuildSegmentationAssignments = "" - if (utils.nodeExists(requeryIdAAIResponse, 'segmentation-assignments')) { - List elementList = ["segmentation-id", "resource-version"] - if (utils.nodeExists(requeryIdAAIResponse, 'segmentation-assignment')) { // new tag - rebuildSegmentationAssignments = buildXMLElements(requeryIdAAIResponse, "segmentation-assignments", "segmentation-assignment", elementList) - } else { - rebuildSegmentationAssignments = buildXMLElements(requeryIdAAIResponse, "", "segmentation-assignments", elementList) - } - } - - // rebuild 'ctag-assignments' / rebuildCtagAssignments - def rebuildCtagAssignmentsList = "" - if (utils.nodeExists(requeryIdAAIResponse, 'ctag-assignment')) { - rebuildCtagAssignmentsList = rebuildCtagAssignments(requeryIdAAIResponse) - } - - // rebuild 'relationship' - def relationshipList = "" - if (utils.nodeExists(requeryIdAAIResponse, 'relationship-list')) { - String rootRelationshipData = getFirstNodeXml(requeryIdAAIResponse, "relationship-list").drop(38).trim().replace("tag0:","").replace(":tag0","") - if (utils.nodeExists(rootRelationshipData, 'relationship')) { - relationshipList = rebuildRelationship(rootRelationshipData) - } - } - - //Check for optional contrail network fqdn within CreateNetworkResponse - String contrailNetworkFQDN - if(utils.nodeExists(createNetworkResponse, "contrail-network-fqdn")){ - contrailNetworkFQDN = utils.getNodeXml(createNetworkResponse, "contrail-network-fqdn") - contrailNetworkFQDN = utils.removeXmlNamespaces(contrailNetworkFQDN) - contrailNetworkFQDN = utils.removeXmlPreamble(contrailNetworkFQDN) - }else{ - contrailNetworkFQDN = "" - } - - contrailNetworkCreatedUpdate = - """<l3-network xmlns="${schemaVersion}"> - ${rebuildNetworkElements} - ${rebuildSubnetList} - ${rebuildSegmentationAssignments} - ${rebuildCtagAssignmentsList} - ${relationshipList} - ${contrailNetworkFQDN} - </l3-network>""".trim() - - } - return contrailNetworkCreatedUpdate - } - - - - /** * This method returns the value for the name paramName. * Ex: <network-params> * <param name="shared">1</param> @@ -534,34 +306,6 @@ class NetworkUtils { } /** - * This method returns the name of param if found/match with paramName. - * Ex: <network-params> - * <param name="shared">1</param> - * <param name="external">0</external> - * </network-params> - * - * @param xmlInput the XML document - * @param paramName the param name (ex: 'shared', ) - * @return a param name for 'shared' (ex: 'shared' if found) - */ - def getParameterName(xmlInput, paramName) { - def rtn="" - if(xmlInput!=null){ - def xml= new XmlSlurper().parseText(xmlInput) - try { - rtn= xml.'**'.find {param->param.'@name' == paramName}.'@name' - } catch (Exception ex) { - rtn="" - } - } - if (rtn==null || rtn=="") { - return "" - } else { - return rtn - } - } - - /** * This method returns the networkParams xml string. * Ex: input: * <network-params> @@ -599,283 +343,8 @@ class NetworkUtils { return build } - def getVlans(xmlInput) { - def rtn = "" - if (xmlInput!=null) { - def vlansList = getListWithElements(xmlInput, 'vlans') - def vlansListSize = vlansList.size() - if (vlansListSize > 0) { - for (i in 0..vlansListSize-1) { - rtn += '<vlans>'+vlansList[i]+'</vlans>' - } - } - } - return rtn - - - } - - /** - * This method returns the uri value for the vpn bindings. - * Return the a list of value of vpn binding in the <related-link> string. - * Ex. - * <relationship-list> - * <relationship> - * <related-to>vpn-binding</related-to> - * <related-link>https://aai-app-e2e.test.openecomp.com:8443/aai/v6/network/vpn-bindings/vpn-binding/85f015d0-2e32-4c30-96d2-87a1a27f8017/</related-link> - * <relationship-data> - * <relationship-key>vpn-binding.vpn-id</relationship-key> - * <relationship-value>85f015d0-2e32-4c30-96d2-87a1a27f8017</relationship-value> - * </relationship-data> - * </relationship> - * <relationship> - * <related-to>vpn-binding</related-to> - * <related-link>https://aai-ext1.test.openecomp.com:8443/aai/v6/network/vpn-bindings/vpn-binding/24a4b507-853a-4a38-99aa-05fcc54be24d/</related-link> - * <relationship-data> - * <relationship-key>vpn-binding.vpn-id</relationship-key> - * <relationship-value>24a4b507-853a-4a38-99aa-05fcc54be24d</relationship-value> - * </relationship-data> - * <related-to-property> - * <property-key>vpn-binding.vpn-name</property-key> - * <property-value>oam_protected_net_6_MTN5_msotest1</property-value> - * </related-to-property> - * </relationship> - * @param xmlInput the XML document - * @return a list of vpn binding values - * ex: ['aai/v6/network/vpn-bindings/vpn-binding/85f015d0-2e32-4c30-96d2-87a1a27f8017/', 'aai/v6/network/vpn-bindings/vpn-binding/c980a6ef-3b88-49f0-9751-dbad8608d0a6/'] - * - **/ - def getVnfBindingObject(xmlInput) { - //def rtn = null - List rtn = [] - if (xmlInput!=null) { - def relationshipList = getListWithElements(xmlInput, 'relationship') - def relationshipListSize = relationshipList.size() - if (relationshipListSize > 0) { - for (i in 0..relationshipListSize-1) { - def relationshipXml = XmlUtil.serialize(relationshipList[i]) - if (utils.getNodeText(relationshipXml, 'related-to') == "vpn-binding") { - def relatedLink = utils.getNodeText(relationshipXml, 'related-link') - if (relatedLink != null || relatedLink != "") { - rtn.add(relatedLink.substring(relatedLink.indexOf("/aai/"), relatedLink.length())) - } - } - } - } - } - return rtn - } - /** - * similar to VNF bindings method - * @param xmlInput the XML document - * @return a list of network policy values - * ex: ['aai/v$/network/network-policies/network-policy/cee6d136-e378-4678-a024-2cd15f0ee0cg', 'aai/v$/network/network-policies/network-policy/cee6d136-e378-4678-a024-2cd15f0ee0cg'] - * - **/ - def getNetworkPolicyObject(xmlInput) { - //def rtn = null - List rtn = [] - if (xmlInput!=null) { - def relationshipList = getListWithElements(xmlInput, 'relationship') - def relationshipListSize = relationshipList.size() - if (relationshipListSize > 0) { - for (i in 0..relationshipListSize-1) { - def relationshipXml = XmlUtil.serialize(relationshipList[i]) - if (utils.getNodeText(relationshipXml, 'related-to') == "network-policy") { - def relatedLink = utils.getNodeText(relationshipXml, 'related-link') - if (relatedLink != null || relatedLink != "") { - rtn.add(relatedLink.substring(relatedLink.indexOf("/aai/"), relatedLink.length())) - } - } - } - } - } - return rtn - } - - /** - * similar to network policymethod - * @param xmlInput the XML document - * @return a list of network policy values - * ex: ['aai/v$/network/route-table-references/route-table-reference/refFQDN1', 'aai/v$/network/route-table-references/route-table-reference/refFQDN2'] - * - **/ - def getNetworkTableRefObject(xmlInput) { - //def rtn = null - List rtn = [] - if (xmlInput!=null) { - def relationshipList = getListWithElements(xmlInput, 'relationship') - def relationshipListSize = relationshipList.size() - if (relationshipListSize > 0) { - for (i in 0..relationshipListSize-1) { - def relationshipXml = XmlUtil.serialize(relationshipList[i]) - if (utils.getNodeText(relationshipXml, 'related-to') == "route-table-reference") { - def relatedLink = utils.getNodeText(relationshipXml, 'related-link') - if (relatedLink != null || relatedLink != "") { - rtn.add(relatedLink.substring(relatedLink.indexOf("/aai/"), relatedLink.length())) - } - } - } - } - } - return rtn - } - - /** - * similar to network policymethod - * @param xmlInput the XML document - * @return a list of IDs for related VNF instances - * - **/ - def getRelatedVnfIdList(xmlInput) { - //def rtn = null - List rtn = [] - if (xmlInput!=null) { - def relationshipList = getListWithElements(xmlInput, 'relationship') - def relationshipListSize = relationshipList.size() - if (relationshipListSize > 0) { - for (i in 0..relationshipListSize-1) { - def relationshipXml = XmlUtil.serialize(relationshipList[i]) - if (utils.getNodeText(relationshipXml, 'related-to') == "generic-vnf") { - def relatedLink = utils.getNodeText(relationshipXml, 'related-link') - if (relatedLink != null || relatedLink != "") { - if (relatedLink.substring(relatedLink.indexOf("/generic-vnf/")+13, relatedLink.length()).contains('/')) { - rtn.add(relatedLink.substring(relatedLink.indexOf("/generic-vnf/")+13, relatedLink.length()-1)) - } else { - rtn.add(relatedLink.substring(relatedLink.indexOf("/generic-vnf/")+13, relatedLink.length())) - } - } - } - } - } - } - return rtn - } - - /** - * similar to network policymethod - * @param xmlInput the XML document - * @return a list of IDs for related Network instances - * - **/ - def getRelatedNetworkIdList(xmlInput) { - //def rtn = null - List rtn = [] - if (xmlInput!=null) { - def relationshipList = getListWithElements(xmlInput, 'relationship') - def relationshipListSize = relationshipList.size() - if (relationshipListSize > 0) { - for (i in 0..relationshipListSize-1) { - def relationshipXml = XmlUtil.serialize(relationshipList[i]) - if (utils.getNodeText(relationshipXml, 'related-to') == "l3-network") { - def relatedLink = utils.getNodeText(relationshipXml, 'related-link') - if (relatedLink != null || relatedLink != "") { - if (relatedLink.substring(relatedLink.indexOf("/l3-network/")+12, relatedLink.length()).contains('/')) { - rtn.add(relatedLink.substring(relatedLink.indexOf("/l3-network/")+12, relatedLink.length()-1)) - } else { - rtn.add(relatedLink.substring(relatedLink.indexOf("/l3-network/")+12, relatedLink.length())) - } - } - } - } - } - } - return rtn - } - - def isVfRelationshipExist(xmlInput) { - Boolean rtn = false - if (xmlInput!=null) { - def relationshipList = getListWithElements(xmlInput, 'relationship') - def relationshipListSize = relationshipList.size() - if (relationshipListSize > 0) { - for (i in 0..relationshipListSize-1) { - def relationshipXml = XmlUtil.serialize(relationshipList[i]) - if (utils.getNodeText(relationshipXml, 'related-to') == "vf-module") { - rtn = true - } - } - } - } - return rtn - - } - - def getCloudRegion(xmlInput) { - String lcpCloudRegion = "" - if (xmlInput!=null) { - def relationshipList = getListWithElements(xmlInput, 'relationship') - def relationshipListSize = relationshipList.size() - if (relationshipListSize > 0) { - for (i in 0..relationshipListSize-1) { - def relationshipXml = XmlUtil.serialize(relationshipList[i]) - if (utils.getNodeText(relationshipXml, 'related-to') == "cloud-region") { - def relatedLink = utils.getNodeText(relationshipXml, 'related-link') - if (relatedLink != null || relatedLink != "") { - AAIResourceUri aaiUri = AAIUriFactory.createResourceFromExistingURI(AAIObjectType.CLOUD_REGION, UriBuilder.fromUri(relatedLink).build()) - lcpCloudRegion = aaiUri.getURIKeys().getOrDefault("cloud-region", "") - } - } - } - } - } - return lcpCloudRegion - } - - def getTenantId(xmlInput) { - String tenantId = "" - if (xmlInput!=null) { - def relationshipList = getListWithElements(xmlInput, 'relationship') - def relationshipListSize = relationshipList.size() - if (relationshipListSize > 0) { - for (i in 0..relationshipListSize-1) { - def relationshipXml = XmlUtil.serialize(relationshipList[i]) - if (utils.getNodeText(relationshipXml, 'related-to') == "tenant") { - def relatedLink = utils.getNodeText(relationshipXml, 'related-link') - if (relatedLink != null || relatedLink != "") { - tenantId = relatedLink.substring(relatedLink.indexOf("/tenant/")+8, relatedLink.length()) - if (tenantId.contains('/')) { - tenantId = relatedLink.substring(relatedLink.indexOf("/tenant/")+8, relatedLink.length()-1) - } - } - } - } - } - } - return tenantId - } - - def isInstanceValueMatch(linkResource, globalSubscriberId, serviceType) { - Boolean rtn = false - try { - String globalSubscriberIdLink = linkResource.substring(linkResource.indexOf("/customer/")+10, linkResource.indexOf("/service-subscriptions")) - String serviceTypeLink = linkResource.substring(linkResource.indexOf("/service-subscription/")+22, linkResource.indexOf("/service-instances")) - if (globalSubscriberIdLink == globalSubscriberId) { - rtn = true - } else { - if (serviceTypeLink == serviceType) { - rtn = true - } - } - - } catch (Exception ex) { - println 'Exception - ' + ex.getMessage() - return false - } - return rtn - } - - def getListWithElements(xmlInput, groupName) { - def rtn = "" - if (xmlInput != null) { - def relationshipData = new XmlSlurper().parseText(xmlInput) - rtn = relationshipData.'**'.findAll {it.name() == groupName} - } - return rtn - - } - // build network single elements + @Deprecated //TODO remove if not used anywhere def buildNetworkElements(l3Network, createNetworkContrailResponse, networkList) { def replaceNetworkId = "" def replaceNeutronNetworkId = "" @@ -917,7 +386,7 @@ class NetworkUtils { } else { //pending-update or PendingUpdate xmlNetwork += "<"+element+">"+"Active"+"</"+element+">" } - } + } if (element=="heat-stack-id") { if (replaceNetworkId != "") { xmlNetwork += "<"+element+">"+replaceNetworkId+"</"+element+">" @@ -942,191 +411,102 @@ class NetworkUtils { } else { //pending-update or PendingUpdate xmlNetwork += "<"+element+">"+"Active"+"</"+element+">" } - } + } } else { xmlNetwork += "<"+element+">"+var.toString()+"</"+element+">" } - } + } } } return xmlNetwork } - def buildSubnets(requeryIdAAIResponse, createNetworkResponse) { + def buildSubnets(L3Network network) { def rebuildingSubnets = "" - if (requeryIdAAIResponse != null && utils.nodeExists(requeryIdAAIResponse, 'subnets')) { - def subnetIdMapValue = "" - def subnetsGroup = utils.getNodeXml(requeryIdAAIResponse, "subnets", false) - def subnetsData = new XmlSlurper().parseText(subnetsGroup) - rebuildingSubnets += "<subnets>" - try { - def subnets = subnetsData.'**'.findAll {it.name() == "subnet"} - def subnetsSize = subnets.size() - for (i in 0..subnetsSize-1) { - def subnet = subnets[i] - def subnetXml = XmlUtil.serialize(subnet) - def orchestrationStatus = utils.getNodeText(subnetXml, "orchestration-status") - if (orchestrationStatus == "PendingDelete" || orchestrationStatus == "pending-delete") { - // skip, do not include in processing, remove!!! - } else { - def subnetList = ["subnet-id", "neutron-subnet-id", "gateway-address", "network-start-address", "cidr-mask", "ip-version", "orchestration-status", "dhcp-enabled", "dhcp-start", "dhcp-end", "subnet-role", "resource-version", "subnet-name", "ip-assignment-direction", "host-routes"] - rebuildingSubnets += buildSubNetworkElements(subnetXml, createNetworkResponse, subnetList, "subnet") - } - } - if (utils.nodeExists(subnetsData, 'relationship')) { - rebuildingSubnets = rebuildRelationship(requeryIdAAIResponse) + Subnets subnets = network.getSubnets() + try{ + for(Subnet s : subnets.getSubnet()){ + def orchestrationStatus = s.getOrchestrationStatus() + if (orchestrationStatus == "pending-delete" || orchestrationStatus == "PendingDelete") { + // skip, do not include in processing, remove!!! + } else { + def subnetList = ["dhcp-start", "dhcp-end", "network-start-address", "cidr-mask", "dhcp-enabled", "gateway-address", "ip-version", "subnet-id", "subnet-name", "ip-assignment-direction", "host-routes"] + rebuildingSubnets += buildSubNetworkElements(s, subnetList, "subnets") + //rebuildingSubnets += buildSubNetworkElements(subnetXml, subnetList, "") } - - } catch (Exception ex) { - // error - } finally { - rebuildingSubnets += "</subnets>" - } - } - return rebuildingSubnets - } - - def buildSubnets(queryIdResponse) { - def rebuildingSubnets = "" - def subnetsData = new XmlSlurper().parseText(queryIdResponse) - //rebuildingSubnets += "<subnets>" - try { - def subnets = subnetsData.'**'.findAll {it.name() == "subnet"} - def subnetsSize = subnets.size() - for (i in 0..subnetsSize-1) { - def subnet = subnets[i] - def subnetXml = XmlUtil.serialize(subnet) - def orchestrationStatus = utils.getNodeText(subnetXml, "orchestration-status") - if (orchestrationStatus == "pending-delete" || orchestrationStatus == "PendingDelete") { - // skip, do not include in processing, remove!!! - } else { - def subnetList = ["dhcp-start", "dhcp-end", "network-start-address", "cidr-mask", "dhcp-enabled", "gateway-address", "ip-version", "subnet-id", "subnet-name", "ip-assignment-direction", "host-routes"] - rebuildingSubnets += buildSubNetworkElements(subnetXml, subnetList, "subnets") - //rebuildingSubnets += buildSubNetworkElements(subnetXml, subnetList, "") - } } } catch (Exception ex) { - // + // } finally { - //rebuildingSubnets += "</subnets>" + //rebuildingSubnets += "</subnets>" } return rebuildingSubnets } - // build subnet sub-network single elements - def buildSubNetworkElements(subnetXml, createNetworkResponse, elementList, parentName) { - String var = "" - def xmlBuild = "" - if (parentName != "") { - xmlBuild += "<"+parentName+">" - } - if (subnetXml != null) { - for (element in elementList) { - def xml= new XmlSlurper().parseText(subnetXml) - var = xml.'**'.find {it.name() == element} - if (var != null) { - if (element=="orchestration-status") { - if(var.toString() == 'pending-create' || var.toString() == 'PendingCreate') { - xmlBuild += "<"+element+">"+"Created"+"</"+element+">" - } else { // pending-update or PendingUpdate' - xmlBuild += "<"+element+">"+"Active"+"</"+element+">" - } - } else { // "subnet-id", "neutron-subnet-id" - if (element=="subnet-id") { - if (utils.nodeExists(createNetworkResponse, "subnetMap")) { - xmlBuild += "<"+element+">"+var.toString()+"</"+element+">" - String neutronSubnetId = extractNeutSubId(createNetworkResponse, var.toString()) - xmlBuild += "<neutron-subnet-id>"+neutronSubnetId+"</neutron-subnet-id>" - } - } else { - if (element=="neutron-subnet-id") { - // skip - } else { - if (element=="host-routes") { - if (subnetXml.contains("host-routes")) { - List elementRoute = ["host-route-id", "route-prefix", "next-hop", "next-hop-type", "resource-version"] - xmlBuild += buildXMLElements(subnetXml, "host-routes", "host-route", elementRoute) - } - } else { - xmlBuild += "<"+element+">"+var.toString()+"</"+element+">" - } - } - } - } - } - } - - } - if (parentName != "") { - xmlBuild += "</"+parentName+">" - } - return xmlBuild - } + def buildSubNetworkElements(Subnet subnet, elementList, parentName) { - // build subnet sub-network single elements - def buildSubNetworkElements(subnetXml, elementList, parentName) { def var = "" def xmlBuild = "" if (parentName != "") { xmlBuild += "<"+parentName+">" } - if (subnetXml != null) { + if (subnet != null) { def networkStartAddress = "" for (element in elementList) { - def xml= new XmlSlurper().parseText(subnetXml) - var = xml.'**'.find {it.name() == element} if (element == "dhcp-start") { + var = subnet.getDhcpStart() xmlBuild += "<allocationPools>" - if (var.toString() == 'null') { + if (var == null) { xmlBuild += "<start>"+""+"</start>" } else { - xmlBuild += "<start>"+var.toString()+"</start>" + xmlBuild += "<start>"+var+"</start>" } } if (element == "dhcp-end") { - if (var.toString() == 'null') { + var = subnet.getDhcpEnd() + if (var == null) { xmlBuild += "<end>"+""+"</end>" } else { - xmlBuild += "<end>"+var.toString()+"</end>" + xmlBuild += "<end>"+var+"</end>" } xmlBuild += "</allocationPools>" } if (element == "network-start-address" || element == "cidr-mask") { if (element == "network-start-address") { - networkStartAddress = var.toString() + networkStartAddress = subnet.getNetworkStartAddress() } if (element == "cidr-mask") { - xmlBuild += "<cidr>"+networkStartAddress+"/"+var.toString()+"</cidr>" + xmlBuild += "<cidr>"+networkStartAddress+"/"+ subnet.getCidrMask() +"</cidr>" } } if (element == "dhcp-enabled") { - xmlBuild += "<enableDHCP>"+var.toString()+"</enableDHCP>" + xmlBuild += "<enableDHCP>"+subnet.isDhcpEnabled()+"</enableDHCP>" } if (element == "gateway-address") { - xmlBuild += "<gatewayIp>"+var.toString()+"</gatewayIp>" + xmlBuild += "<gatewayIp>"+subnet.getGatewayAddress()+"</gatewayIp>" } if (element == "ip-version") { - String ipVersion = getIpvVersion(var.toString()) + String ipVersion = getIpvVersion(subnet.getIpVersion()) xmlBuild += "<ipVersion>"+ipVersion+"</ipVersion>" } if (element == "subnet-id") { - xmlBuild += "<subnetId>"+var.toString()+"</subnetId>" + xmlBuild += "<subnetId>"+subnet.getSubnetId()+"</subnetId>" } - if ((element == "subnet-name") && (var != null)) { - xmlBuild += "<subnetName>"+var.toString()+"</subnetName>" + if ((element == "subnet-name") && (subnet.getSubnetName() != null)) { + xmlBuild += "<subnetName>"+subnet.getSubnetName()+"</subnetName>" } - if ((element == "ip-assignment-direction") && (var != null)) { - xmlBuild += "<addrFromStart>"+var.toString()+"</addrFromStart>" + if ((element == "ip-assignment-direction") && (subnet.getIpAssignmentDirection() != null)) { + xmlBuild += "<addrFromStart>"+subnet.getIpAssignmentDirection()+"</addrFromStart>" } if (element == "host-routes") { def routes = "" - if (subnetXml.contains("host-routes")) { - routes = buildHostRoutes(subnetXml) + if (subnet.getHostRoutes() != null) { + routes = buildHostRoutes(subnet) } - xmlBuild += routes - } - + xmlBuild += routes + } + } } if (parentName != "") { @@ -1136,236 +516,40 @@ class NetworkUtils { } // rebuild host-routes - def buildHostRoutes(subnetXml) { - List routeElementList = ["host-route-id", "route-prefix", "next-hop", "next-hop-type", "resource-version"] - def hostRoutes = buildXMLElements(subnetXml, "host-routes", "host-route", routeElementList) + def buildHostRoutes(Subnet subnet) { def buildHostRoutes = "" - def var = "" - if (hostRoutes!=null) { - def routesData = new XmlSlurper().parseText(hostRoutes) - def routes = routesData.'**'.findAll {it.name() == "host-route"} - def routesSize = routes.size() - for (i in 0..routesSize-1) { - buildHostRoutes += "<hostRoutes>" - def route = routes[i] - def routeXml = XmlUtil.serialize(route) - List elementList = ["route-prefix", "next-hop"] - for (element in elementList) { - def xml= new XmlSlurper().parseText(routeXml) - var = xml.'**'.find {it.name() == element} - if (element == "route-prefix") { - buildHostRoutes += "<prefix>"+var.toString()+"</prefix>" - } - if (element == "next-hop") { - buildHostRoutes += "<nextHop>"+var.toString()+"</nextHop>" - } - } - buildHostRoutes += "</hostRoutes>" - } - } - return buildHostRoutes - - } - - // rebuild ctag-assignments - def rebuildCtagAssignments(xmlInput) { - def rebuildingCtagAssignments = "" - if (xmlInput!=null) { - def ctagAssignmentsData = new XmlSlurper().parseText(xmlInput) - rebuildingCtagAssignments += "<ctag-assignments>" - def ctagAssignments = ctagAssignmentsData.'**'.findAll {it.name() == "ctag-assignment"} - def ctagAssignmentsSize = ctagAssignments.size() - for (i in 0..ctagAssignmentsSize-1) { - def ctagAssignment = ctagAssignments[i] - def ctagAssignmentXml = XmlUtil.serialize(ctagAssignment) - rebuildingCtagAssignments += "<ctag-assignment>" - List elementList = ["vlan-id-inner", "resource-version"] - rebuildingCtagAssignments += buildXMLElements(ctagAssignmentXml, "" , "", elementList) - if (utils.nodeExists(ctagAssignmentXml, 'relationship')) { - rebuildingCtagAssignments += rebuildRelationship(ctagAssignmentXml) - } - rebuildingCtagAssignments += "</ctag-assignment>" + List<HostRoute> routes = subnet.getHostRoutes().getHostRoute() + if(!routes.isEmpty()){ + for(HostRoute route:routes){ + buildHostRoutes += "<hostRoutes>" + buildHostRoutes += "<prefix>" + route.getRoutePrefix() + "</prefix>" + buildHostRoutes += "<nextHop>" + route.getNextHop() + "</nextHop>" + buildHostRoutes += "</hostRoutes>" } - rebuildingCtagAssignments += "</ctag-assignments>" } - return rebuildingCtagAssignments - } - // rebuild 'relationship-list' - def rebuildRelationship(xmlInput) { - def rebuildingSubnets = "" - if (xmlInput!=null) { - def subnetsData = new XmlSlurper().parseText(xmlInput) - rebuildingSubnets += "<relationship-list>" - def relationships = subnetsData.'**'.findAll {it.name() == "relationship"} - def relationshipsSize = relationships.size() - for (i in 0..relationshipsSize-1) { - def relationship = relationships[i] - def relationshipXml = XmlUtil.serialize(relationship) - rebuildingSubnets += "<relationship>" - def relationshipList = ["related-to", "related-link"] - rebuildingSubnets += buildSubNetworkElements(relationshipXml, "", relationshipList, "") - if (utils.nodeExists(relationshipXml, 'relationship-data')) { - def relationshipDataXmlData = new XmlSlurper().parseText(relationshipXml) - def relationshipsData = relationshipDataXmlData.'**'.findAll {it.name() == "relationship-data"} - def relationshipsDataSize = relationshipsData.size() - for (j in 0..relationshipsDataSize-1) { - def relationshipData = relationshipsData[j] - def relationshipDataXml = XmlUtil.serialize(relationshipData) - def relationshipDataList = ["relationship-key", "relationship-value"] - rebuildingSubnets += buildXMLElements(relationshipDataXml, "", "relationship-data", relationshipDataList) - } - } - if (utils.nodeExists(relationshipXml, 'related-to-property')) { - def relationshipDataXmlData = new XmlSlurper().parseText(relationshipXml) - def relationshipsData = relationshipDataXmlData.'**'.findAll {it.name() == "related-to-property"} - def relationshipsDataSize = relationshipsData.size() - for (j in 0..relationshipsDataSize-1) { - def relationshipData = relationshipsData[j] - def relationshipDataXml = XmlUtil.serialize(relationshipData) - def relationshipDataList = ["property-key", "property-value"] - rebuildingSubnets += buildXMLElements(relationshipDataXml, "", "related-to-property", relationshipDataList) - } - } - - rebuildingSubnets += "</relationship>" - } - rebuildingSubnets += "</relationship-list>" - } - return rebuildingSubnets + return buildHostRoutes } - def buildVlans(queryIdResponse) { - def rebuildingSubnets = "<vlans>" - def subnetsData = new XmlSlurper().parseText(queryIdResponse) - - try { - def subnets = subnetsData.'**'.findAll {it.name() == "segmentation-assignments"} - def subnetsSize = subnets.size() - for (i in 0..subnetsSize-1) { - def subnet = subnets[i] - def subnetXml = XmlUtil.serialize(subnet) - - String vlan = utils.getNodeText(subnetXml, "segmentation-id") - if (i>0){ - rebuildingSubnets += "," - } - rebuildingSubnets += vlan - } - } catch (Exception ex) { - // - } finally { - //rebuildingSubnets += "</subnets>" - rebuildingSubnets += "</vlans>" - } - return rebuildingSubnets - } - - /* Utility code to rebuild xml/elements in a list: - * rebuild xml with 1) unbounded groups of elements; or - * 2) one group of elements; or - * 3) just one or more elements (in a list as argument) - * @param xmlInput the XML document - * @param parentName the parent name (ex: 'inputs') - * @param childrenName the chilrendName (ex: 'entry' as unbounded/occurs>1) - * @param elementList the element list of children (ex: 'key', 'value') - * @return a string of rebuild xml - * - * Ex 1: xmlInput: - * <ws:inputs> - * <ws:entry> - * <ws:key>name</ws:key> - * <ws:value>Edward</ws:value> - * </ws:entry> - * <ws:entry> - * <ws:key>age</ws:key> - * <ws:value>30</ws:value> - * </ws:entry> - * <ws:entry> - * <ws:key>age</ws:key> - * <ws:value>30</ws:value> - * </ws:entry> - * <ws:/inputs> - * Usage: - * List elementList = ["key", "value"] - * String rebuild = buildXMLElements(xmlInput, "inputs", "entry", elementList) - * - * Ex 2: xmlInput // no parent tag - * <ws:sdnc-request-header> - * <ws:svc-request-id>fec8ec88-151a-45c9-ad60-8233e0fc8ff2</ws:svc-request-id> - * <ws:svc-notification-url>https://localhost:8443/adapters/rest/SDNCNotify</ws:svc-notification-url> - * <ws:svc-action>assign</ws:svc-action> - * </ws:sdnc-request-header> - * Usage: - * List elementList = ["svc-request-id", "svc-notification-url", "svc-action"] - * String rebuild = buildXMLElements(xmlInput, "" , "sdnc-request-header", elementList) // no parent tag - * - * Ex 3: xmlInput // elements one after another (with no parent & children tag) - * <ws:test-id>myTestid</ws:test-id> - * <ws:test-user>myUser</ws:test-user> - * Usage: - * List elementList = ["test-id", "test-user"] - * String rebuild = buildXMLElements(xmlInput, "" , "", elementList) - * - */ - def buildXMLElements(xmlInput, parentName, childrenName, elementList) { - def varChildren = "" - def var = "" - def xmlBuildUnbounded = "" - if (parentName!="") {xmlBuildUnbounded += "<"+parentName+">" +'\n'} - if (xmlInput != null) { - def xml= new XmlSlurper().parseText(xmlInput) - if (childrenName!="") { - varChildren = xml.'**'.findAll {it.name() == childrenName} - for (i in 0..varChildren.size()-1) { - xmlBuildUnbounded += "<"+childrenName+">" +'\n' - for (element in elementList) { - var = varChildren[i].'*'.find {it.name() == element} - if (var != null) { - xmlBuildUnbounded += "<"+element+">"+var.toString()+"</"+element+">" +'\n' - } - } - xmlBuildUnbounded += "</"+childrenName+">" +'\n' - } - } else { - for (element in elementList) { - var = xml.'*'.find {it.name() == element} - if (var != null) { - xmlBuildUnbounded += "<"+element+">"+var.toString()+"</"+element+">" +'\n' - } + private String buildVlans(L3Network queryIdResponse) { // get seg ids in put in vlan tags + String vlans = "<vlans>" + if(queryIdResponse.getSegmentationAssignments() != null){ + List<SegmentationAssignment> segmentations = queryIdResponse.getSegmentationAssignments().getSegmentationAssignment() + if(!segmentations.isEmpty()){ + for(SegmentationAssignment seg:segmentations){ + String vlan = seg.getSegmentationId() + "," + vlans += vlan } } - } - if (parentName!="") {xmlBuildUnbounded += "</"+parentName+">" +'\n'} - return xmlBuildUnbounded - } - - def getFirstNodeXml(xmlInput, element){ - def nodeAsText = "" - def nodeToSerialize = "" - if (xmlInput != null) { - def fxml= new XmlSlurper().parseText(xmlInput) - if (utils.nodeExists(xmlInput, "payload")) { - nodeToSerialize = fxml.'payload'.'l3-network'.'*'.find {it.name() == element} - if (nodeToSerialize!=null) { - nodeAsText = XmlUtil.serialize(nodeToSerialize) - } else { - nodeAsText = "" - } - - } else { - nodeToSerialize = fxml.'*'.find {it.name() == element} - if (nodeToSerialize!=null) { - nodeAsText = XmlUtil.serialize(nodeToSerialize) - } else { - nodeAsText = "" - } - } + if(vlans.endsWith(",")){ + vlans = vlans.substring(0, vlans.length() - 1) } - return nodeAsText + vlans += "</vlans>" + + return vlans } //TODO: This method still needs to be tested before using. @@ -1504,17 +688,17 @@ class NetworkUtils { } return rollbackEnabled } - - + + /** * This method extracts the version for the the given ip-version. * * @param String ipvVersion - IP protocols version (ex: ipv4 or ipv6 or 4 or 6) * @return String version - digit version (ex: 4 or 6) */ - + public String getIpvVersion (String ipvVersion) { - + String version = "" try { if (ipvVersion.isNumber()) { @@ -1526,7 +710,7 @@ class NetworkUtils { } } } catch (Exception ex) { - version = ipvVersion + version = ipvVersion } return version } diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/OofHoming.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/OofHoming.groovy index b03256b098..5e949fd8d2 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/OofHoming.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/OofHoming.groovy @@ -30,14 +30,14 @@ import org.onap.so.bpmn.core.domain.ServiceDecomposition import org.onap.so.bpmn.core.domain.Subscriber import org.onap.so.bpmn.core.domain.VnfResource import org.onap.so.bpmn.core.json.JsonUtils -import org.onap.so.db.catalog.beans.AuthenticationType +import org.onap.so.client.HttpClient +import org.onap.so.client.HttpClientFactory +import org.onap.so.logger.MsoLogger import org.onap.so.db.catalog.beans.CloudIdentity import org.onap.so.db.catalog.beans.CloudSite import org.onap.so.db.catalog.beans.HomingInstance -import org.onap.so.db.catalog.beans.ServerType -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.utils.TargetEntity import org.json.JSONArray import org.json.JSONObject @@ -45,6 +45,8 @@ import org.springframework.web.util.UriUtils import static org.onap.so.bpmn.common.scripts.GenericUtils.* +import javax.ws.rs.core.Response + /** * This class contains the scripts used * by the OOF Homing Subflow building block. The @@ -135,7 +137,7 @@ class OofHoming extends AbstractServiceTaskProcessor { //Prepare Callback String timeout = execution.getVariable("timeout") - if (isBlank(timeout)) { + if (isBlank(timeout)) { timeout = UrnPropertiesReader.getVariable("mso.oof.timeout", execution); if (isBlank(timeout)) { timeout = "PT30M" @@ -153,25 +155,18 @@ class OofHoming extends AbstractServiceTaskProcessor { execution.setVariable("oofRequest", oofRequest) utils.log("DEBUG", "OOF Request is: " + oofRequest, isDebugEnabled) - String url = UrnPropertiesReader.getVariable("mso.oof.endpoint", execution) - utils.log("DEBUG", "Posting to OOF Url: " + url, isDebugEnabled) + String urlString = UrnPropertiesReader.getVariable("mso.oof.endpoint", execution) + utils.log("DEBUG", "Posting to OOF Url: " + urlString, isDebugEnabled) - logDebug("URL to be used is: " + url, isDebugEnabled) - RESTConfig config = new RESTConfig(url) - RESTClient client = new RESTClient(config).addAuthorizationHeader(authHeader). - addHeader("Content-Type", "application/json") - APIResponse response = client.httpPost(oofRequest) + URL url = new URL(urlString); + HttpClient httpClient = new HttpClientFactory().newJsonClient(url, TargetEntity.SNIRO) + httpClient.addAdditionalHeader("Authorization", authHeader) + Response httpResponse = httpClient.post(oofRequest) - int responseCode = response.getStatusCode() - logDebug("OOF sync response code is: " + responseCode, isDebugEnabled) - String syncResponse = response.getResponseBodyAsString() - execution.setVariable("syncResponse", syncResponse) - logDebug("OOF sync response is: " + syncResponse, isDebugEnabled) + int responseCode = httpResponse.getStatus() + logDebug("OOF sync response code is: " + responseCode, isDebugEnabled) - if(responseCode != 202){ - exceptionUtil.buildAndThrowWorkflowException(execution, responseCode, "Received a Bad Sync Response from OOF.") - } utils.log("DEBUG", "*** Completed Homing Call OOF ***", isDebugEnabled) } diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/OofUtils.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/OofUtils.groovy index f72fc47aa5..af33f38a64 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/OofUtils.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/OofUtils.groovy @@ -33,16 +33,29 @@ import org.onap.so.bpmn.core.domain.ServiceInstance import org.onap.so.bpmn.core.domain.Subscriber import org.onap.so.bpmn.core.domain.VnfResource import org.onap.so.bpmn.core.json.JsonUtils +import org.onap.so.client.HttpClient +import org.onap.so.client.HttpClientFactory import org.onap.so.db.catalog.beans.CloudSite import org.onap.so.db.catalog.beans.HomingInstance -import javax.ws.rs.core.UriBuilder -import org.onap.so.bpmn.common.util.OofInfraUtils +import org.onap.so.utils.TargetEntity +import org.springframework.http.HttpEntity +import org.springframework.http.HttpHeaders +import org.springframework.http.HttpMethod +import org.springframework.http.ResponseEntity +import org.springframework.http.client.BufferingClientHttpRequestFactory +import org.springframework.http.client.HttpComponentsClientHttpRequestFactory +import org.springframework.web.client.RestTemplate +import org.springframework.web.util.UriComponentsBuilder + +import javax.ws.rs.core.MediaType +import javax.ws.rs.core.Response +import javax.xml.ws.http.HTTPException + import static org.onap.so.bpmn.common.scripts.GenericUtils.* class OofUtils { ExceptionUtil exceptionUtil = new ExceptionUtil() JsonUtils jsonUtil = new JsonUtils() - OofInfraUtils oofInfraUtils = new OofInfraUtils() private AbstractServiceTaskProcessor utils @@ -491,10 +504,29 @@ class OofUtils { * * @return void */ - Void createCloudSite(CloudSite cloudSite, DelegateExecution execution) { - oofInfraUtils.createCloudSite(cloudSite, execution) - } + Void createCloudSiteCatalogDb(CloudSite cloudSite, DelegateExecution execution) { + + String endpoint = UrnPropertiesReader.getVariable("mso.catalog.db.spring.endpoint", execution) + String auth = UrnPropertiesReader.getVariable("mso.db.auth", execution) + String uri = "/cloudSite" + + URL url = new URL(endpoint + uri) + HttpClient client = new HttpClientFactory().newJsonClient(url, TargetEntity.EXTERNAL) + client.addAdditionalHeader(HttpHeaders.AUTHORIZATION, auth) + client.addAdditionalHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON) + + Response response = client.post(request.getBody().toString()) + int responseCode = response.getStatus() + logDebug("CatalogDB response code is: " + responseCode, isDebugEnabled) + String syncResponse = response.readEntity(String.class) + logDebug("CatalogDB response is: " + syncResponse, isDebugEnabled) + + if(responseCode != 202){ + exceptionUtil.buildAndThrowWorkflowException(execution, responseCode, "Received a Bad Sync Response from CatalogDB.") + } + } + /** * This method creates a HomingInstance in catalog database. * @@ -505,7 +537,6 @@ class OofUtils { Void createHomingInstance(HomingInstance homingInstance, DelegateExecution execution) { oofInfraUtils.createHomingInstance(homingInstance, execution) } - String getMsbHost(DelegateExecution execution) { String msbHost = UrnPropertiesReader.getVariable("mso.msb.host", execution, "msb-iag.onap") diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/PrepareUpdateAAIVfModule.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/PrepareUpdateAAIVfModule.groovy index 1a55bf2a0e..15f00ac25f 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/PrepareUpdateAAIVfModule.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/PrepareUpdateAAIVfModule.groovy @@ -34,9 +34,6 @@ import org.onap.so.client.aai.entities.AAIResultWrapper import org.onap.so.client.aai.entities.uri.AAIResourceUri import org.onap.so.client.aai.entities.uri.AAIUriFactory import org.onap.so.client.graphinventory.entities.uri.Depth -import org.onap.so.rest.APIResponse -import org.onap.so.rest.RESTClient -import org.onap.so.rest.RESTConfig import org.springframework.web.util.UriUtils import org.onap.so.logger.MessageEnum import org.onap.so.logger.MsoLogger @@ -214,79 +211,38 @@ public class PrepareUpdateAAIVfModule extends VfModuleBase { msoLogger.trace('Entered ' + method) try { - // Construct payload - org.onap.aai.domain.yang.VfModule vfModule = execution.getVariable('PUAAIVfMod_vfModule') - - def orchestrationStatus = execution.getVariable('PUAAIVfMod_orchestrationStatus') - - vfModule.setOrchestrationStatus(orchestrationStatus) - - //def payload = utils.nodeToString(newVfModuleNode) - - // Construct endpoint def vnfId = execution.getVariable('PUAAIVfMod_vnfId') def vfModuleId = execution.getVariable('PUAAIVfMod_vfModuleId') + def orchestrationStatus = execution.getVariable('PUAAIVfMod_orchestrationStatus') - def payload = """{ - "vf-module-id": "${vfModuleId}", - "orchestration-status": "${orchestrationStatus}" - }""" + org.onap.aai.domain.yang.VfModule vfModule = execution.getVariable('PUAAIVfMod_vfModule') - msoLogger.debug("VfModule payload : " + payload) + vfModule.setVfModuleId(vfModuleId) + vfModule.setOrchestrationStatus(orchestrationStatus) - AaiUtil aaiUtil = new AaiUtil(this) + AAIResourcesClient client = new AAIResourcesClient() AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.VF_MODULE, vnfId, vfModuleId) - uri.depth(Depth.ONE) - String endPoint = aaiUtil.createAaiUri(uri) + client.update(uri, vfModule) + execution.setVariable('PUAAIVfMod_updateVfModuleResponseCode', 200) + // Set the output for this flow. The updated VfModule is an output, the generic VNF name, and for + // backward compatibilty, the heat-stack-id is an output + execution.setVariable('PUAAIVfMod_outVfModule', vfModule) + def vnfName = execution.getVariable('PUAAIVfMod_vnfName') + msoLogger.debug('Output PUAAIVfMod_vnfName set to ' + vnfName) + // TODO: Should deprecate use of processKey+Response variable for the response. Will use "WorkflowResponse" instead + execution.setVariable('WorkflowResponse', vfModule) + + def heatStackId = vfModule.getHeatStackId() + execution.setVariable('PUAAIVfMod_heatStackId', heatStackId) + msoLogger.debug('Output PUAAIVfMod_heatStackId set to \'' + heatStackId + '\'') - msoLogger.debug("PrepareUpdateAAIVfModule: AAI endPoint : " + endPoint) - String basicAuthCred = utils.getBasicAuth(UrnPropertiesReader.getVariable("aai.auth", execution),UrnPropertiesReader.getVariable("mso.msoKey", execution)) - try { - RESTConfig config = new RESTConfig(endPoint); - def responseData = '' - def aaiRequestId = utils.getRequestID() - RESTClient client = new RESTClient(config). - addHeader('X-TransactionId', aaiRequestId). - addHeader('X-FromAppId', 'MSO'). - addHeader('Content-Type', 'application/merge-patch+json'). - addHeader('Accept','application/json'); - if (basicAuthCred != null && !"".equals(basicAuthCred)) { - client.addAuthorizationHeader(basicAuthCred) - } - msoLogger.debug('sending PATCH to AAI endpoint \'' + endPoint + '\'' + 'with payload \n' + payload) - APIResponse response = client.httpPatch(payload) - msoLogger.debug("PrepareUpdateAAIVfModule: - invoking httpPatch to AAI") - - responseData = response.getResponseBodyAsString() - execution.setVariable('PUAAIVfMod_updateVfModuleResponseCode', response.getStatusCode()) - execution.setVariable('PUAAIVfMod_updateVfModuleResponse', responseData) - msoLogger.debug('Response code:' + response.getStatusCode()) - msoLogger.debug('Response:' + System.lineSeparator() + responseData) - msoLogger.debug("PrepareUpdateAAIVfModule: AAI Response : " + responseData) - msoLogger.debug("PrepareUpdateAAIVfModule: AAI ResponseCode : " + response.getStatusCode()) - - // Set the output for this flow. The updated VfModule is an output, the generic VNF name, and for - // backward compatibilty, the heat-stack-id is an output - execution.setVariable('PUAAIVfMod_outVfModule', vfModule) - def vnfName = execution.getVariable('PUAAIVfMod_vnfName') - msoLogger.debug('Output PUAAIVfMod_vnfName set to ' + vnfName) - // TODO: Should deprecate use of processKey+Response variable for the response. Will use "WorkflowResponse" instead - execution.setVariable('WorkflowResponse', vfModule) - - def heatStackId = vfModule.getHeatStackId() - execution.setVariable('PUAAIVfMod_heatStackId', heatStackId) - msoLogger.debug('Output PUAAIVfMod_heatStackId set to \'' + heatStackId + '\'') - } catch (Exception ex) { - ex.printStackTrace() - msoLogger.debug('Exception occurred while executing AAI PUT:' + ex.getMessage()) - execution.setVariable('PUAAIVfMod_updateVfModuleResponseCode', 500) - execution.setVariable('PUAAIVfMod_updateVfModuleResponse', 'AAI PATCH Failed:' + ex.getMessage()) - } msoLogger.trace('Exited ' + method) } catch (BpmnError e) { + execution.setVariable('PUAAIVfMod_updateVfModuleResponseCode', 500) throw e; } catch (Exception e) { msoLogger.error(e) + execution.setVariable('PUAAIVfMod_updateVfModuleResponseCode', 500) exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in updateVfModule(): ' + e.getMessage()) } } diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/SDNCAdapter.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/SDNCAdapter.groovy index 852f8d75bd..a430cdb715 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/SDNCAdapter.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/SDNCAdapter.groovy @@ -28,11 +28,10 @@ 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.* // SDNC Adapter Request/Response processing - public class SDNCAdapter extends AbstractServiceTaskProcessor { private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, SDNCAdapter.class); @@ -58,6 +57,11 @@ public class SDNCAdapter extends AbstractServiceTaskProcessor { execution.setVariable("SDNCA_SuccessIndicator", false) execution.setVariable("SDNCA_InterimNotify", false) + String requestId = execution.getVariable("mso-request-id") + if(isBlank(requestId)){ + exceptionUtil.buildAndThrowWorkflowException(execution, 400, 'mso-request-id not provided by calling flow') + } + // Authorization Info String basicAuthValue = UrnPropertiesReader.getVariable("mso.adapters.po.auth", execution) @@ -118,8 +122,8 @@ public class SDNCAdapter extends AbstractServiceTaskProcessor { msoLogger.debug("source: " + source) //calling process should pass a generated uuid if sending multiple sdnc requests - def requestId = utils.getNodeText(requestHeader, "RequestId") - execution.setVariable(Prefix + "requestId", requestId) + def sdncRequestId = utils.getNodeText(requestHeader, "RequestId") + execution.setVariable(Prefix + "requestId", sdncRequestId) // Prepare SDNC Request to the SDNC Adapter String sdncAdapterRequest = """ @@ -127,7 +131,7 @@ public class SDNCAdapter extends AbstractServiceTaskProcessor { <SOAP-ENV:Body> <aetgt:SDNCAdapterRequest xmlns:aetgt="http://org.onap/workflow/sdnc/adapter/schema/v1" xmlns:sdncadaptersc="http://org.onap/workflow/sdnc/adapter/schema/v1"> <sdncadapter:RequestHeader xmlns:sdncadapter="http://org.onap/workflow/sdnc/adapter/schema/v1"> - <sdncadapter:RequestId>${MsoUtils.xmlEscape(requestId)}</sdncadapter:RequestId>""" + <sdncadapter:RequestId>${MsoUtils.xmlEscape(sdncRequestId)}</sdncadapter:RequestId>""" if (sdnca_svcInstanceId != null) { sdncAdapterRequest += """ @@ -180,7 +184,7 @@ public class SDNCAdapter extends AbstractServiceTaskProcessor { callbackHeader = callbackHeader.replace("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n", "") callbackRequestData = callbackRequestData.replace("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n", "") - + msoLogger.trace("EnhancedCallbackRequestData:\n" + callbackRequestData) execution.setVariable("enhancedCallbackRequestData", callbackRequestData) diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/SDNCAdapterRestV1.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/SDNCAdapterRestV1.groovy index f610ea4782..9f1570ee15 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/SDNCAdapterRestV1.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/SDNCAdapterRestV1.groovy @@ -20,7 +20,10 @@ package org.onap.so.bpmn.common.scripts +import org.onap.so.client.HttpClientFactory + import java.text.SimpleDateFormat +import javax.ws.rs.core.Response import java.net.URLEncoder import org.apache.commons.codec.binary.Base64 @@ -36,11 +39,10 @@ import org.onap.so.bpmn.core.UrnPropertiesReader import org.onap.so.bpmn.core.WorkflowException import org.onap.so.bpmn.core.domain.RollbackData import org.onap.so.bpmn.core.json.JsonUtils -import org.onap.so.rest.APIResponse -import org.onap.so.rest.RESTClient -import org.onap.so.rest.RESTConfig +import org.onap.so.client.HttpClient import org.onap.so.logger.MessageEnum import org.onap.so.logger.MsoLogger +import org.onap.so.utils.TargetEntity @@ -205,23 +207,26 @@ class SDNCAdapterRestV1 extends AbstractServiceTaskProcessor { String sdncAdapterRequest = execution.getVariable(prefix + 'sdncAdapterRequest') msoLogger.debug("SDNC Rest Request is: " + sdncAdapterRequest) - RESTConfig config = new RESTConfig(sdncAdapterUrl) - RESTClient client = new RESTClient(config). - addHeader("Content-Type", "application/json") - .addHeader("mso-request-id",execution.getVariable("mso-request-id")) - .addHeader("mso-service-instance-id",execution.getVariable("mso-service-instance-id")) - .addAuthorizationHeader(execution.getVariable(prefix + "basicAuthHeaderValue")) + URL url = new URL(sdncAdapterUrl); + + HttpClient httpClient = new HttpClientFactory().newJsonClient(url, TargetEntity.SDNC_ADAPTER) + httpClient.addAdditionalHeader("X-ONAP-RequestID", execution.getVariable("mso-request-id")) + httpClient.addAdditionalHeader("X-ONAP-InvocationID", UUID.randomUUID().toString()) + httpClient.addAdditionalHeader("X-ONAP-PartnerName", "SO-SDNCAdapter") + httpClient.addAdditionalHeader("mso-request-id", execution.getVariable("mso-request-id")) + httpClient.addAdditionalHeader("mso-service-instance-id", execution.getVariable("mso-service-instance-id")) + httpClient.addAdditionalHeader("Authorization", execution.getVariable(prefix + "basicAuthHeaderValue")) - APIResponse response + Response response if ("GET".equals(sdncAdapterMethod)) { - response = client.httpGet() + response = httpClient.get() } else if ("PUT".equals(sdncAdapterMethod)) { - response = client.httpPut(sdncAdapterRequest) + response = httpClient.put(sdncAdapterRequest) } else if ("POST".equals(sdncAdapterMethod)) { - response = client.httpPost(sdncAdapterRequest) + response = httpClient.post(sdncAdapterRequest) } else if ("DELETE".equals(sdncAdapterMethod)) { - response = client.httpDelete(sdncAdapterRequest) + response = httpClient.delete(sdncAdapterRequest) } else { String msg = 'Unsupported HTTP method "' + sdncAdapterMethod + '" in ' + method + ": " + e msoLogger.debug(msg) @@ -229,13 +234,15 @@ class SDNCAdapterRestV1 extends AbstractServiceTaskProcessor { exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg) } - execution.setVariable(prefix + "sdncAdapterStatusCode", response.getStatusCode()) - execution.setVariable(prefix + "sdncAdapterResponse", response.getResponseBodyAsString()) + execution.setVariable(prefix + "sdncAdapterStatusCode", response.getStatus()) + if(response.hasEntity()){ + execution.setVariable(prefix + "sdncAdapterResponse", response.readEntity(String.class)) + } } catch (BpmnError e) { throw e } catch (Exception e) { String msg = 'Caught exception in ' + method + ": " + e - msoLogger.debug(msg) + msoLogger.debug(msg, e) msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, msg, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, ""); exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg) } diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/SDNCAdapterRestV2.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/SDNCAdapterRestV2.groovy index 967b9fa93f..1a20497bbc 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/SDNCAdapterRestV2.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/SDNCAdapterRestV2.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. @@ -34,9 +34,6 @@ import org.json.JSONObject import org.onap.so.bpmn.core.WorkflowException import org.onap.so.bpmn.core.json.JsonUtils -import org.onap.so.rest.APIResponse -import org.onap.so.rest.RESTClient -import org.onap.so.rest.RESTConfig import org.onap.so.bpmn.core.UrnPropertiesReader import org.onap.so.logger.MessageEnum import org.onap.so.logger.MsoLogger @@ -224,7 +221,7 @@ class SDNCAdapterRestV2 extends SDNCAdapterRestV1 { if (responseType.endsWith('Error')) { sdncAdapterBuildWorkflowException(execution, callback) } - + // Check for possible interim notification execution.setVariable(prefix + "interimNotification", null) execution.setVariable(prefix + "doInterimNotification", false) @@ -235,7 +232,7 @@ class SDNCAdapterRestV2 extends SDNCAdapterRestV1 { execution.setVariable(prefix + "doInterimNotification", true) } } - + } catch (Exception e) { callback = callback == null || String.valueOf(callback).isEmpty() ? "NONE" : callback String msg = "Received error from SDNCAdapter: " + callback @@ -243,7 +240,7 @@ class SDNCAdapterRestV2 extends SDNCAdapterRestV1 { exceptionUtil.buildWorkflowException(execution, 5300, msg) } } - + /** * Prepare to send an interim notification by extracting the variable/value definitions * in the interimNotification JSON object and placing them in the execution. These @@ -254,21 +251,21 @@ class SDNCAdapterRestV2 extends SDNCAdapterRestV1 { 'execution=' + execution.getId() + ')' msoLogger.trace('Entered ' + method) - + String prefix = execution.getVariable('prefix') msoLogger.debug("Preparing Interim Notification") try { def interimNotification = execution.getVariable(prefix + "interimNotification") msoLogger.debug("Preparing Interim Notification:\n" + JsonUtils.prettyJson(interimNotification)) - + for (int i = 0; ; i++) { def variable = JsonUtils.getJsonParamValue(interimNotification, 'variableList', 'variable', i) - + if (variable == null) { break } - + def String variableName = JsonUtils.getJsonValue(variable, "name") if ((variableName != null) && !variableName.isEmpty()) { def variableValue = JsonUtils.getJsonValue(variable, "value") @@ -276,7 +273,7 @@ class SDNCAdapterRestV2 extends SDNCAdapterRestV1 { msoLogger.debug("Setting "+ variableName + "=" + variableValue) } } - + } catch (Exception e) { String msg = "Error preparing interim notification" msoLogger.debug(getProcessKey(execution) + ': ' + msg) diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/SDNCAdapterUtils.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/SDNCAdapterUtils.groovy index 58c8f27de9..bed857dda8 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/SDNCAdapterUtils.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/SDNCAdapterUtils.groovy @@ -20,9 +20,9 @@ package org.onap.so.bpmn.common.scripts; -import org.apache.commons.lang3.* import org.camunda.bpm.engine.delegate.BpmnError import org.camunda.bpm.engine.delegate.DelegateExecution +import org.onap.aai.domain.yang.L3Network import org.onap.so.bpmn.core.WorkflowException import org.onap.so.bpmn.core.json.JsonUtils; import org.springframework.web.util.UriUtils @@ -144,7 +144,7 @@ class SDNCAdapterUtils { def prefix = execution.getVariable('prefix') def request = taskProcessor.getVariable(execution, prefix+'Request') - def requestInformation = """<request-information> + String requestInformation = """<request-information> <request-id>${MsoUtils.xmlEscape(execution.getVariable("mso-request-id"))}</request-id> <request-action>torepl</request-action> <source>${MsoUtils.xmlEscape(execution.getVariable(prefix+"source"))}</source> @@ -172,7 +172,7 @@ class SDNCAdapterUtils { //Build Service Information // Send serviceName from CANOPI to sdnc for service-type - def serviceInformation = """<service-information> + String serviceInformation = """<service-information> <service-type>${MsoUtils.xmlEscape(execution.getVariable(prefix+"serviceName"))}</service-type> <service-instance-id>${MsoUtils.xmlEscape(svcInstanceId)}</service-instance-id> <subscriber-name>${MsoUtils.xmlEscape(execution.getVariable(prefix+"subscriberName"))}</subscriber-name> @@ -495,7 +495,7 @@ class SDNCAdapterUtils { * @param additionalData additional XML content to be inserted into the * RequestData element (may be null) */ - public String sdncTopologyRequestV2 (DelegateExecution execution, String requestXML, String serviceInstanceId, String callbackUrl, String action, String requestAction, String cloudRegionId, networkId, String queryAAIResponse, String additionalData) { + public String sdncTopologyRequestV2 (DelegateExecution execution, String requestXML, String serviceInstanceId, String callbackUrl, String action, String requestAction, String cloudRegionId, networkId, L3Network queryAAIResponse, String additionalData) { def utils=new MsoUtils() // SNDC is expecting request Id for header as unique each call. @@ -526,7 +526,7 @@ class SDNCAdapterUtils { // Replace/Use the value of network-type from aai query (vs input) during Delete Network flows. if (queryAAIResponse != null) { - networkType = utils.getNodeText(queryAAIResponse, "network-type") + networkType = queryAAIResponse.getNetworkType() } String serviceId = "" @@ -536,7 +536,7 @@ class SDNCAdapterUtils { String networkName = "" // Replace/Use the value of network-name from aai query (vs input) if it was already set in AAI if (queryAAIResponse != null) { - networkName = utils.getNodeText(queryAAIResponse, "network-name") + networkName = queryAAIResponse.getNetworkName() } if (networkName.isEmpty() && utils.nodeExists(requestXML, "network-name")) { networkName = utils.getNodeText(requestXML, "network-name") diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/SniroHomingV1.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/SniroHomingV1.groovy index 8d14ead6e0..9556ae7d6a 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/SniroHomingV1.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/SniroHomingV1.groovy @@ -33,15 +33,19 @@ import org.onap.so.bpmn.core.domain.ServiceDecomposition import org.onap.so.bpmn.core.domain.Subscriber import org.onap.so.bpmn.core.domain.VnfResource import org.onap.so.bpmn.core.json.JsonUtils -import org.onap.so.rest.APIResponse -import org.onap.so.rest.RESTClient -import org.onap.so.rest.RESTConfig +import org.onap.so.client.HttpClient +import org.onap.so.client.HttpClientFactory +import org.onap.so.utils.TargetEntity import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor import org.json.JSONArray import org.json.JSONObject import static org.onap.so.bpmn.common.scripts.GenericUtils.*; + +import java.net.URL + +import javax.ws.rs.core.Response import org.onap.so.logger.MessageEnum import org.onap.so.logger.MsoLogger @@ -126,20 +130,25 @@ class SniroHomingV1 extends AbstractServiceTaskProcessor{ String endpoint = UrnPropertiesReader.getVariable("sniro.manager.uri.v1", execution) String host = UrnPropertiesReader.getVariable("sniro.manager.host", execution) - String url = host + endpoint - msoLogger.debug("Sniro Url is: " + url) + String urlString = host + endpoint + msoLogger.debug("Sniro Url is: " + urlString) + + URL url = new URL(urlString); + HttpClient httpClient = new HttpClientFactory().newJsonClient(url, TargetEntity.SNIRO) + httpClient.addAdditionalHeader("Authorization", authHeader) + Response httpResponse = httpClient.post(sniroRequest) - RESTConfig config = new RESTConfig(url); - RESTClient client = new RESTClient(config).addAuthorizationHeader(authHeader).addHeader("Content-Type", "application/json") - APIResponse response = client.httpPost(sniroRequest) + int responseCode = httpResponse.getStatus() - int responseCode = response.getStatusCode() msoLogger.debug("Sniro sync response code is: " + responseCode) - msoLogger.debug("Sniro sync response is: " + response.getResponseBodyAsString()) + if(httpResponse.hasEntity()){ + msoLogger.debug("Sniro sync response is: " + httpResponse.readEntity(String.class)) + } if(responseCode != 202){ exceptionUtil.buildAndThrowWorkflowException(execution, responseCode, "Received a Bad Sync Response from Sniro.") } + msoLogger.trace("Completed Sniro Homing Call Sniro") } }catch(BpmnError b){ diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/UpdateAAIGenericVnf.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/UpdateAAIGenericVnf.groovy index 3e7c4f2d49..f96e3bea0e 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/UpdateAAIGenericVnf.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/UpdateAAIGenericVnf.groovy @@ -22,14 +22,12 @@ package org.onap.so.bpmn.common.scripts import org.camunda.bpm.engine.delegate.BpmnError import org.camunda.bpm.engine.delegate.DelegateExecution +import org.onap.aai.domain.yang.GenericVnf import org.onap.so.bpmn.core.WorkflowException -import org.onap.so.bpmn.core.UrnPropertiesReader import org.onap.so.client.aai.AAIObjectType import org.onap.so.client.aai.entities.uri.AAIResourceUri import org.onap.so.client.aai.entities.uri.AAIUriFactory import org.onap.so.client.graphinventory.entities.uri.Depth -import org.onap.so.rest.APIResponse -import org.springframework.web.util.UriUtils import org.onap.so.logger.MessageEnum import org.onap.so.logger.MsoLogger @@ -37,7 +35,7 @@ import org.onap.so.logger.MsoLogger public class UpdateAAIGenericVnf extends AbstractServiceTaskProcessor { - private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, UpdateAAIGenericVnf.class); + private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, UpdateAAIGenericVnf.class) private XmlParser xmlParser = new XmlParser() @@ -109,9 +107,9 @@ public class UpdateAAIGenericVnf extends AbstractServiceTaskProcessor { msoLogger.trace('Exited ' + method) } catch (BpmnError e) { - throw e; + throw e } catch (Exception e) { - msoLogger.error(e); + msoLogger.error(e) exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in preProcessRequest(): ' + e.getMessage()) } } @@ -131,34 +129,26 @@ public class UpdateAAIGenericVnf extends AbstractServiceTaskProcessor { try { def vnfId = execution.getVariable('UAAIGenVnf_vnfId') - // Construct endpoint - AaiUtil aaiUriUtil = new AaiUtil(this) AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId) uri.depth(Depth.ONE) - String endPoint = aaiUriUtil.createAaiUri(uri) - try { - msoLogger.debug('sending GET to AAI endpoint \'' + endPoint + '\'') - msoLogger.debug("Sending GET to AAI endpoint: " + endPoint) - - APIResponse response = aaiUriUtil.executeAAIGetCall(execution, endPoint) - def responseData = response.getResponseBodyAsString() - execution.setVariable('UAAIGenVnf_getGenericVnfResponseCode', response.getStatusCode()) - execution.setVariable('UAAIGenVnf_getGenericVnfResponse', responseData) - msoLogger.debug("UpdateAAIGenericVnf Response data: " + responseData) - msoLogger.debug('Response code:' + response.getStatusCode()) - msoLogger.debug('Response:' + System.lineSeparator() + responseData) - } catch (Exception ex) { - msoLogger.error(e); + Optional<GenericVnf> genericVnf = getAAIClient().get(GenericVnf.class,uri) + if(genericVnf.isPresent()){ + execution.setVariable('UAAIGenVnf_getGenericVnfResponseCode', 200) + execution.setVariable('UAAIGenVnf_getGenericVnfResponse', genericVnf.get()) + }else{ + execution.setVariable('UAAIGenVnf_getGenericVnfResponseCode', 404) + execution.setVariable('UAAIGenVnf_getGenericVnfResponse', "Generic VNF not found for VNF ID: "+vnfId) + } + }catch (Exception ex) { + msoLogger.error(ex.getMessage()) msoLogger.debug('Exception occurred while executing AAI GET:' + ex.getMessage()) execution.setVariable('UAAIGenVnf_getGenericVnfResponseCode', 500) execution.setVariable('UAAIGenVnf_getGenericVnfResponse', 'AAI GET Failed:' + ex.getMessage()) } msoLogger.trace('Exited ' + method) - } catch (BpmnError e) { - throw e; } catch (Exception e) { - msoLogger.error(e); + msoLogger.error(e) exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in getGenericVnf(): ' + e.getMessage()) } } @@ -176,94 +166,61 @@ public class UpdateAAIGenericVnf extends AbstractServiceTaskProcessor { try { def vnfId = execution.getVariable('UAAIGenVnf_vnfId') - def genericVnf = execution.getVariable('UAAIGenVnf_getGenericVnfResponse') + GenericVnf genericVnf = execution.getVariable('UAAIGenVnf_getGenericVnfResponse') def origRequest = execution.getVariable('UpdateAAIGenericVnfRequest') msoLogger.debug("UpdateGenericVnf Request: " + origRequest) - // Confirm resource-version is in retrieved Generic VNF - def Node genericVnfNode = xmlParser.parseText(genericVnf) - if (utils.getChildNode(genericVnfNode, 'resource-version') == null) { - def msg = 'Can\'t update Generic VNF ' + vnfId + ' since \'resource-version\' is missing' - msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, msg, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, ""); - throw new Exception(msg) - } - // Handle persona-model-id/persona-model-version - def String newPersonaModelId = execution.getVariable('UAAIGenVnf_personaModelId') - def String newPersonaModelVersion = execution.getVariable('UAAIGenVnf_personaModelVersion') - def String personaModelVersionEntry = "" + String newPersonaModelId = execution.getVariable('UAAIGenVnf_personaModelId') + String newPersonaModelVersion = execution.getVariable('UAAIGenVnf_personaModelVersion') + String personaModelVersionEntry = null if (newPersonaModelId != null || newPersonaModelVersion != null) { - - // Confirm "new" persona-model-id is same as "current" persona-model-id - def Node currPersonaModelIdNode = utils.getChildNode(genericVnfNode, 'model-invariant-id') - if (currPersonaModelIdNode == null) { - // check the old attribute name - currPersonaModelIdNode = utils.getChildNode(genericVnfNode, 'persona-model-id') - } - def String currPersonaModelId = '' - if (currPersonaModelIdNode != null) { - currPersonaModelId = currPersonaModelIdNode.text() - } - if (!newPersonaModelId.equals(currPersonaModelId)) { + if (newPersonaModelId != genericVnf.getModelInvariantId()) { def msg = 'Can\'t update Generic VNF ' + vnfId + ' since there is \'persona-model-id\' mismatch between the current and new values' - msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, msg, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, ""); + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, msg, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "") throw new Exception(msg) } // Construct payload - personaModelVersionEntry = updateGenericVnfNode(origRequest, genericVnfNode, 'model-version-id') + personaModelVersionEntry = updateGenericVnfNode(origRequest, 'model-version-id') } // Handle ipv4-oam-address - def String ipv4OamAddress = execution.getVariable('UAAIGenVnf_ipv4OamAddress') - def String ipv4OamAddressEntry = "" + String ipv4OamAddress = execution.getVariable('UAAIGenVnf_ipv4OamAddress') + String ipv4OamAddressEntry = null if (ipv4OamAddress != null) { // Construct payload - ipv4OamAddressEntry = updateGenericVnfNode(origRequest, genericVnfNode, 'ipv4-oam-address') + ipv4OamAddressEntry = updateGenericVnfNode(origRequest, 'ipv4-oam-address') } // Handle management-v6-address - def String managementV6Address = execution.getVariable('UAAIGenVnf_managementV6Address') - def String managementV6AddressEntry = "" + String managementV6Address = execution.getVariable('UAAIGenVnf_managementV6Address') + String managementV6AddressEntry = null if (managementV6Address != null) { // Construct payload - managementV6AddressEntry = updateGenericVnfNode(origRequest, genericVnfNode, 'management-v6-address') + managementV6AddressEntry = updateGenericVnfNode(origRequest, 'management-v6-address') } // Handle orchestration-status - def String orchestrationStatus = execution.getVariable('UAAIGenVnf_orchestrationStatus') - def String orchestrationStatusEntry = "" + String orchestrationStatus = execution.getVariable('UAAIGenVnf_orchestrationStatus') + String orchestrationStatusEntry = null if (orchestrationStatus != null) { // Construct payload - orchestrationStatusEntry = updateGenericVnfNode(origRequest, genericVnfNode, 'orchestration-status') + orchestrationStatusEntry = updateGenericVnfNode(origRequest, 'orchestration-status') } - - def payload = """ - { ${personaModelVersionEntry} - ${ipv4OamAddressEntry} - ${managementV6AddressEntry} - ${orchestrationStatusEntry} - "vnf-id": "${vnfId}" - } - """ - - // Construct endpoint - AaiUtil aaiUriUtil = new AaiUtil(this) + + org.onap.aai.domain.yang.GenericVnf payload = new org.onap.aai.domain.yang.GenericVnf(); + payload.setVnfId(vnfId) + payload.setPersonaModelVersion(personaModelVersionEntry) + payload.setIpv4OamAddress(ipv4OamAddressEntry) + payload.setManagementV6Address(managementV6AddressEntry) + payload.setOrchestrationStatus(orchestrationStatusEntry) + AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId) - String endPoint = aaiUriUtil.createAaiUri(uri) try { - msoLogger.debug('sending PATCH to AAI endpoint \'' + endPoint + '\'' + 'with payload \n' + payload) - msoLogger.debug("Sending PATCH to AAI endpoint: " + endPoint) - - APIResponse response = aaiUriUtil.executeAAIPatchCall(execution, endPoint, payload) - def responseData = response.getResponseBodyAsString() - execution.setVariable('UAAIGenVnf_updateGenericVnfResponseCode', response.getStatusCode()) - execution.setVariable('UAAIGenVnf_updateGenericVnfResponse', responseData) - msoLogger.debug("UpdateAAIGenericVnf Response Data: " + responseData) - msoLogger.debug('Response code:' + response.getStatusCode()) - msoLogger.debug('Response:' + System.lineSeparator() + responseData) + getAAIClient().update(uri,payload) } catch (Exception ex) { ex.printStackTrace() msoLogger.debug('Exception occurred while executing AAI PATCH:' + ex.getMessage()) @@ -271,10 +228,8 @@ public class UpdateAAIGenericVnf extends AbstractServiceTaskProcessor { execution.setVariable('UAAIGenVnf_updateGenericVnfResponse', 'AAI PATCH Failed:' + ex.getMessage()) } msoLogger.trace('Exited ' + method) - } catch (BpmnError e) { - throw e; } catch (Exception e) { - msoLogger.error(e); + msoLogger.error(e) exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in updateGenericVnf(): ' + e.getMessage()) } } @@ -286,19 +241,19 @@ public class UpdateAAIGenericVnf extends AbstractServiceTaskProcessor { * @param genericVnf Current Generic VNF retrieved from AAI. * @param element Name of element to be inserted. */ - public String updateGenericVnfNode(String origRequest, Node genericVnfNode, String elementName) { + public String updateGenericVnfNode(String origRequest, String elementName) { if (!utils.nodeExists(origRequest, elementName)) { - return "" + return null } def elementValue = utils.getNodeText(origRequest, elementName) - if (elementValue.equals('DELETE')) { - // Set the element being deleted to null - return """"${elementName}": null,""" + if (elementValue == 'DELETE') { + // Set the element being deleted to empty string + return "" } else { - return """"${elementName}": "${elementValue}",""" + return elementValue } } @@ -314,8 +269,8 @@ public class UpdateAAIGenericVnf extends AbstractServiceTaskProcessor { ')' msoLogger.trace('Entered ' + method) - msoLogger.error( 'Error occurred attempting to query AAI, Response Code ' + execution.getVariable('UAAIGenVnf_getGenericVnfResponseCode')); - String processKey = getProcessKey(execution); + msoLogger.error( 'Error occurred attempting to query AAI, Response Code ' + execution.getVariable('UAAIGenVnf_getGenericVnfResponseCode')) + String processKey = getProcessKey(execution) WorkflowException exception = new WorkflowException(processKey, 5000, execution.getVariable('UAAIGenVnf_getGenericVnfResponse')) execution.setVariable('WorkflowException', exception) @@ -335,9 +290,9 @@ public class UpdateAAIGenericVnf extends AbstractServiceTaskProcessor { ')' msoLogger.trace('Entered ' + method) - msoLogger.error('Error occurred attempting to update Generic VNF in AAI, Response Code ' + execution.getVariable('UAAIGenVnf_updateGenericVnfResponseCode')); + msoLogger.error('Error occurred attempting to update Generic VNF in AAI, Response Code ' + execution.getVariable('UAAIGenVnf_updateGenericVnfResponseCode')) - String processKey = getProcessKey(execution); + String processKey = getProcessKey(execution) WorkflowException exception = new WorkflowException(processKey, 5000, execution.getVariable('UAAIGenVnf_updateGenericVnfResponse')) execution.setVariable('WorkflowException', exception) @@ -345,4 +300,4 @@ public class UpdateAAIGenericVnf extends AbstractServiceTaskProcessor { msoLogger.debug("Workflow Exception occurred when Updating GenericVnf: " + exception.getErrorMessage()) msoLogger.trace('Exited ' + method) } -}
\ No newline at end of file +} diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/UpdateAAIVfModule.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/UpdateAAIVfModule.groovy index c455ae90ce..3c4edd21ca 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/UpdateAAIVfModule.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/UpdateAAIVfModule.groovy @@ -20,21 +20,17 @@ package org.onap.so.bpmn.common.scripts +import javax.ws.rs.NotFoundException + import org.camunda.bpm.engine.delegate.BpmnError import org.camunda.bpm.engine.delegate.DelegateExecution import org.onap.so.bpmn.core.WorkflowException -import org.onap.so.bpmn.core.UrnPropertiesReader import org.onap.so.client.aai.AAIObjectType import org.onap.so.client.aai.entities.uri.AAIResourceUri import org.onap.so.client.aai.entities.uri.AAIUriFactory -import org.onap.so.rest.APIResponse -import org.springframework.web.util.UriUtils -import org.onap.so.logger.MessageEnum import org.onap.so.logger.MsoLogger - - public class UpdateAAIVfModule extends AbstractServiceTaskProcessor { private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, UpdateAAIVfModule.class); @@ -106,29 +102,21 @@ public class UpdateAAIVfModule extends AbstractServiceTaskProcessor { try { def vnfId = execution.getVariable('UAAIVfMod_vnfId') def vfModuleId = execution.getVariable('UAAIVfMod_vfModuleId') - - AaiUtil aaiUriUtil = new AaiUtil(this) - AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.VF_MODULE, vnfId, vfModuleId) - String endPoint = aaiUriUtil.createAaiUri(uri) - try { - msoLogger.debug('sending GET to AAI endpoint \'' + endPoint + '\'') - msoLogger.debug("UpdateAAIVfModule sending GET to AAI endpoint: " + endPoint) - - APIResponse response = aaiUriUtil.executeAAIGetCall(execution, endPoint) - def responseData = response.getResponseBodyAsString() - execution.setVariable('UAAIVfMod_getVfModuleResponseCode', response.getStatusCode()) - execution.setVariable('UAAIVfMod_getVfModuleResponse', responseData) - msoLogger.debug('Response code:' + response.getStatusCode()) - msoLogger.debug('Response:' + System.lineSeparator() + responseData) - msoLogger.debug("UpdateAAIVfModule response data: " + responseData) + AAIResourceUri resourceUri = AAIUriFactory.createResourceUri(AAIObjectType.VF_MODULE, vnfId, vfModuleId); + Optional<org.onap.aai.domain.yang.VfModule> vfModule = getAAIClient().get(org.onap.aai.domain.yang.VfModule.class, resourceUri) + if (vfModule.isPresent()) { + execution.setVariable('UAAIVfMod_getVfModuleResponseCode', 200) + execution.setVariable('UAAIVfMod_getVfModuleResponse', vfModule.get()) + } else { + execution.setVariable('UAAIVfMod_getVfModuleResponseCode', 404) + execution.setVariable('UAAIVfMod_getVfModuleResponse', "VF Module not found in AAI") + } } catch (Exception ex) { - ex.printStackTrace() msoLogger.debug('Exception occurred while executing AAI GET:' + ex.getMessage()) execution.setVariable('UAAIVfMod_getVfModuleResponseCode', 500) execution.setVariable('UAAIVfMod_getVfModuleResponse', 'AAI GET Failed:' + ex.getMessage()) } - msoLogger.trace('Exited ' + method) } catch (BpmnError e) { throw e; } catch (Exception e) { @@ -151,18 +139,10 @@ public class UpdateAAIVfModule extends AbstractServiceTaskProcessor { try { def vnfId = execution.getVariable('UAAIVfMod_vnfId') def vfModuleId = execution.getVariable('UAAIVfMod_vfModuleId') - def vfModule = execution.getVariable('UAAIVfMod_getVfModuleResponse') + org.onap.aai.domain.yang.VfModule vfModule = execution.getVariable('UAAIVfMod_getVfModuleResponse') def origRequest = execution.getVariable('UpdateAAIVfModuleRequest') - def Node vfModuleNode = xmlParser.parseText(vfModule) - + msoLogger.debug("UpdateAAIVfModule request: " + origRequest) - // Confirm resource-version is in retrieved VF Module - if (utils.getChildNode(vfModuleNode, 'resource-version') == null) { - def msg = 'Can\'t update VF Module ' + vfModuleId + ' since \'resource-version\' is missing' - msoLogger.error(msg); - throw new Exception(msg) - } - // Handle persona-model-id/persona-model-version def boolean doPersonaModelVersion = true def String newPersonaModelId = utils.getNodeText(origRequest, 'persona-model-id') @@ -171,10 +151,10 @@ public class UpdateAAIVfModule extends AbstractServiceTaskProcessor { doPersonaModelVersion = false } else { // Confirm "new" persona-model-id is same as "current" persona-model-id - def String currPersonaModelId = utils.getChildNodeText(vfModuleNode, 'model-invariant-id') + def String currPersonaModelId = vfModule.getModelInvariantId() if (currPersonaModelId == null) { // check the old attribute name - currPersonaModelId = utils.getChildNodeText(vfModuleNode, 'model-version-id') + currPersonaModelId = vfModule.getModelVersionId() } if (currPersonaModelId == null) { currPersonaModelId = '' @@ -187,44 +167,36 @@ public class UpdateAAIVfModule extends AbstractServiceTaskProcessor { } // Construct payload - String orchestrationStatusEntry = updateVfModuleNode(origRequest, vfModuleNode, 'orchestration-status') - String heatStackIdEntry = updateVfModuleNode(origRequest, vfModuleNode, 'heat-stack-id') + String orchestrationStatusEntry = updateVfModuleNode(origRequest , 'orchestration-status') + String heatStackIdEntry = updateVfModuleNode(origRequest, 'heat-stack-id') String personaModelVersionEntry = "" if (doPersonaModelVersion) { - personaModelVersionEntry = updateVfModuleNode(origRequest, vfModuleNode, 'persona-model-version') + personaModelVersionEntry = updateVfModuleNode(origRequest, 'persona-model-version') } - String contrailServiceInstanceFqdnEntry = updateVfModuleNode(origRequest, vfModuleNode, 'contrail-service-instance-fqdn') - def payload = """ - { ${orchestrationStatusEntry} - ${heatStackIdEntry} - ${personaModelVersionEntry} - ${contrailServiceInstanceFqdnEntry} - "vf-module-id": "${vfModuleId}" - } - """ - - AaiUtil aaiUriUtil = new AaiUtil(this) - AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.VF_MODULE, vnfId, vfModuleId) - String endPoint = aaiUriUtil.createAaiUri(uri) - - try { - msoLogger.debug('sending PATCH to AAI endpoint \'' + endPoint + '\'' + 'with payload \n' + payload) - msoLogger.debug("Sending PATCH to AAI endpoint: " + endPoint) - - APIResponse response = aaiUriUtil.executeAAIPatchCall(execution, endPoint, payload) - def responseData = response.getResponseBodyAsString() - execution.setVariable('UAAIVfMod_updateVfModuleResponseCode', response.getStatusCode()) - execution.setVariable('UAAIVfMod_updateVfModuleResponse', responseData) - msoLogger.debug("UpdateAAIVfModule Response data: " + responseData) - msoLogger.debug('Response code:' + response.getStatusCode()) - msoLogger.debug('Response:' + System.lineSeparator() + responseData) - } catch (Exception ex) { - ex.printStackTrace() - msoLogger.debug('Exception occurred while executing AAI PATCH:' + ex.getMessage()) + String contrailServiceInstanceFqdnEntry = updateVfModuleNode(origRequest, 'contrail-service-instance-fqdn') + org.onap.aai.domain.yang.VfModule payload = new org.onap.aai.domain.yang.VfModule(); + payload.setVfModuleId(vfModuleId) + payload.setOrchestrationStatus(orchestrationStatusEntry) + payload.setHeatStackId(heatStackIdEntry) + payload.setPersonaModelVersion(personaModelVersionEntry) + payload.setContrailServiceInstanceFqdn(contrailServiceInstanceFqdnEntry) + + try { + AAIResourceUri resourceUri = AAIUriFactory.createResourceUri(AAIObjectType.VF_MODULE, vnfId, vfModuleId) + getAAIClient().update(resourceUri, payload) + execution.setVariable('UAAIVfMod_updateVfModuleResponseCode', 200) + execution.setVariable('UAAIVfMod_updateVfModuleResponse', "Success") + }catch(NotFoundException ignored){ + msoLogger.debug("VF-Module not found!!") + execution.setVariable('UAAIVfMod_updateVfModuleResponseCode', 404) + execution.setVariable('UAAIVfMod_updateVfModuleResponse', ignored.getMessage()) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "vf-module " + vfModuleId + " not found for under vnf " + vnfId + " in A&AI!") + } + catch(Exception ex){ execution.setVariable('UAAIVfMod_updateVfModuleResponseCode', 500) execution.setVariable('UAAIVfMod_updateVfModuleResponse', 'AAI PATCH Failed:' + ex.getMessage()) - } - msoLogger.trace('Exited ' + method) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, 'Exception occurred while executing AAI PATCH:' + ex.getMessage()) + } } catch (BpmnError e) { throw e; } catch (Exception e) { @@ -237,93 +209,24 @@ public class UpdateAAIVfModule extends AbstractServiceTaskProcessor { * Sets up json attributes for PATCH request for Update * * @param origRequest Incoming update request with VF Module elements to be updated. - * @param vfModule Current VF Module retrieved from AAI. * @param element Name of element to be inserted. */ - private String updateVfModuleNode(String origRequest, Node vfModuleNode, String elementName) { + private String updateVfModuleNode(String origRequest, String elementName) { if (!utils.nodeExists(origRequest, elementName)) { - return "" + return null } def elementValue = utils.getNodeText(origRequest, elementName) if (elementValue.equals('DELETE')) { - // Set the element being deleted to null - return """"${elementName}": null,""" + // Set the element being deleted to empty string + return "" } else { - return """"${elementName}": "${elementValue}",""" + return elementValue } } - - /** - * Check the Volume Group ID from the incoming update request against the Volume Group ID from the - * given VF Module. If they are equal or if they are both 'null', then that is acceptable and 'null' - * is returned. Otherwise a message describing how the values are unacceptable/incompatible is returned. - * - * @param origRequest Incoming update request with VF Module elements to be updated. - * @param vfModuleNode VF Module (as a Node) retrieved from AAI. - * @param isDebugLogEnabled Is DEBUG log enabled? - * @return 'null' if the Volume Group IDs are acceptable. Otherwise return a message describing how the - * values are unacceptable/incompatible. - */ - private String checkVolumeGroupId(String origRequest, Node vfModuleNode, String isDebugLogEnabled) { - def requestVolumeGroupId = utils.getNodeText(origRequest, 'volume-group-id') - def currVolumeGroupId = getCurrVolumeGroupId(vfModuleNode) - - msoLogger.debug('Check volume-group-id: volume-group-id in original request is \'' + requestVolumeGroupId + '\', volume-group-id from VF Module is \'' + currVolumeGroupId + '\'') - - def result = null - - if (requestVolumeGroupId == null) { - if (currVolumeGroupId == null) { - // This is OK - } else { - result = 'Cannot detach a volume group from an existing VF Module' - } - } else { - if (currVolumeGroupId == null) { - result = 'Cannot add a volume gruop to an existing VF Module' - } else { - if (!requestVolumeGroupId.equals(currVolumeGroupId)) { - result = 'Cannot change the volume group on an existing VF Module' - } - } - } - - return result - } - - /** - * Find and return the value of the Volume Group ID for the specified VF Module. If - * the value of the Volume Group ID cannot be found for any reason, 'null' is returned. - * - * @param vfModuleNode VF Module (as a Node) retrieved from AAI. - * @return the value of the Volume Group ID for the specified VF Module. If the - * value of the Volume Group ID cannot be found for any reason, 'null' is returned. - */ - private String getCurrVolumeGroupId(Node vfModuleNode) { - def Node relationshipList = utils.getChildNode(vfModuleNode, 'relationship-list') - if (relationshipList == null) { - return null - } - def NodeList relationships = utils.getIdenticalChildren(relationshipList, 'relationship') - for (Node relationshipNode in relationships) { - def String relatedTo = utils.getChildNodeText(relationshipNode, 'related-to') - if ((relatedTo != null) && relatedTo.equals('volume-group')) { - def NodeList relationshipDataList = utils.getIdenticalChildren(relationshipNode, 'relationship-data') - for (Node relationshipDataNode in relationshipDataList) { - def String relationshipKey = utils.getChildNodeText(relationshipDataNode, 'relationship-key') - if ((relationshipKey != null) && relationshipKey.equals('volume-group.volume-group-id')) { - return utils.getChildNodeText(relationshipDataNode, 'relationship-value') - } - } - } - } - return null - } - /** * Generates a WorkflowException if the AAI query returns a response code other than 200. * @@ -343,25 +246,4 @@ public class UpdateAAIVfModule extends AbstractServiceTaskProcessor { msoLogger.debug("UpdateAAIVfModule query failure: " + exception.getErrorMessage()) msoLogger.trace('Exited ' + method) } - - /** - * Generates a WorkflowException if updating a VF Module in AAI returns a response code other than 200. - * - * @param execution The flow's execution instance. - */ - public void handleUpdateVfModuleFailure(DelegateExecution execution) { - def method = getClass().getSimpleName() + '.handleUpdateVfModuleFailure(' + - 'execution=' + execution.getId() + - ')' - msoLogger.trace('Entered ' + method) - - msoLogger.error('Error occurred attempting to update VF Module in AAI, Response Code ' + execution.getVariable('UAAIVfMod_updateVfModuleResponseCode')); - String processKey = getProcessKey(execution); - WorkflowException exception = new WorkflowException(processKey, 5000, - execution.getVariable('UAAIVfMod_updateVfModuleResponse')) - execution.setVariable('WorkflowException', exception) - - msoLogger.debug("UpdateAAIVfModule failure: " + exception.getErrorMessage()) - msoLogger.trace('Exited ' + method) - } } diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/VfModuleBase.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/VfModuleBase.groovy index fec140da33..c1cd42e893 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/VfModuleBase.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/VfModuleBase.groovy @@ -20,16 +20,9 @@ package org.onap.so.bpmn.common.scripts; -import java.io.ObjectInputStream.BlockDataInputStream - -import java.io.ObjectInputStream.BlockDataInputStream - -//import groovy.util.Node; - import javax.xml.parsers.DocumentBuilder import javax.xml.parsers.DocumentBuilderFactory -import org.apache.commons.lang3.* import org.w3c.dom.Document import org.w3c.dom.Element import org.w3c.dom.Node @@ -38,9 +31,6 @@ import org.xml.sax.InputSource import org.onap.so.logger.MessageEnum import org.onap.so.logger.MsoLogger - - - public abstract class VfModuleBase extends AbstractServiceTaskProcessor { private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, VfModuleBase.class); @@ -195,39 +185,7 @@ public abstract class VfModuleBase extends AbstractServiceTaskProcessor { } return entries } - - /** - * 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. - */ - protected String getTenantIdFromVolumeGroup(String volumeGroupXml) { - def groovy.util.Node volumeGroupNode = xmlParser.parseText(volumeGroupXml) - def groovy.util.Node relationshipList = utils.getChildNode(volumeGroupNode, 'relationship-list') - if (relationshipList != null) { - def groovy.util.NodeList relationships = utils.getIdenticalChildren(relationshipList, 'relationship') - for (groovy.util.Node relationship in relationships) { - def groovy.util.Node relatedTo = utils.getChildNode(relationship, 'related-to') - if ((relatedTo != null) && (relatedTo.text().equals('tenant'))) { - def groovy.util.NodeList relationshipDataList = utils.getIdenticalChildren(relationship, 'relationship-data') - for (groovy.util.Node relationshipData in relationshipDataList) { - def groovy.util.Node relationshipKey = utils.getChildNode(relationshipData, 'relationship-key') - if ((relationshipKey != null) && (relationshipKey.text().equals('tenant.tenant-id'))) { - def groovy.util.Node relationshipValue = utils.getChildNode(relationshipData, 'relationship-value') - if (relationshipValue != null) { - return relationshipValue.text() - } - } - } - } - } - } - return null - } - - + /* * Parses VNF parameters passed in on the incoming requests and SDNC parameters returned from SDNC get response * and puts them into the format expected by VNF adapter. diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/VidUtils.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/VidUtils.groovy index 6e09837274..40b0368eaa 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/VidUtils.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/VidUtils.groovy @@ -116,7 +116,7 @@ class VidUtils { } def modelCustomizationId = requestMap.requestDetails?.modelInfo?.modelCustomizationUuid ?: '' - def xmlReq = """ + String xmlReq = """ <volume-request xmlns="http://www.w3.org/2001/XMLSchema"> <request-info> <action>${MsoUtils.xmlEscape(action)}</action> @@ -251,7 +251,7 @@ class VidUtils { //'sdncVersion' = current, '1610' (non-RPC SDNC) or '1702' (RPC SDNC) def sdncVersion = execution.getVariable("sdncVersion") - def xmlReq = """ + String xmlReq = """ <network-request xmlns="http://www.w3.org/2001/XMLSchema"> <request-info> <request-id>${MsoUtils.xmlEscape(requestId)}</request-id> @@ -393,7 +393,7 @@ class VidUtils { userParamsNode = buildUserParams(userParams) } - def xmlReq = """ + String xmlReq = """ <network-request xmlns="http://www.w3.org/2001/XMLSchema"> <request-info> <request-id>${MsoUtils.xmlEscape(requestId)}</request-id> @@ -512,7 +512,7 @@ class VidUtils { def personaModelVersion = requestMap.requestDetails?.modelInfo?.modelUuid ?: '' def modelCustomizationId = requestMap.requestDetails?.modelInfo?.modelCustomizationUuid ?: '' - def xmlReq = """ + String xmlReq = """ <vnf-request> <request-info> <request-id>${MsoUtils.xmlEscape(requestId)}</request-id> diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/VnfAdapterRestV1.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/VnfAdapterRestV1.groovy index 52f45c205c..78af8768f9 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/VnfAdapterRestV1.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/VnfAdapterRestV1.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,15 +20,19 @@ package org.onap.so.bpmn.common.scripts +import org.onap.so.client.HttpClientFactory + +import javax.ws.rs.core.Response import org.apache.commons.lang3.* import org.camunda.bpm.engine.delegate.BpmnError import org.camunda.bpm.engine.delegate.DelegateExecution import org.onap.so.bpmn.core.UrnPropertiesReader -import org.onap.so.rest.APIResponse -import org.onap.so.rest.RESTClient -import org.onap.so.rest.RESTConfig +import org.onap.so.client.HttpClient import org.onap.so.logger.MessageEnum import org.onap.so.logger.MsoLogger +import org.onap.so.utils.TargetEntity +import java.util.UUID + @@ -67,7 +71,7 @@ class VnfAdapterRestV1 extends AbstractServiceTaskProcessor { if ('rollbackVolumeGroupRequest'.equals(requestType)) { messageId = getMessageIdForVolumeGroupRollback(root) } - + if (messageId == null || messageId.isEmpty()) { String msg = getProcessKey(execution) + ': no messageId in ' + requestType msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, msg, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, ""); @@ -281,7 +285,7 @@ class VnfAdapterRestV1 extends AbstractServiceTaskProcessor { exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg) } } - + public String getVolumeGroupIdFromRollbackRequest(Node root) { return root.'volumeGroupRollback'.'volumeGroupId'.text() } @@ -289,7 +293,7 @@ class VnfAdapterRestV1 extends AbstractServiceTaskProcessor { public String getMessageIdForVolumeGroupRollback(Node root) { return root.'volumeGroupRollback'.'messageId'.text() } - + /** * This method is used instead of an HTTP Connector task because the * connector does not allow DELETE with a body. @@ -307,29 +311,34 @@ class VnfAdapterRestV1 extends AbstractServiceTaskProcessor { String vnfAdapterUrl = execution.getVariable(prefix + 'vnfAdapterUrl') String vnfAdapterRequest = execution.getVariable(prefix + 'vnfAdapterRequest') - RESTConfig config = new RESTConfig(vnfAdapterUrl) - RESTClient client = new RESTClient(config). - addHeader("Content-Type", "application/xml"). - addAuthorizationHeader(execution.getVariable(prefix + "basicAuthHeaderValue")); + URL url = new URL(vnfAdapterUrl); - APIResponse response; + HttpClient httpClient = new HttpClientFactory().newXmlClient(url, TargetEntity.VNF_ADAPTER) + httpClient.addAdditionalHeader("Authorization", execution.getVariable(prefix + "basicAuthHeaderValue")) + + httpClient.addAdditionalHeader("X-ONAP-RequestID", execution.getVariable("mso-request-id")) + httpClient.addAdditionalHeader("X-ONAP-InvocationID", UUID.randomUUID().toString()) + httpClient.addAdditionalHeader("X-ONAP-PartnerName", "SO-VNFAdapter") + Response response; if ("GET".equals(vnfAdapterMethod)) { - response = client.httpGet() + response = httpClient.get() } else if ("PUT".equals(vnfAdapterMethod)) { - response = client.httpPut(vnfAdapterRequest) + response = httpClient.put(vnfAdapterRequest) } else if ("POST".equals(vnfAdapterMethod)) { - response = client.httpPost(vnfAdapterRequest) + response = httpClient.post(vnfAdapterRequest) } else if ("DELETE".equals(vnfAdapterMethod)) { - response = client.httpDelete(vnfAdapterRequest) + response = httpClient.delete(vnfAdapterRequest) } else { String msg = 'Unsupported HTTP method "' + vnfAdapterMethod + '" in ' + method + ": " + e msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, msg, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, ""); exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg) } - execution.setVariable(prefix + "vnfAdapterStatusCode", response.getStatusCode()) - execution.setVariable(prefix + "vnfAdapterResponse", response.getResponseBodyAsString()) + execution.setVariable(prefix + "vnfAdapterStatusCode", response.getStatus()) + if(response.hasEntity()){ + execution.setVariable(prefix + "vnfAdapterResponse", response.readEntity(String.class)) + } } catch (BpmnError e) { throw e } catch (Exception e) { @@ -356,16 +365,15 @@ class VnfAdapterRestV1 extends AbstractServiceTaskProcessor { // TODO: Should deprecate use of processKey+Response variable for the response. Will use "WorkflowResponse" instead. execution.setVariable("WorkflowResponse", callback) + callback = utils.removeXmlPreamble(callback) + Node root = new XmlParser().parseText(callback) if (root.name().endsWith('Exception')) { vnfAdapterWorkflowException(execution, callback) } } catch (Exception e) { - e.printStackTrace() - callback = callback == null || String.valueOf(callback).isEmpty() ? "NONE" : callback - String msg = "Received error from VnfAdapter: " + callback - msoLogger.debug(getProcessKey(execution) + ': ' + msg) - exceptionUtil.buildWorkflowException(execution, 7020, msg) + msoLogger.debug("Error encountered within VnfAdapterRest ProcessCallback method", e) + exceptionUtil.buildAndThrowWorkflowException(execution, 7020, "Error encountered within VnfAdapterRest ProcessCallback method") } } |