diff options
Diffstat (limited to 'bpmn/MSOCommonBPMN')
16 files changed, 321 insertions, 549 deletions
diff --git a/bpmn/MSOCommonBPMN/pom.xml b/bpmn/MSOCommonBPMN/pom.xml index c85bcd7522..934aea8241 100644 --- a/bpmn/MSOCommonBPMN/pom.xml +++ b/bpmn/MSOCommonBPMN/pom.xml @@ -397,5 +397,11 @@ <version>1.2.4.RELEASE</version> <scope>test</scope> </dependency> + <dependency> + <groupId>org.assertj</groupId> + <artifactId>assertj-core</artifactId> + <version>3.11.1</version> + <scope>test</scope> + </dependency> </dependencies> </project> 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/java/org/onap/so/client/restproperties/AaiPropertiesConfiguration.java b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/ConfirmVolumeGroupNameFactory.groovy index b7582922b1..f032d640d5 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/restproperties/AaiPropertiesConfiguration.java +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/ConfirmVolumeGroupNameFactory.groovy @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP - SO * ================================================================================ - * Copyright (C) 2017 - 2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2018 Nokia. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -18,25 +18,14 @@ * ============LICENSE_END========================================================= */ -package org.onap.so.client.restproperties; +package org.onap.so.bpmn.common.scripts -import org.springframework.beans.factory.annotation.Value; -import org.springframework.stereotype.Service; +import org.onap.so.bpmn.common.scripts.ConfirmVolumeGroupName +import org.onap.so.bpmn.common.scripts.ExceptionUtil -@Service -public class AaiPropertiesConfiguration { +public class ConfirmVolumeGroupNameFactory { - @Value("${aai.endpoint}") - private String endpoint; - - @Value("${aai.auth}") - private String auth; - - public String getEndpoint() { - return endpoint; - } - - public String getAuth() { - return auth; - } + ConfirmVolumeGroupName create() { + return new ConfirmVolumeGroupName(new ExceptionUtil()); + } } 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/NetworkUtils.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/NetworkUtils.groovy index 41db603cdf..c1199aefd7 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 @@ -22,7 +22,9 @@ package org.onap.so.bpmn.common.scripts 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 @@ -304,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> @@ -369,172 +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 - - - } - - /** - * 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 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 = "" @@ -633,57 +443,6 @@ class NetworkUtils { 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 - } - // build subnet sub-network single elements def buildSubNetworkElements(Subnet subnet, elementList, parentName) { @@ -757,168 +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>" + 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>" } } - 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 + return buildHostRoutes } - /* 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. 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 8f0e481c9a..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 @@ -223,7 +223,7 @@ public class PrepareUpdateAAIVfModule extends VfModuleBase { AAIResourcesClient client = new AAIResourcesClient() AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.VF_MODULE, vnfId, vfModuleId) 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) @@ -238,9 +238,11 @@ public class PrepareUpdateAAIVfModule extends VfModuleBase { 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 a5e7c0fd06..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 @@ -58,11 +58,10 @@ public class SDNCAdapter extends AbstractServiceTaskProcessor { execution.setVariable("SDNCA_InterimNotify", false) String requestId = execution.getVariable("mso-request-id") - if(isNotBlank(requestId)){ - execution.setVariable(Prefix + "requestId", requestId) - }else{ + 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) @@ -124,6 +123,7 @@ public class SDNCAdapter extends AbstractServiceTaskProcessor { //calling process should pass a generated uuid if sending multiple sdnc requests def sdncRequestId = utils.getNodeText(requestHeader, "RequestId") + execution.setVariable(Prefix + "requestId", sdncRequestId) // Prepare SDNC Request to the SDNC Adapter String sdncAdapterRequest = """ 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 a6568fb80a..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 @@ -184,11 +184,17 @@ public class UpdateAAIVfModule extends AbstractServiceTaskProcessor { 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()) exceptionUtil.buildAndThrowWorkflowException(execution, 2500, 'Exception occurred while executing AAI PATCH:' + ex.getMessage()) } } catch (BpmnError e) { diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/resource/ResourceRequestBuilder.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/resource/ResourceRequestBuilder.java index 1531e4d7b3..7df9c7bf82 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/resource/ResourceRequestBuilder.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/resource/ResourceRequestBuilder.java @@ -262,6 +262,9 @@ public class ResourceRequestBuilder { String catalogEndPoint = UrnPropertiesReader.getVariable("mso.catalog.db.endpoint"); HttpClient client = new HttpClient(UriBuilder.fromUri(catalogEndPoint).path(SERVICE_URL_TOSCA_CSAR).queryParam("serviceModelUuid", uuid).build().toURL(), "application/json", TargetEntity.CATALOG_DB); + client.addAdditionalHeader("Accept", "application/json"); +// client.addBasicAuthHeader (UrnPropertiesReader.getVariable("mso.adapters.db.auth"), UrnPropertiesReader.getVariable("mso.msoKey")); + client.addAdditionalHeader("Authorization", UrnPropertiesReader.getVariable("mso.db.auth")); Response response = client.get(); String value = response.readEntity(String.class); @@ -272,7 +275,7 @@ public class ResourceRequestBuilder { File csarFile = new File(filePath); if(!csarFile.exists()) { - throw new Exception("csar file does not exist."); + throw new Exception("csar file does not exist in filePath:" + csarFile.getAbsolutePath()); } return csarFile.getAbsolutePath(); @@ -284,7 +287,7 @@ public class ResourceRequestBuilder { try { return mapper.readValue(jsonstr, type); } catch(IOException e) { - LOGGER.error(MessageEnum.RA_NS_EXC, "", "", MsoLogger.ErrorCode.BusinessProcesssError, "fail to unMarshal json", e); + LOGGER.error("fail to unMarshal json" + e.getMessage ()); } return null; } diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/BBInputSetup.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/BBInputSetup.java index 985b53d0ce..63f832d706 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/BBInputSetup.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/BBInputSetup.java @@ -609,16 +609,27 @@ public class BBInputSetup implements JavaDelegate { vnf = createGenericVnf(lookupKeyMap, instanceName, platform, lineOfBusiness, resourceId, generatedVnfType, instanceParams); serviceInstance.getVnfs().add(vnf); + mapVnfcCollectionInstanceGroup(vnf, modelInfo, service); } if(vnf != null) { mapCatalogVnf(vnf, modelInfo, service); - mapVnfcCollectionInstanceGroup(vnf, modelInfo, service); - if (instanceGroupId != null && instanceGroupModelInfo != null) { + if (instanceGroupId != null && instanceGroupModelInfo != null + && instanceGroupModelInfo.getModelType().equals(ModelType.networkInstanceGroup) + && !instanceGroupInList(vnf, instanceGroupId)) { mapNetworkCollectionInstanceGroup(vnf, instanceGroupId); } } } + protected boolean instanceGroupInList(GenericVnf vnf, String instanceGroupId) { + for(InstanceGroup instanceGroup : vnf.getInstanceGroups()) { + if(instanceGroup.getId() != null && instanceGroup.getId().equalsIgnoreCase(instanceGroupId)) { + return true; + } + } + return false; + } + protected void mapVnfcCollectionInstanceGroup(GenericVnf genericVnf, ModelInfo modelInfo, Service service) { VnfResourceCustomization vnfResourceCustomization = getVnfResourceCustomizationFromService(modelInfo, service); if(vnfResourceCustomization != null) { @@ -865,8 +876,13 @@ public class BBInputSetup implements JavaDelegate { String serviceInstanceId, boolean aLaCarte, String bbName) throws Exception { ServiceInstance serviceInstance = this.getServiceInstanceHelper(requestDetails, customer, project, owningEntity, lookupKeyMap, serviceInstanceId, aLaCarte, service, bbName); - org.onap.aai.domain.yang.ServiceInstance serviceInstanceAAI = this.bbInputSetupUtils - .getAAIServiceInstanceById(serviceInstanceId); + org.onap.aai.domain.yang.ServiceInstance serviceInstanceAAI = null; + if(customer != null && customer.getServiceSubscription() != null) { + serviceInstanceAAI = bbInputSetupUtils.getAAIServiceInstanceByIdAndCustomer(customer.getGlobalCustomerId(), + customer.getServiceSubscription().getServiceType(), serviceInstanceId); + } else { + serviceInstanceAAI = bbInputSetupUtils.getAAIServiceInstanceById(serviceInstanceId); + } if (serviceInstanceAAI != null && !serviceInstanceAAI.getModelVersionId().equalsIgnoreCase(service.getModelUUID())) { Service tempService = this.bbInputSetupUtils diff --git a/bpmn/MSOCommonBPMN/src/main/resources/subprocess/ConfirmVolumeGroupName.bpmn b/bpmn/MSOCommonBPMN/src/main/resources/subprocess/ConfirmVolumeGroupName.bpmn index 0e99ce9683..403be98c8e 100644 --- a/bpmn/MSOCommonBPMN/src/main/resources/subprocess/ConfirmVolumeGroupName.bpmn +++ b/bpmn/MSOCommonBPMN/src/main/resources/subprocess/ConfirmVolumeGroupName.bpmn @@ -13,7 +13,7 @@ <bpmn2:incoming>SequenceFlow_23</bpmn2:incoming> <bpmn2:outgoing>SequenceFlow_18</bpmn2:outgoing> <bpmn2:script><![CDATA[import org.onap.so.bpmn.common.scripts.* -def cvgn= new ConfirmVolumeGroupName() +def cvgn= new ConfirmVolumeGroupNameFactory().create() cvgn.handleAAIQueryFailure(execution)]]></bpmn2:script> </bpmn2:scriptTask> <bpmn2:sequenceFlow id="SequenceFlow_18" name="" sourceRef="AAIQueryFailure" targetRef="EndEvent_7"/> @@ -25,7 +25,7 @@ cvgn.handleAAIQueryFailure(execution)]]></bpmn2:script> <bpmn2:incoming>SequenceFlow_38</bpmn2:incoming> <bpmn2:outgoing>SequenceFlow_39</bpmn2:outgoing> <bpmn2:script><![CDATA[import org.onap.so.bpmn.common.scripts.* -def cvgn= new ConfirmVolumeGroupName() +def cvgn= new ConfirmVolumeGroupNameFactory().create() cvgn.queryAAIForVolumeGroupId(execution)]]></bpmn2:script> </bpmn2:scriptTask> <bpmn2:sequenceFlow id="SequenceFlow_39" name="" sourceRef="QueryAAIForVolumeGroupId" targetRef="ExclusiveGateway_3"/> @@ -33,7 +33,7 @@ cvgn.queryAAIForVolumeGroupId(execution)]]></bpmn2:script> <bpmn2:incoming>SequenceFlow_1</bpmn2:incoming> <bpmn2:outgoing>SequenceFlow_38</bpmn2:outgoing> <bpmn2:script><![CDATA[import org.onap.so.bpmn.common.scripts.* -def cvgn= new ConfirmVolumeGroupName() +def cvgn= new ConfirmVolumeGroupNameFactory().create() cvgn.preProcessRequest(execution)]]></bpmn2:script> </bpmn2:scriptTask> <bpmn2:sequenceFlow id="SequenceFlow_38" name="" sourceRef="InitializeVariables" targetRef="QueryAAIForVolumeGroupId"/> @@ -42,7 +42,7 @@ cvgn.preProcessRequest(execution)]]></bpmn2:script> <bpmn2:incoming>SequenceFlow_2</bpmn2:incoming> <bpmn2:outgoing>SequenceFlow_4</bpmn2:outgoing> <bpmn2:script><![CDATA[import org.onap.so.bpmn.common.scripts.* -def cvgn= new ConfirmVolumeGroupName() +def cvgn= new ConfirmVolumeGroupNameFactory().create() cvgn.checkAAIQueryResult(execution)]]></bpmn2:script> </bpmn2:scriptTask> <bpmn2:sequenceFlow id="SequenceFlow_4" name="" sourceRef="CheckAAIQueryResult" targetRef="ExclusiveGateway_1"/> @@ -50,7 +50,7 @@ cvgn.checkAAIQueryResult(execution)]]></bpmn2:script> <bpmn2:incoming>SequenceFlow_7</bpmn2:incoming> <bpmn2:outgoing>SequenceFlow_11</bpmn2:outgoing> <bpmn2:script><![CDATA[import org.onap.so.bpmn.common.scripts.* -def cvgn= new ConfirmVolumeGroupName() +def cvgn= new ConfirmVolumeGroupNameFactory().create() cvgn.handleVolumeGroupNameNoMatch(execution)]]></bpmn2:script> </bpmn2:scriptTask> <bpmn2:exclusiveGateway id="ExclusiveGateway_1" default="SequenceFlow_7"> diff --git a/bpmn/MSOCommonBPMN/src/test/groovy/org/onap/so/bpmn/common/scripts/ConfirmVolumeGroupNameTest.groovy b/bpmn/MSOCommonBPMN/src/test/groovy/org/onap/so/bpmn/common/scripts/ConfirmVolumeGroupNameTest.groovy index a96127aa2d..79aacdfbe9 100644 --- a/bpmn/MSOCommonBPMN/src/test/groovy/org/onap/so/bpmn/common/scripts/ConfirmVolumeGroupNameTest.groovy +++ b/bpmn/MSOCommonBPMN/src/test/groovy/org/onap/so/bpmn/common/scripts/ConfirmVolumeGroupNameTest.groovy @@ -4,12 +4,14 @@ * ================================================================================ * 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 - * + * * 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,64 +22,216 @@ package org.onap.so.bpmn.common.scripts -import static org.mockito.Mockito.* - -import javax.ws.rs.core.UriBuilder - +import org.camunda.bpm.engine.delegate.BpmnError import org.camunda.bpm.engine.delegate.DelegateExecution -import org.camunda.bpm.engine.impl.persistence.entity.ExecutionEntity import org.camunda.bpm.extension.mockito.delegate.DelegateExecutionFake -import org.junit.Assert import org.junit.Before import org.junit.Test -import org.mockito.ArgumentCaptor -import org.mockito.Captor -import org.mockito.Mockito +import org.mockito.Mock import org.mockito.MockitoAnnotations -import org.mockito.Spy +import org.onap.aai.domain.yang.RelationshipList import org.onap.aai.domain.yang.VolumeGroup +import org.onap.so.bpmn.common.scripts.ConfirmVolumeGroupName +import org.onap.so.bpmn.common.scripts.ConfirmVolumeGroupNameFactory +import org.onap.so.bpmn.common.scripts.ExceptionUtil import org.onap.so.client.aai.AAIObjectType +import org.onap.so.client.aai.AAIResourcesClient import org.onap.so.client.aai.entities.uri.AAIResourceUri import org.onap.so.client.aai.entities.uri.AAIUriFactory +import org.onap.so.constants.Defaults +import org.springframework.http.HttpStatus + +import javax.ws.rs.core.UriBuilder + +import static org.assertj.core.api.Assertions.catchThrowableOfType +import static org.junit.Assert.assertEquals +import static org.junit.Assert.assertFalse +import static org.junit.Assert.assertTrue +import static org.mockito.Mockito.spy +import static org.mockito.Mockito.when + +class ConfirmVolumeGroupNameTest { + + private static final AAIResourceUri RESOURCE_URI = AAIUriFactory.createResourceFromExistingURI( + AAIObjectType.VOLUME_GROUP, UriBuilder.fromPath('/aai/test/volume-groups/volume-group/testVolumeGroup').build()) + + private ConfirmVolumeGroupName confirmVolumeGroupName + @Mock + private VolumeGroup volumeGroup + @Mock + private AAIResourcesClient client + private ExceptionUtilFake exceptionUtilFake + + private DelegateExecution delegateExecution + + @Before + public void init() throws IOException { + exceptionUtilFake = new ExceptionUtilFake() + confirmVolumeGroupName = spy(new ConfirmVolumeGroupName(exceptionUtilFake)) + MockitoAnnotations.initMocks(this) + delegateExecution = new DelegateExecutionFake() + volumeGroup = createVolumeGroup() + when(confirmVolumeGroupName.getAAIClient()).thenReturn(client) + } + + @Test + public void preProcessRequest_shouldSetUpVariables() { + String volumeGroupId = "volume-group-id-1" + String volumeGroupName = "volume-group-name-1" + String aicCloudRegion = "aic-cloud-region-1" + AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.VOLUME_GROUP, Defaults.CLOUD_OWNER, aicCloudRegion, volumeGroupId) + + delegateExecution.setVariable("ConfirmVolumeGroupName_volumeGroupId", volumeGroupId) + delegateExecution.setVariable("ConfirmVolumeGroupName_volumeGroupName", volumeGroupName) + delegateExecution.setVariable("ConfirmVolumeGroupName_aicCloudRegion", aicCloudRegion) + delegateExecution.setVariable("CVGN_volumeGroupGetEndpoint", uri) + + confirmVolumeGroupName.preProcessRequest(delegateExecution) + + assertEquals(ConfirmVolumeGroupName.Prefix, delegateExecution.getVariable("prefix")) + + assertEquals(volumeGroupId, delegateExecution.getVariable("CVGN_volumeGroupId")) + assertEquals(volumeGroupName, delegateExecution.getVariable("CVGN_volumeGroupName")) + assertEquals(aicCloudRegion, delegateExecution.getVariable("CVGN_aicCloudRegion")) + } + + @Test + public void queryAAIForVolumeGroupId_shouldSucceed_whenVolumeGroupExists() { + delegateExecution.setVariable("CVGN_queryVolumeGroupResponseCode", HttpStatus.OK) + delegateExecution.setVariable("CVGN_queryVolumeGroupResponse", volumeGroup) + delegateExecution.setVariable("CVGN_volumeGroupGetEndpoint", RESOURCE_URI) + when(client.get(VolumeGroup.class, RESOURCE_URI)).thenReturn(Optional.of(volumeGroup)) + + confirmVolumeGroupName.queryAAIForVolumeGroupId(delegateExecution) + + assertEquals(HttpStatus.OK.value(), delegateExecution.getVariable("CVGN_queryVolumeGroupResponseCode")) + assertEquals(volumeGroup, delegateExecution.getVariable("CVGN_queryVolumeGroupResponse")) + } + + @Test + public void queryAAIForVolumeGroupId_shouldFailWith404_whenVolumeGroupDoesNotExist() { + delegateExecution.setVariable("CVGN_volumeGroupGetEndpoint", RESOURCE_URI) + when(client.get(VolumeGroup.class, RESOURCE_URI)).thenReturn(Optional.empty()) + + confirmVolumeGroupName.queryAAIForVolumeGroupId(delegateExecution) + + assertEquals(HttpStatus.NOT_FOUND.value(), delegateExecution.getVariable("CVGN_queryVolumeGroupResponseCode")) + assertEquals("Volume Group not Found!", delegateExecution.getVariable("CVGN_queryVolumeGroupResponse")) + } + + @Test + public void queryAAIForVolumeGroupId_shouldThrowWorkflowException_whenRuntimeExceptionIsThrown() throws BpmnError { + delegateExecution.setVariable("CVGN_volumeGroupGetEndpoint", RESOURCE_URI) + delegateExecution.setVariable("testProcessKey", "process-key1") + + def errorMsg = "my runtime exception" + when(client.get(VolumeGroup.class, RESOURCE_URI)).thenThrow(new RuntimeException(errorMsg)) + + def exceptionMsg = "AAI GET Failed" + + BpmnError error = catchThrowableOfType( + { -> confirmVolumeGroupName.queryAAIForVolumeGroupId(delegateExecution) }, BpmnError.class) + + assertEquals(String.format("MSOWorkflowException: %s", exceptionMsg), error.getMessage()) + assertEquals(HttpStatus.INTERNAL_SERVER_ERROR.value().toString(), error.getErrorCode()) + + assertEquals(HttpStatus.INTERNAL_SERVER_ERROR.value(), delegateExecution.getVariable("CVGN_queryVolumeGroupResponseCode")) + assertEquals(String.format("AAI GET Failed:%s", errorMsg), delegateExecution.getVariable("CVGN_queryVolumeGroupResponse")) + assertEquals(HttpStatus.INTERNAL_SERVER_ERROR.value(), exceptionUtilFake.getErrorCode()) + assertEquals(exceptionMsg, exceptionUtilFake.getErrorMessage()) + assertEquals(delegateExecution, exceptionUtilFake.getDelegateExecution()) + } + + @Test + public void checkAAIQueryResult_shouldSetVolumeGroupNameMatchesToFalse_whenResponseCodeIs404() { + delegateExecution.setVariable("CVGN_queryVolumeGroupResponseCode", HttpStatus.NOT_FOUND) + delegateExecution.setVariable("CVGN_volumeGroupName", "") + + confirmVolumeGroupName.checkAAIQueryResult(delegateExecution) + + assertFalse(delegateExecution.getVariable("CVGN_volumeGroupNameMatches")) + } + + @Test + public void checkAAIQueryResult_shouldSetVolumeGroupNameMatchesToTrue_whenResponseCodeIs200AndVolumeGroupNameExists() { + delegateExecution.setVariable("CVGN_queryVolumeGroupResponseCode", HttpStatus.OK.value()) + delegateExecution.setVariable("CVGN_queryVolumeGroupResponse", volumeGroup) + delegateExecution.setVariable("CVGN_volumeGroupName", volumeGroup.getVolumeGroupName()) + + confirmVolumeGroupName.checkAAIQueryResult(delegateExecution) + + assertTrue(delegateExecution.getVariable("CVGN_volumeGroupNameMatches")) + } + + @Test + public void handleVolumeGroupNameNoMatch_shouldThrowBpmnErrorException() { + def volumeGroupId = "volume-group-id" + def volumeGroupName = "volume-group-name" + + delegateExecution.setVariable("CVGN_volumeGroupId", volumeGroupId) + delegateExecution.setVariable("CVGN_volumeGroupName", volumeGroupName) + + def errorMessage = String.format("Error occurred - volume group id %s is not associated with %s", + delegateExecution.getVariable('CVGN_volumeGroupId'), delegateExecution.getVariable('CVGN_volumeGroupName')) + + BpmnError error = catchThrowableOfType( + { -> confirmVolumeGroupName.handleVolumeGroupNameNoMatch(delegateExecution) }, BpmnError.class) + + assertEquals(String.format("MSOWorkflowException: %s", errorMessage), error.getMessage()) + assertEquals("1002", error.getErrorCode()) + + assertEquals(1002, exceptionUtilFake.getErrorCode()) + assertEquals(errorMessage, exceptionUtilFake.getErrorMessage()) + assertEquals(delegateExecution, exceptionUtilFake.getDelegateExecution()) + } + + @Test + public void reportSuccess_shouldSetWorkflowResponseToEmptyString() { + confirmVolumeGroupName.reportSuccess(delegateExecution) + assertEquals("", delegateExecution.getVariable("WorkflowResponse")) + } + + private VolumeGroup createVolumeGroup() { + VolumeGroup volumeGroup = new VolumeGroup() + + volumeGroup.setVolumeGroupId("volume-group-id") + volumeGroup.setVolumeGroupName("volume-group-name") + volumeGroup.setHeatStackId("heat-stack-id") + volumeGroup.setVnfType("vnf-type") + volumeGroup.setOrchestrationStatus("orchestration-status") + volumeGroup.setModelCustomizationId("model-customization-id") + volumeGroup.setVfModuleModelCustomizationId("vf-module-model-customization-id") + volumeGroup.setResourceVersion("resource-version") + volumeGroup.setRelationshipList(new RelationshipList()) + + return volumeGroup + } + + private static class ExceptionUtilFake extends ExceptionUtil { + + private int errorCode + private String errorMessage + private DelegateExecution execution + + @Override + public void buildAndThrowWorkflowException(DelegateExecution execution, int errorCode, String errorMessage) { + this.errorCode = errorCode + this.errorMessage = errorMessage + this.execution = execution + throw new BpmnError(errorCode.toString(), "MSOWorkflowException: ${errorMessage}") + } + + public int getErrorCode() { + return errorCode + } + + public String getErrorMessage() { + return errorMessage + } + + public DelegateExecution getDelegateExecution() { + return execution + } + } -class ConfirmVolumeGroupNameTest extends MsoGroovyTest { - - @Spy - private ConfirmVolumeGroupName confirmVolumeGroupName; - - @Before - public void init() throws IOException { - super.init("ConfirmVolumeGroupName") - MockitoAnnotations.initMocks(this); - when(confirmVolumeGroupName.getAAIClient()).thenReturn(client) - - } - - @Test - public void testQueryAAIForVolumeGroupId() { - - AAIResourceUri resourceUri = AAIUriFactory.createResourceFromExistingURI(AAIObjectType.VOLUME_GROUP, UriBuilder.fromPath('/aai/test/volume-groups/volume-group/testVolumeGroup').build()); - when(mockExecution.getVariable("CVGN_volumeGroupGetEndpoint")).thenReturn(resourceUri) - VolumeGroup volumeGroup = new VolumeGroup() - volumeGroup.setVolumeGroupId("Test") - when(client.get(VolumeGroup.class,resourceUri)).thenReturn(Optional.of(volumeGroup)) - confirmVolumeGroupName.queryAAIForVolumeGroupId(mockExecution) - Mockito.verify(mockExecution).setVariable("CVGN_queryVolumeGroupResponseCode",200) - Mockito.verify(mockExecution).setVariable("CVGN_queryVolumeGroupResponse",volumeGroup) - } - - @Test - public void testQueryAAIForVolumeGroupId_404() { - AAIResourceUri resourceUri = AAIUriFactory.createResourceFromExistingURI(AAIObjectType.VOLUME_GROUP, UriBuilder.fromPath('/aai/test/volume-groups/volume-group/testVolumeGroup').build()); - when(client.get(VolumeGroup.class, resourceUri)).thenReturn(Optional.empty()) - DelegateExecution execution = new DelegateExecutionFake() - try { - execution.setVariable("CVGN_volumeGroupGetEndpoint", resourceUri) - confirmVolumeGroupName.queryAAIForVolumeGroupId(execution) - } - catch(Exception ex){} - Assert.assertEquals(404, execution.getVariable("CVGN_queryVolumeGroupResponseCode")) - Assert.assertEquals("Volume Group not Found!", execution.getVariable("CVGN_queryVolumeGroupResponse")) - - } } diff --git a/bpmn/MSOCommonBPMN/src/test/groovy/org/onap/so/bpmn/common/scripts/SDNCAdapterTest.groovy b/bpmn/MSOCommonBPMN/src/test/groovy/org/onap/so/bpmn/common/scripts/SDNCAdapterTest.groovy index ec69bf5eb9..e351210586 100644 --- a/bpmn/MSOCommonBPMN/src/test/groovy/org/onap/so/bpmn/common/scripts/SDNCAdapterTest.groovy +++ b/bpmn/MSOCommonBPMN/src/test/groovy/org/onap/so/bpmn/common/scripts/SDNCAdapterTest.groovy @@ -844,11 +844,11 @@ def sdncAdapterResponseError = verify(mockExecution).setVariable("asynchronousResponseTimeout",false) verify(mockExecution).setVariable("continueListening",false) verify(mockExecution).setVariable("serviceConfigActivate",false) - verify(mockExecution).setVariable("SDNCA_requestId", "testReqId") verify(mockExecution).setVariable("SDNCA_SuccessIndicator",false) verify(mockExecution).setVariable("SDNCA_InterimNotify",false) verify(mockExecution).setVariable("BasicAuthHeaderValue","Basic dGVzdDp0ZXN0") verify(mockExecution).setVariable("source","") + verify(mockExecution).setVariable("SDNCA_requestId", "745b1b50-e39e-4685-9cc8-c71f0bde8bf0") verify(mockExecution).setVariable("sdncAdapterRequest", sdncAdapterRequest) } diff --git a/bpmn/MSOCommonBPMN/src/test/groovy/org/onap/so/bpmn/common/scripts/UpdateAAIVfModuleTest.groovy b/bpmn/MSOCommonBPMN/src/test/groovy/org/onap/so/bpmn/common/scripts/UpdateAAIVfModuleTest.groovy index cb9bb5c541..2d2f58b415 100644 --- a/bpmn/MSOCommonBPMN/src/test/groovy/org/onap/so/bpmn/common/scripts/UpdateAAIVfModuleTest.groovy +++ b/bpmn/MSOCommonBPMN/src/test/groovy/org/onap/so/bpmn/common/scripts/UpdateAAIVfModuleTest.groovy @@ -113,6 +113,7 @@ class UpdateAAIVfModuleTest extends MsoGroovyTest { when(mockExecution.getVariable(prefix + "getVfModuleResponse")).thenReturn(vfModule) doNothing().when(client).update(isA(AAIResourceUri.class), anyObject()) updateAAIVfModule.updateVfModule(mockExecution) + verify(mockExecution).setVariable("UAAIVfMod_updateVfModuleResponseCode", 200) } @Test @@ -128,6 +129,7 @@ class UpdateAAIVfModuleTest extends MsoGroovyTest { doThrow(new NotFoundException("Vf Module not found")).when(client).update(isA(AAIResourceUri.class), anyObject()) thrown.expect(BpmnError.class) updateAAIVfModule.updateVfModule(mockExecution) + verify(mockExecution).setVariable("UAAIVfMod_updateVfModuleResponseCode", 404) } @@ -144,6 +146,7 @@ class UpdateAAIVfModuleTest extends MsoGroovyTest { doThrow(new IllegalStateException("Error in AAI client")).when(client).update(isA(AAIResourceUri.class), anyObject()) thrown.expect(BpmnError.class) updateAAIVfModule.updateVfModule(mockExecution) + verify(mockExecution).setVariable("UAAIVfMod_updateVfModuleResponseCode", 500) } } diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/tasks/BBInputSetupTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/tasks/BBInputSetupTest.java index f6e433bf38..78238f0271 100644 --- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/tasks/BBInputSetupTest.java +++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/tasks/BBInputSetupTest.java @@ -1314,12 +1314,11 @@ public class BBInputSetupTest { doReturn(vnf2AAI).when(SPY_bbInputSetupUtils).getAAIGenericVnf(vnf2.getVnfId()); doNothing().when(SPY_bbInputSetup).mapCatalogVnf(vnf2, modelInfo, service); doNothing().when(SPY_bbInputSetup).mapNetworkCollectionInstanceGroup(vnf2, "{instanceGroupId}"); - doNothing().when(SPY_bbInputSetup).mapVnfcCollectionInstanceGroup(vnf2, modelInfo, service); SPY_bbInputSetup.populateGenericVnf(modelInfo, instanceName, platform, lineOfBusiness, service, bbName, serviceInstance, lookupKeyMap, requestDetails.getRelatedInstanceList(), resourceId, vnfType, null); verify(SPY_bbInputSetup, times(2)).mapCatalogVnf(vnf2, modelInfo, service); verify(SPY_bbInputSetup, times(2)).mapNetworkCollectionInstanceGroup(vnf2, "{instanceGroupId}"); - verify(SPY_bbInputSetup, times(2)).mapVnfcCollectionInstanceGroup(vnf2, modelInfo, service); + verify(SPY_bbInputSetup, times(1)).mapVnfcCollectionInstanceGroup(vnf2, modelInfo, service); } @Test diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/restproperties/RestPropertiesPojoTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/restproperties/RestPropertiesPojoTest.java deleted file mode 100644 index 863338548e..0000000000 --- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/restproperties/RestPropertiesPojoTest.java +++ /dev/null @@ -1,47 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 - 2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.so.client.restproperties; - -import org.junit.Test; - -import com.openpojo.reflection.PojoClass; -import com.openpojo.reflection.impl.PojoClassFactory; -import com.openpojo.validation.Validator; -import com.openpojo.validation.ValidatorBuilder; -import com.openpojo.validation.rule.impl.NoPrimitivesRule; -import com.openpojo.validation.rule.impl.NoPublicFieldsRule; -import com.openpojo.validation.test.impl.GetterTester; - -public class RestPropertiesPojoTest { - @Test - public void pojoStructure() { - test(PojoClassFactory.getPojoClass(AaiPropertiesConfiguration.class)); - } - - private void test(PojoClass pojoClass) { - Validator validator = ValidatorBuilder.create() - .with(new NoPrimitivesRule()) - .with(new NoPublicFieldsRule()) - .with(new GetterTester()) - .build(); - validator.validate(pojoClass); - } -} |