aboutsummaryrefslogtreecommitdiffstats
path: root/bpmn/MSOCommonBPMN/src/main/groovy/org/onap
diff options
context:
space:
mode:
authorBenjamin, Max (mb388a) <mb388a@us.att.com>2018-07-30 15:56:09 -0400
committerBenjamin, Max (mb388a) <mb388a@us.att.com>2018-07-31 11:09:25 -0400
commit5a6a6de6f1a26a1897e4917a0df613e25a24eb70 (patch)
tree59a968f27b4b603aacc9d5e7b51fb598aeec5321 /bpmn/MSOCommonBPMN/src/main/groovy/org/onap
parentb6dc38501f3b746426b42d9de4cc883d894149e8 (diff)
Containerization feature of SO
Change-Id: I95381232eeefcd247a66a5cec370a8ce1c288e18 Issue-ID: SO-670 Signed-off-by: Benjamin, Max (mb388a) <mb388a@us.att.com>
Diffstat (limited to 'bpmn/MSOCommonBPMN/src/main/groovy/org/onap')
-rw-r--r--bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/AaiUtil.groovy643
-rw-r--r--bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/AbstractServiceTaskProcessor.groovy768
-rw-r--r--bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/AllottedResourceUtils.groovy343
-rw-r--r--bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/AppCClient.groovy159
-rw-r--r--bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/CatalogDbUtils.groovy1311
-rw-r--r--bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/CompleteMsoProcess.groovy311
-rw-r--r--bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/ConfirmVolumeGroupName.groovy152
-rw-r--r--bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/ConfirmVolumeGroupTenant.groovy193
-rw-r--r--bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/CreateAAIVfModule.groovy612
-rw-r--r--bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/CreateAAIVfModuleVolumeGroup.groovy327
-rw-r--r--bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/CustomE2EGetService.groovy440
-rw-r--r--bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/CustomE2EPutService.groovy283
-rw-r--r--bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/DecomposeService.groovy170
-rw-r--r--bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/DeleteAAIVfModule.groovy335
-rw-r--r--bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/ExceptionUtil.groovy422
-rw-r--r--bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/FalloutHandler.groovy378
-rw-r--r--bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/GenerateVfModuleName.groovy173
-rw-r--r--bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/GenericGetService.groovy470
-rw-r--r--bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/GenericGetVnf.groovy275
-rw-r--r--bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/GenericNotificationService.groovy47
-rw-r--r--bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/GenericPutService.groovy282
-rw-r--r--bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/GenericUtils.groovy40
-rw-r--r--bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/ManualHandling.groovy343
-rw-r--r--bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/MsoUtils.groovy999
-rw-r--r--bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/NetworkUtils.groovy1581
-rw-r--r--bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/OofHoming.groovy348
-rw-r--r--bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/OofUtils.groovy484
-rw-r--r--bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/PrepareUpdateAAIVfModule.groovy366
-rw-r--r--bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/RainyDayHandler.groovy190
-rw-r--r--bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/ReceiveWorkflowMessage.groovy133
-rw-r--r--bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/SDNCAdapter.groovy327
-rw-r--r--bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/SDNCAdapterRestV1.groovy381
-rw-r--r--bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/SDNCAdapterRestV2.groovy286
-rw-r--r--bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/SDNCAdapterUtils.groovy1024
-rw-r--r--bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/ServiceTaskProcessor.groovy33
-rw-r--r--bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/SniroHomingV1.groovy260
-rw-r--r--bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/SniroUtils.groovy353
-rw-r--r--bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/TrinityExceptionUtil.groovy382
-rw-r--r--bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/UpdateAAIGenericVnf.groovy345
-rw-r--r--bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/UpdateAAIVfModule.groovy369
-rw-r--r--bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/VfModule.groovy93
-rw-r--r--bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/VfModuleBase.groovy1285
-rw-r--r--bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/VidUtils.groovy553
-rw-r--r--bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/VnfAdapterRestV1.groovy419
-rw-r--r--bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/VnfAdapterUtils.groovy90
45 files changed, 18778 insertions, 0 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
new file mode 100644
index 0000000000..0bd54ffe64
--- /dev/null
+++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/AaiUtil.groovy
@@ -0,0 +1,643 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.so.bpmn.common.scripts
+import 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.logger.MessageEnum
+import org.onap.so.logger.MsoLogger
+
+
+
+class AaiUtil {
+ private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, AaiUtil.class);
+
+
+ public MsoUtils utils = new MsoUtils()
+ public static final String AAI_NAMESPACE_STRING_KEY = 'mso.workflow.global.default.aai.namespace'
+ public static final String DEFAULT_VERSION_KEY = 'mso.workflow.global.default.aai.version'
+
+ private String aaiNamespace = null;
+
+ private AbstractServiceTaskProcessor taskProcessor
+
+ public AaiUtil(AbstractServiceTaskProcessor taskProcessor) {
+ this.taskProcessor = taskProcessor
+ }
+
+ public String getNetworkGenericVnfEndpoint(DelegateExecution execution) {
+ String endpoint = UrnPropertiesReader.getVariable("aai.endpoint", execution)
+ def uri = getNetworkGenericVnfUri(execution)
+ msoLogger.debug('AaiUtil.getNetworkGenericVnfEndpoint() - AAI endpoint: ' + endpoint + uri)
+ return endpoint + uri
+ }
+
+ public String getNetworkGenericVnfUri(DelegateExecution execution) {
+ def uri = getUri(execution, 'generic-vnf')
+ msoLogger.debug('AaiUtil.getNetworkGenericVnfUri() - AAI URI: ' + uri)
+ return uri
+ }
+
+ public String getNetworkVpnBindingUri(DelegateExecution execution) {
+ def uri = getUri(execution, 'vpn-binding')
+ msoLogger.debug('AaiUtil.getNetworkVpnBindingUri() - AAI URI: ' + uri)
+ return uri
+ }
+
+ public String getNetworkPolicyUri(DelegateExecution execution) {
+ def uri = getUri(execution, 'network-policy')
+ msoLogger.debug('AaiUtil.getNetworkPolicyUri() - AAI URI: ' + uri)
+ return uri
+ }
+
+ public String getNetworkTableReferencesUri(DelegateExecution execution) {
+ def uri = getUri(execution, 'route-table-reference')
+ msoLogger.debug('AaiUtil.getNetworkTableReferencesUri() - AAI URI: ' + uri)
+ return uri
+ }
+
+ public String getNetworkVceUri(DelegateExecution execution) {
+ def uri = getUri(execution, 'vce')
+ msoLogger.debug('AaiUtil.getNetworkVceUri() - AAI URI: ' + uri)
+ return uri
+ }
+
+ public String getNetworkL3NetworkUri(DelegateExecution execution) {
+ def uri = getUri(execution, 'l3-network')
+ msoLogger.debug('AaiUtil.getNetworkL3NetworkUri() - AAI URI: ' + uri)
+ return uri
+ }
+
+ public String getBusinessCustomerUri(DelegateExecution execution) {
+ def uri = getUri(execution, 'customer')
+ msoLogger.debug('AaiUtil.getBusinessCustomerUri() - AAI URI: ' + uri)
+ return uri
+ }
+
+ //public String getBusinessCustomerUriv7(DelegateExecution execution) {
+ // // //def uri = getUri(execution, BUSINESS_CUSTOMERV7)
+ // def uri = getUri(execution, 'Customer')
+ // msoLogger.debug('AaiUtil.getBusinessCustomerUriv7() - AAI URI: ' + uri)
+ // return uri
+ //}
+
+ public String getCloudInfrastructureCloudRegionEndpoint(DelegateExecution execution) {
+ String endpoint = UrnPropertiesReader.getVariable("aai.endpoint", execution)
+ def uri = getCloudInfrastructureCloudRegionUri(execution)
+ msoLogger.debug('AaiUtil.getCloudInfrastructureCloudRegionEndpoint() - AAI endpoint: ' + endpoint + uri)
+ return endpoint + uri
+ }
+
+ public String getCloudInfrastructureCloudRegionUri(DelegateExecution execution) {
+ def uri = getUri(execution, 'cloud-region')
+ msoLogger.debug('AaiUtil.getCloudInfrastructureCloudRegionUri() - AAI URI: ' + uri)
+ return uri
+ }
+
+ public String getCloudInfrastructureTenantUri(DelegateExecution execution) {
+ def uri = getUri(execution, 'tenant')
+ msoLogger.debug('AaiUtil.getCloudInfrastructureTenantUri() - AAI URI: ' + uri)
+ return uri
+ }
+
+ public String getSearchNodesQueryUri(DelegateExecution execution) {
+ def uri = getUri(execution, 'nodes-query')
+ msoLogger.debug('AaiUtil.getSearchNodesQueryUri() - AAI URI: ' + uri)
+ return uri
+ }
+
+ public String getSearchNodesQueryEndpoint(DelegateExecution execution) {
+ String endpoint = UrnPropertiesReader.getVariable("aai.endpoint", execution)
+ def uri = getSearchNodesQueryUri(execution)
+ msoLogger.debug('AaiUtil.getSearchNodesQueryEndpoint() - AAI endpoint: ' + endpoint + uri)
+ return endpoint + uri
+ }
+
+ public String getSearchGenericQueryUri(DelegateExecution execution) {
+ def uri = getUri(execution, 'generic-query')
+ msoLogger.debug('AaiUtil.getSearchGenericQueryUri() - 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 getUri(DelegateExecution execution, resourceName) {
+
+ def processKey = taskProcessor.getMainProcessKey(execution)
+
+ //set namespace
+ setNamespace(execution)
+
+ // Check for flow+resource specific first
+ def key = "mso.workflow.${processKey}.aai.${resourceName}.uri"
+ def uri = UrnPropertiesReader.getVariable(key, execution)
+ if(uri) {
+ msoLogger.debug("AaiUtil.getUri() - using flow+resource specific key: ${key}=${uri}")
+ return uri
+ }
+
+ // Check for versioned key
+ def version = getVersion(execution, resourceName, processKey)
+ key = "mso.workflow.default.aai.v${version}.${resourceName}.uri"
+ uri = UrnPropertiesReader.getVariable(key, execution)
+
+ if(uri) {
+ msoLogger.debug("AaiUtil.getUri() - using versioned URI key: ${key}=${uri}")
+ return uri
+ }
+
+ (new ExceptionUtil()).buildAndThrowWorkflowException(execution, 9999, 'Internal Error: AAI URI entry for ' + key + ' not defined in the MSO URN properties file')
+ }
+
+ 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')
+ }
+ }
+
+ /**
+ * 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) {
+ if (aaiNamespace == null) {
+ throw new Exception('Internal Error: AAI Namespace has not been set yet. A getUri() method needs to be invoked first.')
+ }
+ String namespace = aaiNamespace
+ 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) {
+ def version = ""
+ def savedVersion = ""
+ for (int x=2; x<6; x++) {
+ version = uri.substring(uri.indexOf("v")+1, uri.indexOf("v")+x)
+ if (!Character.isDigit(version.charAt(version.size()-1))) {
+ break
+ }
+ savedVersion = version
+ }
+ return savedVersion
+ }
+
+
+ /**
+ * 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.get()
+
+ 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)
+ * @param execution
+ * @param url - url for AAI get cloud region
+ * @param backend - "PO" - real region, or "SDNC" - v2.5 (fake region).
+ */
+
+ 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()
+ msoLogger.debug("Call AAI Cloud Region Return code: " + returnCode)
+ execution.setVariable(execution.getVariable("prefix")+"queryCloudRegionReturnCode", returnCode)
+
+ if(returnCode == "200"){
+ msoLogger.debug("Call AAI Cloud Region is Successful.")
+
+ String regionVersion = taskProcessor.utils.getNodeText(aaiResponseAsString, "cloud-region-version")
+ msoLogger.debug("Cloud Region Version from AAI for " + backend + " is: " + regionVersion)
+ if (backend == "PO") {
+ regionId = taskProcessor.utils.getNodeText(aaiResponseAsString, "cloud-region-id")
+ } else { // backend not "PO"
+ if (regionVersion == "2.5" ) {
+ regionId = "AAIAIC25"
+ } else {
+ regionId = taskProcessor.utils.getNodeText(aaiResponseAsString, "cloud-region-id")
+ }
+ }
+ if(regionId == null){
+ throw new BpmnError("MSOWorkflowException")
+ }
+ msoLogger.debug("Cloud Region Id from AAI " + backend + " is: " + regionId)
+ }else if (returnCode == "404"){ // not 200
+ if (backend == "PO") {
+ regionId = inputCloudRegion
+ }else{ // backend not "PO"
+ regionId = "AAIAIC25"
+ }
+ msoLogger.debug("Cloud Region value for code='404' of " + backend + " is: " + regionId)
+ }else{
+ msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Call AAI Cloud Region is NOT Successful.", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "");
+ throw new BpmnError("MSOWorkflowException")
+ }
+ }catch(Exception e) {
+ msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception occured while getting the Cloud Reqion.", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, e.getMessage());
+ (new ExceptionUtil()).buildAndThrowWorkflowException(execution, 9999, e.getMessage())
+ }
+ 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"),
+ * the value for filtering is specified in "value" parameter
+ *
+ * @param execution
+ * @param aaiVnfResponse
+ * @param key
+ * @param value
+ *
+ * @return moduleIndex
+ *
+ */
+ public int getLowestUnusedVfModuleIndexFromAAIVnfResponse(DelegateExecution execution, String aaiVnfResponse, String key, String value) {
+ if (aaiVnfResponse != null) {
+ String vfModulesText = taskProcessor.utils.getNodeXml(aaiVnfResponse, "vf-modules")
+ if (vfModulesText == null || vfModulesText.isEmpty()) {
+ msoLogger.debug("There are no VF modules in this VNF yet")
+ return 0
+ }
+ else {
+ def xmlVfModules= new XmlSlurper().parseText(vfModulesText)
+ def vfModules = xmlVfModules.'**'.findAll {it.name() == "vf-module"}
+ int vfModulesSize = 0
+ if (vfModules != null) {
+ vfModulesSize = vfModules.size()
+ }
+ String matchingVfModules = "<vfModules>"
+ for (i in 0..vfModulesSize-1) {
+ def vfModuleXml = groovy.xml.XmlUtil.serialize(vfModules[i])
+ def keyFromAAI = taskProcessor.utils.getNodeText(vfModuleXml, key)
+ if (keyFromAAI != null && keyFromAAI.equals(value)) {
+ matchingVfModules = matchingVfModules + taskProcessor.utils.removeXmlPreamble(vfModuleXml)
+ }
+ }
+ matchingVfModules = matchingVfModules + "</vfModules>"
+ msoLogger.debug("Matching VF Modules: " + matchingVfModules)
+ String lowestUnusedIndex = taskProcessor.utils.getLowestUnusedIndex(matchingVfModules)
+ return Integer.parseInt(lowestUnusedIndex)
+ }
+ }
+ else {
+ return 0
+ }
+ }
+} \ No newline at end of file
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
new file mode 100644
index 0000000000..1e2a703e70
--- /dev/null
+++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/AbstractServiceTaskProcessor.groovy
@@ -0,0 +1,768 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.so.bpmn.common.scripts;
+
+import groovy.json.JsonSlurper
+
+import org.camunda.bpm.engine.delegate.BpmnError
+import org.camunda.bpm.engine.delegate.DelegateExecution
+import org.camunda.bpm.engine.variable.VariableMap
+import org.camunda.bpm.engine.variable.Variables
+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.springframework.web.util.UriUtils
+
+public abstract class AbstractServiceTaskProcessor implements ServiceTaskProcessor {
+ public MsoUtils utils = new MsoUtils()
+
+
+ /**
+ * Logs a message at the ERROR level.
+ * @param message the message
+ */
+ public void logError(String message) {
+ log('ERROR', message, null, "true")
+ }
+
+ /**
+ * Logs a message at the ERROR level.
+ * @param message the message
+ * @param cause the cause (stracktrace will be included in the output)
+ */
+ public void logError(String message, Throwable cause) {
+ log('ERROR', message, cause, "true")
+ }
+
+ /**
+ * Logs a message at the WARN level.
+ * @param message the message
+ */
+ public void logWarn(String message) {
+ log('WARN', message, null, "true")
+ }
+
+ /**
+ * Logs a message at the WARN level.
+ * @param message the message
+ * @param cause the cause (stracktrace will be included in the output)
+ */
+ public void logWarn(String message, Throwable cause) {
+ log('WARN', message, cause, "true")
+ }
+
+ /**
+ * Logs a message at the DEBUG level.
+ * @param message the message
+ * @param isDebugLogEnabled a flag indicating if DEBUG level is enabled
+ */
+ public void logDebug(String message, String isDebugLogEnabled) {
+ log('DEBUG', message, null, isDebugLogEnabled)
+ }
+
+ /**
+ * Logs a message at the DEBUG level.
+ * @param message the message
+ * @param cause the cause (stracktrace will be included in the output)
+ * @param isDebugLogEnabled a flag indicating if DEBUG level is enabled
+ */
+ public void logDebug(String message, Throwable cause, String isDebugLogEnabled) {
+ log('DEBUG', message, cause, isDebugLogEnabled)
+ }
+
+ /**
+ * Logs a message at the specified level.
+ * @param level the level (DEBUG, INFO, WARN, ERROR)
+ * @param message the message
+ * @param isLevelEnabled a flag indicating if the level is enabled
+ * (used only at the DEBUG level)
+ */
+ public void log(String level, String message, String isLevelEnabled) {
+ log(level, message, null, isLevelEnabled)
+ }
+
+ /**
+ * Logs a message at the specified level.
+ * @param level the level (DEBUG, INFO, WARN, ERROR)
+ * @param message the message
+ * @param cause the cause (stracktrace will be included in the output)
+ * @param isLevelEnabled a flag indicating if the level is enabled
+ * (used only at the DEBUG level)
+ */
+ public void log(String level, String message, Throwable cause, String isLevelEnabled) {
+ if (cause == null) {
+ utils.log(level, message, isLevelEnabled);
+ } else {
+ StringWriter stringWriter = new StringWriter();
+ PrintWriter printWriter = new PrintWriter(stringWriter);
+ printWriter.println(message);
+ cause.printStackTrace(printWriter);
+ utils.log(level, stringWriter.toString(), isLevelEnabled);
+ printWriter.close();
+ }
+ }
+
+ /**
+ * Logs a WorkflowException at the ERROR level with the specified message.
+ * @param execution the execution
+ */
+ public void logWorkflowException(DelegateExecution execution, String message) {
+ def workflowException = execution.getVariable("WorkflowException")
+
+ if (workflowException == null) {
+ logError(message);
+ } else {
+ logError(message + ": " + workflowException)
+ }
+ }
+
+ /**
+ * Saves the WorkflowException in the execution to the specified variable,
+ * clearing the WorkflowException variable so the workflow can continue
+ * processing (perhaps catching another WorkflowException).
+ * @param execution the execution
+ * @return the name of the destination variable
+ */
+ public saveWorkflowException(DelegateExecution execution, String variable) {
+ if (variable == null) {
+ throw new NullPointerException();
+ }
+
+ execution.setVariable(variable, execution.getVariable("WorkflowException"))
+ execution.setVariable("WorkflowException", null)
+ }
+
+
+ /**
+ * Validates that the request exists and that the mso-request-id variable is set.
+ * Additional required variables may be checked by specifying their names.
+ * NOTE: services requiring mso-service-instance-id must specify it explicitly!
+ * If a problem is found, buildAndThrowWorkflowException builds a WorkflowException
+ * and throws an MSOWorkflowException. This method also sets up the log context for
+ * the workflow.
+ *
+ * @param execution the execution
+ * @return the validated request
+ */
+ public String validateRequest(DelegateExecution execution, String... requiredVariables) {
+ ExceptionUtil exceptionUtil = new ExceptionUtil()
+ def method = getClass().getSimpleName() + '.validateRequest(' +
+ 'execution=' + execution.getId() +
+ ', requredVariables=' + requiredVariables +
+ ')'
+ def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
+ logDebug('Entered ' + method, isDebugLogEnabled)
+
+ String processKey = getProcessKey(execution)
+ def prefix = execution.getVariable("prefix")
+
+ if (prefix == null) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 1002, processKey + " prefix is null")
+ }
+
+ try {
+ def request = execution.getVariable(prefix + 'Request')
+
+ if (request == null) {
+ request = execution.getVariable(processKey + 'Request')
+
+ if (request == null) {
+ request = execution.getVariable('bpmnRequest')
+ }
+
+ setVariable(execution, processKey + 'Request', null)
+ setVariable(execution, 'bpmnRequest', null)
+ setVariable(execution, prefix + 'Request', request)
+ }
+
+ if (request == null) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 1002, processKey + " request is null")
+ }
+
+ // All requests must have a request ID.
+ // Some requests (e.g. SDN-MOBILITY) do not have a service instance ID.
+
+ String requestId = null
+ String serviceInstanceId = null
+
+ List<String> allRequiredVariables = new ArrayList<String>()
+ allRequiredVariables.add("mso-request-id")
+
+ if (requiredVariables != null) {
+ for (String variable : requiredVariables) {
+ if (!allRequiredVariables.contains(variable)) {
+ allRequiredVariables.add(variable)
+ }
+ }
+ }
+
+ for (String variable : allRequiredVariables) {
+ def value = execution.getVariable(variable)
+ if (value == null || ((value instanceof CharSequence) && value.length() == 0)) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 1002, processKey +
+ " request was received with no '" + variable + "' variable")
+ }
+
+ if ("mso-request-id".equals(variable)) {
+ requestId = (String) value
+ } else if ("mso-service-instance-id".equals(variable)) {
+ serviceInstanceId = (String) value
+ }
+ }
+
+ if (serviceInstanceId == null) {
+ serviceInstanceId = (String) execution.getVariable("mso-service-instance-id")
+ }
+
+ utils.logContext(requestId, serviceInstanceId)
+ logDebug('Incoming message: ' + System.lineSeparator() + request, isDebugLogEnabled)
+ logDebug('Exited ' + method, isDebugLogEnabled)
+ return request
+ } catch (BpmnError e) {
+ throw e
+ } catch (Exception e) {
+ logError('Caught exception in ' + method, e)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Invalid Message")
+ }
+ }
+
+ /**
+ * gets vars stored in a JSON object in prefix+Request and returns as a LazyMap
+ * setting log context here too
+ * @param execution the execution
+ * @return the inputVars
+ */
+ public Map validateJSONReq(DelegateExecution execution) {
+ def method = getClass().getSimpleName() + '.validateJSONReq(' +
+ 'execution=' + execution.getId() +
+ ')'
+ def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
+ logDebug('Entered ' + method, isDebugLogEnabled)
+
+ String processKey = getProcessKey(execution);
+ def prefix = execution.getVariable("prefix")
+
+ def requestId =getVariable(execution, "mso-request-id")
+ def serviceInstanceId = getVariable(execution, "mso-service-instance-id")
+ if(requestId!=null && serviceInstanceId!=null){
+ utils.logContext(requestId, serviceInstanceId)
+ }
+
+
+ def request = getVariable(execution, prefix + 'Request')
+
+ if (request == null) {
+ request = getVariable(execution, processKey + 'Request')
+
+ if (request == null) {
+ request = getVariable(execution, 'bpmnRequest')
+ }
+ execution.setVariable(prefix + 'Request', request)
+ }
+
+ def jsonSlurper = new JsonSlurper()
+ def parsed = jsonSlurper.parseText(request)
+
+
+ logDebug('Incoming message: ' + System.lineSeparator() + request, isDebugLogEnabled)
+ logDebug('Exited ' + method, isDebugLogEnabled)
+ return parsed
+
+ }
+
+ /**
+ * Sends a response to the workflow service that invoked the process. This method
+ * may only be used by top-level processes that were directly invoked by the
+ * asynchronous workflow service.
+ * @param execution the execution
+ * @param responseCode the response code
+ * @param content the message content
+ * @throws IllegalArgumentException if the response code is invalid
+ * by HTTP standards
+ * @throws UnsupportedOperationException if not invoked by an asynchronous,
+ * top-level process
+ * @throws IllegalStateException if a response has already been sent
+ */
+ protected void sendWorkflowResponse(DelegateExecution execution, Object responseCode, String response) {
+ def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
+ try {
+ String processKey = getProcessKey(execution);
+
+ // isAsyncProcess is injected by the workflow service that started the flow
+ if (!String.valueOf(execution.getVariable("isAsyncProcess")).equals("true")) {
+ throw new UnsupportedOperationException(processKey + ": " +
+ "sendWorkflowResponse is valid only in asynchronous workflows");
+ }
+
+ if (String.valueOf(execution.getVariable(processKey + "WorkflowResponseSent")).equals("true")) {
+ logDebug("Sync response has already been sent for " + processKey, isDebugLogEnabled)
+ }else{
+
+ logDebug("Building " + processKey + " response ", isDebugLogEnabled)
+
+ int intResponseCode;
+
+ try {
+ intResponseCode = Integer.parseInt(String.valueOf(responseCode));
+
+ if (intResponseCode < 100 || intResponseCode > 599) {
+ throw new NumberFormatException(String.valueOf(responseCode));
+ }
+ } catch (NumberFormatException e) {
+ throw new IllegalArgumentException("Process " + processKey
+ + " provided an invalid HTTP response code: " + responseCode);
+ }
+
+ // Only 2XX responses are considered "Success"
+ String status = (intResponseCode >= 200 && intResponseCode <= 299) ?
+ "Success" : "Fail";
+
+ // TODO: Should deprecate use of processKey+Response variable for the response. Will use "WorkflowResponse" instead
+ execution.setVariable(processKey + "ResponseCode", String.valueOf(intResponseCode))
+ execution.setVariable(processKey + "Response", response);
+ execution.setVariable(processKey + "Status", status);
+ execution.setVariable("WorkflowResponse", response)
+
+ logDebug("Sending response for " + processKey
+ + " ResponseCode=" + intResponseCode
+ + " Status=" + status
+ + " Response=\n" + response,
+ isDebugLogEnabled)
+
+ // TODO: ensure that this flow was invoked asynchronously?
+
+ WorkflowCallbackResponse callbackResponse = new WorkflowCallbackResponse()
+ callbackResponse.setStatusCode(intResponseCode)
+ callbackResponse.setMessage(status)
+ callbackResponse.setResponse(response)
+
+ // TODO: send this data with HTTP POST
+
+ WorkflowContextHolder.getInstance().processCallback(
+ processKey,
+ execution.getProcessInstanceId(),
+ execution.getVariable("mso-request-id"),
+ callbackResponse)
+
+ execution.setVariable(processKey + "WorkflowResponseSent", "true");
+ }
+
+ } catch (Exception ex) {
+ logError("Unable to send workflow response to client ....", ex)
+ }
+ }
+
+ /**
+ * Returns true if a workflow response has already been sent.
+ * @param execution the execution
+ */
+ protected boolean isWorkflowResponseSent(DelegateExecution execution) {
+ def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
+ String processKey = getProcessKey(execution);
+ return String.valueOf(execution.getVariable(processKey + "WorkflowResponseSent")).equals("true");
+ }
+
+ /**
+ * Returns the process definition key (i.e. the process name) of the
+ * current process.
+ *
+ * @param execution the execution
+ */
+ public String getProcessKey(DelegateExecution execution) {
+ def testKey = execution.getVariable("testProcessKey")
+ if(testKey!=null){
+ return testKey
+ }
+ return execution.getProcessEngineServices().getRepositoryService()
+ .getProcessDefinition(execution.getProcessDefinitionId()).getKey()
+ }
+
+ /**
+ * Returns the process definition key (i.e. the process name) of the
+ * top-level process.
+ * @param execution the execution
+ */
+ public String getMainProcessKey(DelegateExecution execution) {
+ DelegateExecution exec = execution
+
+ while (true) {
+ DelegateExecution parent = exec.getSuperExecution()
+
+ if (parent == null) {
+ parent = exec.getParent()
+
+ if (parent == null) {
+ break
+ }
+ }
+
+ exec = parent
+ }
+
+ return execution.getProcessEngineServices().getRepositoryService()
+ .getProcessDefinition(exec.getProcessDefinitionId()).getKey()
+ }
+
+ /**
+ * Gets the node for the named element from the given xml. If the element
+ * does not exist in the xml or is empty, a WorkflowException is created
+ * (and as a result, a MSOWorkflowException event is thrown).
+ *
+ * @param execution The flow's execution.
+ * @param xml Xml to search.
+ * @param elementName Name of element to search for.
+ * @return The element node, if found in the xml.
+ */
+ protected String getRequiredNodeXml(DelegateExecution execution, String xml, String elementName) {
+ ExceptionUtil exceptionUtil = new ExceptionUtil()
+ def element = utils.getNodeXml(xml, elementName, false)
+ if (element.trim().isEmpty()) {
+ def msg = 'Required element \'' + elementName + '\' is missing or empty'
+ logError(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg)
+ } else {
+ return element
+ }
+ }
+
+ /**
+ * Gets the value of the named element from the given xml. If the element
+ * does not exist in the xml or is empty, a WorkflowException is created
+ * (and as a result, a MSOWorkflowException event is thrown).
+ *
+ * @param execution The flow's execution.
+ * @param xml Xml to search.
+ * @param elementName Name of element to whose value to get.
+ * @return The non-empty value of the element, if found in the xml.
+ */
+ protected String getRequiredNodeText(DelegateExecution execution, String xml, String elementName) {
+ ExceptionUtil exceptionUtil = new ExceptionUtil()
+ def elementText = utils.getNodeText(xml, elementName)
+ if ((elementText == null) || (elementText.isEmpty())) {
+ def msg = 'Required element \'' + elementName + '\' is missing or empty'
+ logError(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg)
+ } else {
+ return elementText
+ }
+ }
+
+ /**
+ * Get the text for the specified element from the specified xml. If
+ * the element does not exist, return the specified default value.
+ *
+ * @param xml Xml from which to get the element's text
+ * @param elementName Name of element whose text to get
+ * @param defaultValue the default value
+ * @return the element's text or the default value if the element does not
+ * exist in the given xml
+ */
+ protected String getNodeText(String xml, String elementName, String defaultValue) {
+ def nodeText = utils.getNodeText(xml, elementName)
+ return (nodeText == null) ? defaultValue : nodeText
+ }
+
+ /**
+ * Get the text for the specified element from the specified xml. If
+ * the element does not exist, return an empty string.
+ *
+ * @param xml Xml from which to get the element's text.
+ * @param elementName Name of element whose text to get.
+ * @return the element's text or an empty string if the element does not
+ * exist in the given xml.
+ */
+ protected String getNodeTextForce(String xml, String elementName) {
+ return getNodeText(xml, elementName, '');
+ }
+
+ /**
+ *Store the variable as typed with java serialization type
+ *@param execution
+ *@param name
+ *@param value
+ */
+ public void setVariable(DelegateExecution execution, String name, Object value) {
+ VariableMap variables = Variables.createVariables()
+ variables.putValueTyped('payload', Variables.objectValue(value)
+ .serializationDataFormat(SerializationDataFormats.JAVA) // tells the engine to use java serialization for persisting the value
+ .create())
+ execution.setVariable(name,variables)
+ }
+
+ //TODO not sure how this will look in Cockpit
+
+ /**
+ * Returns the variable map
+ *@param execution
+ *@param name
+ *@return
+ **/
+ public String getVariable(DelegateExecution execution, String name) {
+ def myObj = execution.getVariable(name)
+ if(myObj instanceof VariableMap){
+ VariableMap serializedObjectMap = (VariableMap) myObj
+ ObjectValueImpl payloadObj = serializedObjectMap.getValueTyped('payload')
+ return payloadObj.getValue()
+ }else{
+ return myObj
+ }
+ }
+
+
+ /**
+ * Returns true if a value equals one of the provided set. Equality is
+ * determined by using the equals method if the value object and the
+ * object in the provided set have the same class. Otherwise, the objects
+ * are converted to strings and then compared. Nulls are permitted for
+ * the value as well as in the provided set
+ * Example:
+ * <pre>
+ * def statusCode = getStatusCode()
+ * isOneOf(statusCode, 200, 201, 204)
+ * </pre>
+ * @param value the value to test
+ * @param these a set of permissable values
+ * @return true if the value is in the provided set
+ */
+ public boolean isOneOf(Object value, Object... these) {
+ for (Object thisOne : these) {
+ if (thisOne == null) {
+ if (value == null) {
+ return true
+ }
+ } else {
+ if (value != null) {
+ if (value.getClass() == thisOne.getClass()) {
+ if (value.equals(thisOne)) {
+ return true
+ }
+ } else {
+ if (String.valueOf(value).equals(String.valueOf(thisOne))) {
+ return true
+ }
+ }
+ }
+ }
+ }
+ return false
+ }
+
+ /**
+ * Sets flows success indicator variable.
+ *
+ */
+ public void setSuccessIndicator(DelegateExecution execution, boolean isSuccess) {
+ String prefix = execution.getVariable('prefix')
+ def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
+
+ logDebug('Entered SetSuccessIndicator Method', isDebugLogEnabled)
+ execution.setVariable(prefix+'SuccessIndicator', isSuccess)
+ logDebug('Outgoing SuccessIndicator is: ' + execution.getVariable(prefix+'SuccessIndicator') + '', isDebugLogEnabled)
+ }
+
+ /**
+ * Sends a Error Sync Response
+ *
+ */
+ public void sendSyncError(DelegateExecution execution) {
+ def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
+ String requestId = execution.getVariable("mso-request-id")
+ logDebug('sendSyncError, requestId: ' + requestId, isDebugEnabled)
+ WorkflowException workflowExceptionObj = execution.getVariable("WorkflowException")
+ if (workflowExceptionObj != null) {
+ String errorMessage = workflowExceptionObj.getErrorMessage()
+ def errorCode = workflowExceptionObj.getErrorCode()
+ logDebug('sendSyncError, requestId: ' + requestId + ' | errorMessage: ' + errorMessage + ' | errorCode: ' + errorCode, isDebugEnabled)
+ sendWorkflowResponse(execution, errorCode, errorMessage)
+ }
+ }
+
+ /**
+ * Executes a named groovy script method in the current object
+ */
+ public void executeMethod(String methodName, Object... args) {
+
+ if (args != null && args.size() > 0) {
+
+ // First argument of method to call is always the execution object
+ DelegateExecution execution = (DelegateExecution) args[0]
+
+ def classAndMethod = getClass().getSimpleName() + '.' + methodName + '(execution=' + execution.getId() + ')'
+ def isDebugEnabled = execution.getVariable('isDebugLogEnabled')
+
+ logDebug('Entered ' + classAndMethod, isDebugEnabled)
+ logDebug('Received parameters: ' + args, isDebugEnabled)
+
+ try{
+ def methodToCall = this.metaClass.getMetaMethod(methodName, args)
+ logDebug('Method to call: ' + methodToCall, isDebugEnabled)
+ methodToCall?.invoke(this, args)
+ }
+ catch(BpmnError bpmnError) {
+ logDebug('Rethrowing BpmnError ' + bpmnError.getMessage(), isDebugEnabled)
+ throw bpmnError
+ }
+ catch(Exception e) {
+ e.printStackTrace()
+ logDebug('Unexpected error encountered - ' + e.getMessage(), isDebugEnabled)
+ (new ExceptionUtil()).buildAndThrowWorkflowException(execution, 9999, e.getMessage())
+ }
+ finally {
+ logDebug('Exited ' + classAndMethod, isDebugEnabled)
+ }
+ }
+ }
+
+ /**
+ *This method determines and adds the appropriate ending to come
+ *after a number (-st, -nd, -rd, or -th)
+ *
+ *@param int n
+ *
+ *@return String ending - number with suffix
+ */
+ public static String labelMaker(Object n) {
+ Integer num
+ if(n instanceof String){
+ num = Integer.parseInt(n)
+ }else{
+ num = n
+ }
+
+ String ending = ""; //the end to be added to the number
+ if(num != null){
+ if ((num % 10 == 1) && (num != 11)) {
+ ending = num + "st";
+ } else if ((num % 10 == 2) && (num != 12)) {
+ ending = num + "nd";
+ } else if ((num % 10 == 3) && (num != 13)) {
+ ending = num + "rd";
+ } else {
+ ending = num + "th";
+ }
+ }
+ return ending
+ }
+
+ /**
+ * Constructs a workflow message callback URL for the specified message type and correlator.
+ * This type of callback URL is used when a workflow wants an MSO adapter (like the SDNC
+ * adapter) to call it back. In other words, this is for callbacks internal to the MSO
+ * complex. Use <code>createWorkflowMessageAdapterCallbackURL</code> if the callback
+ * will come from outside the MSO complex.
+ * @param messageType the message type (e.g. SDNCAResponse or VNFAResponse)
+ * @param correlator the correlator value (e.g. a request ID)
+ */
+ public String createCallbackURL(DelegateExecution execution, String messageType, String correlator) {
+ String endpoint = UrnPropertiesReader.getVariable("mso.workflow.message.endpoint", execution)
+
+ if (endpoint == null || endpoint.isEmpty()) {
+ ExceptionUtil exceptionUtil = new ExceptionUtil()
+ exceptionUtil.buildAndThrowWorkflowException(execution, 2000,
+ 'mso:workflow:message:endpoint URN mapping is not set')
+ }
+
+ while (endpoint.endsWith('/')) {
+ endpoint = endpoint.substring(0, endpoint.length()-1)
+ }
+
+ return endpoint +
+ '/' + UriUtils.encodePathSegment(messageType, 'UTF-8') +
+ '/' + UriUtils.encodePathSegment(correlator, 'UTF-8')
+ }
+
+ /**
+ *
+ * Constructs a workflow message callback URL for the specified message type and correlator.
+ * This type of callback URL is used when a workflow wants a system outside the MSO complex
+ * to call it back through the Workflow Message Adapter.
+ * @param messageType the message type (e.g. SNIROResponse)
+ * @param correlator the correlator value (e.g. a request ID)
+ */
+ public String createWorkflowMessageAdapterCallbackURL(DelegateExecution execution, String messageType, String correlator) {
+ String endpoint = UrnPropertiesReader.getVariable("mso.adapters.workflow.message.endpoint", execution)
+
+ if (endpoint == null || endpoint.isEmpty()) {
+ ExceptionUtil exceptionUtil = new ExceptionUtil()
+ exceptionUtil.buildAndThrowWorkflowException(execution, 2000,
+ 'mso:adapters:workflow:message:endpoint URN mapping is not set')
+ }
+
+ while (endpoint.endsWith('/')) {
+ endpoint = endpoint.substring(0, endpoint.length()-1)
+ }
+
+ return endpoint +
+ '/' + UriUtils.encodePathSegment(messageType, 'UTF-8') +
+ '/' + UriUtils.encodePathSegment(correlator, 'UTF-8')
+ }
+
+ public void setRollbackEnabled(DelegateExecution execution, isDebugLogEnabled) {
+
+ // Rollback settings
+ def prefix = execution.getVariable('prefix')
+ def disableRollback = execution.getVariable("disableRollback")
+ def defaultRollback = UrnPropertiesReader.getVariable("mso.rollback", execution).toBoolean()
+
+ logDebug('disableRollback: ' + disableRollback, isDebugLogEnabled)
+ logDebug('defaultRollback: ' + defaultRollback, isDebugLogEnabled)
+
+ def rollbackEnabled
+
+ if(disableRollback == null || disableRollback == '' ) {
+ // get from default urn settings for mso_rollback
+ disableRollback = !defaultRollback
+ rollbackEnabled = defaultRollback
+ logDebug('disableRollback is null or empty!', isDebugLogEnabled)
+ }
+ else {
+ if(disableRollback == true) {
+ rollbackEnabled = false
+ }
+ else if(disableRollback == false){
+ rollbackEnabled = true
+ }
+ else {
+ rollbackEnabled = defaultRollback
+ }
+ }
+
+ execution.setVariable(prefix+"backoutOnFailure", rollbackEnabled)
+ logDebug('rollbackEnabled (aka backoutOnFailure): ' + rollbackEnabled, isDebugLogEnabled)
+ }
+
+ public void setBasicDBAuthHeader(DelegateExecution execution, isDebugLogEnabled) {
+ try {
+ String basicAuthValueDB = UrnPropertiesReader.getVariable("mso.adapters.db.auth", execution)
+ utils.log("DEBUG", " Obtained BasicAuth userid password for Catalog DB adapter: " + basicAuthValueDB, isDebugLogEnabled)
+
+ def encodedString = utils.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("DEBUG", dataErrorMessage, isDebugLogEnabled)
+ (new ExceptionUtil()).buildAndThrowWorkflowException(execution, 2500, dataErrorMessage)
+ }
+ }
+} \ 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
new file mode 100644
index 0000000000..b054c0f934
--- /dev/null
+++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/AllottedResourceUtils.groovy
@@ -0,0 +1,343 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.so.bpmn.common.scripts
+
+import static org.apache.commons.lang3.StringUtils.*;
+
+import org.apache.commons.lang3.*
+import org.camunda.bpm.engine.delegate.BpmnError
+import org.camunda.bpm.engine.delegate.DelegateExecution;
+import org.onap.so.bpmn.core.UrnPropertiesReader
+import org.onap.so.bpmn.core.WorkflowException
+import org.onap.so.logger.MessageEnum
+import org.onap.so.logger.MsoLogger
+import org.onap.so.rest.APIResponse;
+
+
+
+class AllottedResourceUtils {
+ private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, AllottedResourceUtils.class);
+
+
+ private AbstractServiceTaskProcessor taskProcessor
+ ExceptionUtil exceptionUtil = new ExceptionUtil()
+ MsoUtils utils;
+
+ public AllottedResourceUtils(AbstractServiceTaskProcessor taskProcessor) {
+ this.taskProcessor = taskProcessor
+ this.utils = taskProcessor.utils
+ }
+
+ /*Used on Create - called from DoCreate
+ * Using Consuming ServiceInstanceId get related Allotted Resources Orchestration status from AAI
+ * 1) get related AR links for CSI 2) get AR from AR links
+ * return: null -> AR Not found
+ * return: " " -> AR found with empty orchStatus
+ * return: orchStatus - > AR found with this orchStatus
+ * setsVariable aaiARGetResponse
+ */
+ public String getAROrchStatus (DelegateExecution execution) {
+
+ msoLogger.trace("getAROrchStatus ")
+ String msg = ""
+ String serviceInstanceId = execution.getVariable("serviceInstanceId")
+ 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)
+ try {
+ if (!isBlank(siXml)) {
+ def groovy.util.Node siNode = xmlParser.parseText(siXml)
+ def groovy.util.Node relationshipList = utils.getChildNode(siNode, '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('allotted-resource'))) {
+ 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))
+ {
+ orchStatus = execution.getVariable("aaiAROrchStatus")
+ break
+ }
+ }
+ }
+ }
+ }
+ }
+ }catch(Exception e){
+ msoLogger.debug(" Error encountered in getAROrchStatus" + e.getMessage())
+ exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error in getAROrchStatus" + e.getMessage())
+ }
+ msoLogger.trace(" Exit getAROrchStatus - OrchStatus:" + orchStatus)
+ return orchStatus
+ }
+
+ // get Allotted Resource by AllottedResourceId
+ // used on Delete - called from doDeleteAR
+ // setsVariable aaiARGetResponse
+ public String getARbyId (DelegateExecution execution, String allottedResourceId) {
+ msoLogger.trace("getARbyId ")
+ String arLink = getARLinkbyId(execution, allottedResourceId)
+ String ar = null
+ if (!isBlank(arLink))
+ {
+ ar = getARbyLink(execution, arLink, "")
+ }
+ msoLogger.trace(" Exit GetARbyId - AR:" + ar)
+ return ar;
+ }
+
+ public String getPSIFmARLink(DelegateExecution execution, String arLink)
+ {
+ // Path: /aai/{version}/business/customers/customer/{cust}/service-subscriptions/service-subscription/{subs}/service-instances/service-instance/{psiid}/allotted-resources/allotted-resource/{arid}
+ msoLogger.trace(" getPSIFmARLink - path:" + arLink)
+ String[] split = arLink.split("/service-instance/")
+ String[] splitB = split[1].split("/allotted-resources/")
+ String siId = splitB[0]
+ msoLogger.trace(" Exit getARLinkbyId - parentServiceInstanceId:" + siId )
+ return siId
+ }
+
+ // get Allotted Resource Link by AllottedResourceId using Nodes Query
+ // used on Delete - called from getARbyId
+ public String getARLinkbyId (DelegateExecution execution, String allottedResourceId) {
+ msoLogger.trace("getARLinkbyId ")
+ String arLink = null
+ try {
+ AaiUtil aaiUriUtil = new AaiUtil(taskProcessor)
+ String aaiNQUri = aaiUriUtil.getSearchNodesQueryEndpoint(execution)
+ String aaiEndpoint = UrnPropertiesReader.getVariable("aai.endpoint", execution)
+ String aaiUrl = "${aaiNQUri}?search-node-type=allotted-resource&filter=id:EQUALS:${allottedResourceId}"
+
+ msoLogger.debug("getARLinkbyId url: \n" + aaiUrl)
+
+ APIResponse response = aaiUriUtil.executeAAIGetCall(execution, aaiUrl)
+ 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, "result-data")){
+ msoLogger.debug("Query for AllottedResource Url Response Does Contain Data" )
+ arLink = utils.getNodeText(aaiResponse, "resource-link")
+ }else{
+ msoLogger.debug("GET AR Response Does NOT Contain Data" )
+ }
+ }else if(responseCode == 404){
+ 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 GetARbyId" + e.getMessage())
+ }
+ msoLogger.trace(" Exit GetARLinkbyId - Link:" + arLink)
+ return arLink
+ }
+
+ // get Allotted resource using Link
+ // used on Create called from getARORchStatus
+ // used on Delete called from getARbyId
+ // setsVariable aaiARPath - used for Patch in create
+ public String getARbyLink (DelegateExecution execution, String link, String role) {
+ msoLogger.trace("getARbyLink ")
+ String ar = null
+ String arUrl = null
+ try {
+ AaiUtil aaiUriUtil = new AaiUtil(taskProcessor)
+ String aai_endpoint = UrnPropertiesReader.getVariable("aai.endpoint", execution)
+ String arEndpoint = ""
+
+ if(!isBlank(link)) {
+ msoLogger.debug("Incoming AR Resource Link is: " + link)
+ String[] split = link.split("/aai/")
+ arEndpoint = "/aai/" + split[1]
+ }
+
+ arUrl = "${aai_endpoint}" + arEndpoint
+
+ msoLogger.debug("GET AR Aai Path is: \n" + arUrl)
+
+ APIResponse response = aaiUriUtil.executeAAIGetCall(execution, arUrl)
+ int responseCode = response.getStatusCode()
+ msoLogger.debug(" GET AR response code is: " + responseCode)
+
+ String aaiResponse = response.getResponseBodyAsString()
+ msoLogger.debug("GET AR:" + aaiResponse)
+ if(responseCode == 200 || responseCode == 202){
+ msoLogger.debug("GET AR Received a Good Response Code")
+ if(utils.nodeExists(aaiResponse, "allotted-resource")){
+ if (!isBlank(role))
+ {
+ if (utils.nodeExists(aaiResponse, "role") && role.equals(utils.getNodeText(aaiResponse, "role"))) {
+ ar = aaiResponse
+ }else{
+ msoLogger.debug("AAI AR does not match input role:" + role)
+ }
+ }
+ else
+ {
+ ar = aaiResponse
+ }
+ }
+ else
+ {
+ msoLogger.debug("GET AR Does NOT Contain Data" )
+ }
+ }else if(responseCode == 404){
+ 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)
+ }
+
+ String orchStatus = null
+ if (utils.nodeExists(ar, "orchestration-status")) {
+ orchStatus= utils.getNodeText(ar, "orchestration-status")
+ }
+ else
+ {
+ orchStatus = " "
+ }
+ execution.setVariable("aaiAROrchStatus", orchStatus)
+ }
+ 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}"
+ }
+ """
+
+ 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
+ }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())
+ }
+ msoLogger.trace("Exit updateAROrchStatus ")
+ }
+
+ //Sets Variable "wasDeleted"
+ 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
+ }catch(Exception e){
+ msoLogger.debug(" Error encountered in deleteAR!" + e)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured During Delete AR")
+ }
+ msoLogger.trace("Exit deleteAR ")
+ }
+
+ public void buildAAIErrorResponse(DelegateExecution execution, String response, String errorMessage){
+ msoLogger.trace("BuildAAIErrorResponse")
+
+ if((response != null) && (response.contains("Fault") || response.contains("RESTFault"))){
+ WorkflowException workflowException = exceptionUtil.MapAAIExceptionToWorkflowException(response, execution)
+ execution.setVariable("WorkflowException", workflowException)
+ }else{
+ exceptionUtil.buildWorkflowException(execution, 500, errorMessage)
+ }
+
+ msoLogger.trace("Exit BuildAAIErrorResponse Process")
+ throw new BpmnError("MSOWorkflowException")
+ }
+
+}
diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/AppCClient.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/AppCClient.groovy
new file mode 100644
index 0000000000..bb1de36eac
--- /dev/null
+++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/AppCClient.groovy
@@ -0,0 +1,159 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.so.bpmn.common.scripts
+
+import org.onap.so.bpmn.core.UrnPropertiesReader
+
+import java.util.HashMap;
+import org.camunda.bpm.engine.delegate.BpmnError
+import org.camunda.bpm.engine.delegate.DelegateExecution
+import org.hibernate.event.internal.AbstractLockUpgradeEventListener
+import org.onap.so.bpmn.core.json.JsonUtils
+import org.onap.so.client.appc.ApplicationControllerOrchestrator
+import org.onap.so.client.appc.ApplicationControllerOrchestratorException
+import org.onap.appc.client.lcm.model.Action
+import org.onap.appc.client.lcm.model.Status
+import org.onap.so.bpmn.appc.payload.PayloadClient
+import org.onap.so.client.appc.ApplicationControllerAction;
+import groovy.transform.TypeChecked;
+import java.util.UUID;
+import org.onap.so.logger.MessageEnum
+import org.onap.so.logger.MsoLogger
+
+/**
+ * This groovy class supports the <class>AppCClient.bpmn</class> process.
+ *
+ * Inputs:
+ * @param - msoRequestId
+ * @param - mso-request-Id
+ * @param - isDebugLogEnabled
+ * @param - requestId
+ * @param - vnfId
+ * @param - action
+ * @param - payload
+ *
+ * Outputs:
+ * @param - errorcode
+ * @param - errorText
+ * @param - responsePayload
+ * @param - healthCheckIndex
+ * @param - workstep
+ */
+
+public class AppCClient extends AbstractServiceTaskProcessor{
+ private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, AppCClient.class);
+
+ ExceptionUtil exceptionUtil = new ExceptionUtil()
+ JsonUtils jsonUtils = new JsonUtils()
+ def prefix = "UPDVnfI_"
+
+ public void preProcessRequest(DelegateExecution execution){
+
+ }
+
+ public void runAppcCommand(DelegateExecution execution) {
+ msoLogger.trace("Start runCommand ")
+ def method = getClass().getSimpleName() + '.runAppcCommand(' +
+ 'execution=' + execution.getId() +
+ ')'
+ msoLogger.trace('Entered ' + method)
+ execution.setVariable("rollbackVnfStop", false)
+ execution.setVariable("rollbackVnfLock", false)
+ execution.setVariable("rollbackQuiesceTraffic", false)
+ String appcCode = "1002"
+ String responsePayload = ""
+ String appcMessage = ""
+ Action action = null
+ try {
+ action = (Action) execution.getVariable("action")
+ String vnfId = execution.getVariable('vnfId')
+ String msoRequestId = execution.getVariable('msoRequestId')
+ String vnfName = execution.getVariable('vnfName')
+ String aicIdentity = execution.getVariable('aicIdentity')
+ String vnfHostIpAddress = execution.getVariable('vnfHostIpAddress')
+ String vmIdList = execution.getVariable("vmIdList")
+ String vserverIdList = execution.getVariable("vserverIdList")
+ String identityUrl = execution.getVariable("identityUrl")
+ String controllerType = execution.getVariable("controllerType")
+ String vfModuleId = execution.getVariable("vfModuleId")
+ HashMap<String, String> payloadInfo = new HashMap<String, String>();
+ payloadInfo.put("vnfName", vnfName)
+ payloadInfo.put("aicIdentity", aicIdentity)
+ payloadInfo.put("vnfHostIpAddress", vnfHostIpAddress)
+ payloadInfo.put("vmIdList", vmIdList)
+ payloadInfo.put("vserverIdList", vserverIdList)
+ payloadInfo.put("identityUrl", identityUrl)
+ payloadInfo.put("vfModuleId",vfModuleId)
+ Optional<String> payload
+ msoLogger.debug("Running APP-C action: " + action.toString())
+ msoLogger.debug("VNFID: " + vnfId)
+ execution.setVariable('msoRequestId', msoRequestId)
+ execution.setVariable("failedActivity", "APP-C")
+ execution.setVariable('workStep', action.toString())
+ if(execution.getVariable("payload") != null){
+ String pay = execution.getVariable("payload")
+ payload = Optional.of(pay)
+ }
+ if(action.equals(Action.HealthCheck)){
+ String healthCheckIndex = execution.getVariable('healthCheckIndex')
+ execution.setVariable('workStep', action.toString() + healthCheckIndex)
+ execution.setVariable('healthCheckIndex', healthCheckIndex + 1)
+ }
+ ApplicationControllerAction client = new ApplicationControllerAction()
+ msoLogger.debug("Created Application Controller Action Object")
+ //PayloadInfo contains extra information that adds on to payload before making request to appc
+ client.runAppCCommand(action, msoRequestId, vnfId, payload, payloadInfo, controllerType)
+ msoLogger.debug("ran through the main method for Application Contoller")
+ appcCode = client.getErrorCode()
+ appcMessage = client.getErrorMessage()
+ }
+ catch (BpmnError e) {
+ msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e);
+ appcMessage = e.getMessage()
+ }
+ execution.setVariable("errorCode", appcCode)
+ if (appcCode == '0' && action != null) {
+ if (action.equals(Action.Lock)) {
+ execution.setVariable("rollbackVnfLock", true)
+ }
+ if (action.equals(Action.Unlock)) {
+ execution.setVariable("rollbackVnfLock", false)
+ }
+ if (action.equals(Action.Start)) {
+ execution.setVariable("rollbackVnfStop", true)
+ }
+ if (action.equals(Action.Stop)) {
+ execution.setVariable("rollbackVnfStop", false)
+ }
+ if (action.equals(Action.QuiesceTraffic)) {
+ execution.setVariable("rollbackQuiesceTraffic", true)
+ }
+ if (action.equals(Action.ResumeTraffic)) {
+ execution.setVariable("rollbackQuiesceTraffic", false)
+ }
+ }
+ execution.setVariable("errorText", appcMessage)
+ execution.setVariable("responsePayload", responsePayload)
+ msoLogger.debug("Error Message: " + appcMessage)
+ msoLogger.debug("ERROR CODE: " + execution.getVariable("errorCode"))
+ msoLogger.trace("End of runCommand ")
+ }
+}
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
new file mode 100644
index 0000000000..9ce29dedb8
--- /dev/null
+++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/CatalogDbUtils.groovy
@@ -0,0 +1,1311 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.so.bpmn.common.scripts
+
+import 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.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.onap.so.logger.MessageEnum
+
+
+
+/***
+ * Utilities for accessing Catalog DB Adapter to retrieve Networks, VNF/VFModules, AllottedResources and complete ServiceResources information
+ *
+ */
+
+class CatalogDbUtils {
+ private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, CatalogDbUtils.class);
+
+
+ MsoUtils utils = new MsoUtils()
+ JsonUtils jsonUtils = new 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
+ }
+
+ public JSONArray getAllVnfsByVnfModelCustomizationUuid(DelegateExecution execution, String vnfModelCustomizationUuid, String catalogUtilsVersion) {
+ 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) {
+ 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
+ }
+
+ /**
+ * 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")
+ try {
+ String catalogDbResponse = getResponseFromCatalogDb(execution, endPoint)
+
+ if (catalogDbResponse != null) {
+ if (!catalogUtilsVersion.equals("v1")) {
+ resources = new JSONObject(catalogDbResponse)
+ }
+ else {
+ resources = parseServiceResourcesJson(catalogDbResponse, catalogUtilsVersion)
+ }
+ }
+ }
+ 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);
+ throw e
+ }
+
+ return resources
+ }
+
+ 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
+ }
+
+ }
+ 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) {
+ JSONObject resources = null
+ String endPoint = "/serviceResources?serviceModelInvariantUuid=" + UriUtils.encode(serviceModelInvariantUuid, "UTF-8")
+ try {
+ String catalogDbResponse = getResponseFromCatalogDb(execution, endPoint)
+
+ if (catalogDbResponse != null) {
+ if (!catalogUtilsVersion.equals("v1")) {
+ resources = new JSONObject(catalogDbResponse)
+ }
+ else {
+ resources = parseServiceResourcesJson(catalogDbResponse, 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 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")
+ try {
+ String catalogDbResponse = getResponseFromCatalogDb(execution, endPoint)
+
+ if (catalogDbResponse != null) {
+ if (!catalogUtilsVersion.equals("v1")) {
+ resources = new JSONObject(catalogDbResponse)
+ }
+ else {
+ resources = parseServiceResourcesJson(catalogDbResponse, 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 resources
+ }
+
+
+
+ private JSONArray parseNetworksJson (String catalogDbResponse, String arrayName, String catalogUtilsVersion) {
+ JSONArray modelInfos = null
+
+ msoLogger.debug("parseNetworksJson - catalogUtilsVersion is " + catalogUtilsVersion)
+ try {
+ // Create array of jsons
+
+ JSONObject responseJson = new JSONObject(catalogDbResponse)
+ JSONArray networks = responseJson.getJSONArray(arrayName)
+ modelInfos = new JSONArray()
+
+ for (int i = 0; i < networks.length(); i++) {
+
+ JSONObject network = networks.getJSONObject(i)
+ JSONObject modelJson = new JSONObject()
+ JSONObject modelInfo = buildModelInfo("network", network, catalogUtilsVersion)
+ modelJson.put("modelInfo", modelInfo)
+ String networkType = jsonUtils.getJsonValueForKey(network, "networkType")
+ modelJson.put("networkType", networkType)
+
+ switch (catalogUtilsVersion) {
+ case "v1":
+ break
+ default:
+ String toscaNodeType = jsonUtils.getJsonValueForKey(network, "toscaNodeType")
+ modelJson.put("toscaNodeType", toscaNodeType)
+ String networkTechnology = jsonUtils.getJsonValueForKey(network, "networkTechnology")
+ modelJson.put("networkTechnology", networkTechnology)
+ String networkRole = jsonUtils.getJsonValueForKey(network, "networkRole")
+ modelJson.put("networkRole", networkRole)
+ String networkScope = jsonUtils.getJsonValueForKey(network, "networkScope")
+ modelJson.put("networkScope", networkScope)
+ break
+ }
+ modelInfos.put(modelJson)
+ }
+
+ String modelInfosString = modelInfos.toString()
+ msoLogger.debug("Returning networks JSON: " + modelInfosString)
+
+ } 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 modelInfos
+ }
+
+ private JSONArray parseVnfsJson (String catalogDbResponse, String arrayName, String catalogUtilsVersion) {
+ JSONArray modelInfos = null
+
+ msoLogger.debug("parseVnfsJson - catalogUtilsVersion is " + catalogUtilsVersion)
+
+ try {
+ // Create array of jsons
+
+ JSONObject responseJson = new JSONObject(catalogDbResponse)
+ JSONArray vnfs = responseJson.getJSONArray(arrayName)
+ modelInfos = new JSONArray()
+
+ for (int i = 0; i < vnfs.length(); i++) {
+ JSONObject vnf = vnfs.getJSONObject(i)
+
+ msoLogger.debug(vnf.toString(2))
+ JSONObject modelInfo = buildModelInfo("vnf", vnf, catalogUtilsVersion)
+ JSONObject modelJson = new JSONObject()
+ modelJson.put("modelInfo", modelInfo)
+ switch(catalogUtilsVersion) {
+ case "v1":
+ break
+ default:
+ String toscaNodeType = jsonUtils.getJsonValueForKey(vnf, "toscaNodeType")
+ modelJson.put("toscaNodeType", toscaNodeType)
+ String nfType = jsonUtils.getJsonValueForKey(vnf, "nfType")
+ modelJson.put("nfType", nfType)
+ String nfRole = jsonUtils.getJsonValueForKey(vnf, "nfRole")
+ modelJson.put("nfRole", nfRole)
+ String nfCode = jsonUtils.getJsonValueForKey(vnf, "nfCode")
+ modelJson.put("nfNamingCode", nfCode)
+ String nfFunction = jsonUtils.getJsonValueForKey(vnf, "nfFunction")
+ modelJson.put("nfFunction", nfFunction)
+ String multiStageDesign = jsonUtils.getJsonValueForKey(vnf, "multiStageDesign")
+ modelJson.put("multiStageDesign", multiStageDesign)
+ break
+ }
+
+ JSONArray vfModules = null
+ try {
+ vfModules = vnf.getJSONArray("vfModules")
+ } catch (Exception e)
+ {
+ msoLogger.debug("Cannot find VF MODULE ARRAY: " + i + ", exception is " + e.message)
+ }
+
+ if (vfModules != null) {
+ JSONArray vfModuleInfo = new JSONArray()
+ for (int j = 0; j < vfModules.length(); j++) {
+ JSONObject vfModule = vfModules.getJSONObject(j)
+ JSONObject vfModuleModelInfo = buildModelInfo("vfModule", vfModule, catalogUtilsVersion)
+ JSONObject vfModuleModelJson = new JSONObject()
+ 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
+ }
+ String vfModuleLabel = jsonUtils.getJsonValueForKey(vfModule, "label")
+ vfModuleModelJson.put("vfModuleLabel", vfModuleLabel)
+ Integer initialCount = jsonUtils.getJsonIntValueForKey(vfModule, "initialCount")
+ vfModuleModelJson.put("initialCount", initialCount.intValue())
+ vfModuleInfo.put(vfModuleModelJson)
+ }
+ modelJson.put("vfModules", vfModuleInfo)
+ }
+ modelInfos.put(modelJson)
+ }
+
+ String modelInfosString = modelInfos.toString()
+ msoLogger.debug("Returning vnfs JSON: " + modelInfosString)
+
+ } 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 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
+
+ msoLogger.debug("parseAllottedResourcesJson - catalogUtilsVersion is " + catalogUtilsVersion)
+
+ try {
+ // Create array of jsons
+
+ JSONObject responseJson = new JSONObject(catalogDbResponse)
+ JSONArray allottedResources = responseJson.getJSONArray(arrayName)
+ modelInfos = new JSONArray()
+
+ for (int i = 0; i < allottedResources.length(); i++) {
+ JSONObject allottedResource = allottedResources.getJSONObject(i)
+ JSONObject modelInfo = buildModelInfo("allottedResource", allottedResource, catalogUtilsVersion)
+ JSONObject modelJson = new JSONObject()
+ modelJson.put("modelInfo", modelInfo)
+ switch(catalogUtilsVersion) {
+ case "v1":
+ break
+ default:
+ String toscaNodeType = jsonUtils.getJsonValueForKey(allottedResource, "toscaNodeType")
+ modelJson.put("toscaNodeType", toscaNodeType)
+ String nfType = jsonUtils.getJsonValueForKey(allottedResource, "nfType")
+ modelJson.put("nfType", nfType)
+ String nfRole = jsonUtils.getJsonValueForKey(allottedResource, "nfRole")
+ modelJson.put("nfRole", nfRole)
+ String nfCode = jsonUtils.getJsonValueForKey(allottedResource, "nfCode")
+ modelJson.put("nfNamingCode", nfCode)
+ String nfFunction = jsonUtils.getJsonValueForKey(allottedResource, "nfFunction")
+ modelJson.put("nfFunction", nfFunction)
+ String providingServiceModelName = jsonUtils.getJsonValueForKey(allottedResource, "providingServiceModelName")
+ modelJson.put("providingServiceModelName", providingServiceModelName)
+ String providingServiceModelUuid = jsonUtils.getJsonValueForKey(allottedResource, "providingServiceModelUuid")
+ modelJson.put("providingServiceModelUuid", providingServiceModelUuid)
+ break
+ }
+
+
+ modelInfos.put(modelJson)
+ }
+
+ String modelInfosString = modelInfos.toString()
+ msoLogger.debug("Returning allottedResources JSON: " + modelInfosString)
+
+ } 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 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
+
+ JSONObject responseJson = new JSONObject(catalogDbResponse)
+ JSONObject serviceResourcesRoot = responseJson.getJSONObject("serviceResources")
+ JSONObject modelInfo = buildModelInfo("", serviceResourcesRoot, catalogUtilsVersion)
+ serviceResources.put("modelInfo", modelInfo)
+ JSONArray vnfsArray = parseVnfsJson(serviceResourcesRoot.toString(), "serviceVnfs", catalogUtilsVersion)
+ serviceResources.put("serviceVnfs", vnfsArray)
+ JSONArray networksArray = parseNetworksJson(serviceResourcesRoot.toString(), "serviceNetworks", catalogUtilsVersion)
+ serviceResources.put("serviceNetworks", networksArray)
+ JSONArray allottedResourcesArray = parseAllottedResourcesJson(serviceResourcesRoot.toString(), "serviceAllottedResources", catalogUtilsVersion)
+ serviceResources.put("serviceAllottedResources", allottedResourcesArray)
+ serviceResourcesObject.put("serviceResources", serviceResources)
+
+ serviceResourcesString = serviceResourcesObject.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 serviceResourcesObject
+ }
+
+ private JSONObject buildModelInfo(String modelType, JSONObject modelFromDb, String catalogUtilsVersion) {
+ JSONObject modelInfo = null
+ try {
+ modelInfo = new JSONObject()
+ modelInfo.put("modelType", modelType)
+ String modelInvariantId = jsonUtils.getJsonValueForKey(modelFromDb, "modelInvariantUuid")
+ modelInfo.put("modelInvariantId", modelInvariantId)
+ if(modelType.equalsIgnoreCase("allottedResource") || modelType.equalsIgnoreCase("vnf")){
+ String modelInstanceName = jsonUtils.getJsonValueForKey(modelFromDb, "modelInstanceName")
+ modelInfo.put("modelInstanceName", modelInstanceName)
+ }
+ if ((!"vfModule".equals(modelType) && !"vnf".equals(modelType)) || !catalogUtilsVersion.equals("v1")) {
+ String modelVersionId = jsonUtils.getJsonValueForKey(modelFromDb, "modelUuid")
+ modelInfo.put("modelVersionId", modelVersionId)
+ }
+ else {
+ String modelVersionId = jsonUtils.getJsonValueForKey(modelFromDb, "asdcUuid")
+ modelInfo.put("modelVersionId", modelVersionId)
+ }
+ String modelName = jsonUtils.getJsonValueForKey(modelFromDb, "modelName")
+ modelInfo.put("modelName", modelName)
+ String modelVersion = jsonUtils.getJsonValueForKey(modelFromDb, "modelVersion")
+ modelInfo.put("modelVersion", modelVersion)
+ if (!"vfModule".equals(modelType)) {
+ String modelCustomizationName = jsonUtils.getJsonValueForKey(modelFromDb, "modelCustomizationName")
+ modelInfo.put("modelCustomizationName", modelCustomizationName)
+ }
+ String modelCustomizationId = jsonUtils.getJsonValueForKey(modelFromDb, "modelCustomizationUuid")
+ switch (catalogUtilsVersion) {
+ case "v1":
+ modelInfo.put("modelCustomizationId", modelCustomizationId)
+ break
+ default:
+ modelInfo.put("modelCustomizationUuid", modelCustomizationId)
+ break
+ }
+ JSONObject modelJson = new JSONObject()
+ modelJson.put("modelInfo", modelInfo)
+ }
+ catch (Exception e) {
+ msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception while parsing model information", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, e.message);
+ }
+ return modelInfo
+ }
+
+ private String getResponseFromCatalogDb (DelegateExecution execution, String endPoint) {
+ try {
+
+ 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');
+
+ String basicAuthCred = execution.getVariable("BasicAuthHeaderValueDB")
+ if (basicAuthCred != null && !"".equals(basicAuthCred)) {
+ client.addAuthorizationHeader(basicAuthCred)
+ }else {
+ client.addAuthorizationHeader(getBasicDBAuthHeader(execution))
+ }
+ msoLogger.debug('sending GET to Catalog DB endpoint: ' + endPoint)
+ APIResponse response = client.httpGet()
+
+ responseData = response.getResponseBodyAsString()
+ if (responseData != null) {
+ msoLogger.debug("Received data from Catalog DB: " + responseData)
+ }
+
+ msoLogger.debug('Response code:' + response.getStatusCode())
+ msoLogger.debug('Response:' + System.lineSeparator() + responseData)
+ if (response.getStatusCode() == 200) {
+ // parse response as needed
+ return responseData
+ }
+ else {
+ return null
+ }
+ }
+ catch (Exception e) {
+ msoLogger.debug("ERROR WHILE QUERYING CATALOG DB: " + e.message)
+ throw e
+ }
+
+ }
+
+ /**
+ * get resource recipe by resource model uuid and action
+ */
+ public JSONObject getResourceRecipe(DelegateExecution execution, String resourceModelUuid, String action) {
+ String endPoint = "/resourceRecipe?resourceModelUuid=" + UriUtils.encode(resourceModelUuid, "UTF-8")+ "&action=" + UriUtils.encode(action, "UTF-8")
+ JSONObject responseJson = null
+ try {
+ msoLogger.debug("ENDPOINT: " + endPoint)
+ String catalogDbResponse = getResponseFromCatalogDb(execution, endPoint)
+
+ if (catalogDbResponse != null) {
+ responseJson = new JSONObject(catalogDbResponse)
+ }
+ }
+ catch (Exception e) {
+ utils.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))
+ execution.setVariable("BasicAuthHeaderValueDB",encodedString)
+ } catch (IOException ex) {
+ String dataErrorMessage = " Unable to encode Catalog DB user/password string - " + ex.getMessage()
+ utils.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/CompleteMsoProcess.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/CompleteMsoProcess.groovy
new file mode 100644
index 0000000000..9c4c73fb7d
--- /dev/null
+++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/CompleteMsoProcess.groovy
@@ -0,0 +1,311 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.so.bpmn.common.scripts
+
+import org.apache.commons.lang3.*
+import org.camunda.bpm.engine.delegate.BpmnError
+import org.camunda.bpm.engine.delegate.DelegateExecution
+import org.onap.so.logger.MessageEnum
+import org.onap.so.logger.MsoLogger
+
+public class CompleteMsoProcess extends AbstractServiceTaskProcessor {
+ private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, CompleteMsoProcess.class);
+
+ String Prefix="CMSO_"
+ ExceptionUtil exceptionUtil = new ExceptionUtil()
+
+ // Complete MSO Request processing
+ public initializeProcessVariables(DelegateExecution execution){
+
+ def method = getClass().getSimpleName() + '.initializeProcessVariables(' +'execution=' + execution.getId() +')'
+ msoLogger.trace('Entered ' + method)
+ try {
+
+ /* Initialize all the process request variables in this block */
+ execution.setVariable("prefix",Prefix)
+ execution.setVariable("CMSO_request_id","")
+ execution.setVariable("CMSO_notification-url","")
+ execution.setVariable("CMSO_mso-bpel-name","")
+ execution.setVariable("CMSO_request_action","")
+ execution.setVariable("CMSO_notification-url-Ok", false)
+ execution.setVariable("CMSO_request_id-Ok", false)
+
+ //updateRequest Adapter process variables
+ execution.setVariable("CMSO_updateRequestResponse", "")
+ execution.setVariable("CMSO_updateRequestResponseCode", "")
+ execution.setVariable("CMSO_updateFinalNotifyAckStatusFailedPayload", "")
+
+ //Set DB adapter variables here
+ execution.setVariable("CMSO_updateDBStatusToSuccessPayload", "")
+ execution.setVariable("CMSO_updateInfraRequestDBPayload", "")
+ execution.setVariable("CMSO_setUpdateDBstatustoSuccessPayload", "")
+
+ //Auth variables
+ execution.setVariable("BasicAuthHeaderValue","")
+
+ //Response variables
+ execution.setVariable("CompletionHandlerResponse","")
+ execution.setVariable("CMSO_ErrorResponse", null)
+ execution.setVariable("CMSO_ResponseCode", "")
+
+ setSuccessIndicator(execution, false)
+
+ } catch (BpmnError e) {
+ throw e;
+ } catch (Exception e) {
+ msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e);
+ exceptionUtil.buildAndThrowWorkflowException(execution, 2000, "Internal Error - Occured in" + method)
+ }
+
+ }
+
+ public void preProcessRequest (DelegateExecution execution) {
+
+ initializeProcessVariables(execution)
+ def method = getClass().getSimpleName() + '.preProcessRequest(' +'execution=' + execution.getId() +')'
+ // msoLogger.trace("Started CompleteMsoProcess preProcessRequest Method ");
+ msoLogger.trace('Entered ' + method)
+
+ setBasicDBAuthHeader(execution, execution.getVariable('isDebugLogEnabled'))
+
+ try {
+ def xml = execution.getVariable("CompleteMsoProcessRequest")
+
+ msoLogger.debug("CompleteMsoProcess Request: " + xml)
+ msoLogger.debug("Incoming Request is: "+ xml)
+
+ //mso-bpel-name from the incoming request
+ def msoBpelName = utils.getNodeText(xml,"mso-bpel-name")
+ execution.setVariable("CMSO_mso-bpel-name",msoBpelName)
+
+ //Check the incoming request type
+ //Incoming request can be ACTIVE_REQUESTS (request-information node) or INFRA_ACTIVE_REQUESTS (request-info node)
+ if (utils.nodeExists(xml, "request-information")) {
+ execution.setVariable("CMSO_request_id-Ok", true) // Incoming request is for ACTIVE_REQUESTS
+ }
+
+ //Check for rehome indicator
+ def rehomeIndicator = utils.getNodeText(xml,"rehomeDone")
+ execution.setVariable("rehomeDone", rehomeIndicator)
+
+ //Check notification-url for the incoming request type
+ //ACTIVE_REQUESTS may have notificationurl node
+ //INFRA_ACTIVE_REQUESTS notificationurl node does not exist
+ def notificationurl = ""
+ if (utils.nodeExists(xml, "notification-url")) {
+ notificationurl = utils.getNodeText(xml,"notification-url")
+ if(notificationurl != null && !notificationurl.isEmpty()) {
+ execution.setVariable("CMSO_notification-url-Ok", true)
+ execution.setVariable("CMSO_notification-url",notificationurl)
+ }
+ }
+
+ //Check request_id for the incoming request type
+ //For INFRA_ACTIVE_REQUESTS payload request-id IS optional (Not sure why this is option since req id is primary key ... also tried exe through SOAP UI to check if MSO code handles null like auto generated seq not it does not)
+ //For ACTIVE_REQUESTS payload request-id is NOT optional
+ def request_id = ""
+ if (utils.nodeExists(xml, "request-id")) {
+ execution.setVariable("CMSO_request_id",utils.getNodeText(xml,"request-id"))
+ }
+
+
+ // INFRA_ACTIVE_REQUESTS have "action" element ... mandatory
+ // ACTIVE_REQUEST have "request-action" ... mandatory
+ if (utils.nodeExists(xml, "request-action")) {
+ execution.setVariable("CMSO_request_action",utils.getNodeText(xml,"request-action"))
+ } else if (utils.nodeExists(xml, "action")) {
+ execution.setVariable("CMSO_request_action",utils.getNodeText(xml,"action"))
+ }
+
+ //Check source for the incoming request type
+ //For INFRA_ACTIVE_REQUESTS payload source IS optional
+ //For ACTIVE_REQUESTS payload source is NOT optional
+ def source = ""
+ if (utils.nodeExists(xml, "source")) {
+ execution.setVariable("CMSO_source",utils.getNodeText(xml,"source"))
+ }
+
+ msoLogger.trace("--> " + execution.getVariable(""))
+ msoLogger.trace("--> " + execution.getVariable(""))
+
+ // set the DHV/Service Instantiation values if specified in the request
+ execution.setVariable("CMSO_is_srv_inst_req", String.valueOf("true".equals(utils.getNodeText(xml, "is-srv-inst-req"))))
+ msoLogger.trace("--> " + execution.getVariable(""))
+ execution.setVariable("CMSO_is_json_content", String.valueOf("JSON".equals(utils.getNodeText(xml, "resp-content-type"))))
+ msoLogger.trace("--> " + execution.getVariable(""))
+ execution.setVariable("CMSO_service_inst_id", utils.getNodeText(xml, "service-instance-id"))
+ msoLogger.trace("--> " + execution.getVariable(""))
+ execution.setVariable("CMSO_start_time", utils.getNodeText(xml, "start-time"))
+ msoLogger.trace("--> " + execution.getVariable(""))
+ // this variable is used by the camunda flow to set the Content-Type for the async response
+ if (execution.getVariable("CMSO_is_srv_inst_req").equals("true") &&
+ execution.getVariable("CMSO_is_json_content").equals("true")) {
+ execution.setVariable("CMSO_content_type", "application/json")
+ } else {
+ execution.setVariable("CMSO_content_type", "text/xml")
+ }
+
+ msoLogger.trace('Exited ' + method)
+ } catch (BpmnError e) {
+ throw e;
+ } catch (Exception e) {
+ msoLogger.debug("Exception Occured During PreProcessRequest: " + e);
+ exceptionUtil.buildAndThrowWorkflowException(execution, 2000, "Internal Error - Occured in " + method)
+ }
+
+// msoLogger.trace("Completed CompleteMsoProcess preProcessRequest Method ");
+ }
+
+ public void setUpdateDBstatustoSuccessPayload (DelegateExecution execution){
+
+ def method = getClass().getSimpleName() + '.setUpdateDBstatustoSuccessPayload(' +'execution=' + execution.getId() +')'
+ msoLogger.trace('Entered ' + method)
+
+ try {
+
+ def xml = execution.getVariable("CompleteMsoProcessRequest")
+
+ //Get statusMessage if exists
+ def statusMessage
+ if(utils.nodeExists(xml, "status-message")){
+ statusMessage = utils.getNodeText(xml, "status-message")
+ }else{
+ statusMessage = "Resource Completed Successfully"
+ }
+
+ //Get instance Id if exist
+ String idXml = ""
+ if(utils.nodeExists(xml, "vnfId")){
+ idXml = utils.getNodeXml(xml, "vnfId")
+ }else if(utils.nodeExists(xml, "networkId")){
+ idXml = utils.getNodeXml(xml, "networkId")
+ }else if(utils.nodeExists(xml, "configurationId")){
+ idXml = utils.getNodeXml(xml, "configurationId")
+ }else if(utils.nodeExists(xml, "serviceInstanceId")){
+ idXml = utils.getNodeXml(xml, "serviceInstanceId")
+ }else if(utils.nodeExists(xml, "vfModuleId")){
+ idXml = utils.getNodeXml(xml, "vfModuleId")
+ }else if(utils.nodeExists(xml, "volumeGroupId")){
+ idXml = utils.getNodeXml(xml, "volumeGroupId")
+ }else{
+ idXml = ""
+ }
+ idXml = utils.removeXmlPreamble(idXml)
+ msoLogger.debug("Incoming Instance Id Xml: " + idXml)
+
+ String payload = """
+ <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:req="http://org.onap.so/requestsdb">
+ <soapenv:Header/>
+ <soapenv:Body>
+ <req:updateInfraRequest>
+ <requestId>${MsoUtils.xmlEscape(execution.getVariable("CMSO_request_id"))}</requestId>
+ <lastModifiedBy>${MsoUtils.xmlEscape(execution.getVariable("CMSO_mso-bpel-name"))}</lastModifiedBy>
+ <statusMessage>${MsoUtils.xmlEscape(statusMessage)}</statusMessage>
+ <requestStatus>COMPLETE</requestStatus>
+ <progress>100</progress>
+ ${idXml}
+ </req:updateInfraRequest>
+ </soapenv:Body>
+ </soapenv:Envelope>"""
+
+ execution.setVariable("CMSO_setUpdateDBstatustoSuccessPayload", payload)
+ msoLogger.debug("Outgoing Update Mso Request Payload is: " + payload)
+ msoLogger.debug("setUpdateDBstatustoSuccessPayload: " + payload)
+
+ } catch (BpmnError e) {
+ throw e;
+ } catch (Exception e) {
+ msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e);
+ exceptionUtil.buildAndThrowWorkflowException(execution, 2000, "Internal Error - Occured in" + method)
+ }
+ msoLogger.trace('Exited ' + method)
+ }
+
+ public void buildDataError (DelegateExecution execution, String message) {
+
+ def method = getClass().getSimpleName() + '.buildDataError(' +'execution=' + execution.getId() +')'
+ msoLogger.trace('Entered ' + method)
+ try {
+
+ def 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>
+ """.trim()
+
+ // Format Response
+ def xmlMsoCompletionResponse = utils.formatXml(msoCompletionResponse)
+ String buildMsoCompletionResponseAsString = xmlMsoCompletionResponse.drop(38).trim()
+ msoLogger.debug("CompleteMsoProcess Response: " + buildMsoCompletionResponseAsString)
+ execution.setVariable("CompleteMsoProcessResponse", buildMsoCompletionResponseAsString)
+ msoLogger.debug("@@ CompleteMsoProcess Response @@ " + "\n" + execution.getVariable("CompletionHandlerResponse"))
+
+ exceptionUtil.buildAndThrowWorkflowException(execution, 500, message)
+
+ } catch (BpmnError e) {
+ msoLogger.debug("Rethrowing MSOWorkflowException")
+ throw e;
+ } catch (Exception e) {
+ msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e);
+ exceptionUtil.buildAndThrowWorkflowException(execution, 2000, "Internal Error - Occured in" + method)
+ }
+
+ }
+
+ public void postProcessResponse (DelegateExecution execution) {
+
+ def method = getClass().getSimpleName() + '.postProcessResponse(' +'execution=' + execution.getId() +')'
+ msoLogger.trace('Entered ' + method)
+ // msoLogger.trace("Started CompleteMsoProcess PostProcessRequest Method ");
+ try {
+
+ def 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>
+ """.trim()
+
+ // Format Response
+ def xmlMsoCompletionResponse = utils.formatXML(msoCompletionResponse)
+ String buildMsoCompletionResponseAsString = xmlMsoCompletionResponse.drop(38).trim()
+ // TODO: Should deprecate use of processKey+Response variable for the response. Will use "WorkflowResponse" instead
+ execution.setVariable("WorkflowResponse", buildMsoCompletionResponseAsString)
+ msoLogger.debug("CompleteMsoProcess Response: " + buildMsoCompletionResponseAsString)
+ execution.setVariable("CompleteMsoProcessResponse", buildMsoCompletionResponseAsString)
+ execution.setVariable("CMSO_ResponseCode", "200")
+
+ setSuccessIndicator(execution, true)
+
+ msoLogger.debug("@@ CompleteMsoProcess Response @@ " + "\n" + execution.getVariable("CompleteMsoProcessResponse"))
+
+ msoLogger.trace('Exited ' + method)
+ } catch (BpmnError e) {
+ throw e;
+ } catch (Exception e) {
+ msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e);
+ exceptionUtil.buildAndThrowWorkflowException(execution, 2000, "Internal Error - Occured in" + method)
+ }
+ // msoLogger.trace("Completed CompleteMsoProcess PostProcessRequest Method ");
+
+ }
+
+
+}
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
new file mode 100644
index 0000000000..8b786bc152
--- /dev/null
+++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/ConfirmVolumeGroupName.groovy
@@ -0,0 +1,152 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.so.bpmn.common.scripts
+import org.camunda.bpm.engine.delegate.DelegateExecution
+import org.onap.so.bpmn.core.UrnPropertiesReader
+import org.onap.so.rest.APIResponse
+import org.onap.so.logger.MessageEnum
+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()
+
+ public void initProcessVariables(DelegateExecution execution) {
+ execution.setVariable("prefix",Prefix)
+ execution.setVariable("CVGN_volumeGroupId",null)
+ execution.setVariable("CVGN_volumeGroupName",null)
+ execution.setVariable("CVGN_aicCloudRegion", null)
+ execution.setVariable("CVGN_volumeGroupGetEndpoint",null)
+
+ // ConfirmVolumeGroupName workflow response variable placeholders
+ execution.setVariable("CVGN_volumeGroupNameMatches", false)
+ execution.setVariable("CVGN_queryVolumeGroupResponseCode",null)
+ execution.setVariable("CVGN_queryVolumeGroupResponse","")
+ execution.setVariable("CVGN_ResponseCode",null)
+// execution.setVariable("CVGN_ErrorResponse","")
+ execution.setVariable("RollbackData", null)
+ }
+
+ // store the incoming data in the flow DelegateExecution
+ public void preProcessRequest(DelegateExecution execution) {
+ def volumeGroupId = execution.getVariable("ConfirmVolumeGroupName_volumeGroupId")
+ def volumeGroupName= execution.getVariable("ConfirmVolumeGroupName_volumeGroupName")
+ def aicCloudRegion = execution.getVariable("ConfirmVolumeGroupName_aicCloudRegion")
+
+ initProcessVariables(execution)
+ execution.setVariable("CVGN_volumeGroupId", volumeGroupId)
+ execution.setVariable("CVGN_volumeGroupName", volumeGroupName)
+ execution.setVariable("CVGN_aicCloudRegion", aicCloudRegion)
+
+ AaiUtil aaiUriUtil = new AaiUtil(this)
+ def aai_uri = aaiUriUtil.getCloudInfrastructureCloudRegionUri(execution)
+ msoLogger.debug('AAI URI is: ' + aai_uri)
+ msoLogger.debug("AAI URI: " + aai_uri)
+ execution.setVariable("CVGN_volumeGroupGetEndpoint","${aai_uri}/${aicCloudRegion}/volume-groups/volume-group/" +
+ volumeGroupId)
+ }
+
+ // send a GET request to AA&I to retrieve the Volume information based on volume-group-id
+ // expect a 200 response with the information in the response body or a 404 if the volume group id does not exist
+ public void queryAAIForVolumeGroupId(DelegateExecution execution) {
+ def endPoint = UrnPropertiesReader.getVariable("aai.endpoint", execution) + execution.getVariable("CVGN_volumeGroupGetEndpoint")
+
+ try {
+ msoLogger.debug("invoking GET call to AAI endpoint :"+System.lineSeparator()+endPoint)
+ msoLogger.debug("queryAAIForVolumeGroupId() endpoint-" + endPoint)
+ msoLogger.debug("ConfirmVolumeGroup sending GET call to AAI Endpoint: " + endPoint)
+
+ AaiUtil aaiUtil = new AaiUtil(this)
+ APIResponse response = aaiUtil.executeAAIGetCall(execution, endPoint)
+ def responseData = response.getResponseBodyAsString()
+ def responseStatusCode = response.getStatusCode()
+ execution.setVariable("CVGN_queryVolumeGroupResponseCode", responseStatusCode)
+ execution.setVariable("CVGN_queryVolumeGroupResponse", responseData)
+
+ msoLogger.debug("Response code:" + responseStatusCode)
+ msoLogger.debug("Response:" + responseData)
+ msoLogger.debug("Response code:" + responseStatusCode)
+ msoLogger.debug("Response:" + System.lineSeparator()+responseData)
+ } catch (Exception ex) {
+ // ex.printStackTrace()
+ msoLogger.debug("Exception occurred while executing AAI GET:" + ex.getMessage())
+ execution.setVariable("CVGN_queryVolumeGroupResponseCode", 500)
+ execution.setVariable("CVGN_queryVolumeGroupResponse", "AAI GET Failed:" + ex.getMessage())
+ exceptionUtil.buildAndThrowWorkflowException(execution, 500, "AAI GET Failed")
+ }
+ }
+
+ // process the result from queryAAIVolumeGroupId()
+
+ public void checkAAIQueryResult(DelegateExecution execution) {
+ def result = execution.getVariable("CVGN_queryVolumeGroupResponse")
+
+ if (execution.getVariable("CVGN_queryVolumeGroupResponseCode") == 404) {
+ msoLogger.debug('volumeGroupId does not exist in AAI')
+ }
+ else if (execution.getVariable("CVGN_queryVolumeGroupResponseCode") == 200) {
+ msoLogger.debug("volumeGroupId exists in AAI")
+ }
+ def xml = execution.getVariable("CVGN_queryVolumeGroupResponse")
+ def actualVolumeGroupName = ""
+ if (utils.nodeExists(xml, "volume-group-name")) {
+ actualVolumeGroupName = utils.getNodeText(xml, "volume-group-name")
+ }
+ execution.setVariable("CVGN_volumeGroupNameMatches", false)
+ def volumeGroupName = execution.getVariable("CVGN_volumeGroupName")
+
+ if (volumeGroupName.equals(actualVolumeGroupName)) {
+ msoLogger.debug('Volume Group Name Matches AAI records')
+ execution.setVariable("CVGN_volumeGroupNameMatches", true)
+ }
+ }
+
+
+ // generates a WorkflowException if the A&AI query returns a response code other than 200/404
+ public void handleAAIQueryFailure(DelegateExecution execution) {
+ msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Error occurred attempting to query AAI, Response Code " + execution.getVariable("CVGN_queryVolumeGroupResponseCode"), "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "ErrorResponse is:\n" + execution.getVariable("CVGN_queryVolumeGroupResponse"));
+ //String processKey = getProcessKey(execution);
+ //WorkflowException exception = new WorkflowException(processKey, 5000,
+ //execution.getVariable("CVGN_queryVolumeGroupResponse"))
+ //execution.setVariable("WorkflowException", exception)
+ }
+
+ // 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")
+ msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, errorNotAssociated, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "");
+ exceptionUtil.buildAndThrowWorkflowException(execution, 1002, errorNotAssociated)
+ //String processKey = getProcessKey(execution);
+ //WorkflowException exception = new WorkflowException(processKey, 1002,
+ // errorNotAssociated)
+ //execution.setVariable("WorkflowException", exception)
+ }
+
+ // sends a successful WorkflowResponse
+ public void reportSuccess(DelegateExecution execution) {
+ msoLogger.debug("Sending 200 back to the caller")
+ def responseXML = ""
+ execution.setVariable("WorkflowResponse", responseXML)
+ }
+} \ No newline at end of file
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
new file mode 100644
index 0000000000..c0ed81c553
--- /dev/null
+++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/ConfirmVolumeGroupTenant.groovy
@@ -0,0 +1,193 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.so.bpmn.common.scripts
+
+import 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
+
+/**
+ * Vnf Module Subflow for confirming the volume group belongs
+ * to the tenant
+ *
+ * @param tenantId
+ * @param volumeGroupId
+ *
+ */
+class ConfirmVolumeGroupTenant extends AbstractServiceTaskProcessor{
+ private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, ConfirmVolumeGroupTenant.class);
+
+ String Prefix="CVGT_"
+ ExceptionUtil exceptionUtil = new ExceptionUtil()
+
+ 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")
+ String aai = UrnPropertiesReader.getVariable("aai.endpoint", execution)
+
+ AaiUtil aaiUriUtil = new AaiUtil(this)
+ def aai_uri = aaiUriUtil.getCloudInfrastructureCloudRegionUri(execution)
+ msoLogger.debug('AAI URI is: ' + aai_uri)
+
+ String path = aai + "${aai_uri}/${aicCloudRegion}/volume-groups/volume-group/" + volumeGroupId
+
+ 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)
+
+ 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()
+ }
+ }
+ }
+ }
+ }
+ }
+
+ //Determine if Tenant Ids match
+ if(incomingTenantId.equals(volumeGroupTenantId)){
+ msoLogger.debug("Tenant Ids Match")
+ execution.setVariable("tenantIdsMatch", true)
+ }else{
+ msoLogger.debug("Tenant Ids DO NOT Match")
+ execution.setVariable("tenantIdsMatch", false)
+ }
+
+ //Determine if Volume Group Names match
+ String volumeGroupName = utils.getNodeText(response, "volume-group-name")
+ if(incomingGroupName == null || incomingGroupName.length() < 1){
+ msoLogger.debug("Incoming Volume Group Name is NOT Provided.")
+ execution.setVariable("groupNamesMatch", true)
+ }else{
+ msoLogger.debug("Incoming Volume Group Name is: " + incomingGroupName)
+ if(volumeGroupName.equals(incomingGroupName)){
+ msoLogger.debug("Volume Group Names Match.")
+ execution.setVariable("groupNamesMatch", true)
+ }else{
+ msoLogger.debug("Volume Group Names DO NOT Match.")
+ execution.setVariable("groupNamesMatch", false)
+ }
+ }
+ }else{
+ msoLogger.debug("QueryAAIForVolumeGroup Bad REST Response!")
+ exceptionUtil.buildAndThrowWorkflowException(execution, 1, "Error Searching AAI for Volume Group. Received a Bad Response.")
+ }
+
+ }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);
+ exceptionUtil.buildAndThrowWorkflowException(execution, 5000, "Internal Error - Occured in preProcessRequest.")
+ }
+ msoLogger.trace("COMPLETED queryAAIForVolumeGroup Process ")
+ }
+
+ public void assignVolumeHeatId(DelegateExecution execution){
+ execution.setVariable("prefix", Prefix)
+ try{
+ msoLogger.trace("Started assignVolumeHeatId Process ")
+
+ String response = execution.getVariable("queryAAIVolumeGroupResponse")
+ String heatStackId = utils.getNodeText(response, "heat-stack-id")
+ execution.setVariable("volumeHeatStackId", heatStackId)
+ execution.setVariable("ConfirmVolumeGroupTenantResponse", heatStackId)
+ // TODO: Should deprecate use of processKey+Response variable for the response. Will use "WorkflowResponse" instead
+ execution.setVariable("WorkflowResponse", heatStackId)
+ msoLogger.debug("Volume Heat Stack Id is: " + heatStackId)
+
+ }catch(Exception e){
+ msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception Occured Processing assignVolumeHeatId.", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, e);
+ exceptionUtil.buildAndThrowWorkflowException(execution, 5000, "Internal Error - Occured in assignVolumeHeatId.")
+ }
+ msoLogger.trace("COMPLETED assignVolumeHeatId Process ")
+ msoLogger.trace("COMPLETED Confirm Volume Group Tenant Subflow ")
+}
+
+ public void assignWorkflowException(DelegateExecution execution, String message){
+ execution.setVariable("prefix", Prefix)
+ String processKey = getProcessKey(execution);
+ msoLogger.trace("STARTED Assign Workflow Exception ")
+ try{
+ String volumeGroupId = execution.getVariable("volumeGroupId")
+ int errorCode = 1
+ String errorMessage = "Volume Group " + volumeGroupId + " " + message
+
+ exceptionUtil.buildWorkflowException(execution, errorCode, errorMessage)
+ }catch(Exception e){
+ msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception Occured Processing assignWorkflowException.", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, e);
+ }
+ msoLogger.trace("COMPLETED Assign Workflow Exception =")
+ }
+
+
+
+}
+
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
new file mode 100644
index 0000000000..84dd70682d
--- /dev/null
+++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/CreateAAIVfModule.groovy
@@ -0,0 +1,612 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.so.bpmn.common.scripts
+import org.camunda.bpm.engine.delegate.DelegateExecution
+import org.onap.so.bpmn.core.RollbackData
+import org.onap.so.bpmn.core.UrnPropertiesReader
+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_"
+ ExceptionUtil exceptionUtil = new ExceptionUtil()
+ public void initProcessVariables(DelegateExecution execution) {
+ execution.setVariable("prefix",Prefix)
+ execution.setVariable("CAAIVfMod_vnfId",null)
+ execution.setVariable("CAAIVfMod_vnfName",null)
+ execution.setVariable("CAAIVfMod_vnfType",null)
+ execution.setVariable("CAAIVfMod_serviceId",null)
+ execution.setVariable("CAAIVfMod_personaId",null)
+ execution.setVariable("CAAIVfMod_personaVer",null)
+ execution.setVariable("CAAIVfMod_modelCustomizationId",null)
+ execution.setVariable("CAAIVfMod_vnfPersonaId",null)
+ execution.setVariable("CAAIVfMod_vnfPersonaVer",null)
+ execution.setVariable("CAAIVfMod_isBaseVfModule", false)
+ execution.setVariable("CAAIVfMod_moduleName",null)
+ execution.setVariable("CAAIVfMod_moduleModelName",null)
+ execution.setVariable("CAAIVfMod_newGenericVnf",false)
+ execution.setVariable("CAAIVfMod_genericVnfGetEndpoint",null)
+ execution.setVariable("CAAIVfMod_genericVnfPutEndpoint",null)
+ execution.setVariable("CAAIVfMod_aaiNamespace",null)
+ execution.setVariable("CAAIVfMod_moduleExists",false)
+ execution.setVariable("CAAIVfMod_baseModuleConflict", false)
+ execution.setVariable("CAAIVfMod_vnfNameFromAAI", null)
+
+
+ // CreateAAIVfModule workflow response variable placeholders
+ execution.setVariable("CAAIVfMod_queryGenericVnfResponseCode",null)
+ execution.setVariable("CAAIVfMod_queryGenericVnfResponse","")
+ execution.setVariable("CAAIVfMod_createGenericVnfResponseCode",null)
+ execution.setVariable("CAAIVfMod_createGenericVnfResponse","")
+ execution.setVariable("CAAIVfMod_createVfModuleResponseCode",null)
+ execution.setVariable("CAAIVfMod_createVfModuleResponse","")
+ execution.setVariable("CAAIVfMod_parseModuleResponse","")
+ execution.setVariable("CAAIVfMod_deleteGenericVnfResponseCode",null)
+ execution.setVariable("CAAIVfMod_deleteGenericVnfResponse","")
+ execution.setVariable("CAAIVfMod_deleteVfModuleResponseCode",null)
+ execution.setVariable("CAAIVfMod_deleteVfModuleResponse","")
+// execution.setVariable("CAAIVfMod_ResponseCode",null)
+// execution.setVariable("CAAIVfMod_ErrorResponse","")
+ execution.setVariable("CreateAAIVfModuleResponse","")
+ execution.setVariable("RollbackData", null)
+
+ }
+
+ // parse the incoming CREATE_VF_MODULE request and store the Generic VNF
+ // and VF Module data in the flow DelegateExecution
+ public void preProcessRequest(DelegateExecution execution) {
+ initProcessVariables(execution)
+
+ def vnfId = execution.getVariable("vnfId")
+ if (vnfId == null || vnfId.isEmpty()) {
+ execution.setVariable("CAAIVfMod_newGenericVnf", true)
+ execution.setVariable("CAAIVfMod_vnfId","")
+ }
+ else {
+ execution.setVariable("CAAIVfMod_vnfId",vnfId)
+ }
+
+ def vnfName = execution.getVariable("vnfName")
+ 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_serviceId", execution.getVariable("serviceId"))
+
+ String personaModelId = execution.getVariable("personaModelId")
+
+ if (personaModelId != null && !personaModelId.isEmpty()) {
+ execution.setVariable("CAAIVfMod_personaId",personaModelId)
+ } else {
+ execution.setVariable("CAAIVfMod_personaId","")
+ }
+
+ String personaModelVersion = execution.getVariable("personaModelVersion")
+
+ if (personaModelVersion != null && !personaModelVersion.isEmpty()) {
+ execution.setVariable("CAAIVfMod_personaVer", personaModelVersion)
+ } else {
+ execution.setVariable("CAAIVfMod_personaVer","")
+ }
+
+
+ String modelCustomizationId = execution.getVariable("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","")
+ }
+
+ String vnfPersonaModelVersion = execution.getVariable("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")
+ if (isBaseVfModuleString != null && isBaseVfModuleString.equals("true")) {
+ isBaseVfModule = true
+ }
+ execution.setVariable("CAAIVfMod_isBaseVfModule", isBaseVfModule)
+
+ String isVidRequest = execution.getVariable("isVidRequest")
+ if (isVidRequest != null && "true".equals(isVidRequest)) {
+ msoLogger.debug("VID Request received")
+ }
+
+ execution.setVariable("CAAIVfMod_moduleName",execution.getVariable("vfModuleName"))
+ execution.setVariable("CAAIVfMod_moduleModelName",execution.getVariable("vfModuleModelName"))
+
+ AaiUtil aaiUriUtil = new AaiUtil(this)
+ def aai_uri = aaiUriUtil.getNetworkGenericVnfUri(execution)
+ msoLogger.debug('AAI URI is: ' + aai_uri)
+ String aaiNamespace = aaiUriUtil.getNamespaceFromUri(execution, aai_uri)
+ msoLogger.debug('AAI namespace is: ' + aaiNamespace)
+
+ execution.setVariable("CAAIVfMod_aaiNamespace","${aaiNamespace}")
+
+ if (vnfId == null || vnfId.isEmpty()) {
+ // TBD - assert that the vnfName is not empty
+ execution.setVariable("CAAIVfMod_genericVnfGetEndpoint",
+ "${aai_uri}/?vnf-name=" +
+ UriUtils.encode(vnfName,"UTF-8") + "&depth=1")
+ } else {
+ execution.setVariable("CAAIVfMod_genericVnfGetEndpoint",
+ "${aai_uri}/" + UriUtils.encode(vnfId,"UTF-8") + "?depth=1")
+ }
+
+ msoLogger.debug("CreateAAIVfModule VNF PUT Endpoint: ${aai_uri}/")
+ execution.setVariable("CAAIVfMod_genericVnfPutEndpoint","${aai_uri}/")
+ }
+
+ // 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) {
+ def endPoint = UrnPropertiesReader.getVariable("aai.endpoint", execution) + execution.getVariable("CAAIVfMod_genericVnfGetEndpoint")
+
+ 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)
+
+ AaiUtil aaiUtil = new AaiUtil(this)
+ 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)
+ } catch (Exception ex) {
+ msoLogger.debug("Exception occurred while executing AAI GET:" + ex.getMessage())
+ exceptionUtil.buildAndThrowWorkflowException(execution, 5000, "Internal Error - Occured in queryAAIForGenericVnf.")
+
+ }
+ }
+
+ // 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")
+ } else if (execution.getVariable("CAAIVfMod_queryGenericVnfResponseCode") == 200 &&
+ !execution.getVariable("CAAIVfMod_vnfId").isEmpty()) {
+ msoLogger.debug("Adding module to existing Generic VNF")
+ } else if (execution.getVariable("CAAIVfMod_queryGenericVnfResponseCode") == 200 &&
+ execution.getVariable("CAAIVfMod_vnfId").isEmpty()) {
+ msoLogger.debug("Invalid request for new Generic VNF which already exists")
+ execution.setVariable("CAAIVfMod_queryGenericVnfResponse",
+ "Invalid request for new Generic VNF which already exists, Vnf Name=" +
+ execution.getVariable("CAAIVfMod_vnfName"))
+ } else { // execution.getVariable("CAAIVfMod_queryGenericVnfResponseCode") == 404 &&
+ // !execution.getVariable("CAAIVfMod_vnfId").isEmpty())
+ msoLogger.debug("Invalid request for Add-on Module requested for non-existant Generic VNF")
+ execution.setVariable("CAAIVfMod_createVfModuleResponse",
+ "Invalid request for Add-on Module requested for non-existant Generic VNF, VNF Id=" +
+ execution.getVariable("CAAIVfMod_vnfId"))
+ }
+ }
+
+ // construct and send a PUT request to A&AI to create a new Generic VNF
+ // note: to get here, the vnf-id in the original CREATE_VF_MODULE request was absent or ""
+ public void createGenericVnf(DelegateExecution execution) {
+ // TBD - is this how we want to generate the Id for the new Generic VNF?
+ def newVnfId = UUID.randomUUID().toString()
+ def endPoint = UrnPropertiesReader.getVariable("aai.endpoint", execution) +
+ execution.getVariable("CAAIVfMod_genericVnfPutEndpoint") + newVnfId
+ // update the flow execution with the new Vnf Id
+ execution.setVariable("CAAIVfMod_vnfId",newVnfId)
+
+ // AaiUriUtil aaiUriUtil = new AaiUriUtil(this)
+ // def aai_uri = aaiUriUtil.getNetworkGenericVnfUri(execution)
+ // msoLogger.debug('AAI URI is: ' + aai_uri)
+ // String namespace = aaiUriUtil.getNamespaceFromUri(aai_uri)
+ // msoLogger.debug('AAI namespace is: ' + namespace)
+
+
+ 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)
+
+ try {
+ 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)
+
+ AaiUtil aaiUtil = new AaiUtil(this);
+ 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)
+ } catch (Exception ex) {
+ ex.printStackTrace()
+ msoLogger.debug("Exception occurred while executing AAI PUT:" + ex.getMessage())
+ exceptionUtil.buildAndThrowWorkflowException(execution, 5000, "Internal Error - Occured in createGenericVnf.")
+ }
+ }
+
+ // construct and send a PUT request to A&AI to create a Base or Add-on VF Module
+ public void createVfModule(DelegateExecution execution, Boolean isBaseModule) {
+ // TBD - is this how we want to generate the Id for the new (Base) VF Module?
+
+ // Generate the new VF Module ID here if it has not been provided by the parent process
+ def newModuleId = execution.getVariable('newVfModuleId')
+ if (newModuleId == null || newModuleId.isEmpty()) {
+ newModuleId = UUID.randomUUID().toString()
+ }
+ def endPoint = UrnPropertiesReader.getVariable("aai.endpoint", execution) + execution.getVariable("CAAIVfMod_genericVnfPutEndpoint")
+ // need to append the existing Vnf Id or the one generated in createGenericVnf() to the url
+ endPoint = endPoint + UriUtils.encode(execution.getVariable("CAAIVfMod_vnfId"), "UTF-8") +
+ "/vf-modules/vf-module/" + newModuleId;
+ 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)
+ }
+ 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
+ def rollbackData = execution.getVariable("RollbackData")
+ if (rollbackData == null) {
+ rollbackData = new RollbackData();
+ }
+ rollbackData.put("VFMODULE", "vnfId", execution.getVariable("CAAIVfMod_vnfId"))
+ rollbackData.put("VFMODULE", "vnfName", execution.getVariable("CAAIVfMod_vnfName"))
+ 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)
+
+ try {
+ 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)
+
+ AaiUtil aaiUtil = new AaiUtil(this)
+ APIResponse response = aaiUtil.executeAAIPutCall(execution, endPoint, payload)
+ def responseData = response.getResponseBodyAsString()
+ def statusCode = response.getStatusCode()
+ 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)
+ // 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)) {
+ rollbackData.put("VFMODULE", "vfModuleId", newModuleId)
+ rollbackData.put("VFMODULE", "vfModuleName", execution.getVariable("CAAIVfMod_moduleName"))
+ execution.setVariable("RollbackData", rollbackData)
+ msoLogger.debug("RollbackData:" + rollbackData)
+
+ String responseOut = ""
+
+ String isVidRequest = execution.getVariable("isVidRequest")
+
+ if (isBaseModule && (isVidRequest == null || "false".equals(isVidRequest))) {
+
+ responseOut = """<CreateAAIVfModuleResponse>
+ <vnf-id>${MsoUtils.xmlEscape(execution.getVariable("CAAIVfMod_vnfId"))}</vnf-id>
+ <vf-module-id>${MsoUtils.xmlEscape(newModuleId)}</vf-module-id>
+ <vf-module-index>${MsoUtils.xmlEscape(moduleIndexString)}</vf-module-index>
+ </CreateAAIVfModuleResponse>""" as String
+ }
+ else {
+ responseOut = """<CreateAAIVfModuleResponse>
+ <vnf-name>${MsoUtils.xmlEscape(execution.getVariable("CAAIVfMod_vnfNameFromAAI"))}</vnf-name>
+ <vnf-id>${MsoUtils.xmlEscape(execution.getVariable("CAAIVfMod_vnfId"))}</vnf-id>
+ <vf-module-id>${MsoUtils.xmlEscape(newModuleId)}</vf-module-id>
+ <vf-module-index>${MsoUtils.xmlEscape(moduleIndexString)}</vf-module-index>
+ </CreateAAIVfModuleResponse>""" as String
+ }
+
+ execution.setVariable("CreateAAIVfModuleResponse", responseOut)
+ msoLogger.debug("CreateAAIVfModuleResponse:" + System.lineSeparator()+responseOut)
+ msoLogger.debug("CreateAAIVfModule Response /n " + responseOut)
+ }
+ } catch (Exception ex) {
+ msoLogger.debug("Exception occurred while executing AAI PUT:" + ex.getMessage())
+ exceptionUtil.buildAndThrowWorkflowException(execution, 5000, "Internal Error - Occured in createVfModule.")
+ }
+ }
+
+ // 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")
+ 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 (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"))
+ execution.setVariable("CAAIVfMod_moduleExists", true)
+ execution.setVariable("CAAIVfMod_parseModuleResponse",
+ "VF Module " + qryModuleName + " already exists for Generic VNF " +
+ execution.getVariable("CAAIVfMod_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"))
+ execution.setVariable("CAAIVfMod_parseModuleResponse",
+ "VF Module " + newModuleName + " does not exist for Generic VNF " +
+ execution.getVariable("CAAIVfMod_vnfNameFromAAI"))
+ }
+ }
+
+ // 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 parseForBaseModule(DelegateExecution execution) {
+ def xml = execution.getVariable("CAAIVfMod_queryGenericVnfResponse")
+ def vnfNameFromAAI = utils.getNodeText(xml, "vnf-name")
+ 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 (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"))
+ execution.setVariable("CAAIVfMod_baseModuleConflict", true)
+ execution.setVariable("CAAIVfMod_parseModuleResponse",
+ "VF Module " + qryModuleName + " already exists for Generic VNF " +
+ execution.getVariable("CAAIVfMod_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")) {
+ // a base module already exists in this VNF - failure
+ msoLogger.debug("Base VF Module already exists for Generic VNF " + execution.getVariable("CAAIVfMod_vnfNameFromAAI"))
+ execution.setVariable("CAAIVfMod_baseModuleConflict", true)
+ execution.setVariable("CAAIVfMod_parseModuleResponse",
+ "Base VF Module already exists for Generic VNF " +
+ execution.getVariable("CAAIVfMod_vnfNameFromAAI"))
+ break
+ }
+ }
+
+ }
+ if (execution.getVariable("CAAIVfMod_moduleExists") == false && 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"))
+ }
+ }
+
+ // generates a WorkflowException when the A&AI query returns a response code other than 200 or 404
+ public void handleAAIQueryFailure(DelegateExecution execution) {
+ msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Error occurred attempting to query AAI, Response Code " + execution.getVariable("CAAIVfMod_queryGenericVnfResponseCode") + ", Error Response " + execution.getVariable("CAAIVfMod_queryGenericVnfResponse"), "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "");
+ int code = execution.getVariable("CAAIVfMod_queryGenericVnfResponseCode")
+ exceptionUtil.buildAndThrowWorkflowException(execution, code, "Error occurred attempting to query AAI")
+
+ }
+
+ // generates a WorkflowException if
+ // - the A&AI Generic VNF PUT returns a response code other than 200 or 201
+ // - the requested Generic VNF already exists but vnf-id == null
+ // - the requested Generic VNF does not exist but vnf-id != null
+ // - the A&AI VF Module PUT returns a response code other than 200 or 201
+ // - the requested VF Module already exists for the Generic VNF
+ public void handleCreateVfModuleFailure(DelegateExecution execution) {
+ def errorCode
+ def errorResponse
+ if (execution.getVariable("CAAIVfMod_createGenericVnfResponseCode") != null &&
+ !isOneOf(execution.getVariable("CAAIVfMod_createGenericVnfResponseCode"), 200, 201)) {
+ msoLogger.debug("Failure creating Generic VNF: " + execution.getVariable("CAAIVfMod_createGenericVnfResponse"))
+ errorResponse = execution.getVariable("CAAIVfMod_createGenericVnfResponse")
+ errorCode = 5000
+ } else if (execution.getVariable("CAAIVfMod_queryGenericVnfResponse") != null &&
+ execution.getVariable("CAAIVfMod_newGenericVnf") == true) {
+ // attempted to create a Generic VNF that already exists but vnf-id == null
+ msoLogger.debug(execution.getVariable("CAAIVfMod_queryGenericVnfResponse"))
+ errorResponse = execution.getVariable("CAAIVfMod_queryGenericVnfResponse")
+ errorCode = 1002
+ } else if (execution.getVariable("CAAIVfMod_queryGenericVnfResponseCode") == 404 &&
+ execution.getVariable("CAAIVfMod_newGenericVnf") == false) {
+ // attempted to create a Generic VNF where vnf-name does not exist but vnf-id != null
+ msoLogger.debug(execution.getVariable("CAAIVfMod_queryGenericVnfResponse"))
+ errorResponse = execution.getVariable("CAAIVfMod_queryGenericVnfResponse")
+ errorCode = 1002
+ } else if (execution.getVariable("CAAIVfMod_createVfModuleResponseCode") != null) {
+ msoLogger.debug("Failed to add VF Module: " + execution.getVariable("CAAIVfMod_createVfModuleResponse"))
+ errorResponse = execution.getVariable("CAAIVfMod_createVfModuleResponse")
+ errorCode = 5000
+ } else if (execution.getVariable("CAAIVfMod_moduleExists") == true) {
+ msoLogger.debug("Attempting to add VF Module that already exists: " + execution.getVariable("CAAIVfMod_parseModuleResponse"))
+ errorResponse = execution.getVariable("CAAIVfMod_parseModuleResponse")
+ errorCode = 1002
+ } else if (execution.getVariable("CAAIVfMod_baseModuleConflict") == true) {
+ msoLogger.debug("Attempting to add Base VF Module to VNF that already has a Base VF Module: " + execution.getVariable("CAAIVfMod_parseModuleResponse"))
+ errorResponse = execution.getVariable("CAAIVfMod_parseModuleResponse")
+ errorCode = 1002
+ } else {
+ // if the responses get populated corerctly, we should never get here
+ errorResponse = "Unknown error occurred during CreateAAIVfModule flow"
+ errorCode = 2000
+ }
+
+ msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Error occurred during CreateAAIVfModule flow", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, errorResponse);
+ 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)
+ def aai_uri = aaiUriUtil.getNetworkGenericVnfUri(execution)
+ msoLogger.debug('AAI URI is: ' + aai_uri)
+ msoLogger.debug("CreateAAIVfModule rollback AAI URI: " + aai_uri)
+
+ 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)
+ execution.setVariable("DAAIVfMod_genericVnfEndpoint", "${aai_uri}/" + vnfId)
+ execution.setVariable("DAAIVfMod_vfModuleEndpoint", "${aai_uri}/" + vnfId +
+ "/vf-modules/vf-module/" + 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")
+// execution.setVariable("RollbackResult", "SUCCESS")
+ } 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.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
new file mode 100644
index 0000000000..ec691f299e
--- /dev/null
+++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/CreateAAIVfModuleVolumeGroup.groovy
@@ -0,0 +1,327 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.so.bpmn.common.scripts
+
+import 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.logger.MessageEnum
+import org.onap.so.logger.MsoLogger
+
+public class CreateAAIVfModuleVolumeGroup extends AbstractServiceTaskProcessor {
+ private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, CreateAAIVfModuleVolumeGroup.class);
+
+ private XmlParser xmlParser = new XmlParser()
+ ExceptionUtil exceptionUtil = new ExceptionUtil()
+
+ /**
+ * Initialize the flow's variables.
+ *
+ * @param execution The flow's execution instance.
+ */
+ public void initProcessVariables(DelegateExecution execution) {
+ execution.setVariable('prefix', 'CAAIVfModVG_')
+ execution.setVariable('CAAIVfModVG_vnfId', null)
+ execution.setVariable('CAAIVfModVG_vfModuleId', null)
+ execution.setVariable('CAAIVfModVG_aicCloudRegion', null)
+ execution.setVariable('CAAIVfModVG_volumeGroupId', null)
+ execution.setVariable('CAAIVfModVG_getVfModuleResponseCode' ,null)
+ execution.setVariable('CAAIVfModVG_getVfModuleResponse', '')
+ execution.setVariable('CAAIVfModVG_updateVfModuleResponseCode', null)
+ execution.setVariable('CAAIVfModVG_updateVfModuleResponse', '')
+ }
+
+ /**
+ * Check for missing elements in the received request.
+ *
+ * @param execution The flow's execution instance.
+ */
+ public void preProcessRequest(DelegateExecution execution) {
+ def method = getClass().getSimpleName() + '.preProcessRequest(' +
+ 'execution=' + execution.getId() +
+ ')'
+ msoLogger.trace('Entered ' + method)
+
+ try {
+ def xml = execution.getVariable('CreateAAIVfModuleVolumeGroupRequest')
+ msoLogger.debug('Received request xml:\n' + xml)
+ msoLogger.debug("CreateAAIVfModuleVolume Received Request XML: " + xml)
+ initProcessVariables(execution)
+
+ def vnfId = getRequiredNodeText(execution, xml,'vnf-id')
+ execution.setVariable('CAAIVfModVG_vnfId', vnfId)
+
+ def vfModuleId = getRequiredNodeText(execution, xml,'vf-module-id')
+ execution.setVariable('CAAIVfModVG_vfModuleId', vfModuleId)
+
+ def aicCloudRegion = getRequiredNodeText(execution, xml,'aic-cloud-region')
+ execution.setVariable('CAAIVfModVG_aicCloudRegion', aicCloudRegion)
+
+ def volumeGroupId = getRequiredNodeText(execution, xml,'volume-group-id')
+ execution.setVariable('CAAIVfModVG_volumeGroupId', volumeGroupId)
+
+ msoLogger.trace('Exited ' + method)
+ } catch (BpmnError e) {
+ throw e;
+ } catch (Exception e) {
+ msoLogger.error(e);
+ exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in preProcessRequest(): ' + e.getMessage())
+
+ }
+ }
+
+ /**
+ * Using the received vnfId and vfModuleId, query AAI to get the corresponding VF Module.
+ * A 200 response is expected with the VF Module in the response body.
+ *
+ * @param execution The flow's execution instance.
+ */
+ public void getVfModule(DelegateExecution execution) {
+ def method = getClass().getSimpleName() + '.getVfModule(' +
+ 'execution=' + execution.getId() +
+ ')'
+ msoLogger.trace('Entered ' + method)
+
+ try {
+ def vnfId = execution.getVariable('CAAIVfModVG_vnfId')
+ def vfModuleId = execution.getVariable('CAAIVfModVG_vfModuleId')
+
+ // Construct endpoint
+ AaiUtil aaiUtil = new AaiUtil(this)
+ def aai_uri = aaiUtil.getNetworkGenericVnfUri(execution)
+ msoLogger.debug('AAI URI is: ' + aai_uri)
+ String endPoint = UrnPropertiesReader.getVariable("aai.endpoint", execution) + aai_uri + '/' + URLEncoder.encode(vnfId, "UTF-8") + '/vf-modules/vf-module/' + URLEncoder.encode(vfModuleId, "UTF-8")
+
+ 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) {
+ ex.printStackTrace()
+ msoLogger.debug('Exception occurred while executing AAI GET:' + ex.getMessage())
+ execution.setVariable('CAAIVfModVG_getVfModuleResponseCode', 500)
+ execution.setVariable('CAAIVfModVG_getVfModuleResponse', 'AAI GET Failed:' + ex.getMessage())
+ }
+ msoLogger.trace('Exited ' + method)
+ } catch (BpmnError e) {
+ throw e;
+ } catch (Exception e) {
+ msoLogger.error(e);
+ exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in getVfModule(): ' + e.getMessage())
+ }
+ }
+
+ /**
+ * Construct and send a PUT request to AAI to update the VF Module with the
+ * created Volume Group relationship.
+ *
+ * @param execution The flow's execution instance.
+ */
+ public void updateVfModule(DelegateExecution execution) {
+ def method = getClass().getSimpleName() + '.updateVfModule(' +
+ 'execution=' + execution.getId() +
+ ')'
+ msoLogger.trace('Entered ' + method)
+
+ 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)
+
+ // 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)
+ }
+
+ // Construct payload by creating a Volume Group relationhip and inserting it into the VF Module
+ def aicCloudRegion = execution.getVariable('CAAIVfModVG_aicCloudRegion')
+ def volumeGroupId = execution.getVariable('CAAIVfModVG_volumeGroupId')
+ def Node vgRelationshipNode = createVolumeGroupRelationshipNode(aicCloudRegion, volumeGroupId)
+ insertVolumeGroupRelationshipNode(vfModuleNode, vgRelationshipNode)
+ def payload = utils.nodeToString(vfModuleNode)
+
+ // Construct endpoint
+ AaiUtil aaiUtil = new AaiUtil(this)
+ def aai_uri = aaiUtil.getNetworkGenericVnfUri(execution)
+ msoLogger.debug('AAI URI is: ' + aai_uri)
+ String endPoint = UrnPropertiesReader.getVariable("aai.endpoint", execution) + aai_uri + '/' + URLEncoder.encode(vnfId, "UTF-8") + '/vf-modules/vf-module/' + URLEncoder.encode(vfModuleId, "UTF-8")
+
+ 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)
+ } catch (Exception ex) {
+ ex.printStackTrace()
+ msoLogger.debug('Exception occurred while executing AAI PUT:' + ex.getMessage())
+ execution.setVariable('CAAIVfModVG_updateVfModuleResponseCode', 500)
+ execution.setVariable('CAAIVfModVG_updateVfModuleResponse', 'AAI PUT Failed:' + ex.getMessage())
+ }
+ msoLogger.trace('Exited ' + method)
+ } catch (BpmnError e) {
+ throw e;
+ } catch (Exception e) {
+ msoLogger.error(e);
+ 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 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', 'att-aic')
+ 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
+ * 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 Node getCurrVolumeGroupRelationshipNode(Node relationshipList) {
+ def Node currVolumeGroupRelationshipNode = 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')) {
+ currVolumeGroupRelationshipNode = relationshipNode
+ }
+ }
+ return currVolumeGroupRelationshipNode
+ }
+
+ /**
+ * Generates a WorkflowException if the AAI query returns a response code other than 200.
+ *
+ * @param execution The flow's execution instance.
+ */
+ public void handleAAIQueryFailure(DelegateExecution execution) {
+ def method = getClass().getSimpleName() + '.handleAAIQueryFailure(' +
+ 'execution=' + execution.getId() +
+ ')'
+ msoLogger.trace('Entered ' + method)
+ msoLogger.error( 'Error occurred attempting to query AAI, Response Code ' + execution.getVariable('CAAIVfModVG_getVfModuleResponseCode'));
+ ExceptionUtil exceptionUtil = new ExceptionUtil()
+ exceptionUtil.buildWorkflowException(execution, 5000, execution.getVariable('CAAIVfModVG_getVfModuleResponse'))
+
+ 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('CAAIVfModVG_updateVfModuleResponseCode'));
+ ExceptionUtil exceptionUtil = new ExceptionUtil()
+ exceptionUtil.buildWorkflowException(execution, 5000, execution.getVariable('CAAIVfModVG_updateVfModuleResponse'))
+
+ msoLogger.trace('Exited ' + method)
+ }
+}
diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/CustomE2EGetService.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/CustomE2EGetService.groovy
new file mode 100644
index 0000000000..5aef1d6ea5
--- /dev/null
+++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/CustomE2EGetService.groovy
@@ -0,0 +1,440 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017 Huawei Technologies Co., Ltd. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.so.bpmn.common.scripts
+
+import static org.apache.commons.lang3.StringUtils.*
+
+import org.apache.commons.lang3.*
+import org.camunda.bpm.engine.delegate.BpmnError
+import org.camunda.bpm.engine.delegate.DelegateExecution
+import org.onap.so.rest.APIResponse
+import org.springframework.web.util.UriUtils
+import org.onap.so.bpmn.core.UrnPropertiesReader
+import org.onap.so.logger.MessageEnum
+import org.onap.so.logger.MsoLogger
+
+
+/**
+ * This class supports the GenericGetService Sub Flow.
+ * This Generic sub flow can be used by any flow for accomplishing
+ * the goal of getting a Service-Instance or Service-Subscription (from AAI).
+ * The calling flow must set the GENGS_type variable as "service-instance"
+ * or "service-subscription".
+ *
+ * When using to Get a Service-Instance:
+ * If the global-customer-id and service-type are not provided
+ * this flow executes a query to get the service- Url using the
+ * Service Id or Name (whichever is provided).
+ *
+ * When using to Get a Service-Subscription:
+ * The global-customer-id and service-type must be
+ * provided.
+ *
+ * Upon successful completion of this sub flow the
+ * GENGS_SuccessIndicator will be true and the query response payload
+ * will be set to GENGS_service. An MSOWorkflowException will
+ * be thrown upon unsuccessful completion or if an error occurs
+ * at any time during this sub flow. Please map variables
+ * to the corresponding variable names below.
+ *
+ * Note - If this sub flow receives a Not Found (404) response
+ * from AAI at any time this will be considered an acceptable
+ * successful response however the GENGS_FoundIndicator
+ * will be set to false. This variable will allow the calling flow
+ * to distinguish between the two Success scenarios,
+ * "Success where service- is found" and
+ * "Success where service- is NOT found".
+ *
+ *
+ * Variable Mapping Below:
+ *
+ * In Mapping Variables:
+ * For Allotted-Resource:
+ * @param - GENGS_allottedResourceId
+ * @param - GENGS_type
+ * @param (Optional) - GENGS_serviceInstanceId
+ * @param (Optional) - GENGS_serviceType
+ * @param (Optional) - GENGS_globalCustomerId
+ *
+ * For Service-Instance:
+ * @param - GENGS_serviceInstanceId or @param - GENGS_serviceInstanceName
+ * @param - GENGS_type
+ * @param (Optional) - GENGS_serviceType
+ * @param (Optional) - GENGS_globalCustomerId
+ *
+ * For Service-Subscription:
+ * @param - GENGS_type
+ * @param - GENGS_serviceType
+ * @param - GENGS_globalCustomerId
+ *
+ *
+ * Out Mapping Variables:
+ * @param - GENGS_service
+ * @param - GENGS_FoundIndicator
+ * @param - WorkflowException
+ */
+class CustomE2EGetService extends AbstractServiceTaskProcessor{
+ private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, CustomE2EGetService.class);
+
+ String Prefix = "GENGS_"
+ ExceptionUtil exceptionUtil = new ExceptionUtil()
+
+ /**
+ * This method validates the incoming variables and
+ * determines the subsequent event based on which
+ * variables the calling flow provided.
+ *
+ * @param - execution
+ *
+ */
+ public void preProcessRequest(DelegateExecution execution) {
+ execution.setVariable("prefix",Prefix)
+ msoLogger.trace("STARTED GenericGetService PreProcessRequest Process")
+
+ execution.setVariable("GENGS_obtainObjectsUrl", false)
+ execution.setVariable("GENGS_obtainServiceInstanceUrlByName", false)
+ execution.setVariable("GENGS_SuccessIndicator", false)
+ execution.setVariable("GENGS_FoundIndicator", false)
+ execution.setVariable("GENGS_resourceLink", null)
+ execution.setVariable("GENGS_siResourceLink", null)
+
+ try{
+ // Get Variables
+ String allottedResourceId = execution.getVariable("GENGS_allottedResourceId")
+ String serviceInstanceId = execution.getVariable("GENGS_serviceInstanceId")
+ String serviceInstanceName = execution.getVariable("GENGS_serviceInstanceName")
+ String serviceType = execution.getVariable("GENGS_serviceType")
+ String globalCustomerId = execution.getVariable("GENGS_globalCustomerId")
+ String type = execution.getVariable("GENGS_type")
+
+ if(type != null){
+ msoLogger.debug("Incoming GENGS_type is: " + type)
+ if(type.equalsIgnoreCase("allotted-resource")){
+ if(isBlank(allottedResourceId)){
+ msoLogger.debug("Incoming allottedResourceId is null. Allotted Resource Id is required to Get an allotted-resource.")
+ exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Incoming allottedResourceId is null. Allotted Resource Id is required to Get an allotted-resource.")
+ }else{
+ msoLogger.debug("Incoming Allotted Resource Id is: " + allottedResourceId)
+ if(isBlank(globalCustomerId) || isBlank(serviceType) || isBlank(serviceInstanceId)){
+ execution.setVariable("GENGS_obtainObjectsUrl", true)
+ }else{
+ msoLogger.debug("Incoming Service Instance Id is: " + serviceInstanceId)
+ msoLogger.debug("Incoming Service Type is: " + serviceType)
+ msoLogger.debug("Incoming Global Customer Id is: " + globalCustomerId)
+ }
+ }
+ }else if(type.equalsIgnoreCase("service-instance")){
+ if(isBlank(serviceInstanceId) && isBlank(serviceInstanceName)){
+ msoLogger.debug("Incoming serviceInstanceId and serviceInstanceName are null. ServiceInstanceId or ServiceInstanceName is required to Get a service-instance.")
+ exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Incoming serviceInstanceId and serviceInstanceName are null. ServiceInstanceId or ServiceInstanceName is required to Get a service-instance.")
+ }else{
+ msoLogger.debug("Incoming Service Instance Id is: " + serviceInstanceId)
+ msoLogger.debug("Incoming Service Instance Name is: " + serviceInstanceName)
+ if(isBlank(globalCustomerId) || isBlank(serviceType)){
+ execution.setVariable("GENGS_obtainObjectsUrl", true)
+ if(isBlank(serviceInstanceId)){
+ execution.setVariable("GENGS_obtainServiceInstanceUrlByName", true)
+ }
+ }else{
+ msoLogger.debug("Incoming Global Customer Id is: " + globalCustomerId)
+ msoLogger.debug("Incoming Service Type is: " + serviceType)
+ }
+ }
+ }else if(type.equalsIgnoreCase("service-subscription")){
+ if(isBlank(serviceType) || isBlank(globalCustomerId)){
+ msoLogger.debug("Incoming ServiceType or GlobalCustomerId is null. These variables are required to Get a service-subscription.")
+ exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Incoming ServiceType or GlobalCustomerId is null. These variables are required to Get a service-subscription.")
+ }else{
+ msoLogger.debug("Incoming Service Type is: " + serviceType)
+ msoLogger.debug("Incoming Global Customer Id is: " + globalCustomerId)
+ }
+ }else{
+ exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Incoming Type is Invalid. Please Specify Type as service-instance or service-subscription")
+ }
+ }else{
+ exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Incoming GENGS_type is null. Variable is Required.")
+ }
+
+ }catch(BpmnError b){
+ msoLogger.debug("Rethrowing MSOWorkflowException")
+ throw b
+ }catch(Exception e){
+ msoLogger.debug("Internal Error encountered within GenericGetService PreProcessRequest method!" + e)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured in GenericGetService PreProcessRequest")
+
+ }
+ msoLogger.trace("COMPLETED GenericGetService PreProcessRequest Process ")
+ }
+
+ /**
+ * This method obtains the Url to the provided service instance
+ * using the Service Instance Id.
+ *
+ * @param - execution
+ */
+ public void obtainServiceInstanceUrlById(DelegateExecution execution){
+ execution.setVariable("prefix",Prefix)
+ msoLogger.trace("STARTED GenericGetService ObtainServiceInstanceUrlById Process")
+ try {
+ AaiUtil aaiUriUtil = new AaiUtil(this)
+ String aai_uri = aaiUriUtil.getSearchNodesQueryEndpoint(execution)
+ String aai_endpoint = UrnPropertiesReader.getVariable("aai.endpoint", execution)
+
+ String type = execution.getVariable("GENGS_type")
+ String path = ""
+ if(type.equalsIgnoreCase("service-instance")){
+ String serviceInstanceId = execution.getVariable("GENGS_serviceInstanceId")
+ msoLogger.debug(" Querying Node for Service-Instance URL by using Service-Instance Id: " + serviceInstanceId)
+ path = "${aai_uri}?search-node-type=service-instance&filter=service-instance-id:EQUALS:${serviceInstanceId}"
+ msoLogger.debug("Service Instance Node Query Url is: " + path)
+ msoLogger.debug("Service Instance Node Query Url is: " + path)
+ }else if(type.equalsIgnoreCase("allotted-resource")){
+ String allottedResourceId = execution.getVariable("GENGS_allottedResourceId")
+ msoLogger.debug(" Querying Node for Service-Instance URL by using Allotted Resource Id: " + allottedResourceId)
+ path = "${aai_uri}?search-node-type=allotted-resource&filter=id:EQUALS:${allottedResourceId}"
+ msoLogger.debug("Allotted Resource Node Query Url is: " + path)
+ msoLogger.debug("Allotted Resource Node Query Url is: " + path)
+ }
+
+ //String url = "${aai_endpoint}${path}" host name needs to be removed from property
+ String url = "${path}"
+ execution.setVariable("GENGS_genericQueryPath", url)
+
+ APIResponse response = aaiUriUtil.executeAAIGetCall(execution, url)
+ int responseCode = response.getStatusCode()
+ execution.setVariable("GENGS_genericQueryResponseCode", responseCode)
+ msoLogger.debug(" GET Service Instance response code is: " + responseCode)
+ msoLogger.debug("GenericGetService AAI GET Response Code: " + responseCode)
+
+ String aaiResponse = response.getResponseBodyAsString()
+ execution.setVariable("GENGS_obtainSIUrlResponseBeforeUnescaping", aaiResponse)
+ msoLogger.debug("GenericGetService AAI Response before unescaping: " + aaiResponse)
+ execution.setVariable("GENGS_genericQueryResponse", aaiResponse)
+ msoLogger.debug("GenericGetService AAI Response: " + aaiResponse)
+ msoLogger.debug("GenericGetService AAI Response: " + aaiResponse)
+
+ //Process Response
+ if(responseCode == 200){
+ msoLogger.debug("Generic Query Received a Good Response Code")
+ execution.setVariable("GENGS_SuccessIndicator", true)
+ if(utils.nodeExists(aaiResponse, "result-data")){
+ msoLogger.debug("Generic Query Response Does Contain Data" )
+ execution.setVariable("GENGS_FoundIndicator", true)
+ String resourceLink = utils.getNodeText(aaiResponse, "resource-link")
+ execution.setVariable("GENGS_resourceLink", resourceLink)
+ execution.setVariable("GENGS_siResourceLink", resourceLink)
+ }else{
+ msoLogger.debug("Generic Query Response Does NOT Contains Data" )
+ execution.setVariable("WorkflowResponse", " ") //for junits
+ }
+ }else if(responseCode == 404){
+ msoLogger.debug("Generic Query Received a Not Found (404) Response")
+ execution.setVariable("GENGS_SuccessIndicator", true)
+ execution.setVariable("WorkflowResponse", " ") //for junits
+ }else{
+ msoLogger.debug("Generic Query Received a BAD REST Response: \n" + aaiResponse)
+ exceptionUtil.MapAAIExceptionToWorkflowExceptionGeneric(execution, aaiResponse, responseCode)
+ throw new BpmnError("MSOWorkflowException")
+ }
+ }catch(BpmnError b){
+ msoLogger.debug("Rethrowing MSOWorkflowException")
+ throw b
+ }catch(Exception e){
+ msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, " Error encountered within GenericGetService ObtainServiceInstanceUrlById method!" + e, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "");
+ exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured During ObtainServiceInstanceUrlById")
+ }
+ msoLogger.trace("COMPLETED GenericGetService ObtainServiceInstanceUrlById Process")
+ }
+
+ /**
+ * This method obtains the Url to the provided service instance
+ * using the Service Instance Name.
+ *
+ * @param - execution
+ */
+ public void obtainServiceInstanceUrlByName(DelegateExecution execution){
+ execution.setVariable("prefix",Prefix)
+ msoLogger.trace("STARTED GenericGetService ObtainServiceInstanceUrlByName Process")
+ try {
+ String serviceInstanceName = execution.getVariable("GENGS_serviceInstanceName")
+ msoLogger.debug(" Querying Node for Service-Instance URL by using Service-Instance Name " + serviceInstanceName)
+
+ AaiUtil aaiUriUtil = new AaiUtil(this)
+ String aai_uri = aaiUriUtil.getSearchNodesQueryEndpoint(execution)
+ String aai_endpoint = UrnPropertiesReader.getVariable("aai.endpoint", execution)
+ String path = "${aai_uri}?search-node-type=service-instance&filter=service-instance-name:EQUALS:${serviceInstanceName}"
+
+ //String url = "${aai_endpoint}${path}" host name needs to be removed from property
+ String url = "${path}"
+ execution.setVariable("GENGS_obtainSIUrlPath", url)
+
+ msoLogger.debug("GenericGetService AAI Endpoint: " + aai_endpoint)
+ APIResponse response = aaiUriUtil.executeAAIGetCall(execution, url)
+ int responseCode = response.getStatusCode()
+ execution.setVariable("GENGS_obtainSIUrlResponseCode", responseCode)
+ msoLogger.debug(" GET Service Instance response code is: " + responseCode)
+ msoLogger.debug("GenericGetService AAI Response Code: " + responseCode)
+
+ String aaiResponse = response.getResponseBodyAsString()
+ execution.setVariable("GENGS_obtainSIUrlResponse", aaiResponse)
+ msoLogger.debug("GenericGetService AAI Response: " + aaiResponse)
+ //Process Response
+ if(responseCode == 200){
+ msoLogger.debug(" Query for Service Instance Url Received a Good Response Code")
+ execution.setVariable("GENGS_SuccessIndicator", true)
+ if(utils.nodeExists(aaiResponse, "result-data")){
+ msoLogger.debug("Query for Service Instance Url Response Does Contain Data" )
+ execution.setVariable("GENGS_FoundIndicator", true)
+ String resourceLink = utils.getNodeText(aaiResponse, "resource-link")
+ execution.setVariable("GENGS_resourceLink", resourceLink)
+ execution.setVariable("GENGS_siResourceLink", resourceLink)
+ }else{
+ msoLogger.debug("Query for Service Instance Url Response Does NOT Contains Data" )
+ execution.setVariable("WorkflowResponse", " ") //for junits
+ }
+ }else if(responseCode == 404){
+ msoLogger.debug(" Query for Service Instance Received a Not Found (404) Response")
+ execution.setVariable("GENGS_SuccessIndicator", true)
+ execution.setVariable("WorkflowResponse", " ") //for junits
+ }else{
+ msoLogger.debug("Query for Service Instance Received a BAD REST Response: \n" + aaiResponse)
+ exceptionUtil.MapAAIExceptionToWorkflowExceptionGeneric(execution, aaiResponse, responseCode)
+ throw new BpmnError("MSOWorkflowException")
+ }
+ }catch(BpmnError b){
+ msoLogger.debug("Rethrowing MSOWorkflowException")
+ throw b
+ }catch(Exception e){
+ msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, " Error encountered within GenericGetService ObtainServiceInstanceUrlByName method!" + e, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "");
+ exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured During ObtainServiceInstanceUrlByName")
+ }
+ msoLogger.trace("COMPLETED GenericGetService ObtainServiceInstanceUrlByName Process")
+ }
+
+
+ /**
+ * This method executes a GET call to AAI to obtain the
+ * service-instance or service-subscription
+ *
+ * @param - execution
+ */
+ public void getServiceObject(DelegateExecution execution){
+ execution.setVariable("prefix",Prefix)
+ msoLogger.trace("STARTED GenericGetService GetServiceObject Process")
+ try {
+ String type = execution.getVariable("GENGS_type")
+ AaiUtil aaiUriUtil = new AaiUtil(this)
+ String aai_endpoint = UrnPropertiesReader.getVariable("aai.endpoint", execution)
+ String serviceEndpoint = ""
+
+ msoLogger.debug("GenericGetService getServiceObject AAI Endpoint: " + aai_endpoint)
+ if(type.equalsIgnoreCase("service-instance")){
+ String siResourceLink = execution.getVariable("GENGS_resourceLink")
+ if(isBlank(siResourceLink)){
+ String serviceInstanceId = execution.getVariable("GENGS_serviceInstanceId")
+ msoLogger.debug(" Incoming GENGS_serviceInstanceId is: " + serviceInstanceId)
+ String serviceType = execution.getVariable("GENGS_serviceType")
+ msoLogger.debug(" Incoming GENGS_serviceType is: " + serviceType)
+ String globalCustomerId = execution.getVariable("GENGS_globalCustomerId")
+ msoLogger.debug("Incoming Global Customer Id is: " + globalCustomerId)
+
+ String aai_uri = aaiUriUtil.getBusinessCustomerUri(execution)
+ msoLogger.debug('AAI URI is: ' + aai_uri)
+ serviceEndpoint = "${aai_uri}/" + UriUtils.encode(globalCustomerId,"UTF-8") + "/service-subscriptions/service-subscription/" + UriUtils.encode(serviceType,"UTF-8") + "/service-instances/service-instance/" + UriUtils.encode(serviceInstanceId,"UTF-8")
+ }else{
+ msoLogger.debug("Incoming Service Instance Url is: " + siResourceLink)
+ String[] split = siResourceLink.split("/aai/")
+ serviceEndpoint = "/aai/" + split[1]
+ }
+ }else if(type.equalsIgnoreCase("allotted-resource")){
+ String siResourceLink = execution.getVariable("GENGS_resourceLink")
+ if(isBlank(siResourceLink)){
+ String allottedResourceId = execution.getVariable("GENGS_allottedResourceId")
+ msoLogger.debug(" Incoming GENGS_allottedResourceId is: " + allottedResourceId)
+ String serviceInstanceId = execution.getVariable("GENGS_serviceInstanceId")
+ msoLogger.debug(" Incoming GENGS_serviceInstanceId is: " + serviceInstanceId)
+ String serviceType = execution.getVariable("GENGS_serviceType")
+ msoLogger.debug(" Incoming GENGS_serviceType is: " + serviceType)
+ String globalCustomerId = execution.getVariable("GENGS_globalCustomerId")
+ msoLogger.debug("Incoming Global Customer Id is: " + globalCustomerId)
+
+ String aai_uri = aaiUriUtil.getBusinessCustomerUri(execution)
+ msoLogger.debug('AAI URI is: ' + aai_uri)
+ serviceEndpoint = "${aai_uri}/" + UriUtils.encode(globalCustomerId,"UTF-8") + "/service-subscriptions/service-subscription/" + UriUtils.encode(serviceType,"UTF-8") + "/service-instances/service-instance/" + UriUtils.encode(serviceInstanceId,"UTF-8") + "/allotted-resources/allotted-resource/" + UriUtils.encode(allottedResourceId,"UTF-8")
+ }else{
+ msoLogger.debug("Incoming Allotted-Resource Url is: " + siResourceLink)
+ String[] split = siResourceLink.split("/aai/")
+ serviceEndpoint = "/aai/" + split[1]
+ }
+ }else if(type.equalsIgnoreCase("service-subscription")){
+ String aai_uri = aaiUriUtil.getBusinessCustomerUri(execution)
+ String globalCustomerId = execution.getVariable("GENGS_globalCustomerId")
+ String serviceType = execution.getVariable("GENGS_serviceType")
+ serviceEndpoint = "${aai_uri}/" + UriUtils.encode(globalCustomerId,"UTF-8") + "/service-subscriptions/service-subscription/" + UriUtils.encode(serviceType,"UTF-8")
+ }
+
+ String serviceUrl = "${aai_endpoint}" + serviceEndpoint
+
+ execution.setVariable("GENGS_getServiceUrl", serviceUrl)
+ msoLogger.debug("GET Service AAI Path is: \n" + serviceUrl)
+
+ APIResponse response = aaiUriUtil.executeAAIGetCall(execution, serviceUrl)
+ int responseCode = response.getStatusCode()
+ execution.setVariable("GENGS_getServiceResponseCode", responseCode)
+ msoLogger.debug(" GET Service response code is: " + responseCode)
+ msoLogger.debug("GenericGetService AAI Response Code: " + responseCode)
+
+ String aaiResponse = response.getResponseBodyAsString()
+ execution.setVariable("GENGS_getServiceResponse", aaiResponse)
+ msoLogger.debug("GenericGetService AAI Response: " + aaiResponse)
+ //Process Response
+ if(responseCode == 200 || responseCode == 202){
+ msoLogger.debug("GET Service Received a Good Response Code")
+ if(utils.nodeExists(aaiResponse, "service-instance") || utils.nodeExists(aaiResponse, "service-subscription")){
+ msoLogger.debug("GET Service Response Contains a service-instance" )
+ execution.setVariable("GENGS_FoundIndicator", true)
+ execution.setVariable("GENGS_service", aaiResponse)
+ execution.setVariable("WorkflowResponse", aaiResponse)
+
+ }else{
+ msoLogger.debug("GET Service Response Does NOT Contain Data" )
+ }
+ }else if(responseCode == 404){
+ msoLogger.debug("GET Service Received a Not Found (404) Response")
+ execution.setVariable("WorkflowResponse", " ") //for junits
+ }
+ else{
+ msoLogger.debug(" GET Service Received a Bad Response: \n" + aaiResponse)
+ exceptionUtil.MapAAIExceptionToWorkflowExceptionGeneric(execution, aaiResponse, responseCode)
+ throw new BpmnError("MSOWorkflowException")
+ }
+ }catch(BpmnError b){
+ msoLogger.debug("Rethrowing MSOWorkflowException")
+ throw b
+ }catch(Exception e){
+ msoLogger.debug(" Error encountered within GenericGetService GetServiceObject method!" + e)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured During GenericGetService")
+ }
+ msoLogger.trace("COMPLETED GenericGetService GetServiceObject Process")
+ }
+
+} \ No newline at end of file
diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/CustomE2EPutService.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/CustomE2EPutService.groovy
new file mode 100644
index 0000000000..43d540cc74
--- /dev/null
+++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/CustomE2EPutService.groovy
@@ -0,0 +1,283 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017 Huawei Technologies Co., Ltd. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.so.bpmn.common.scripts
+
+import static org.apache.commons.lang3.StringUtils.*;
+
+import org.camunda.bpm.engine.delegate.BpmnError
+import org.camunda.bpm.engine.delegate.DelegateExecution;
+import org.apache.commons.codec.binary.Base64
+import org.apache.commons.lang3.*
+
+import org.onap.so.bpmn.core.json.JsonUtils
+import org.onap.so.bpmn.core.WorkflowException
+import org.onap.so.rest.APIResponse;
+import org.onap.so.rest.RESTClient
+import org.onap.so.rest.RESTConfig
+
+import java.net.URLEncoder;
+import org.springframework.web.util.UriUtils
+import org.onap.so.bpmn.core.UrnPropertiesReader
+import org.onap.so.logger.MessageEnum
+import org.onap.so.logger.MsoLogger
+
+/**
+ * This class supports the GenericPutService Sub Flow.
+ * This Generic sub flow can be used by any flow for the
+ * goal of creating a Service Instance or Service-Subscription in AAI. Upon successful completion of
+ * this sub flow the GENPS_SuccessIndicator will be true.
+ * The calling flow must set the GENPS_type variable as "service-instance"
+ * or "service-subscription".
+ * A MSOWorkflowException will be thrown Upon unsuccessful
+ * completion or if an error occurs within this flow.
+ * Please map variables to the corresponding variable names
+ * below.
+ *
+ *
+ * Incoming Required Variables:
+ * @param - GENPS_requestId
+ * @param - GENPS_type - Required field. This will be required field populated as service-instance or service-subscription
+ * @param - GENPS_globalSubscriberId - Required field
+ * @param - GENPS_serviceType - Required Field
+ * @param - GENPS_payload - Required Field This will be the payload that needs to be sent.
+ *
+ * @param - GENPS_serviceInstanceId - Conditional Field. Required for service-instance.
+ * @param - GENPS_allottedResourceId - Conditional Field. Required for allotted-resource.
+ * @param - GENPS_tunnelXconnectId - Conditional Field. Required for tunnel-xconnect.
+ *
+ * @param - GENPS_serviceResourceVersion - Conditional Field. Needs to be provided only in case of update for both service-instance and service subscription. The calling flows
+ * should check if a service-instance or servic-subscription exists by calling the subflow GenericGetService. if it exists then resourceversion should be
+ * obtained from aai and sent as an input parameter.
+ *
+ * Outgoing Variables:
+ * @param - GENPS_SuccessIndicator
+ * @param - WorkflowException
+ *
+ *
+ */
+
+
+class CustomE2EPutService extends AbstractServiceTaskProcessor{
+ private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, CustomE2EPutService.class);
+
+ String Prefix = "GENPS_"
+ ExceptionUtil exceptionUtil = new ExceptionUtil()
+
+
+ public void preProcessRequest(DelegateExecution execution) {
+ execution.setVariable("prefix",Prefix)
+ msoLogger.trace("STARTED GenericPutService PreProcessRequest Process")
+
+ execution.setVariable("GENPS_SuccessIndicator", false)
+
+ try{
+ // Get Variables
+ String requestId = execution.getVariable("GENPS_requestId")
+ msoLogger.debug("Incoming GENPS_requestId is: " + requestId)
+
+ String globalSubscriberId = execution.getVariable("GENPS_globalSubscriberId")
+ String serviceInstanceId = execution.getVariable("GENPS_serviceInstanceId")
+ String serviceType = execution.getVariable("GENPS_serviceType")
+ String allottedResourceId = execution.getVariable("GENPS_allottedResourceId")
+ String tunnelXconnectId = execution.getVariable("GENPS_tunnelXconnectId")
+ String type = execution.getVariable("GENPS_type")
+
+ if(type != null){
+ msoLogger.debug("Incoming GENPS_type is: " + type)
+ if(type.equalsIgnoreCase("service-instance")){
+ if(isBlank(globalSubscriberId) || isBlank(serviceType) || isBlank(serviceInstanceId)){
+ msoLogger.debug("Incoming Required Variable is missing or null!")
+ exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Incoming Required Variable is Missing or Null!")
+ }else{
+ msoLogger.debug("Incoming Global Subscriber Id is: " + globalSubscriberId)
+ msoLogger.debug("Incoming Service Instance Id is: " + serviceInstanceId)
+ msoLogger.debug("Incoming Service Type is: " + serviceType)
+ }
+ }else if(type.equalsIgnoreCase("service-subscription")){
+ if(isBlank(serviceType) || isBlank(globalSubscriberId)){
+ msoLogger.debug("Incoming ServiceType or GlobalSubscriberId is null. These variables are required to create a service-subscription.")
+ exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Incoming ServiceType or GlobalCustomerId is null. These variables are required to Get a service-subscription.")
+ }else{
+ msoLogger.debug("Incoming Service Type is: " + serviceType)
+ msoLogger.debug("Incoming Global Subscriber Id is: " + globalSubscriberId)
+ }
+ }else if(type.equalsIgnoreCase("allotted-resource")){
+ if(isBlank(globalSubscriberId) || isBlank(serviceType) || isBlank(serviceInstanceId) || isBlank(allottedResourceId)){
+ msoLogger.debug("Incoming Global Subscriber Id is: " + globalSubscriberId)
+ msoLogger.debug("Incoming Service Instance Id is: " + serviceInstanceId)
+ msoLogger.debug("Incoming Service Type is: " + serviceType)
+ msoLogger.debug("Incoming Allotted Resource Id is: " + allottedResourceId)
+ msoLogger.debug("Incoming Required Variable is missing or null!")
+ exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Incoming Required Variable is Missing or Null!")
+ }else{
+ msoLogger.debug("Incoming Global Subscriber Id is: " + globalSubscriberId)
+ msoLogger.debug("Incoming Service Instance Id is: " + serviceInstanceId)
+ msoLogger.debug("Incoming Service Type is: " + serviceType)
+ msoLogger.debug("Incoming Allotted Resource Id is: " + allottedResourceId)
+ }
+ }else if(type.equalsIgnoreCase("tunnel-xconnect")){
+ if(isBlank(globalSubscriberId) || isBlank(serviceType) || isBlank(serviceInstanceId) || isBlank(allottedResourceId) || isBlank(tunnelXconnectId)){
+ msoLogger.debug("Incoming Global Subscriber Id is: " + globalSubscriberId)
+ msoLogger.debug("Incoming Service Instance Id is: " + serviceInstanceId)
+ msoLogger.debug("Incoming Service Type is: " + serviceType)
+ msoLogger.debug("Incoming Allotted Resource Id is: " + allottedResourceId)
+ msoLogger.debug("Incoming Tunnel Xconnect Id is: " + tunnelXconnectId)
+ msoLogger.debug("Incoming Required Variable is missing or null!")
+ exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Incoming Required Variable is Missing or Null!")
+ }else{
+ msoLogger.debug("Incoming Global Subscriber Id is: " + globalSubscriberId)
+ msoLogger.debug("Incoming Service Instance Id is: " + serviceInstanceId)
+ msoLogger.debug("Incoming Service Type is: " + serviceType)
+ msoLogger.debug("Incoming Allotted Resource Id is: " + allottedResourceId)
+ msoLogger.debug("Incoming Tunnel Xconnect Id is: " + tunnelXconnectId)
+ }
+ }else{
+ exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Incoming Type is Invalid. Please Specify Type as service-instance or service-subscription")
+ }
+ }else{
+ exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Incoming GENPS_type is null. Variable is Required.")
+ }
+
+ }catch(BpmnError b){
+ msoLogger.debug("Rethrowing MSOWorkflowException")
+ throw b
+ }catch(Exception e){
+ msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, " Error encountered within GenericPutService PreProcessRequest method!" + e, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "");
+ exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured in GenericPutService PreProcessRequest")
+
+ }
+ msoLogger.trace("COMPLETED GenericPutService PreProcessRequest Process ")
+
+ }
+
+
+
+ /**
+ * This method executes a Put call to AAI for the provided
+ * service instance.
+ *
+ * @param - execution
+ *
+ */
+ public void putServiceInstance(DelegateExecution execution){
+ execution.setVariable("prefix",Prefix)
+ msoLogger.trace("STARTED GenericPutService PutServiceInstance method")
+ try {
+ String type = execution.getVariable("GENPS_type")
+
+ AaiUtil aaiUriUtil = new AaiUtil(this)
+ String aai_uri = aaiUriUtil.getBusinessCustomerUri(execution)
+ msoLogger.debug('AAI URI is: ' + aai_uri)
+ String namespace = aaiUriUtil.getNamespaceFromUri(execution, aai_uri)
+ msoLogger.debug('AAI namespace is: ' + namespace)
+
+ String aai_endpoint = UrnPropertiesReader.getVariable("aai.endpoint", execution)
+ String serviceAaiPath = ""
+ String payload = execution.getVariable("GENPS_payload")
+ execution.setVariable("GENPS_payload", payload)
+ msoLogger.debug("Incoming GENPS_payload is: " + payload)
+ msoLogger.debug(payload)
+
+ String serviceType = execution.getVariable("GENPS_serviceType")
+ msoLogger.debug(" Incoming GENPS_serviceType is: " + serviceType)
+ String globalSubscriberId = execution.getVariable("GENPS_globalSubscriberId")
+ msoLogger.debug("Incoming Global Subscriber Id is: " + globalSubscriberId)
+
+ // This IF clause is if we need to create a new Service Instance
+ if(type.equalsIgnoreCase("service-instance")){
+
+ String serviceInstanceId = execution.getVariable("GENPS_serviceInstanceId")
+ msoLogger.debug(" Incoming GENPS_serviceInstanceId is: " + serviceInstanceId)
+
+ // serviceAaiPath = "${aai_endpoint}${aai_uri}/" + URLEncoder.encode(globalSubscriberId,"UTF-8") + "/service-subscriptions/service-subscription/" + URLEncoder.encode(serviceType,"UTF-8") + "/service-instances/service-instance/" + URLEncoder.encode(serviceInstanceId,"UTF-8")
+ serviceAaiPath = "${aai_endpoint}${aai_uri}/" + UriUtils.encode(globalSubscriberId,"UTF-8") + "/service-subscriptions/service-subscription/" + UriUtils.encode(serviceType,"UTF-8") + "/service-instances/service-instance/" + UriUtils.encode(serviceInstanceId,"UTF-8")
+
+ }else if(type.equalsIgnoreCase("service-subscription")){
+
+ // serviceAaiPath = "${aai_endpoint}${aai_uri}/" + URLEncoder.encode(globalSubscriberId,"UTF-8") + "/service-subscriptions/service-subscription/" + URLEncoder.encode(serviceType,"UTF-8")
+ serviceAaiPath = "${aai_endpoint}${aai_uri}/" + UriUtils.encode(globalSubscriberId,"UTF-8") + "/service-subscriptions/service-subscription/" + UriUtils.encode(serviceType,"UTF-8")
+ }else if(type.equalsIgnoreCase("allotted-resource")){
+
+ String serviceInstanceId = execution.getVariable("GENPS_serviceInstanceId")
+ msoLogger.debug(" Incoming GENPS_serviceInstanceId is: " + serviceInstanceId)
+ String allottedResourceId = execution.getVariable("GENPS_allottedResourceId")
+ msoLogger.debug(" Incoming GENPS_allottedResourceId is: " + allottedResourceId)
+
+ // serviceAaiPath = "${aai_endpoint}${aai_uri}/" + URLEncoder.encode(globalSubscriberId,"UTF-8") + "/service-subscriptions/service-subscription/" + URLEncoder.encode(serviceType,"UTF-8")
+ serviceAaiPath = "${aai_endpoint}${aai_uri}/" + UriUtils.encode(globalSubscriberId,"UTF-8") + "/service-subscriptions/service-subscription/" + UriUtils.encode(serviceType,"UTF-8") + "/service-instances/service-instance/" + UriUtils.encode(serviceInstanceId,"UTF-8") + "/allotted-resources/allotted-resource/" + UriUtils.encode(allottedResourceId,"UTF-8")
+ }else if(type.equalsIgnoreCase("tunnel-xconnect")){
+
+ String serviceInstanceId = execution.getVariable("GENPS_serviceInstanceId")
+ msoLogger.debug(" Incoming GENPS_serviceInstanceId is: " + serviceInstanceId)
+ String allottedResourceId = execution.getVariable("GENPS_allottedResourceId")
+ msoLogger.debug(" Incoming GENPS_allottedResourceId is: " + allottedResourceId)
+ String tunnelXconnectId = execution.getVariable("GENPS_tunnelXconnectId")
+ msoLogger.debug(" Incoming GENPS_tunnelXconnectId is: " + tunnelXconnectId)
+
+ // serviceAaiPath = "${aai_endpoint}${aai_uri}/" + URLEncoder.encode(globalSubscriberId,"UTF-8") + "/service-subscriptions/service-subscription/" + URLEncoder.encode(serviceType,"UTF-8")
+ serviceAaiPath = "${aai_endpoint}${aai_uri}/" + UriUtils.encode(globalSubscriberId,"UTF-8") + "/service-subscriptions/service-subscription/" + UriUtils.encode(serviceType,"UTF-8") + "/service-instances/service-instance/" + UriUtils.encode(serviceInstanceId,"UTF-8") + "/allotted-resources/allotted-resource/" + UriUtils.encode(allottedResourceId,"UTF-8") + "/tunnel-xconnects/tunnel-xconnect/" + UriUtils.encode(tunnelXconnectId,"UTF-8")
+ }
+
+ String resourceVersion = execution.getVariable("GENPS_serviceResourceVersion")
+ msoLogger.debug("Incoming Resource Version is: " + resourceVersion)
+ if(resourceVersion !=null){
+ serviceAaiPath = serviceAaiPath +'?resource-version=' + UriUtils.encode(resourceVersion,"UTF-8")
+ }
+
+ execution.setVariable("GENPS_putServiceInstanceAaiPath", serviceAaiPath)
+ msoLogger.debug("PUT Service Instance AAI Path is: " + "\n" + serviceAaiPath)
+
+ APIResponse response = aaiUriUtil.executeAAIPutCall(execution, serviceAaiPath, payload)
+ int responseCode = response.getStatusCode()
+ execution.setVariable("GENPS_putServiceInstanceResponseCode", responseCode)
+ msoLogger.debug(" Put Service Instance response code is: " + responseCode)
+
+ String aaiResponse = response.getResponseBodyAsString()
+ execution.setVariable("GENPS_putServiceInstanceResponse", aaiResponse)
+
+
+ //Process Response
+ if(responseCode == 200 || responseCode == 201 || responseCode == 202 )
+ //200 OK 201 CREATED 202 ACCEPTED
+ {
+ msoLogger.debug("PUT Service Instance Received a Good Response")
+ execution.setVariable("GENPS_SuccessIndicator", true)
+ }
+
+ else{
+ msoLogger.debug("Put Generic Service Instance Received a Bad Response Code. Response Code is: " + responseCode)
+ exceptionUtil.MapAAIExceptionToWorkflowExceptionGeneric(execution, aaiResponse, responseCode)
+ throw new BpmnError("MSOWorkflowException")
+ }
+ }catch(BpmnError b){
+ msoLogger.debug("Rethrowing MSOWorkflowException")
+ throw b
+ }catch(Exception e){
+ msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, " Error encountered within GenericPutService PutServiceInstance method!" + e, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "");
+ exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured During Put Service Instance")
+ }
+ msoLogger.trace("COMPLETED GenericPutService PutServiceInstance Process")
+ }
+
+
+
+}
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
new file mode 100644
index 0000000000..739bc4b7ed
--- /dev/null
+++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/DecomposeService.groovy
@@ -0,0 +1,170 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.so.bpmn.common.scripts
+
+import 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;
+import org.onap.so.bpmn.core.domain.ServiceDecomposition
+import org.onap.so.bpmn.core.json.DecomposeJsonUtil;
+import org.onap.so.bpmn.core.json.JsonUtils
+import org.onap.so.logger.MsoLogger
+
+/**
+ * This groovy class supports the <class>DecomposeService.bpmn</class> process.
+ *
+ * @author
+ *
+ * Inputs:
+ * @param - msoRequestId
+ * @param - isDebugLogEnabled
+ * @param - serviceInstanceId
+ * @param - serviceModelInfo
+ * @param - requestParameters (may be null)
+ *
+ * Outputs:
+ * @param - rollbackData (null)
+ * @param - rolledBack (null)
+ * @param - WorkflowException
+ * @param - serviceDecomposition
+ *
+ */
+public class DecomposeService extends AbstractServiceTaskProcessor {
+ private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, DecomposeService.class);
+
+
+ String Prefix="DDS_"
+ ExceptionUtil exceptionUtil = new ExceptionUtil()
+ CatalogDbUtils catalogDbUtils = new CatalogDbUtils()
+ JsonUtils jsonUtils = new JsonUtils()
+
+ public void preProcessRequest (DelegateExecution execution) {
+ String msg = ""
+ msoLogger.trace("preProcessRequest of DecomposeService ")
+ setBasicDBAuthHeader(execution, execution.getVariable('isDebugLogEnabled'))
+
+ try {
+ execution.setVariable("prefix", Prefix)
+ // check for required input
+ String requestId = execution.getVariable("msoRequestId")
+ String serviceInstanceId = execution.getVariable("serviceInstanceId")
+ String serviceModelInfo = execution.getVariable("serviceModelInfo")
+ String invariantId
+ if(jsonUtils.jsonElementExist(serviceModelInfo, "modelInvariantUuid")){
+ invariantId = jsonUtils.getJsonValue(serviceModelInfo, "modelInvariantUuid")
+ }else if(jsonUtils.jsonElementExist(serviceModelInfo, "modelInvariantId")){
+ invariantId = jsonUtils.getJsonValue(serviceModelInfo, "modelInvariantId")
+ }
+ execution.setVariable("DDS_serviceModelInvariantId", invariantId)
+ execution.setVariable("DDS_serviceModelUuid", jsonUtils.getJsonValue(serviceModelInfo, "modelUuid"))
+ execution.setVariable("DDS_modelVersion", jsonUtils.getJsonValue(serviceModelInfo, "modelVersion"))
+ } catch (BpmnError e) {
+ throw e;
+ } catch (Exception ex){
+ msg = "Exception in preProcessRequest " + ex.getMessage()
+ msoLogger.debug(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
+ }
+ msoLogger.trace("Exit preProcessRequest of DecomposeService ")
+ }
+
+ public void queryCatalogDb (DelegateExecution execution) {
+ String msg = ""
+ msoLogger.trace("queryCatalogDB of DecomposeService ")
+
+ try {
+
+ // check for input
+ String serviceModelInvariantId = execution.getVariable("DDS_serviceModelInvariantId")
+ String serviceModelUuid = execution.getVariable("DDS_serviceModelUuid")
+ String modelVersion = execution.getVariable("DDS_modelVersion")
+
+ msoLogger.debug("serviceModelInvariantId: " + serviceModelInvariantId)
+ msoLogger.debug("modelVersion: " + modelVersion)
+
+ JSONObject catalogDbResponse = null
+ if(serviceModelUuid != null && serviceModelUuid.length() > 0)
+ catalogDbResponse = catalogDbUtils.getServiceResourcesByServiceModelUuid(execution, serviceModelUuid, "v2")
+ else if (modelVersion != null && modelVersion.length() > 0)
+ catalogDbResponse = catalogDbUtils.getServiceResourcesByServiceModelInvariantUuidAndServiceModelVersion(execution, serviceModelInvariantId, modelVersion, "v2")
+ else
+ catalogDbResponse = catalogDbUtils.getServiceResourcesByServiceModelInvariantUuid(execution, serviceModelInvariantId, "v2")
+
+ if (catalogDbResponse == null || catalogDbResponse.toString().equalsIgnoreCase("null")) {
+ msg = "No data found in Catalog DB"
+ msoLogger.debug(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
+ }
+
+ String catalogDbResponseString = catalogDbResponse.toString()
+
+ execution.setVariable("DDS_catalogDbResponse", catalogDbResponseString)
+ msoLogger.debug("catalog DB response string: "+ catalogDbResponseString)
+
+ } catch (BpmnError e) {
+ throw e;
+ } catch (Exception ex){
+ msg = "Exception in queryCatalogDb " + ex.getMessage()
+ msoLogger.debug(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
+ }
+ msoLogger.trace("Exit queryCatalogDb of DecomposeService ")
+ }
+
+
+
+ public void actuallyDecomposeService (DelegateExecution execution) {
+ String msg = ""
+ msoLogger.trace("actuallyDecomposeService of DecomposeService ")
+
+ try {
+
+ // check for input
+ String requestId = execution.getVariable("msoRequestId")
+ String serviceInstanceId = execution.getVariable("serviceInstanceId")
+ String serviceModelInvariantId = execution.getVariable("DDS_serviceModelInvariantId")
+
+ msoLogger.debug("serviceModelInvariantId: " + serviceModelInvariantId)
+
+ msoLogger.debug("getting service decomposition")
+
+ String catalogDbResponse = execution.getVariable("DDS_catalogDbResponse")
+ ServiceDecomposition serviceDecomposition = DecomposeJsonUtil.jsonToServiceDecomposition(catalogDbResponse, serviceInstanceId)
+
+ execution.setVariable("serviceDecomposition", serviceDecomposition)
+ execution.setVariable("serviceDecompositionString", serviceDecomposition.toJsonString())
+
+ msoLogger.debug("service decomposition: "+ serviceDecomposition.toJsonString())
+
+ } catch (BpmnError e) {
+ throw e;
+ } catch (Exception ex){
+ msg = "Exception in actuallyDecomposeService " + ex.getMessage()
+ msoLogger.debug(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
+ }
+ msoLogger.trace("Exit actuallyDecomposeService of DecomposeService ")
+ }
+
+}
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
new file mode 100644
index 0000000000..bb9846c112
--- /dev/null
+++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/DeleteAAIVfModule.groovy
@@ -0,0 +1,335 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.so.bpmn.common.scripts
+import org.camunda.bpm.engine.delegate.DelegateExecution
+import org.onap.so.bpmn.core.WorkflowException
+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.logger.MessageEnum
+import org.onap.so.logger.MsoLogger
+
+public class DeleteAAIVfModule extends AbstractServiceTaskProcessor{
+ private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, DeleteAAIVfModule.class);
+
+ def Prefix="DAAIVfMod_"
+ ExceptionUtil exceptionUtil = new ExceptionUtil()
+ private MsoUtils utils = new MsoUtils()
+ public void initProcessVariables(DelegateExecution execution) {
+ execution.setVariable("prefix",Prefix)
+ execution.setVariable("DAAIVfMod_vnfId",null)
+ execution.setVariable("DAAIVfMod_vnfName",null)
+ execution.setVariable("DAAIVfMod_genVnfRsrcVer",null)
+ execution.setVariable("DAAIVfMod_vfModuleId",null)
+ execution.setVariable("DAAIVfMod_vfModRsrcVer",null)
+ execution.setVariable("DAAIVfMod_genericVnfEndpoint",null)
+ execution.setVariable("DAAIVfMod_vfModuleEndpoint",null)
+ execution.setVariable("DAAIVfMod_moduleExists",false)
+ execution.setVariable("DAAIVfMod_isBaseModule", false)
+ execution.setVariable("DAAIVfMod_isLastModule", false)
+
+ // DeleteAAIVfModule workflow response variable placeholders
+ execution.setVariable("DAAIVfMod_queryGenericVnfResponseCode",null)
+ execution.setVariable("DAAIVfMod_queryGenericVnfResponse","")
+ execution.setVariable("DAAIVfMod_parseModuleResponse","")
+ execution.setVariable("DAAIVfMod_deleteGenericVnfResponseCode",null)
+ execution.setVariable("DAAIVfMod_deleteGenericVnfResponse","")
+ execution.setVariable("DAAIVfMod_deleteVfModuleResponseCode",null)
+ execution.setVariable("DAAIVfMod_deleteVfModuleResponse","")
+
+ }
+
+ // parse the incoming DELETE_VF_MODULE request and store the Generic Vnf
+ // and Vf Module Ids in the flow DelegateExecution
+ public void preProcessRequest(DelegateExecution execution) {
+ def xml = execution.getVariable("DeleteAAIVfModuleRequest")
+ msoLogger.debug("DeleteAAIVfModule Request: " + xml)
+ msoLogger.debug("input request xml:" + xml)
+ initProcessVariables(execution)
+ def vnfId = utils.getNodeText(xml,"vnf-id")
+ def vfModuleId = utils.getNodeText(xml,"vf-module-id")
+ execution.setVariable("DAAIVfMod_vnfId", vnfId)
+ execution.setVariable("DAAIVfMod_vfModuleId", vfModuleId)
+
+ AaiUtil aaiUriUtil = new AaiUtil(this)
+ def aai_uri = aaiUriUtil.getNetworkGenericVnfUri(execution)
+ msoLogger.debug('AAI URI is: ' + aai_uri)
+
+ execution.setVariable("DAAIVfMod_genericVnfEndpoint", "${aai_uri}/" + vnfId)
+ execution.setVariable("DAAIVfMod_vfModuleEndpoint", "${aai_uri}/" + vnfId +
+ "/vf-modules/vf-module/" + vfModuleId)
+ }
+
+ // send a GET request to AA&I to retrieve the Generic Vnf/Vf Module information based on a Vnf Id
+ // 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) {
+ def delModuleId = execution.getVariable("DAAIVfMod_vfModuleId")
+ def endPoint = UrnPropertiesReader.getVariable("aai.endpoint", execution) + execution.getVariable("DAAIVfMod_genericVnfEndpoint") + "?depth=1"
+ msoLogger.debug("DeleteAAIVfModule endPoint: " + endPoint)
+ def aaiRequestId = utils.getRequestID()
+
+ RESTConfig config = new RESTConfig(endPoint);
+ msoLogger.debug("queryAAIForGenericVnf() endpoint-" + endPoint)
+ def responseData = ""
+ try {
+ RESTClient client = new RESTClient(config).addHeader("X-TransactionId", aaiRequestId).addHeader("X-FromAppId", "MSO").
+ addHeader("Accept","application/xml");
+ String basicAuthCred = utils.getBasicAuth(UrnPropertiesReader.getVariable("aai.auth", execution),UrnPropertiesReader.getVariable("mso.msoKey", execution))
+
+ if (basicAuthCred != null && !"".equals(basicAuthCred)) {
+ client.addAuthorizationHeader(basicAuthCred)
+ }
+ msoLogger.debug("invoking GET call to AAI endpoint :"+System.lineSeparator()+endPoint)
+ APIResponse response = client.httpGet()
+ msoLogger.debug("DeleteAAIVfModule - invoking httpGet to AAI")
+
+ responseData = response.getResponseBodyAsString()
+ execution.setVariable("DAAIVfMod_queryGenericVnfResponseCode", response.getStatusCode())
+ execution.setVariable("DAAIVfMod_queryGenericVnfResponse", responseData)
+ msoLogger.debug("AAI Response: " + responseData)
+ msoLogger.debug("Response code:" + response.getStatusCode())
+ msoLogger.debug("Response:" + System.lineSeparator()+responseData)
+ } catch (Exception ex) {
+ msoLogger.debug("Exception occurred while executing AAI GET:" + ex.getMessage())
+ execution.setVariable("DAAIVfMod_queryGenericVnfResponse", "AAI GET Failed:" + ex.getMessage())
+ exceptionUtil.buildAndThrowWorkflowException(execution, 5000, "Internal Error - Occured during queryAAIForGenericVnf")
+
+ }
+ }
+
+ // construct and send a DELETE request to A&AI to delete a Generic Vnf
+ // note: to get here, all the modules associated with the Generic Vnf must already be deleted
+ public void deleteGenericVnf(DelegateExecution execution) {
+ def aaiRequestId = utils.getRequestID()
+ def endPoint = UrnPropertiesReader.getVariable("aai.endpoint", execution) + execution.getVariable("DAAIVfMod_genericVnfEndpoint") +
+ "/?resource-version=" + execution.getVariable("DAAIVfMod_genVnfRsrcVer")
+ msoLogger.debug("AAI endPoint: " + endPoint)
+ RESTConfig config = new RESTConfig(endPoint);
+ msoLogger.debug("deleteGenericVnf() endpoint-" + endPoint)
+ def responseData = ""
+ try {
+ RESTClient client = new RESTClient(config).addHeader("X-TransactionId", aaiRequestId).addHeader("X-FromAppId", "MSO").
+ addHeader("Accept","application/xml");
+
+ String basicAuthCred = utils.getBasicAuth(UrnPropertiesReader.getVariable("aai.auth", execution),UrnPropertiesReader.getVariable("mso.msoKey", execution))
+
+ if (basicAuthCred != null && !"".equals(basicAuthCred)) {
+ client.addAuthorizationHeader(basicAuthCred)
+ }
+ APIResponse response = client.httpDelete()
+
+ 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)
+ } catch (Exception ex) {
+ ex.printStackTrace()
+ msoLogger.debug("Exception occurred while executing AAI DELETE:" + ex.getMessage())
+ exceptionUtil.buildAndThrowWorkflowException(execution, 5000, "Internal Error - Occured during deleteGenericVnf")
+ }
+ }
+
+ // construct and send a DELETE request to A&AI to delete the Base or Add-on Vf Module
+ public void deleteVfModule(DelegateExecution execution) {
+ def endPoint = UrnPropertiesReader.getVariable("aai.endpoint", execution) + execution.getVariable("DAAIVfMod_vfModuleEndpoint") +
+ "/?resource-version=" + execution.getVariable("DAAIVfMod_vfModRsrcVer")
+ def aaiRequestId = utils.getRequestID()
+
+ RESTConfig config = new RESTConfig(endPoint);
+ msoLogger.debug("deleteVfModule() endpoint-" + endPoint)
+ def responseData = ""
+ try {
+ RESTClient client = new RESTClient(config).addHeader("X-TransactionId", aaiRequestId).addHeader("X-FromAppId", "MSO").
+ addHeader("Accept","application/xml");
+
+ String basicAuthCred = utils.getBasicAuth(UrnPropertiesReader.getVariable("aai.auth", execution),UrnPropertiesReader.getVariable("mso.msoKey", execution))
+
+ if (basicAuthCred != null && !"".equals(basicAuthCred)) {
+ client.addAuthorizationHeader(basicAuthCred)
+ }
+ APIResponse response = client.httpDelete()
+
+ msoLogger.debug("DeleteAAIVfModule - invoking httpDelete to AAI")
+
+ 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)
+
+ } catch (Exception ex) {
+ ex.printStackTrace()
+ msoLogger.debug("Exception occurred while executing AAI PUT:" + ex.getMessage())
+ exceptionUtil.buildAndThrowWorkflowException(execution, 5000, "Internal Error - Occured during deleteVfModule")
+ }
+ }
+
+ // 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 parseForVfModule(DelegateExecution execution) {
+ def xml = execution.getVariable("DAAIVfMod_queryGenericVnfResponse")
+ msoLogger.debug("DeleteAAIVfModule - queryGenericVnfResponse" + xml)
+
+ 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"))
+ }
+ }
+
+ // 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)
+ }
+
+
+ // generates a WorkflowException if the A&AI query returns a response code other than 200
+ public void handleAAIQueryFailure(DelegateExecution execution) {
+ msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Error occurred attempting to query AAI, Response Code " + execution.getVariable("DAAIVfMod_queryGenericVnfResponseCode") + ", Error Response " + execution.getVariable("DAAIVfMod_queryGenericVnfResponse"), "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "");
+ def errorCode = 5000
+ // set the errorCode to distinguish between a A&AI failure
+ // and the Generic Vnf Id not found
+ if (execution.getVariable("DAAIVfMod_queryGenericVnfResponseCode") == 404) {
+ errorCode = 1002
+ }
+ exceptionUtil.buildAndThrowWorkflowException(execution, errorCode, execution.getVariable("DAAIVfMod_queryGenericVnfResponse"))
+ }
+
+ // generates a WorkflowException if
+ // - the A&AI Vf Module DELETE returns a response code other than 200
+ // - the Vf Module is a Base Module that is not the last Vf Module
+ // - the Vf Module does not exist for the Generic Vnf
+ public void handleDeleteVfModuleFailure(DelegateExecution execution) {
+ def errorCode = 2000
+ def errorResponse = ""
+ if (execution.getVariable("DAAIVfMod_deleteVfModuleResponseCode") != null &&
+ execution.getVariable("DAAIVfMod_deleteVfModuleResponseCode") != 200) {
+ msoLogger.debug("AAI failure deleting a Vf Module: " + execution.getVariable("DAAIVfMod_deleteVfModuleResponse"))
+ errorResponse = execution.getVariable("DAAIVfMod_deleteVfModuleResponse")
+ msoLogger.debug("DeleteAAIVfModule - deleteVfModuleResponse" + errorResponse)
+ errorCode = 5000
+ } else {
+ if (execution.getVariable("DAAIVfMod_isBaseModule", true) == true &&
+ execution.getVariable("DAAIVfMod_isLastModule") == false) {
+ // attempt to delete a Base Module that is not the last Vf Module
+ msoLogger.debug(execution.getVariable("DAAIVfMod_parseModuleResponse"))
+ errorResponse = execution.getVariable("DAAIVfMod_parseModuleResponse")
+ msoLogger.debug("DeleteAAIVfModule - parseModuleResponse" + errorResponse)
+ errorCode = 1002
+ } else {
+ // attempt to delete a non-existant Vf Module
+ if (execution.getVariable("DAAIVfMod_moduleExists") == false) {
+ msoLogger.debug(execution.getVariable("DAAIVfMod_parseModuleResponse"))
+ errorResponse = execution.getVariable("DAAIVfMod_parseModuleResponse")
+ msoLogger.debug("DeleteAAIVfModule - parseModuleResponse" + errorResponse)
+ errorCode = 1002
+ } else {
+ // if the responses get populated corerctly, we should never get here
+ errorResponse = "Unknown error occurred during DeleteAAIVfModule flow"
+ }
+ }
+ }
+
+ msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Error occurred during DeleteAAIVfModule flow", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, errorResponse);
+ exceptionUtil.buildAndThrowWorkflowException(execution, errorCode, errorResponse)
+
+ }
+
+ // generates a WorkflowException if
+ // - the A&AI Generic Vnf DELETE returns a response code other than 200
+ public void handleDeleteGenericVnfFailure(DelegateExecution execution) {
+ 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
new file mode 100644
index 0000000000..de5408fac5
--- /dev/null
+++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/ExceptionUtil.groovy
@@ -0,0 +1,422 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.so.bpmn.common.scripts
+
+import static org.apache.commons.lang3.StringUtils.*
+
+import com.google.common.xml.XmlEscapers
+
+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.logger.MessageEnum
+import org.onap.so.logger.MsoLogger
+
+
+
+/**
+ * @version 1.0
+ */
+class ExceptionUtil extends AbstractServiceTaskProcessor {
+ private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, ExceptionUtil.class);
+
+
+
+ /**
+ * This error handling method maps an AAI Exception response to a
+ * WorkflowException Object. It then sets the WorkflowException Object
+ * on the execution as "WorkflowException".
+ *
+ * This method formats the exception from AAI into the WorkflowException's
+ * errorMessage that CCD expects.
+ *
+ * @param execution the execution
+ * @param response the aai exception
+ */
+ WorkflowException MapAAIExceptionToWorkflowException(String response, DelegateExecution execution)
+ {
+ def utils=new MsoUtils()
+ def prefix=execution.getVariable("prefix")
+ def errorMsg = execution.getVariable(prefix+"ErrorResponse")
+ msoLogger.trace("Begin MapAAIExceptionToWorkflowException ")
+ String text = null
+ def variables
+ String errorCode = '5000'
+ WorkflowException wfex
+ msoLogger.debug("response: " + response)
+ try{
+ try {
+ //String msg = utils.getNodeXml(response, "Fault")
+ variables = utils.getMultNodes(response, "variable")
+ text = utils.getNodeText(response, "text")
+ } catch (Exception ex) {
+ //Ignore the exception - cases include non xml payload
+ msoLogger.debug("error mapping error, ignoring: " + ex)
+ }
+
+ if(text != null) {
+ if(variables.size()>=4){
+ text = text.replaceFirst("%1", variables[0])
+ text = text.replaceFirst("%2", variables[1])
+ text = text.replaceFirst("%3", variables[2])
+ text = text.replaceFirst("%4", variables[3])
+ }
+ String modifiedErrorMessage = 'Received error from A&amp;AI (' + text +')'
+ msoLogger.debug("ModifiedErrorMessage " + modifiedErrorMessage)
+ // let $ModifiedErrorMessage := concat( 'Received error from A',$exceptionaai:ampersand,'AI (' ,functx:replace-multi($ErrorMessage,$from,$Variables ),')')
+ buildWorkflowException(execution, 5000, modifiedErrorMessage)
+
+ wfex = execution.getVariable("WorkflowException")
+ msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Fault", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, wfex.errorMessage);
+ return wfex
+ } else {
+ try {
+ errorCode = MapErrorCode(errorMsg)
+ String mappedErrorMessage = MapErrorMessage(errorMsg, errorCode)
+
+ int errorCodeInt = Integer.parseInt(errorCode)
+ buildWorkflowException(execution, errorCodeInt, mappedErrorMessage)
+
+ msoLogger.debug("mappedErrorMessage " + mappedErrorMessage)
+ wfex = execution.getVariable("WorkflowException")
+ msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Fault", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, wfex.errorMessage);
+ return wfex
+ } catch(Exception ex) {
+ msoLogger.debug("error mapping error, return null: " + ex)
+ return null
+
+ }
+ }
+ }catch(Exception e){
+ msoLogger.debug("Exception occured during MapAAIExceptionToWorkflowException: " + e)
+ buildWorkflowException(execution, 5000, "Error mapping AAI Response to WorkflowException")
+ }
+ }
+
+ /**
+ * This error handling method maps an AAI Exception response to a
+ * WorkflowException Object. It then sets the WorkflowException Object
+ * on the execution as "WorkflowException".
+ *
+ * This method takes the exact exception inside the <Fault> tags from AAI Response
+ * and puts it into the WorkflowException's errorMessage.
+ *
+ * @param execution the execution
+ * @param response the aai exception
+ */
+ WorkflowException MapAAIExceptionToWorkflowExceptionGeneric(DelegateExecution execution, String response, int resCode){
+ def utils=new MsoUtils()
+ msoLogger.debug("Start MapAAIExceptionToWorkflowExceptionGeneric Process")
+
+ WorkflowException wfex
+ try {
+ if(utils.nodeExists(response, "Fault")){
+ String fault = utils.getNodeXml(response, "Fault")
+ fault = utils.removeXmlPreamble(fault)
+ fault = fault.replace("<Fault>", "").replace("</Fault>", "")
+ fault = fault.replaceAll("\\s+\\s+", "") // Removes extra white spaces
+ buildWorkflowException(execution, resCode, fault)
+ }else if(utils.nodeExists(response, "RESTFault")){
+ String rFault = utils.getNodeXml(response, "RESTFault")
+ buildWorkflowException(execution, resCode, rFault)
+ }else{
+ buildWorkflowException(execution, resCode, "Received a bad response from AAI")
+ }
+ } catch (Exception ex) {
+ msoLogger.debug("Exception Occured during MapAAIExceptionToWorkflowExceptionGeneric: " + ex)
+ buildWorkflowException(execution, resCode, "Internal Error - Occured in MapAAIExceptionToWorkflowExceptionGeneric")
+
+ }
+ msoLogger.debug("Outgoing WorkflowException is: " + execution.getVariable("WorkflowException"))
+ msoLogger.debug("Completed MapAAIExceptionToWorkflowExceptionGeneric Process")
+ }
+
+ /**
+ * This method takes a WorkflowException Object and builds
+ * WorkflowException Xml. This method should only be used
+ * for the purpose of sending a sync error response or for
+ * creating a FalloutHandler request.
+ *
+ *@param - WorkflowException Object
+ *
+ *@return - String WorkflowException Xml
+ *
+ *
+ */
+ String buildErrorResponseXml(WorkflowException wfex) {
+ String xml
+ if(wfex != null){
+ String mes = XmlEscapers.xmlContentEscaper().escape(wfex.getErrorMessage())
+ int code = wfex.getErrorCode()
+ xml =
+ """<aetgt:WorkflowException xmlns:aetgt="http://org.onap/so/workflow/schema/v1">
+ <aetgt:ErrorMessage>${MsoUtils.xmlEscape(mes)}</aetgt:ErrorMessage>
+ <aetgt:ErrorCode>${MsoUtils.xmlEscape(code)}</aetgt:ErrorCode>
+ </aetgt:WorkflowException>"""
+
+ }else{
+ xml =
+ """<aetgt:WorkflowException xmlns:aetgt="http://org.onap/so/workflow/schema/v1">
+ <aetgt:ErrorMessage>Internal Error</aetgt:ErrorMessage>
+ <aetgt:ErrorCode>2500</aetgt:ErrorCode>
+ </aetgt:WorkflowException>"""
+ }
+ return xml
+ }
+
+ /*
+ 5000 Received error from A&AI ($A&AI_ERROR) Asynchronous During orchestration of the recipe, A&AI returned an error. The error returned by A&AI is passed through in $A&AI_ERROR.
+ 5010 Could not communicate with A&AI Asynchronous During orchestration of the recipe, a connection with A&AI could not be established.
+ 5020 No response from A&AI Asynchronous During orchestration of the recipe, communication was established with A&AI, but no response was received within the configured timeout.
+ */
+ /**
+ *
+ * Utility Method for MapAAIExceptionToWorkflowException
+ *
+ *@param - String ErrorMessage
+ *
+ *@return - String ErrorCode
+ *
+ */
+ private String MapErrorCode(String errorMessage)
+ {
+ if(errorMessage==null){
+ return '5000'
+ }
+ errorMessage = errorMessage.toLowerCase();
+ if(errorMessage.contains('timed out') || errorMessage.contains('timeout'))
+ return '5020'
+ else if (errorMessage.contains('connection'))
+ return '5010'
+ else
+ return '5000'
+ }
+
+ /**
+ *
+ * Utility Method for MapAAIExceptionToWorkflowException
+ *
+ *@param - String ErrorMessage
+ *@param - String ErrorCode
+ *
+ *@return - String ErrorMessage
+ *
+ */
+ private String MapErrorMessage(String errorMessage, String errorCode)
+ {
+ if(errorMessage == null){
+ errorMessage=""
+ }
+ if( errorCode.equals('5010')){
+ return 'Could not communicate with A&AI'
+ }else if (errorCode.equals('5020')){
+ return 'No response from A&AI'
+ }else{
+ return 'Received error from A&AI (' +errorMessage +')'
+ }
+ }
+
+ /**
+ *
+ * Utility Method for Mapping SDNC
+ * Adapter Response Codes
+ *
+ *@param - String sdncResponseCode
+ *
+ *@return - String code
+ *
+ */
+ String MapSDNCResponseCodeToErrorCode(String sdncResponseCode)
+ {
+ if (sdncResponseCode == '500') {
+ return '5310'
+ } else if ( sdncResponseCode == '408') {
+ return '5320'
+ } else if ( sdncResponseCode == '60010') {
+ return '5350'
+ } else {
+ return '5300'
+ }
+ }
+
+ /**
+ * This error handling method builds a WorkflowException Object. It sets it on
+ * the execution as "WorkflowException".
+ *
+ * @param execution the execution
+ * @param errorCode the error code
+ * @param errorMessage the error message
+ */
+ public void buildWorkflowException(DelegateExecution execution, int errorCode, String errorMessage) {
+ MsoUtils utils = new MsoUtils()
+ String processKey = getProcessKey(execution);
+ msoLogger.debug("Building a WorkflowException for " + processKey)
+
+ WorkflowException exception = new WorkflowException(processKey, errorCode, errorMessage);
+ execution.setVariable("WorkflowException", exception);
+ msoLogger.debug("Outgoing WorkflowException is " + exception)
+ }
+
+ /**
+ * This error handling method builds a WorkflowException Object and throws a
+ * MSOWorkflowException. It throws a "MSOWorkflowException" BpmnError after
+ * setting the WorkflowException Object on the execution as "WorkflowException".
+ *
+ * @param execution the execution
+ * @param errorCode the error code
+ * @param errorMessage the error message
+ */
+ public void buildAndThrowWorkflowException(DelegateExecution execution, int errorCode, String errorMessage) {
+ String processKey = getProcessKey(execution);
+ msoLogger.debug("Building a WorkflowException for Subflow " + processKey)
+
+ WorkflowException exception = new WorkflowException(processKey, errorCode, errorMessage);
+ execution.setVariable("WorkflowException", exception);
+ msoLogger.debug("Outgoing WorkflowException is " + exception)
+ msoLogger.debug("Throwing MSOWorkflowException")
+ throw new BpmnError("MSOWorkflowException")
+ }
+
+ /**
+ * This method is executed after an MSOWorkflowException is caught by a
+ * subflow (during subflows "Error Handling Sub Process").
+ * It ensures the WorkflowException variable is populated before ending the
+ * subflow and also logs the subflows outgoing WorkflowException Variable.
+ *
+ * @param - execution
+ *
+ */
+ public void processSubflowsBPMNException(DelegateExecution execution){
+ String processKey = getProcessKey(execution)
+ try{
+ msoLogger.debug("Started ProcessSubflowsBPMNException Method")
+ if(execution.getVariable("WorkflowException") == null){
+ buildWorkflowException(execution, 2500, "Internal Error - Occured During " + processKey)
+ }
+
+ msoLogger.debug(processKey + " Outgoing WorkflowException is: " + execution.getVariable("WorkflowException"))
+ }catch(Exception e){
+ msoLogger.debug("Caught Exception during ProcessSubflowsBPMNException Method: " + e)
+ }
+ msoLogger.debug("Completed ProcessSubflowsBPMNException Method")
+ }
+
+ /**
+ * This method is executed after an MSOWorkflowException is caught by a
+ * Mainflow. It builds and returns a FalloutHandler Request. It also
+ * verifies the WorkflowException variable is populated.
+ *
+ * @param - execution
+ * @param - requestInfo
+ *
+ * @return - falloutHandlerRequest
+ *
+ */
+ public String processMainflowsBPMNException(DelegateExecution execution, String requestInfo){
+ String processKey = getProcessKey(execution)
+ try{
+ msoLogger.debug("Started ProcessMainflowBPMNException Method")
+ if(execution.getVariable("WorkflowException") == null || isBlank(requestInfo)){
+ buildWorkflowException(execution, 2500, "Internal Error - WorkflowException Object and/or RequestInfo is null! " + processKey)
+ }
+ requestInfo = utils.removeXmlPreamble(requestInfo)
+ WorkflowException wfex = execution.getVariable("WorkflowException")
+ String errorMessage = XmlEscapers.xmlContentEscaper().escape(wfex.getErrorMessage())
+ int errorCode = wfex.getErrorCode()
+
+ String falloutHandlerRequest =
+ """<aetgt:FalloutHandlerRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1"
+ xmlns:ns="http://org.onap/so/request/types/v1"
+ xmlns:wfsch="http://org.onap/so/workflow/schema/v1">
+ ${requestInfo}
+ <aetgt:WorkflowException xmlns:aetgt="http://org.onap/so/workflow/schema/v1">
+ <aetgt:ErrorMessage>${MsoUtils.xmlEscape(errorMessage)}</aetgt:ErrorMessage>
+ <aetgt:ErrorCode>${MsoUtils.xmlEscape(errorCode)}</aetgt:ErrorCode>
+ </aetgt:WorkflowException>
+ </aetgt:FalloutHandlerRequest>"""
+
+ msoLogger.debug(processKey + " Outgoing WorkflowException is: " + execution.getVariable("WorkflowException"))
+ msoLogger.debug(processKey + " Outgoing FalloutHandler Request is: " + falloutHandlerRequest)
+
+ return falloutHandlerRequest
+
+ }catch(Exception e){
+ msoLogger.debug("Caught Exception during ProcessMainflowBPMNException Method: " + e)
+ return null
+ }
+ msoLogger.debug("Completed ProcessMainflowBPMNException Method")
+ }
+
+ /**
+ *
+ * This method is executed after an Java Exception is caught
+ * It sets the WorkflowException variable. The method can be used in either mainflow or subflows.
+ *
+ * @param - execution
+ *
+ */
+ public void processJavaException(DelegateExecution execution){
+ String processKey = getProcessKey(execution)
+ try{
+ msoLogger.debug("Caught a Java Exception in " + processKey)
+ msoLogger.debug("Started processJavaException Method")
+ // if the BPMN flow java error handler sets "BPMN_javaExpMsg", append it to the WFE
+ String javaExpMsg = execution.getVariable("BPMN_javaExpMsg")
+ String wfeExpMsg = "Catch a Java Lang Exception in " + processKey
+ if (javaExpMsg != null && !javaExpMsg.empty) {
+ wfeExpMsg = wfeExpMsg + ": " + javaExpMsg
+ }
+ buildWorkflowException(execution, 2500, wfeExpMsg)
+
+ }catch(BpmnError b){
+ throw b
+ }catch(Exception e){
+ msoLogger.debug("Caught Exception during processJavaException Method: " + e)
+ buildWorkflowException(execution, 2500, "Internal Error - During Process Java Exception")
+ }
+ msoLogger.debug("Completed processJavaException Method")
+ }
+
+
+ public void preProcessRequest(DelegateExecution execution) {
+ // TODO Auto-generated method stub
+
+ }
+
+ public String getErrorMessage(WorkflowException wfe, String processKey) {
+ if(wfe == null) {
+ return "Unexpected error encountered in " + processKey
+ }
+ else {
+ return wfe.getErrorMessage()
+ }
+ }
+
+ public int getErrorCode(WorkflowException wfe) {
+ if(wfe == null) {
+ return 2500
+ }
+ else {
+ return wfe.getErrorCode()
+ }
+ }
+}
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
new file mode 100644
index 0000000000..9732693f38
--- /dev/null
+++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/FalloutHandler.groovy
@@ -0,0 +1,378 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.so.bpmn.common.scripts
+
+import org.onap.so.bpmn.core.UrnPropertiesReader
+
+import java.text.SimpleDateFormat
+
+import org.apache.commons.lang3.*
+import org.camunda.bpm.engine.delegate.DelegateExecution
+import org.onap.so.logger.MessageEnum
+import org.onap.so.logger.MsoLogger
+
+public class FalloutHandler extends AbstractServiceTaskProcessor {
+ private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, FalloutHandler.class);
+
+ String Prefix="FH_"
+ ExceptionUtil exceptionUtil = new ExceptionUtil()
+
+ public initializeProcessVariables(DelegateExecution execution){
+ def method = getClass().getSimpleName() + '.initializeProcessVariables(' +'execution=' + execution.getId() +')'
+ msoLogger.trace('Entered ' + method)
+
+ try {
+ execution.setVariable("prefix",Prefix)
+
+ //These variables are form the input Message to the BPMN
+ execution.setVariable("FH_request_id","")
+ execution.setVariable("FH_request_action","")
+ execution.setVariable("FH_notification-url","")
+ execution.setVariable("FH_mso-bpel-name","")
+ execution.setVariable("FH_ErrorCode", "")
+ execution.setVariable("FH_ErrorMessage", "")
+
+ execution.setVariable("FH_notification-url-Ok", false)
+ execution.setVariable("FH_request_id-Ok", false)
+
+ //These variables are for Get Mso Aai Password Adapter
+ execution.setVariable("FH_deliveryStatus", true)
+
+ //update Response Status to pending ...Adapter variables
+ execution.setVariable("FH_updateResponseStatusPayload", null)
+ execution.setVariable("FH_updateResponseStatusResponse", null)
+
+ //update Request Gamma ...Adapter variables
+ execution.setVariable("FH_updateRequestGammaPayload", "")
+ execution.setVariable("FH_updateRequestGammaResponse", null)
+ execution.setVariable("FH_updateRequestGammaResponseCode", null)
+
+ //update Request Infra ...Adapter variables
+ execution.setVariable("FH_updateRequestInfraPayload", "")
+ execution.setVariable("FH_updateRequestInfraResponse", null)
+ execution.setVariable("FH_updateRequestInfraResponseCode", null)
+
+ //assign True to success variable
+ execution.setVariable("FH_success", true)
+
+ //Set notify status to Failed variable
+ execution.setVariable("FH_NOTIFY_STATUS", "SUCCESS")
+
+ //Set DB update variable
+ execution.setVariable("FH_updateRequestPayload", "")
+ execution.setVariable("FH_updateRequestResponse", null)
+ execution.setVariable("FH_updateRequestResponseCode", null)
+
+ //Auth variables
+ execution.setVariable("BasicAuthHeaderValue","")
+
+ //Parameter list
+ execution.setVariable("FH_parameterList", "")
+
+ //Response variables
+ execution.setVariable("FalloutHandlerResponse","")
+ execution.setVariable("FH_ErrorResponse", null)
+ execution.setVariable("FH_ResponseCode", "")
+
+ } catch (Exception e) {
+ msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e);
+ // exceptionUtil.buildWorkflowException(execution, 2000, "Internal Error - Occured in " + method)
+ }
+ }
+
+ public void preProcessRequest (DelegateExecution execution) {
+ def method = getClass().getSimpleName() + '.preProcessRequest(' +'execution=' + execution.getId() +')'
+ msoLogger.trace('Entered ' + method)
+
+ // Initialize flow variables
+ initializeProcessVariables(execution)
+ setSuccessIndicator(execution, false)
+
+ setBasicDBAuthHeader(execution, execution.getVariable('isDebugLogEnabled'))
+
+ try {
+ def xml = execution.getVariable("FalloutHandlerRequest")
+ msoLogger.debug(" XML --> " + xml)
+ msoLogger.debug("FalloutHandler request: " + xml)
+
+ //Check the incoming request type
+ //Incoming request can be ACTIVE_REQUESTS (request-information node) or INFRA_ACTIVE_REQUESTS (request-info node)
+ if (utils.nodeExists(xml, "request-information")) {
+ execution.setVariable("FH_request_id-Ok", true) // Incoming request is for ACTIVE_REQUESTS
+ }
+
+ //Check notification-url for the incoming request type
+ //ACTIVE_REQUESTS may have notificationurl node
+ //INFRA_ACTIVE_REQUESTS notificationurl node does not exist
+ def notificationurl = ""
+ if (utils.nodeExists(xml, "notification-url")) {
+ notificationurl = utils.getNodeText(xml,"notification-url")
+ if(notificationurl != null && !notificationurl.isEmpty()) {
+ msoLogger.debug("********** Incoming notification Url is: " + notificationurl);
+ execution.setVariable("FH_notification-url-Ok", true)
+ execution.setVariable("FH_notification-url",notificationurl)
+ }
+ }
+
+ //Check request_id for the incoming request type
+ //For INFRA_ACTIVE_REQUESTS payload request-id IS optional (Not sure why this is option since req id is primary key ... also tried exe through SOAP UI to check if MSO code handles null like auto generated seq not it does not)
+ //For ACTIVE_REQUESTS payload request-id is NOT optional
+ def request_id = ""
+ if (utils.nodeExists(xml, "request-id")) {
+ execution.setVariable("FH_request_id",utils.getNodeText(xml,"request-id"))
+ }
+ msoLogger.debug("FH_request_id: " + execution.getVariable("FH_request_id"))
+
+ // INFRA_ACTIVE_REQUESTS have "action" element ... mandatory
+ // ACTIVE_REQUEST have "request-action" ... mandatory
+ if (utils.nodeExists(xml, "request-action")) {
+ execution.setVariable("FH_request_action",utils.getNodeText(xml,"request-action"))
+ } else if (utils.nodeExists(xml, "action")) {
+ execution.setVariable("FH_request_action",utils.getNodeText(xml,"action"))
+ }
+
+
+ //Check source for the incoming request type
+ //For INFRA_ACTIVE_REQUESTS payload source IS optional
+ //For ACTIVE_REQUESTS payload source is NOT optional
+ def source = ""
+ if (utils.nodeExists(xml, "source")) {
+ execution.setVariable("FH_source",utils.getNodeText(xml,"source"))
+ }
+
+ //Check if ErrorCode node exists. If yes, initialize it from request xml, if no, it will stay with defaulf value already set in initializeProcessVariables() method above.
+ def errorCode = ""
+ if (utils.nodeExists(xml, "ErrorCode")) {
+ errorCode = utils.getNodeText(xml,"ErrorCode")
+ if(errorCode != null && !errorCode.isEmpty()) {
+ execution.setVariable("FH_ErrorCode", errorCode)
+ }
+ }
+ msoLogger.debug("FH_ErrorCode: " + errorCode)
+
+ //Check if ErrorMessage node exists. If yes, initialize it from request xml, if no, it will stay with defaulf value already set in initializeProcessVariables() method above.
+ def errorMessage = ""
+ if (utils.nodeExists(xml, "ErrorMessage")) {
+ errorCode = utils.getNodeText(xml,"ErrorMessage")
+ if(errorCode != null && !errorCode.isEmpty()) {
+ errorCode = errorCode
+ execution.setVariable("FH_ErrorMessage", errorCode)
+ }
+ }
+
+ //Check for Parameter List
+ if (utils.nodeExists(xml, "parameter-list")) {
+ def parameterList = utils.getNodeXml(xml, "parameter-list", false)
+ execution.setVariable("FH_parameterList", parameterList)
+ }
+
+ msoLogger.trace("--> " + execution.getVariable(""))
+ msoLogger.debug("FH_request_id-OK --> " + execution.getVariable("FH_request_id-Ok"))
+
+ // set the DHV/Service Instantiation values if specified in the request
+ execution.setVariable("FH_is_srv_inst_req", String.valueOf("true".equals(utils.getNodeText(xml, "is-srv-inst-req"))))
+ msoLogger.trace("--> " + execution.getVariable(""))
+ execution.setVariable("FH_is_json_content", String.valueOf("JSON".equals(utils.getNodeText(xml, "resp-content-type"))))
+ msoLogger.trace("--> " + execution.getVariable(""))
+ execution.setVariable("FH_service_inst_id", utils.getNodeText(xml, "service-instance-id"))
+ msoLogger.trace("--> " + execution.getVariable(""))
+ execution.setVariable("FH_start_time", utils.getNodeText(xml, "start-time"))
+ msoLogger.trace("--> " + execution.getVariable(""))
+ // this variable is used by the camunda flow to set the Content-Type for the async response
+ if (execution.getVariable("FH_is_srv_inst_req").equals("true") &&
+ execution.getVariable("FH_is_json_content").equals("true")) {
+ execution.setVariable("FH_content_type", "application/json")
+ } else {
+ execution.setVariable("FH_content_type", "text/xml")
+ }
+ } catch (Exception e) {
+ msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e);
+ // exceptionUtil.buildWorkflowException(execution, 2000, "Internal Error - Occured in" + method)
+ }
+
+ msoLogger.debug("OUTOF --> Initialize Variables Fallout Handler #########");
+ }
+
+ public String updateRequestPayload (DelegateExecution execution){
+ def method = getClass().getSimpleName() + '.updateRequestPayload(' +'execution=' + execution.getId() +')'
+ msoLogger.trace('Entered ' + method)
+
+ try {
+ String payload = """
+ <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:req="http://org.onap.so/requestsdb">
+ <soapenv:Header/>
+ <soapenv:Body>
+ <req:updateRequest>
+ <requestId>${MsoUtils.xmlEscape(execution.getVariable("FH_request_id"))}</requestId>
+ <lastModifiedBy>BPEL</lastModifiedBy>
+ <finalErrorMessage>${MsoUtils.xmlEscape(execution.getVariable("FH_ErrorMessage"))}</finalErrorMessage>
+ <finalErrorCode>${MsoUtils.xmlEscape(execution.getVariable("FH_ErrorCode"))}</finalErrorCode>
+ <status>FAILED</status>
+ <responseStatus>${MsoUtils.xmlEscape(execution.getVariable("FH_NOTIFY_STATUS"))}</responseStatus>
+ </req:updateRequest>
+ </soapenv:Body>
+ </soapenv:Envelope>
+ """
+
+ msoLogger.debug("updateRequestPayload: " + payload)
+ execution.setVariable("FH_updateRequestPayload", payload)
+ return execution.getVariable("FH_updateRequestPayload")
+ } catch (Exception e) {
+ msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e);
+ // exceptionUtil.buildWorkflowException(execution, 2000, "Internal Error - Occured in " + method)
+ }
+ }
+
+ public String updateRequestInfraPayload (DelegateExecution execution){
+ def method = getClass().getSimpleName() + '.updateRequestInfraPayload(' +'execution=' + execution.getId() +')'
+ msoLogger.trace('Entered ' + method)
+
+ try {
+ String payload = """
+ <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:req="http://org.onap.so/requestsdb">
+ <soapenv:Header/>
+ <soapenv:Body>
+ <req:updateInfraRequest>
+ <requestId>${MsoUtils.xmlEscape(execution.getVariable("FH_request_id"))}</requestId>
+ <lastModifiedBy>BPEL</lastModifiedBy>
+ <statusMessage>${MsoUtils.xmlEscape(execution.getVariable("FH_ErrorMessage"))}</statusMessage>
+ <requestStatus>FAILED</requestStatus>
+ <progress>100</progress>
+ </req:updateInfraRequest>
+ </soapenv:Body>
+ </soapenv:Envelope>
+ """
+
+ execution.setVariable("FH_updateRequestInfraPayload", payload)
+ msoLogger.debug("updateRequestInfraPayload: " + payload)
+ return execution.getVariable("FH_updateRequestInfraPayload")
+ } catch (Exception e) {
+ msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e);
+ // exceptionUtil.buildWorkflowException(execution, 2000, "Internal Error - Occured in " + method)
+ }
+ }
+
+ public String updateRequestGammaPayload (DelegateExecution execution){
+ def method = getClass().getSimpleName() + '.updateRequestGammaPayload(' +'execution=' + execution.getId() +')'
+ msoLogger.trace('Entered ' + method)
+
+ try {
+ String payload = """
+ <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:req="${UrnPropertiesReader.getVariable("mso.default.adapter.namespace", execution)}/requestsdb">
+ <soapenv:Header/>
+ <soapenv:Body>
+ <req:updateRequest>
+ <requestId>${MsoUtils.xmlEscape(execution.getVariable("FH_request_id"))}</requestId>
+ <lastModifiedBy>BPEL</lastModifiedBy>
+ <finalErrorMessage>${MsoUtils.xmlEscape(execution.getVariable("FH_ErrorMessage"))}</finalErrorMessage>
+ <finalErrorCode>${MsoUtils.xmlEscape(execution.getVariable("FH_ErrorCode"))}</finalErrorCode>
+ <status>FAILED</status>
+ </req:updateRequest>
+ </soapenv:Body>
+ </soapenv:Envelope>
+ """
+
+ execution.setVariable("FH_updateRequestGammaPayload", payload)
+ msoLogger.debug("updateRequestGammaPayload: " + payload)
+ return execution.getVariable("FH_updateRequestGammaPayload")
+ } catch (Exception e) {
+ msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e);
+ // exceptionUtil.buildWorkflowException(execution, 2000, "Internal Error - Occured in " + method)
+ }
+ }
+
+ public String updateResponseStatusPayload (DelegateExecution execution){
+ def method = getClass().getSimpleName() + '.updateResponseStatusPayload(' +'execution=' + execution.getId() +')'
+ msoLogger.trace('Entered ' + method)
+
+ try {
+ String payload = """
+ <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:req="http://org.onap.so/requestsdb">
+ <soapenv:Header/>
+ <soapenv:Body>
+ <req:updateResponseStatus>
+ <requestId>${MsoUtils.xmlEscape(execution.getVariable("FH_request_id"))}</requestId>
+ <lastModifiedBy>BPEL</lastModifiedBy>
+ <responseStatus>SENDING_FINAL_NOTIFY</responseStatus>
+ </req:updateResponseStatus>
+ </soapenv:Body>
+ </soapenv:Envelope>
+ """
+
+ execution.setVariable("FH_updateResponseStatusPayload", payload)
+ msoLogger.debug("updateResponseStatusPayload: " + payload)
+ return execution.getVariable("FH_updateResponseStatusPayload")
+ } catch (Exception e) {
+ msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e);
+ // exceptionUtil.buildWorkflowException(execution, 2000, "Internal Error - Occured in " + method)
+ }
+ }
+
+ public void buildDBWorkflowException(DelegateExecution execution, String responseCodeVariable) {
+ def method = getClass().getSimpleName() + '.buildDBWorkflowException(' +
+ 'execution=' + execution.getId() +
+ ', responseCodeVariable=' + responseCodeVariable + ')'
+ msoLogger.trace('Entered ' + method)
+
+ try {
+ def responseCode = execution.getVariable(responseCodeVariable)
+ // If the HTTP response code was null, it means a connection fault occurred (a java exception)
+ def errorMessage = responseCode == null ? "Could not connect to DB Adapter" : "DB Adapter returned ${responseCode} response"
+ def errorCode = responseCode == null ? 7000 : 7020
+ // exceptionUtil.buildWorkflowException(execution, errorCode, errorMessage)
+ } catch (Exception e) {
+ msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e);
+ // exceptionUtil.buildWorkflowException(execution, 2000, "Internal Error - Occured in " + method)
+ }
+ }
+
+ /**
+ * Used to create a workflow response in success and failure cases.
+ */
+ public void postProcessResponse (DelegateExecution execution) {
+ def method = getClass().getSimpleName() + '.postProcessResponse(' +'execution=' + execution.getId() +')'
+ msoLogger.trace('Entered ' + method)
+
+ try {
+ Boolean success = (Boolean) execution.getVariable("FH_success")
+ String out = success ? "Fallout Handler Succeeded" : "Fallout Handler Failed";
+
+ def falloutHandlerResponse = """
+ <workflow:FalloutHandlerResponse xmlns:workflow="http://org.onap/so/workflow/schema/v1">
+ <workflow:out>${MsoUtils.xmlEscape(out)}</workflow:out>
+ </workflow:FalloutHandlerResponse>
+ """
+
+ falloutHandlerResponse = utils.formatXml(falloutHandlerResponse)
+ msoLogger.debug("FalloutHandler Response: " + falloutHandlerResponse);
+
+ execution.setVariable("FalloutHandlerResponse", falloutHandlerResponse)
+ execution.setVariable("WorkflowResponse", falloutHandlerResponse)
+ execution.setVariable("FH_ResponseCode", success ? "200" : "500")
+ setSuccessIndicator(execution, success)
+
+ msoLogger.debug("FalloutHandlerResponse =\n" + falloutHandlerResponse)
+ } catch (Exception e) {
+ // Do NOT throw WorkflowException!
+ msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e);
+ }
+ }
+} \ No newline at end of file
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
new file mode 100644
index 0000000000..5cdcd0d5bf
--- /dev/null
+++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/GenerateVfModuleName.groovy
@@ -0,0 +1,173 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.so.bpmn.common.scripts
+
+import org.onap.so.bpmn.core.UrnPropertiesReader
+
+import java.io.Serializable;
+
+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.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
+
+public class GenerateVfModuleName extends AbstractServiceTaskProcessor{
+ private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, GenerateVfModuleName.class);
+
+ def Prefix="GVFMN_"
+ ExceptionUtil exceptionUtil = new ExceptionUtil()
+
+
+
+ public void preProcessRequest(DelegateExecution execution) {
+ try {
+ def vnfId = execution.getVariable("vnfId")
+ msoLogger.debug("vnfId is " + vnfId)
+ def vnfName = execution.getVariable("vnfName")
+ msoLogger.debug("vnfName is " + vnfName)
+ def vfModuleLabel = execution.getVariable("vfModuleLabel")
+ msoLogger.debug("vfModuleLabel is " + vfModuleLabel)
+ def personaModelId = execution.getVariable("personaModelId")
+ msoLogger.debug("personaModelId is " + personaModelId)
+ execution.setVariable("GVFMN_vfModuleXml", "")
+ }catch(BpmnError b){
+ throw b
+ }catch(Exception e){
+ exceptionUtil.buildAndThrowWorkflowException(execution, 2000, "Internal Error encountered in initVariables method!")
+ }
+ }
+
+
+ public void queryAAI(DelegateExecution execution) {
+ def method = getClass().getSimpleName() + '.queryAAI(' +
+ 'execution=' + execution.getId() +
+ ')'
+ msoLogger.trace('Entered ' + method)
+
+ try {
+ def vnfId = execution.getVariable('vnfId')
+ def personaModelId = execution.getVariable('personaModelId')
+
+ AaiUtil aaiUriUtil = new AaiUtil(this)
+ String aai_uri = aaiUriUtil.getNetworkGenericVnfUri(execution)
+ msoLogger.debug('AAI URI is: ' + aai_uri)
+
+ String endPoint = UrnPropertiesReader.getVariable("aai.endpoint", execution) + "${aai_uri}/" + UriUtils.encode(vnfId, "UTF-8") + "?depth=1"
+ msoLogger.debug("AAI endPoint: " + endPoint)
+
+ try {
+ RESTConfig config = new RESTConfig(endPoint);
+ def responseData = ''
+ def aaiRequestId = UUID.randomUUID().toString()
+ RESTClient client = new RESTClient(config).
+ addHeader('X-TransactionId', aaiRequestId).
+ addHeader('X-FromAppId', 'MSO').
+ addHeader('Content-Type', 'application/xml').
+ addHeader('Accept','application/xml');
+ msoLogger.debug('sending GET to AAI endpoint \'' + endPoint + '\'')
+ APIResponse response = client.httpGet()
+ msoLogger.debug("GenerateVfModuleName - invoking httpGet() to AAI")
+
+ responseData = response.getResponseBodyAsString()
+ if (responseData != null) {
+ msoLogger.debug("Received generic VNF data: " + responseData)
+
+ }
+
+ msoLogger.debug("GenerateVfModuleName - queryAAIVfModule Response: " + responseData)
+ msoLogger.debug("GenerateVfModuleName - queryAAIVfModule ResponseCode: " + response.getStatusCode())
+
+ execution.setVariable('GVFMN_queryAAIVfModuleResponseCode', response.getStatusCode())
+ execution.setVariable('GVFMN_queryAAIVfModuleResponse', responseData)
+ msoLogger.debug('Response code:' + response.getStatusCode())
+ msoLogger.debug('Response:' + System.lineSeparator() + responseData)
+ if (response.getStatusCode() == 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")
+ execution.setVariable("GVFMN_vfModuleXml", null)
+ }
+ else {
+ def xmlVfModules= new XmlSlurper().parseText(vfModulesText)
+ def vfModules = xmlVfModules.'**'.findAll {it.name() == "vf-module"}
+ int vfModulesSize = 0
+ if (vfModules != null) {
+ vfModulesSize = vfModules.size()
+ }
+ String matchingVfModules = "<vfModules>"
+ for (i in 0..vfModulesSize-1) {
+ def vfModuleXml = groovy.xml.XmlUtil.serialize(vfModules[i])
+ def personaModelIdFromAAI = utils.getNodeText(vfModuleXml, "model-invariant-id")
+ if (!personaModelIdFromAAI) {
+ // check old attribute name
+ 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)
+ execution.setVariable("GVFMN_vfModuleXml", matchingVfModules)
+ }
+ }
+ }
+ } catch (Exception ex) {
+ ex.printStackTrace()
+ msoLogger.debug('Exception occurred while executing AAI GET:' + ex.getMessage())
+ exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'AAI GET Failed:' + ex.getMessage())
+ }
+ msoLogger.trace('Exited ' + method)
+ } catch (BpmnError e) {
+ throw e;
+ } catch (Exception e) {
+ msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e);
+ 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)
+ msoLogger.debug("moduleIndex is: " + moduleIndex)
+ def vnfName = execution.getVariable("vnfName")
+ def vfModuleLabel = execution.getVariable("vfModuleLabel")
+ def vfModuleName = vnfName + "_" + vfModuleLabel + "_" + moduleIndex
+ msoLogger.debug("vfModuleName is: " + vfModuleName)
+ execution.setVariable("vfModuleName", vfModuleName)
+ }
+}
diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/GenericGetService.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/GenericGetService.groovy
new file mode 100644
index 0000000000..857df16772
--- /dev/null
+++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/GenericGetService.groovy
@@ -0,0 +1,470 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.so.bpmn.common.scripts
+
+import org.onap.so.bpmn.core.UrnPropertiesReader
+
+import org.apache.commons.lang3.StringEscapeUtils
+import org.camunda.bpm.engine.delegate.BpmnError
+import org.camunda.bpm.engine.delegate.DelegateExecution
+import org.onap.so.rest.APIResponse
+import org.springframework.web.util.UriUtils
+import org.onap.so.logger.MessageEnum
+import org.onap.so.logger.MsoLogger
+
+import static org.apache.commons.lang3.StringUtils.isBlank
+
+
+
+/**
+ * This class supports the GenericGetService Sub Flow.
+ * This Generic sub flow can be used by any flow for accomplishing
+ * the goal of getting a Service-Instance or Service-Subscription (from AAI).
+ * The calling flow must set the GENGS_type variable as "service-instance"
+ * or "service-subscription".
+ *
+ * When using to Get a Service-Instance:
+ * If the global-customer-id and service-type are not provided
+ * this flow executes a query to get the service- Url using the
+ * Service Id or Name (whichever is provided).
+ *
+ * When using to Get a Service-Subscription:
+ * The global-customer-id and service-type must be
+ * provided.
+ *
+ * Upon successful completion of this sub flow the
+ * GENGS_SuccessIndicator will be true and the query response payload
+ * will be set to GENGS_service. An MSOWorkflowException will
+ * be thrown upon unsuccessful completion or if an error occurs
+ * at any time during this sub flow. Please map variables
+ * to the corresponding variable names below.
+ *
+ * Note - If this sub flow receives a Not Found (404) response
+ * from AAI at any time this will be considered an acceptable
+ * successful response however the GENGS_FoundIndicator
+ * will be set to false. This variable will allow the calling flow
+ * to distinguish between the two Success scenarios,
+ * "Success where service- is found" and
+ * "Success where service- is NOT found".
+ *
+ *
+ * Variable Mapping Below:
+ *
+ * In Mapping Variables:
+ * For Allotted-Resource:
+ * @param - GENGS_allottedResourceId
+ * @param - GENGS_type
+ * @param (Optional) - GENGS_serviceInstanceId
+ * @param (Optional) - GENGS_serviceType
+ * @param (Optional) - GENGS_globalCustomerId
+ *
+ * For Service-Instance:
+ * @param - GENGS_serviceInstanceId or @param - GENGS_serviceInstanceName
+ * @param - GENGS_type
+ * @param (Optional) - GENGS_serviceType
+ * @param (Optional) - GENGS_globalCustomerId
+ *
+ * For Service-Subscription:
+ * @param - GENGS_type
+ * @param - GENGS_serviceType
+ * @param - GENGS_globalCustomerId
+ *
+ *
+ * Out Mapping Variables:
+ * @param - GENGS_service
+ * @param - GENGS_FoundIndicator
+ * @param - WorkflowException
+ */
+class GenericGetService extends AbstractServiceTaskProcessor{
+ private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, GenericGetService.class);
+
+
+ String Prefix = "GENGS_"
+ ExceptionUtil exceptionUtil = new ExceptionUtil()
+
+ /**
+ * This method validates the incoming variables and
+ * determines the subsequent event based on which
+ * variables the calling flow provided.
+ *
+ * @param - execution
+ *
+ */
+ public void preProcessRequest(DelegateExecution execution) {
+ execution.setVariable("prefix",Prefix)
+ msoLogger.trace("STARTED GenericGetService PreProcessRequest Process")
+
+ execution.setVariable("GENGS_obtainObjectsUrl", false)
+ execution.setVariable("GENGS_obtainServiceInstanceUrlByName", false)
+ execution.setVariable("GENGS_SuccessIndicator", false)
+ execution.setVariable("GENGS_FoundIndicator", false)
+ execution.setVariable("GENGS_resourceLink", null)
+ execution.setVariable("GENGS_siResourceLink", null)
+
+ try{
+ // Get Variables
+ String allottedResourceId = execution.getVariable("GENGS_allottedResourceId")
+ String serviceInstanceId = execution.getVariable("GENGS_serviceInstanceId")
+ String serviceInstanceName = execution.getVariable("GENGS_serviceInstanceName")
+ String serviceType = execution.getVariable("GENGS_serviceType")
+ String globalCustomerId = execution.getVariable("GENGS_globalCustomerId")
+ String type = execution.getVariable("GENGS_type")
+
+ if(type != null){
+ msoLogger.debug("Incoming GENGS_type is: " + type)
+ if(type.equalsIgnoreCase("allotted-resource")){
+ if(isBlank(allottedResourceId)){
+ msoLogger.debug("Incoming allottedResourceId is null. Allotted Resource Id is required to Get an allotted-resource.")
+ exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Incoming allottedResourceId is null. Allotted Resource Id is required to Get an allotted-resource.")
+ }else{
+ msoLogger.debug("Incoming Allotted Resource Id is: " + allottedResourceId)
+ if(isBlank(globalCustomerId) || isBlank(serviceType) || isBlank(serviceInstanceId)){
+ execution.setVariable("GENGS_obtainObjectsUrl", true)
+ }else{
+ msoLogger.debug("Incoming Service Instance Id is: " + serviceInstanceId)
+ msoLogger.debug("Incoming Service Type is: " + serviceType)
+ msoLogger.debug("Incoming Global Customer Id is: " + globalCustomerId)
+ }
+ }
+ }else if(type.equalsIgnoreCase("service-instance")){
+ if(isBlank(serviceInstanceId) && isBlank(serviceInstanceName)){
+ msoLogger.debug("Incoming serviceInstanceId and serviceInstanceName are null. ServiceInstanceId or ServiceInstanceName is required to Get a service-instance.")
+ exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Incoming serviceInstanceId and serviceInstanceName are null. ServiceInstanceId or ServiceInstanceName is required to Get a service-instance.")
+ }else{
+ msoLogger.debug("Incoming Service Instance Id is: " + serviceInstanceId)
+ msoLogger.debug("Incoming Service Instance Name is: " + serviceInstanceName)
+ if(isBlank(globalCustomerId) || isBlank(serviceType)){
+ execution.setVariable("GENGS_obtainObjectsUrl", true)
+ if(isBlank(serviceInstanceId)){
+ execution.setVariable("GENGS_obtainServiceInstanceUrlByName", true)
+ }
+ }else{
+ msoLogger.debug("Incoming Global Customer Id is: " + globalCustomerId)
+ msoLogger.debug("Incoming Service Type is: " + serviceType)
+ }
+ }
+ }else if(type.equalsIgnoreCase("service-subscription")){
+ if(isBlank(serviceType) || isBlank(globalCustomerId)){
+ msoLogger.debug("Incoming ServiceType or GlobalCustomerId is null. These variables are required to Get a service-subscription.")
+ exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Incoming ServiceType or GlobalCustomerId is null. These variables are required to Get a service-subscription.")
+ }else{
+ msoLogger.debug("Incoming Service Type is: " + serviceType)
+ msoLogger.debug("Incoming Global Customer Id is: " + globalCustomerId)
+ }
+ }else{
+ exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Incoming Type is Invalid. Please Specify Type as service-instance or service-subscription")
+ }
+ }else{
+ exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Incoming GENGS_type is null. Variable is Required.")
+ }
+
+ }catch(BpmnError b){
+ msoLogger.debug("Rethrowing MSOWorkflowException")
+ throw b
+ }catch(Exception e){
+ msoLogger.debug("Internal Error encountered within GenericGetService PreProcessRequest method!" + e)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured in GenericGetService PreProcessRequest")
+
+ }
+ msoLogger.trace("COMPLETED GenericGetService PreProcessRequest Process ")
+ }
+
+ /**
+ * This method obtains the Url to the provided service instance
+ * using the Service Instance Id.
+ *
+ * @param - execution
+ */
+ public void obtainServiceInstanceUrlById(DelegateExecution execution){
+ execution.setVariable("prefix",Prefix)
+ msoLogger.trace("STARTED GenericGetService ObtainServiceInstanceUrlById Process")
+ try {
+ AaiUtil aaiUriUtil = new AaiUtil(this)
+ String aai_uri = aaiUriUtil.getSearchNodesQueryEndpoint(execution)
+ String aai_endpoint = UrnPropertiesReader.getVariable("aai.endpoint", execution)
+
+ String type = execution.getVariable("GENGS_type")
+ String path = ""
+ if(type.equalsIgnoreCase("service-instance")){
+ String serviceInstanceId = execution.getVariable("GENGS_serviceInstanceId")
+ msoLogger.debug(" Querying Node for Service-Instance URL by using Service-Instance Id: " + serviceInstanceId)
+ path = "${aai_uri}?search-node-type=service-instance&filter=service-instance-id:EQUALS:${serviceInstanceId}"
+ msoLogger.debug("Service Instance Node Query Url is: " + path)
+ msoLogger.debug("Service Instance Node Query Url is: " + path)
+ }else if(type.equalsIgnoreCase("allotted-resource")){
+ String allottedResourceId = execution.getVariable("GENGS_allottedResourceId")
+ msoLogger.debug(" Querying Node for Service-Instance URL by using Allotted Resource Id: " + allottedResourceId)
+ path = "${aai_uri}?search-node-type=allotted-resource&filter=id:EQUALS:${allottedResourceId}"
+ msoLogger.debug("Allotted Resource Node Query Url is: " + path)
+ msoLogger.debug("Allotted Resource Node Query Url is: " + path)
+ }
+
+ //String url = "${aai_endpoint}${path}" host name needs to be removed from property
+ String url = "${path}"
+ execution.setVariable("GENGS_genericQueryPath", url)
+
+ APIResponse response = aaiUriUtil.executeAAIGetCall(execution, url)
+ int responseCode = response.getStatusCode()
+ execution.setVariable("GENGS_genericQueryResponseCode", responseCode)
+ msoLogger.debug(" GET Service Instance response code is: " + responseCode)
+ msoLogger.debug("GenericGetService AAI GET Response Code: " + responseCode)
+
+ String aaiResponse = response.getResponseBodyAsString()
+ execution.setVariable("GENGS_obtainSIUrlResponseBeforeUnescaping", aaiResponse)
+ msoLogger.debug("GenericGetService AAI Response before unescaping: " + aaiResponse)
+ execution.setVariable("GENGS_genericQueryResponse", aaiResponse)
+ msoLogger.debug("GenericGetService AAI Response: " + aaiResponse)
+ msoLogger.debug("GenericGetService AAI Response: " + aaiResponse)
+
+ //Process Response
+ if(responseCode == 200){
+ msoLogger.debug("Generic Query Received a Good Response Code")
+ execution.setVariable("GENGS_SuccessIndicator", true)
+ if(utils.nodeExists(aaiResponse, "result-data")){
+ msoLogger.debug("Generic Query Response Does Contain Data" )
+ execution.setVariable("GENGS_FoundIndicator", true)
+ String resourceLink = utils.getNodeText(aaiResponse, "resource-link")
+ execution.setVariable("GENGS_resourceLink", resourceLink)
+ execution.setVariable("GENGS_siResourceLink", resourceLink)
+ }else{
+ msoLogger.debug("Generic Query Response Does NOT Contains Data" )
+ execution.setVariable("WorkflowResponse", " ") //for junits
+ }
+ }else if(responseCode == 404){
+ msoLogger.debug("Generic Query Received a Not Found (404) Response")
+ execution.setVariable("GENGS_SuccessIndicator", true)
+ execution.setVariable("WorkflowResponse", " ") //for junits
+ }else{
+ msoLogger.debug("Generic Query Received a BAD REST Response: \n" + aaiResponse)
+ exceptionUtil.MapAAIExceptionToWorkflowExceptionGeneric(execution, aaiResponse, responseCode)
+ throw new BpmnError("MSOWorkflowException")
+ }
+ }catch(BpmnError b){
+ msoLogger.debug("Rethrowing MSOWorkflowException")
+ throw b
+ }catch(Exception e){
+ msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, " Error encountered within GenericGetService ObtainServiceInstanceUrlById method!" + e, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "");
+ exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured During ObtainServiceInstanceUrlById")
+ }
+ msoLogger.trace("COMPLETED GenericGetService ObtainServiceInstanceUrlById Process")
+ }
+
+ /**
+ * This method obtains the Url to the provided service instance
+ * using the Service Instance Name.
+ *
+ * @param - execution
+ */
+ public void obtainServiceInstanceUrlByName(DelegateExecution execution){
+ execution.setVariable("prefix",Prefix)
+ msoLogger.trace("STARTED GenericGetService ObtainServiceInstanceUrlByName Process")
+ try {
+ String serviceInstanceName = execution.getVariable("GENGS_serviceInstanceName")
+ msoLogger.debug(" Querying Node for Service-Instance URL by using Service-Instance Name " + serviceInstanceName)
+
+ AaiUtil aaiUriUtil = new AaiUtil(this)
+ String aai_uri = aaiUriUtil.getSearchNodesQueryEndpoint(execution)
+ String aai_endpoint = UrnPropertiesReader.getVariable("aai.endpoint", execution)
+ String path = "${aai_uri}?search-node-type=service-instance&filter=service-instance-name:EQUALS:${serviceInstanceName}"
+
+ //String url = "${aai_endpoint}${path}" host name needs to be removed from property
+ String url = "${path}"
+ execution.setVariable("GENGS_obtainSIUrlPath", url)
+
+ msoLogger.debug("GenericGetService AAI Endpoint: " + aai_endpoint)
+ APIResponse response = aaiUriUtil.executeAAIGetCall(execution, url)
+ int responseCode = response.getStatusCode()
+ execution.setVariable("GENGS_obtainSIUrlResponseCode", responseCode)
+ msoLogger.debug(" GET Service Instance response code is: " + responseCode)
+ msoLogger.debug("GenericGetService AAI Response Code: " + responseCode)
+
+ String aaiResponse = response.getResponseBodyAsString()
+ execution.setVariable("GENGS_obtainSIUrlResponse", aaiResponse)
+ msoLogger.debug("GenericGetService AAI Response: " + aaiResponse)
+ //Process Response
+ if(responseCode == 200){
+ msoLogger.debug(" Query for Service Instance Url Received a Good Response Code")
+ execution.setVariable("GENGS_SuccessIndicator", true)
+ String globalCustomerId = execution.getVariable("GENGS_globalCustomerId")
+ boolean nodeExists = isBlank(globalCustomerId) ? utils.nodeExists(aaiResponse, "result-data") : hasCustomerServiceInstance(aaiResponse, globalCustomerId)
+ if(nodeExists){
+ msoLogger.debug("Query for Service Instance Url Response Does Contain Data" )
+ execution.setVariable("GENGS_FoundIndicator", true)
+ String resourceLink = utils.getNodeText(aaiResponse, "resource-link")
+ execution.setVariable("GENGS_resourceLink", resourceLink)
+ execution.setVariable("GENGS_siResourceLink", resourceLink)
+ }else{
+ msoLogger.debug("Query for Service Instance Url Response Does NOT Contains Data" )
+ execution.setVariable("WorkflowResponse", " ") //for junits
+ }
+ }else if(responseCode == 404){
+ msoLogger.debug(" Query for Service Instance Received a Not Found (404) Response")
+ execution.setVariable("GENGS_SuccessIndicator", true)
+ execution.setVariable("WorkflowResponse", " ") //for junits
+ }else{
+ msoLogger.debug("Query for Service Instance Received a BAD REST Response: \n" + aaiResponse)
+ exceptionUtil.MapAAIExceptionToWorkflowExceptionGeneric(execution, aaiResponse, responseCode)
+ throw new BpmnError("MSOWorkflowException")
+ }
+ }catch(BpmnError b){
+ msoLogger.debug("Rethrowing MSOWorkflowException")
+ throw b
+ }catch(Exception e){
+ msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, " Error encountered within GenericGetService ObtainServiceInstanceUrlByName method!" + e, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "");
+ exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured During ObtainServiceInstanceUrlByName")
+ }
+ msoLogger.trace("COMPLETED GenericGetService ObtainServiceInstanceUrlByName Process")
+ }
+
+
+ /**
+ * This method executes a GET call to AAI to obtain the
+ * service-instance or service-subscription
+ *
+ * @param - execution
+ */
+ public void getServiceObject(DelegateExecution execution){
+ execution.setVariable("prefix",Prefix)
+ msoLogger.trace("STARTED GenericGetService GetServiceObject Process")
+ try {
+ String type = execution.getVariable("GENGS_type")
+ AaiUtil aaiUriUtil = new AaiUtil(this)
+ String aai_endpoint = UrnPropertiesReader.getVariable("aai.endpoint", execution)
+ String serviceEndpoint = ""
+
+ msoLogger.debug("GenericGetService getServiceObject AAI Endpoint: " + aai_endpoint)
+ if(type.equalsIgnoreCase("service-instance")){
+ String siResourceLink = execution.getVariable("GENGS_resourceLink")
+ if(isBlank(siResourceLink)){
+ String serviceInstanceId = execution.getVariable("GENGS_serviceInstanceId")
+ msoLogger.debug(" Incoming GENGS_serviceInstanceId is: " + serviceInstanceId)
+ String serviceType = execution.getVariable("GENGS_serviceType")
+ msoLogger.debug(" Incoming GENGS_serviceType is: " + serviceType)
+ String globalCustomerId = execution.getVariable("GENGS_globalCustomerId")
+ msoLogger.debug("Incoming Global Customer Id is: " + globalCustomerId)
+
+ String aai_uri = aaiUriUtil.getBusinessCustomerUri(execution)
+ msoLogger.debug('AAI URI is: ' + aai_uri)
+ serviceEndpoint = "${aai_uri}/" + UriUtils.encode(globalCustomerId,"UTF-8") + "/service-subscriptions/service-subscription/" + UriUtils.encode(serviceType,"UTF-8") + "/service-instances/service-instance/" + UriUtils.encode(serviceInstanceId,"UTF-8")
+ }else{
+ msoLogger.debug("Incoming Service Instance Url is: " + siResourceLink)
+ String[] split = siResourceLink.split("/aai/")
+ serviceEndpoint = "/aai/" + split[1]
+ }
+ }else if(type.equalsIgnoreCase("allotted-resource")){
+ String siResourceLink = execution.getVariable("GENGS_resourceLink")
+ if(isBlank(siResourceLink)){
+ String allottedResourceId = execution.getVariable("GENGS_allottedResourceId")
+ msoLogger.debug(" Incoming GENGS_allottedResourceId is: " + allottedResourceId)
+ String serviceInstanceId = execution.getVariable("GENGS_serviceInstanceId")
+ msoLogger.debug(" Incoming GENGS_serviceInstanceId is: " + serviceInstanceId)
+ String serviceType = execution.getVariable("GENGS_serviceType")
+ msoLogger.debug(" Incoming GENGS_serviceType is: " + serviceType)
+ String globalCustomerId = execution.getVariable("GENGS_globalCustomerId")
+ msoLogger.debug("Incoming Global Customer Id is: " + globalCustomerId)
+
+ String aai_uri = aaiUriUtil.getBusinessCustomerUri(execution)
+ msoLogger.debug('AAI URI is: ' + aai_uri)
+ serviceEndpoint = "${aai_uri}/" + UriUtils.encode(globalCustomerId,"UTF-8") + "/service-subscriptions/service-subscription/" + UriUtils.encode(serviceType,"UTF-8") + "/service-instances/service-instance/" + UriUtils.encode(serviceInstanceId,"UTF-8") + "/allotted-resources/allotted-resource/" + UriUtils.encode(allottedResourceId,"UTF-8")
+ }else{
+ msoLogger.debug("Incoming Allotted-Resource Url is: " + siResourceLink)
+ String[] split = siResourceLink.split("/aai/")
+ serviceEndpoint = "/aai/" + split[1]
+ }
+ }else if(type.equalsIgnoreCase("service-subscription")){
+ String aai_uri = aaiUriUtil.getBusinessCustomerUri(execution)
+ String globalCustomerId = execution.getVariable("GENGS_globalCustomerId")
+ String serviceType = execution.getVariable("GENGS_serviceType")
+ serviceEndpoint = "${aai_uri}/" + UriUtils.encode(globalCustomerId,"UTF-8") + "/service-subscriptions/service-subscription/" + UriUtils.encode(serviceType,"UTF-8")
+ }
+
+ String serviceUrl = "${aai_endpoint}" + serviceEndpoint
+
+ execution.setVariable("GENGS_getServiceUrl", serviceUrl)
+ msoLogger.debug("GET Service AAI Path is: \n" + serviceUrl)
+
+ APIResponse response = aaiUriUtil.executeAAIGetCall(execution, serviceUrl)
+ int responseCode = response.getStatusCode()
+ execution.setVariable("GENGS_getServiceResponseCode", responseCode)
+ msoLogger.debug(" GET Service response code is: " + responseCode)
+ msoLogger.debug("GenericGetService AAI Response Code: " + responseCode)
+
+ String aaiResponse = response.getResponseBodyAsString()
+ execution.setVariable("GENGS_getServiceResponse", aaiResponse)
+ msoLogger.debug("GenericGetService AAI Response: " + aaiResponse)
+ //Process Response
+ if(responseCode == 200 || responseCode == 202){
+ msoLogger.debug("GET Service Received a Good Response Code")
+ if(utils.nodeExists(aaiResponse, "service-instance") || utils.nodeExists(aaiResponse, "service-subscription")){
+ msoLogger.debug("GET Service Response Contains a service-instance" )
+ execution.setVariable("GENGS_FoundIndicator", true)
+ execution.setVariable("GENGS_service", aaiResponse)
+ execution.setVariable("WorkflowResponse", aaiResponse)
+
+ }else{
+ msoLogger.debug("GET Service Response Does NOT Contain Data" )
+ }
+ }else if(responseCode == 404){
+ msoLogger.debug("GET Service Received a Not Found (404) Response")
+ execution.setVariable("WorkflowResponse", " ") //for junits
+ }
+ else{
+ msoLogger.debug(" GET Service Received a Bad Response: \n" + aaiResponse)
+ exceptionUtil.MapAAIExceptionToWorkflowExceptionGeneric(execution, aaiResponse, responseCode)
+ throw new BpmnError("MSOWorkflowException")
+ }
+ }catch(BpmnError b){
+ msoLogger.debug("Rethrowing MSOWorkflowException")
+ throw b
+ }catch(Exception e){
+ msoLogger.debug(" Error encountered within GenericGetService GetServiceObject method!" + e)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured During GenericGetService")
+ }
+ msoLogger.trace("COMPLETED GenericGetService GetServiceObject Process")
+ }
+
+ /**
+ * An utility method which check whether a service(by name) is already present within a globalCustomerId or not.
+ * @param jsonResponse raw response received from AAI by searching ServiceInstance by Name.
+ * @param globalCustomerId
+ * @return {@code true} if globalCustomerId is found at 6th position within "resource-link", {@code false} in any other cases.
+ */
+ public boolean hasCustomerServiceInstance(String aaiResponse, final String globalCustomerId) {
+ if (isBlank(aaiResponse)) {
+ return false
+ }
+ aaiResponse = utils.removeXmlNamespaces(aaiResponse)
+ ArrayList<String> linksArray = utils.getMultNodeObjects(aaiResponse, "resource-link")
+ if (linksArray == null || linksArray.size() == 0) {
+ return false
+ }
+ for (String resourceLink : linksArray) {
+ int custStart = resourceLink.indexOf("customer/")
+ int custEnd = resourceLink.indexOf("/service-subscriptions/")
+ String receivedCustomerId = resourceLink.substring(custStart + 9, custEnd)
+ if (globalCustomerId.equals(receivedCustomerId)) {
+ return true
+ }
+ }
+ return false
+ }
+
+} \ No newline at end of file
diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/GenericGetVnf.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/GenericGetVnf.groovy
new file mode 100644
index 0000000000..01d8e9b8d5
--- /dev/null
+++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/GenericGetVnf.groovy
@@ -0,0 +1,275 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.so.bpmn.common.scripts
+
+import org.onap.so.bpmn.core.UrnPropertiesReader
+import static org.onap.so.bpmn.common.scripts.GenericUtils.*;
+
+import org.apache.commons.lang3.*
+import org.camunda.bpm.engine.delegate.BpmnError
+import org.camunda.bpm.engine.delegate.DelegateExecution
+import org.onap.so.rest.APIResponse
+import org.springframework.web.util.UriUtils
+import org.onap.so.logger.MessageEnum
+import org.onap.so.logger.MsoLogger
+
+
+
+
+/**
+ * TODO: Support getting vnf type = vpe
+ *
+ * This class supports the GenericGetVnf Sub Flow.
+ * This Generic sub flow can be used by any flow for accomplishing
+ * the goal of getting a Vnf Object (from AAI). The flow currently
+ * supports the querying of 2 types of Vnfs, generic-vnf and vce. The
+ * type must be provided by the calling flow and the type should
+ * be mapped to the variable GENGV_type. The type should either be
+ * "generic-vnf" or "vce". If the Vnf Id is not provided by the calling
+ * flow then this sub flow will execute the query to get the
+ * Vnf using the Vnf Name. Therefore, the calling flow must provide
+ * either the Vnf Id or Vnf Name.
+ *
+ * Upon successful completion of this sub flow the
+ * GENGV_SuccessIndicator will be true and the query response payload
+ * will be set to GENGV_vnf. An MSOWorkflowException will
+ * be thrown upon unsuccessful completion or if an error occurs
+ * at any time during this sub flow. Please map variables
+ * to the corresponding variable names below.
+ *
+ * Note - if this sub flow receives a Not Found (404) response
+ * from AAI at any time this will be considered an acceptable
+ * successful response however the GENGV_FoundIndicator
+ * set to false. This will allow the calling flow to distinguish
+ * between the two success scenarios, "Success where Vnf is found"
+ * and "Success where Vnf is NOT found".
+ *
+ *
+ * Variable Mapping Below
+ *
+ * In Mapping Variables:
+ * @param - GENGV_vnfId or @param - GENGV_vnfName
+ * @param - GENGV_type
+ *
+ * Out Mapping Variables:
+ * @param - GENGV_vnf
+ * @param - GENGV_SuccessIndicator
+ * @param - GENGV_FoundIndicator
+ * @param - WorkflowException
+ *
+ *
+ */
+class GenericGetVnf extends AbstractServiceTaskProcessor{
+ private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, GenericGetVnf.class);
+
+
+ String Prefix = "GENGV_"
+ ExceptionUtil exceptionUtil = new ExceptionUtil()
+
+ /**
+ * This method validates the incoming variables and
+ * determines the subsequent event based on which
+ * variables the calling flow provided.
+ *
+ * @param - execution
+ */
+ public void preProcessRequest(DelegateExecution execution) {
+ execution.setVariable("prefix",Prefix)
+ msoLogger.trace("STARTED GenericGetVnf PreProcessRequest Process")
+
+ execution.setVariable("GENGV_getVnfByName", false)
+ execution.setVariable("GENGV_SuccessIndicator", false)
+ execution.setVariable("GENGV_FoundIndicator", false)
+
+ try{
+ // Get Variables
+ String vnfId = execution.getVariable("GENGV_vnfId")
+ msoLogger.debug("Incoming Vnf Id is: " + vnfId)
+ String vnfName = execution.getVariable("GENGV_vnfName")
+ msoLogger.debug("Incoming Vnf Name is: " + vnfName)
+
+ if(isBlank(vnfId) && isBlank(vnfName)){
+ msoLogger.debug("Incoming Vnf Name and Vnf Id are null. At least one is required!")
+ exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Incoming Vnf Name and Vnf Id are null. At least one is required.")
+ }else{
+ if(isBlank(vnfId)){
+ execution.setVariable("GENGV_getVnfByName", true)
+ }
+ }
+
+ }catch(BpmnError b){
+ msoLogger.debug("Rethrowing MSOWorkflowException")
+ throw b
+ }catch(Exception e){
+ msoLogger.debug(" Error encountered within GenericGetVnf PreProcessRequest method!" + e)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured in GenericGetVnf PreProcessRequest")
+
+ }
+ msoLogger.trace("COMPLETED GenericGetVnf PreProcessRequest Process ")
+ }
+
+ /**
+ * This method executes a GET call to AAI to obtain the
+ * Vnf using the Vnf Name
+ *
+ * @param - execution
+ */
+ public void getVnfByName(DelegateExecution execution){
+ execution.setVariable("prefix",Prefix)
+ msoLogger.trace("STARTED GenericGetVnf GetVnfByName Process")
+ try {
+ String vnfName = execution.getVariable("GENGV_vnfName")
+ msoLogger.debug("Getting Vnf by Vnf Name: " + vnfName)
+ String type = execution.getVariable("GENGV_type")
+ msoLogger.debug("Type of Vnf Getting is: " + type)
+
+ String aai_endpoint = UrnPropertiesReader.getVariable("aai.endpoint", execution)
+ AaiUtil aaiUriUtil = new AaiUtil(this)
+
+ //Determine Type of Vnf Querying For.
+ def aai_uri = ""
+ if(type.equals("generic-vnf")){
+ aai_uri = aaiUriUtil.getNetworkGenericVnfUri(execution)
+ }else if(type.equals("vce")){
+ aai_uri = aaiUriUtil.getNetworkVceUri(execution)
+ }else{
+ msoLogger.debug("Invalid Incoming GENGV_type")
+ exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Invalid Incoming GENGV_type")
+ }
+
+ String getVnfPath = "${aai_endpoint}${aai_uri}?vnf-name=" + UriUtils.encode(vnfName, "UTF-8") + "&depth=1"
+
+ execution.setVariable("GENGV_getVnfPath", getVnfPath)
+ msoLogger.debug("Get Vnf Url is: " + getVnfPath)
+
+ APIResponse response = aaiUriUtil.executeAAIGetCall(execution, getVnfPath)
+ int responseCode = response.getStatusCode()
+ execution.setVariable("GENGV_getVnfResponseCode", responseCode)
+ msoLogger.debug(" GET Vnf response code is: " + responseCode)
+
+ String aaiResponse = response.getResponseBodyAsString()
+ execution.setVariable("GENGV_getVnfResponse", aaiResponse)
+
+ //Process Response
+ if(responseCode == 200){
+ msoLogger.debug("GET Vnf Received a Good Response")
+ if(utils.nodeExists(aaiResponse, type)){
+ msoLogger.debug("GET Vnf Response Contains a Vnf")
+ execution.setVariable("GENGV_FoundIndicator", true)
+ execution.setVariable("GENGV_vnf", aaiResponse)
+ execution.setVariable("WorkflowResponse", aaiResponse)
+ }else{
+ msoLogger.debug("GET Vnf Response Does NOT Contain a Vnf")
+ }
+
+ }else if(responseCode == 404){
+ msoLogger.debug("GET Vnf Received a Not Found (404) Response")
+ }else{
+ msoLogger.debug("GET Vnf Received a Bad Response: \n" + aaiResponse)
+ exceptionUtil.MapAAIExceptionToWorkflowExceptionGeneric(execution, aaiResponse, responseCode)
+ throw new BpmnError("MSOWorkflowException")
+ }
+ }catch(BpmnError b){
+ msoLogger.debug("Rethrowing MSOWorkflowException")
+ throw b
+ }catch(Exception e){
+ msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, " Error encountered within GenericGetVnf GetVnfByName method!" + e, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "");
+ exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured During GetVnfByName")
+ }
+ msoLogger.trace("COMPLETED GenericGetVnf GetVnfByName Process")
+ }
+
+ /**
+ * This method executes a GET call to AAI to obtain the
+ * Vnf using the Vnf Id
+ *
+ * @param - execution
+ */
+ public void getVnfById(DelegateExecution execution){
+ execution.setVariable("prefix",Prefix)
+ msoLogger.trace("STARTED GenericGetVnf GetVnfById Process")
+ try {
+ String vnfId = execution.getVariable("GENGV_vnfId")
+ msoLogger.debug("Getting Vnf by Vnf Id: " + vnfId)
+ String type = execution.getVariable("GENGV_type")
+ msoLogger.debug("Type of Vnf Getting is: " + type)
+
+ String aai_endpoint = UrnPropertiesReader.getVariable("aai.endpoint", execution)
+ AaiUtil aaiUriUtil = new AaiUtil(this)
+
+ //Determine Type of Vnf Querying For.
+ def aai_uri = ""
+ if(type.equals("generic-vnf")){
+ aai_uri = aaiUriUtil.getNetworkGenericVnfUri(execution)
+ }else if(type.equals("vce")){
+ aai_uri = aaiUriUtil.getNetworkVceUri(execution)
+ }else if(type.equals("vpe")){
+ exceptionUtil.buildAndThrowWorkflowException(execution, 500, "GenericGetVnf does not yet support getting type of vnf = vpe")
+ }else{
+ msoLogger.debug("Invalid Incoming GENGV_type")
+ exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Invalid Incoming GENGV_type")
+ }
+ msoLogger.debug("Using AAI Uri: " + aai_uri)
+
+ String getVnfPath = "${aai_endpoint}${aai_uri}/" + UriUtils.encode(vnfId, "UTF-8") + "?depth=1"
+ msoLogger.debug("GET Vnf Endpoint is: " + getVnfPath)
+
+ execution.setVariable("GENGV_getVnfPath", getVnfPath)
+ msoLogger.debug("Get Vnf Url is: " + getVnfPath)
+
+ APIResponse response = aaiUriUtil.executeAAIGetCall(execution, getVnfPath)
+ int responseCode = response.getStatusCode()
+ execution.setVariable("GENGV_getVnfResponseCode", responseCode)
+ msoLogger.debug(" GET Vnf response code is: " + responseCode)
+
+ String aaiResponse = response.getResponseBodyAsString()
+ execution.setVariable("GENGV_getVnfResponse", aaiResponse)
+
+ //Process Response
+ if(responseCode == 200){
+ msoLogger.debug("GET Vnf Received a Good Response")
+ if(utils.nodeExists(aaiResponse, type)){
+ msoLogger.debug("GET Vnf Response Contains a Vnf")
+ execution.setVariable("GENGV_FoundIndicator", true)
+ execution.setVariable("GENGV_vnf", aaiResponse)
+ execution.setVariable("WorkflowResponse", aaiResponse)
+ }else{
+ msoLogger.debug("GET Vnf Response Does NOT Contain a Vnf")
+ }
+
+ }else if(responseCode == 404){
+ msoLogger.debug("GET Vnf Received a Not Found (404) Response")
+ }else{
+ msoLogger.debug("GET Vnf Received a BAD REST Response: \n" + aaiResponse)
+ exceptionUtil.MapAAIExceptionToWorkflowExceptionGeneric(execution, aaiResponse, responseCode)
+ throw new BpmnError("MSOWorkflowException")
+ }
+ }catch(BpmnError b){
+ msoLogger.debug("Rethrowing MSOWorkflowException")
+ throw b
+ }catch(Exception e){
+ msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, " Error encountered within GenericGetVnf GetVnfById method!" + e, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "");
+ exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured During GetVnfById")
+ }
+ msoLogger.trace("COMPLETED GenericGetVnf GetVnfById Process")
+ }
+
+}
diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/GenericNotificationService.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/GenericNotificationService.groovy
new file mode 100644
index 0000000000..591e76e491
--- /dev/null
+++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/GenericNotificationService.groovy
@@ -0,0 +1,47 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.so.bpmn.common.scripts
+
+import org.camunda.bpm.engine.delegate.BpmnError
+import org.camunda.bpm.engine.delegate.DelegateExecution
+import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor
+import org.onap.so.bpmn.common.scripts.ExceptionUtil
+import org.onap.so.bpmn.core.WorkflowException
+import org.onap.so.bpmn.core.json.JsonUtils
+import java.text.SimpleDateFormat
+import org.onap.so.logger.MessageEnum
+import org.onap.so.logger.MsoLogger
+
+
+
+public class GenericNotificationService extends AbstractServiceTaskProcessor {
+ private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, GenericNotificationService.class);
+
+
+
+
+ ExceptionUtil exceptionUtil = new ExceptionUtil()
+
+ public void preProcessRequest (DelegateExecution execution) {
+
+ }
+
+}
diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/GenericPutService.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/GenericPutService.groovy
new file mode 100644
index 0000000000..d41134be91
--- /dev/null
+++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/GenericPutService.groovy
@@ -0,0 +1,282 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.so.bpmn.common.scripts
+
+import org.onap.so.bpmn.core.UrnPropertiesReader
+
+import static org.apache.commons.lang3.StringUtils.*;
+
+import org.camunda.bpm.engine.delegate.BpmnError
+import org.camunda.bpm.engine.delegate.DelegateExecution;
+import org.apache.commons.codec.binary.Base64
+import org.apache.commons.lang3.*
+
+import org.onap.so.bpmn.core.json.JsonUtils
+import org.onap.so.bpmn.core.WorkflowException
+import org.onap.so.rest.APIResponse;
+import org.onap.so.rest.RESTClient
+import org.onap.so.rest.RESTConfig
+
+import java.net.URLEncoder;
+import org.springframework.web.util.UriUtils
+import org.onap.so.logger.MessageEnum
+import org.onap.so.logger.MsoLogger
+
+
+
+/**
+ * This class supports the GenericPutService Sub Flow.
+ * This Generic sub flow can be used by any flow for the
+ * goal of creating a Service Instance or Service-Subscription in AAI. Upon successful completion of
+ * this sub flow the GENPS_SuccessIndicator will be true.
+ * The calling flow must set the GENPS_type variable as "service-instance"
+ * or "service-subscription".
+ * A MSOWorkflowException will be thrown Upon unsuccessful
+ * completion or if an error occurs within this flow.
+ * Please map variables to the corresponding variable names
+ * below.
+ *
+ *
+ * Incoming Required Variables:
+ * @param - GENPS_requestId
+ * @param - GENPS_type - Required field. This will be required field populated as service-instance or service-subscription
+ * @param - GENPS_globalSubscriberId - Required field
+ * @param - GENPS_serviceType - Required Field
+ * @param - GENPS_payload - Required Field This will be the payload that needs to be sent.
+ *
+ * @param - GENPS_serviceInstanceId - Conditional Field. Required for service-instance.
+ * @param - GENPS_allottedResourceId - Conditional Field. Required for allotted-resource.
+ * @param - GENPS_tunnelXconnectId - Conditional Field. Required for tunnel-xconnect.
+ *
+ * @param - GENPS_serviceResourceVersion - Conditional Field. Needs to be provided only in case of update for both service-instance and service subscription. The calling flows
+ * should check if a service-instance or servic-subscription exists by calling the subflow GenericGetService. if it exists then resourceversion should be
+ * obtained from aai and sent as an input parameter.
+ *
+ * Outgoing Variables:
+ * @param - GENPS_SuccessIndicator
+ * @param - WorkflowException
+ *
+ *
+ */
+
+
+class GenericPutService extends AbstractServiceTaskProcessor{
+ private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, GenericPutService.class);
+
+
+ String Prefix = "GENPS_"
+ ExceptionUtil exceptionUtil = new ExceptionUtil()
+
+
+ public void preProcessRequest(DelegateExecution execution) {
+ execution.setVariable("isDebugLogEnabled","true")
+ execution.setVariable("prefix",Prefix)
+ msoLogger.trace("STARTED GenericPutService PreProcessRequest Process")
+
+ execution.setVariable("GENPS_SuccessIndicator", false)
+
+ try{
+ // Get Variables
+ String requestId = execution.getVariable("GENPS_requestId")
+ msoLogger.debug("Incoming GENPS_requestId is: " + requestId)
+
+ String globalSubscriberId = execution.getVariable("GENPS_globalSubscriberId")
+ String serviceInstanceId = execution.getVariable("GENPS_serviceInstanceId")
+ String serviceType = execution.getVariable("GENPS_serviceType")
+ String allottedResourceId = execution.getVariable("GENPS_allottedResourceId")
+ String tunnelXconnectId = execution.getVariable("GENPS_tunnelXconnectId")
+ String type = execution.getVariable("GENPS_type")
+
+ if(type != null){
+ msoLogger.debug("Incoming GENPS_type is: " + type)
+ if(type.equalsIgnoreCase("service-instance")){
+ if(isBlank(globalSubscriberId) || isBlank(serviceType) || isBlank(serviceInstanceId)){
+ msoLogger.debug("Incoming Required Variable is missing or null!")
+ exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Incoming Required Variable is Missing or Null!")
+ }else{
+ msoLogger.debug("Incoming Global Subscriber Id is: " + globalSubscriberId)
+ msoLogger.debug("Incoming Service Instance Id is: " + serviceInstanceId)
+ msoLogger.debug("Incoming Service Type is: " + serviceType)
+ }
+ }else if(type.equalsIgnoreCase("service-subscription")){
+ if(isBlank(serviceType) || isBlank(globalSubscriberId)){
+ msoLogger.debug("Incoming ServiceType or GlobalSubscriberId is null. These variables are required to create a service-subscription.")
+ exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Incoming ServiceType or GlobalCustomerId is null. These variables are required to Get a service-subscription.")
+ }else{
+ msoLogger.debug("Incoming Service Type is: " + serviceType)
+ msoLogger.debug("Incoming Global Subscriber Id is: " + globalSubscriberId)
+ }
+ }else if(type.equalsIgnoreCase("allotted-resource")){
+ if(isBlank(globalSubscriberId) || isBlank(serviceType) || isBlank(serviceInstanceId) || isBlank(allottedResourceId)){
+ msoLogger.debug("Incoming Global Subscriber Id is: " + globalSubscriberId)
+ msoLogger.debug("Incoming Service Instance Id is: " + serviceInstanceId)
+ msoLogger.debug("Incoming Service Type is: " + serviceType)
+ msoLogger.debug("Incoming Allotted Resource Id is: " + allottedResourceId)
+ msoLogger.debug("Incoming Required Variable is missing or null!")
+ exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Incoming Required Variable is Missing or Null!")
+ }else{
+ msoLogger.debug("Incoming Global Subscriber Id is: " + globalSubscriberId)
+ msoLogger.debug("Incoming Service Instance Id is: " + serviceInstanceId)
+ msoLogger.debug("Incoming Service Type is: " + serviceType)
+ msoLogger.debug("Incoming Allotted Resource Id is: " + allottedResourceId)
+ }
+ }else if(type.equalsIgnoreCase("tunnel-xconnect")){
+ if(isBlank(globalSubscriberId) || isBlank(serviceType) || isBlank(serviceInstanceId) || isBlank(allottedResourceId) || isBlank(tunnelXconnectId)){
+ msoLogger.debug("Incoming Global Subscriber Id is: " + globalSubscriberId)
+ msoLogger.debug("Incoming Service Instance Id is: " + serviceInstanceId)
+ msoLogger.debug("Incoming Service Type is: " + serviceType)
+ msoLogger.debug("Incoming Allotted Resource Id is: " + allottedResourceId)
+ msoLogger.debug("Incoming Tunnel Xconnect Id is: " + tunnelXconnectId)
+ msoLogger.debug("Incoming Required Variable is missing or null!")
+ exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Incoming Required Variable is Missing or Null!")
+ }else{
+ msoLogger.debug("Incoming Global Subscriber Id is: " + globalSubscriberId)
+ msoLogger.debug("Incoming Service Instance Id is: " + serviceInstanceId)
+ msoLogger.debug("Incoming Service Type is: " + serviceType)
+ msoLogger.debug("Incoming Allotted Resource Id is: " + allottedResourceId)
+ msoLogger.debug("Incoming Tunnel Xconnect Id is: " + tunnelXconnectId)
+ }
+ }else{
+ exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Incoming Type is Invalid. Please Specify Type as service-instance or service-subscription")
+ }
+ }else{
+ exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Incoming GENPS_type is null. Variable is Required.")
+ }
+
+ }catch(BpmnError b){
+ msoLogger.debug("Rethrowing MSOWorkflowException")
+ throw b
+ }catch(Exception e){
+ msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, " Error encountered within GenericPutService PreProcessRequest method!" + e, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "");
+ exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured in GenericPutService PreProcessRequest")
+
+ }
+ msoLogger.trace("COMPLETED GenericPutService PreProcessRequest Process ")
+
+ }
+
+ /**
+ * This method executes a Put call to AAI for the provided
+ * service instance.
+ *
+ * @param - execution
+ *
+ */
+ public void putServiceInstance(DelegateExecution execution){
+ execution.setVariable("prefix",Prefix)
+ msoLogger.trace("STARTED GenericPutService PutServiceInstance method")
+ try {
+ String type = execution.getVariable("GENPS_type")
+
+ AaiUtil aaiUriUtil = new AaiUtil(this)
+ String aai_uri = aaiUriUtil.getBusinessCustomerUri(execution)
+ msoLogger.debug('AAI URI is: ' + aai_uri)
+ String namespace = aaiUriUtil.getNamespaceFromUri(execution, aai_uri)
+ msoLogger.debug('AAI namespace is: ' + namespace)
+
+ String aai_endpoint = UrnPropertiesReader.getVariable("aai.endpoint", execution)
+ String serviceAaiPath = ""
+ String payload = execution.getVariable("GENPS_payload")
+ execution.setVariable("GENPS_payload", payload)
+ msoLogger.debug("Incoming GENPS_payload is: " + payload)
+ msoLogger.debug(payload)
+
+ String serviceType = execution.getVariable("GENPS_serviceType")
+ msoLogger.debug(" Incoming GENPS_serviceType is: " + serviceType)
+
+ String globalSubscriberId = execution.getVariable("GENPS_globalSubscriberId")
+ msoLogger.debug("Incoming Global Subscriber Id is: " + globalSubscriberId)
+
+ // This IF clause is if we need to create a new Service Instance
+ if(type.equalsIgnoreCase("service-instance")){
+
+ String serviceInstanceId = execution.getVariable("GENPS_serviceInstanceId")
+ msoLogger.debug(" Incoming GENPS_serviceInstanceId is: " + serviceInstanceId)
+
+ // serviceAaiPath = "${aai_endpoint}${aai_uri}/" + URLEncoder.encode(globalSubscriberId,"UTF-8") + "/service-subscriptions/service-subscription/" + URLEncoder.encode(serviceType,"UTF-8") + "/service-instances/service-instance/" + URLEncoder.encode(serviceInstanceId,"UTF-8")
+ serviceAaiPath = "${aai_endpoint}${aai_uri}/" + UriUtils.encode(globalSubscriberId,"UTF-8") + "/service-subscriptions/service-subscription/" + UriUtils.encode(serviceType,"UTF-8") + "/service-instances/service-instance/" + UriUtils.encode(serviceInstanceId,"UTF-8")
+
+ }else if(type.equalsIgnoreCase("service-subscription")){
+
+ // serviceAaiPath = "${aai_endpoint}${aai_uri}/" + URLEncoder.encode(globalSubscriberId,"UTF-8") + "/service-subscriptions/service-subscription/" + URLEncoder.encode(serviceType,"UTF-8")
+ serviceAaiPath = "${aai_endpoint}${aai_uri}/" + UriUtils.encode(globalSubscriberId,"UTF-8") + "/service-subscriptions/service-subscription/" + UriUtils.encode(serviceType,"UTF-8")
+ }else if(type.equalsIgnoreCase("allotted-resource")){
+
+ String serviceInstanceId = execution.getVariable("GENPS_serviceInstanceId")
+ msoLogger.debug(" Incoming GENPS_serviceInstanceId is: " + serviceInstanceId)
+ String allottedResourceId = execution.getVariable("GENPS_allottedResourceId")
+ msoLogger.debug(" Incoming GENPS_allottedResourceId is: " + allottedResourceId)
+
+ // serviceAaiPath = "${aai_endpoint}${aai_uri}/" + URLEncoder.encode(globalSubscriberId,"UTF-8") + "/service-subscriptions/service-subscription/" + URLEncoder.encode(serviceType,"UTF-8")
+ serviceAaiPath = "${aai_endpoint}${aai_uri}/" + UriUtils.encode(globalSubscriberId,"UTF-8") + "/service-subscriptions/service-subscription/" + UriUtils.encode(serviceType,"UTF-8") + "/service-instances/service-instance/" + UriUtils.encode(serviceInstanceId,"UTF-8") + "/allotted-resources/allotted-resource/" + UriUtils.encode(allottedResourceId,"UTF-8")
+ }else if(type.equalsIgnoreCase("tunnel-xconnect")){
+
+ String serviceInstanceId = execution.getVariable("GENPS_serviceInstanceId")
+ msoLogger.debug(" Incoming GENPS_serviceInstanceId is: " + serviceInstanceId)
+ String allottedResourceId = execution.getVariable("GENPS_allottedResourceId")
+ msoLogger.debug(" Incoming GENPS_allottedResourceId is: " + allottedResourceId)
+ String tunnelXconnectId = execution.getVariable("GENPS_tunnelXconnectId")
+ msoLogger.debug(" Incoming GENPS_tunnelXconnectId is: " + tunnelXconnectId)
+
+ // serviceAaiPath = "${aai_endpoint}${aai_uri}/" + URLEncoder.encode(globalSubscriberId,"UTF-8") + "/service-subscriptions/service-subscription/" + URLEncoder.encode(serviceType,"UTF-8")
+ serviceAaiPath = "${aai_endpoint}${aai_uri}/" + UriUtils.encode(globalSubscriberId,"UTF-8") + "/service-subscriptions/service-subscription/" + UriUtils.encode(serviceType,"UTF-8") + "/service-instances/service-instance/" + UriUtils.encode(serviceInstanceId,"UTF-8") + "/allotted-resources/allotted-resource/" + UriUtils.encode(allottedResourceId,"UTF-8") + "/tunnel-xconnects/tunnel-xconnect/" + UriUtils.encode(tunnelXconnectId,"UTF-8")
+ }
+
+ String resourceVersion = execution.getVariable("GENPS_serviceResourceVersion")
+ msoLogger.debug("Incoming Resource Version is: " + resourceVersion)
+ if(resourceVersion !=null){
+ serviceAaiPath = serviceAaiPath +'?resource-version=' + UriUtils.encode(resourceVersion,"UTF-8")
+ }
+
+ execution.setVariable("GENPS_putServiceInstanceAaiPath", serviceAaiPath)
+ msoLogger.debug("PUT Service Instance AAI Path is: " + "\n" + serviceAaiPath)
+ APIResponse response = aaiUriUtil.executeAAIPutCall(execution, serviceAaiPath, payload)
+ int responseCode = response.getStatusCode()
+ execution.setVariable("GENPS_putServiceInstanceResponseCode", responseCode)
+ msoLogger.debug(" Put Service Instance response code is: " + responseCode)
+
+ String aaiResponse = response.getResponseBodyAsString()
+ execution.setVariable("GENPS_putServiceInstanceResponse", aaiResponse)
+
+ //Process Response
+ if(responseCode == 200 || responseCode == 201 || responseCode == 202 )
+ //200 OK 201 CREATED 202 ACCEPTED
+ {
+ msoLogger.debug("PUT Service Instance Received a Good Response")
+ execution.setVariable("GENPS_SuccessIndicator", true)
+ }
+
+ else{
+ msoLogger.debug("Put Generic Service Instance Received a Bad Response Code. Response Code is: " + responseCode)
+ exceptionUtil.MapAAIExceptionToWorkflowExceptionGeneric(execution, aaiResponse, responseCode)
+ throw new BpmnError("MSOWorkflowException")
+ }
+ }catch(BpmnError b){
+ msoLogger.debug("Rethrowing MSOWorkflowException")
+ throw b
+ }catch(Exception e){
+ msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, " Error encountered within GenericPutService PutServiceInstance method!" + e, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "");
+ exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured During Put Service Instance")
+ }
+ msoLogger.trace("COMPLETED GenericPutService PutServiceInstance Process")
+ }
+
+}
diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/GenericUtils.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/GenericUtils.groovy
new file mode 100644
index 0000000000..cc261a2750
--- /dev/null
+++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/GenericUtils.groovy
@@ -0,0 +1,40 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.so.bpmn.common.scripts
+
+import org.apache.commons.lang3.StringUtils;
+
+class GenericUtils extends StringUtils{
+
+ @Override
+ public static boolean isBlank(final CharSequence cs) {
+ int strLen;
+ if (cs == null || (strLen = cs.length()) == 0 || cs.equals("null")) {
+ return true;
+ }
+ for (int i = 0; i < strLen; i++) {
+ if (!Character.isWhitespace(cs.charAt(i))) {
+ return false;
+ }
+ }
+ return true;
+ }
+}
diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/ManualHandling.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/ManualHandling.groovy
new file mode 100644
index 0000000000..820364b1f7
--- /dev/null
+++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/ManualHandling.groovy
@@ -0,0 +1,343 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.so.bpmn.common.scripts;
+
+import static org.apache.commons.lang3.StringUtils.*;
+
+import java.time.chrono.AbstractChronology
+import java.util.List
+import java.text.SimpleDateFormat
+import java.util.Date
+
+import org.apache.commons.lang3.*
+import org.camunda.bpm.engine.TaskService
+import org.camunda.bpm.engine.task.Task
+import org.camunda.bpm.engine.task.TaskQuery
+import org.camunda.bpm.engine.delegate.BpmnError
+import org.camunda.bpm.engine.delegate.DelegateTask
+import org.camunda.bpm.engine.delegate.DelegateExecution
+import org.camunda.bpm.engine.delegate.DelegateExecution
+import org.json.JSONObject;
+import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor
+import org.onap.so.bpmn.common.scripts.ExceptionUtil
+import org.onap.so.bpmn.core.domain.ServiceDecomposition
+import org.onap.so.bpmn.core.json.JsonUtils
+import org.onap.so.client.ruby.*
+import org.onap.so.logger.MessageEnum
+import org.onap.so.logger.MsoLogger
+
+
+
+
+
+/**
+ * This groovy class supports the <class>ManualHandling.bpmn</class> process.
+ *
+ * @author
+ *
+ * Inputs:
+ * @param - msoRequestId
+ * @param - isDebugLogEnabled
+ * @param - serviceType
+ * @param - vnfType
+ * @param - requestorId
+ * @param - currentActivity
+ * @param - workStep
+ * @param - failedActivity
+ * @param - errorCode
+ * @param - errorText
+ * @param - validResponses
+ * @param - vnfName
+ *
+ * Outputs:
+ * @param - WorkflowException
+ * @param - taskId
+ *
+ */
+public class ManualHandling extends AbstractServiceTaskProcessor {
+ private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, ManualHandling.class);
+
+
+ String Prefix="MH_"
+ ExceptionUtil exceptionUtil = new ExceptionUtil()
+
+ JsonUtils jsonUtils = new JsonUtils()
+
+ public void preProcessRequest (DelegateExecution execution) {
+ String msg = ""
+ msoLogger.trace("preProcessRequest of ManualHandling ")
+
+ try {
+ execution.setVariable("prefix", Prefix)
+ setBasicDBAuthHeader(execution, execution.getVariable('isDebugLogEnabled'))
+ // check for required input
+ String requestId = execution.getVariable("msoRequestId")
+ msoLogger.debug("msoRequestId is: " + requestId)
+ def serviceType = execution.getVariable("serviceType")
+ msoLogger.debug("serviceType is: " + serviceType)
+ def vnfType = execution.getVariable("vnfType")
+ msoLogger.debug("vnftype is: " + vnfType)
+ def currentActivity = execution.getVariable("currentActivity")
+ msoLogger.debug("currentActivity is: " + currentActivity)
+ def workStep = execution.getVariable("workStep")
+ msoLogger.debug("workStep is: " + workStep)
+ def failedActivity = execution.getVariable("failedActivity")
+ msoLogger.debug("failedActivity is: " + failedActivity)
+ def errorCode = execution.getVariable("errorCode")
+ msoLogger.debug("errorCode is: " + errorCode)
+ def errorText = execution.getVariable("errorText")
+ msoLogger.debug("errorText is: " + errorText)
+ def requestorId = execution.getVariable("requestorId")
+ msoLogger.debug("requestorId is: " + requestorId)
+ def validResponses = execution.getVariable("validResponses")
+ msoLogger.debug("validResponses is: " + validResponses)
+
+ } catch (BpmnError e) {
+ throw e;
+ } catch (Exception ex){
+ msg = "Exception in preProcessRequest " + ex.getMessage()
+ msoLogger.debug(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
+ }
+ msoLogger.trace("Exit preProcessRequest of RainyDayHandler ")
+ }
+
+ public void createManualTask (DelegateExecution execution) {
+ String msg = ""
+ msoLogger.trace("createManualTask of ManualHandling ")
+
+ try {
+ String taskId = UUID.randomUUID()
+ execution.setVariable('taskId', taskId)
+ String type = "fallout"
+ String nfRole = execution.getVariable("vnfType")
+ String subscriptionServiceType = execution.getVariable("serviceType")
+ String originalRequestId = execution.getVariable("msoRequestId")
+ String originalRequestorId = execution.getVariable("requestorId")
+ String errorSource = execution.getVariable("failedActivity")
+ String errorCode = execution.getVariable("errorCode")
+ String errorMessage = execution.getVariable("errorText")
+ String buildingBlockName = execution.getVariable("currentActivity")
+ String buildingBlockStep = execution.getVariable("workStep")
+ String validResponses = execution.getVariable("validResponses")
+
+ msoLogger.debug("Before creating task")
+
+ Map<String, String> taskVariables = new HashMap<String, String>()
+ taskVariables.put("type", type)
+ taskVariables.put("nfRole", nfRole)
+ taskVariables.put("subscriptionServiceType", subscriptionServiceType)
+ taskVariables.put("originalRequestId", originalRequestId)
+ taskVariables.put("originalRequestorId", originalRequestorId)
+ taskVariables.put("errorSource", errorSource)
+ taskVariables.put("errorCode", errorCode)
+ taskVariables.put("errorMessage", errorMessage)
+ taskVariables.put("buildingBlockName", buildingBlockName)
+ taskVariables.put("buildingBlockStep", buildingBlockStep)
+ taskVariables.put("validResponses", validResponses)
+
+ TaskService taskService = execution.getProcessEngineServices().getTaskService()
+ Task manualTask = taskService.newTask(taskId)
+ taskService.saveTask(manualTask)
+ taskService.setVariables(taskId, taskVariables)
+ msoLogger.debug("successfully created task: "+ taskId)
+ } catch (BpmnError e) {
+ msoLogger.debug("BPMN exception: " + e.errorMessage)
+ throw e;
+ } catch (Exception ex){
+ msg = "Exception in createManualTask " + ex.getMessage()
+ msoLogger.debug(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
+ }
+ msoLogger.trace("Exit createManualTask of ManualHandling ")
+ }
+
+ public void setTaskVariables (DelegateTask task) {
+
+ DelegateExecution execution = task.getExecution()
+
+ String msg = ""
+ msoLogger.trace("setTaskVariables of ManualHandling ")
+ String taskId = task.getId()
+ msoLogger.debug("taskId is: " + taskId)
+
+ try {
+ execution.setVariable('taskId', taskId)
+ String type = "fallout"
+ String nfRole = execution.getVariable("vnfType")
+ String subscriptionServiceType = execution.getVariable("serviceType")
+ String originalRequestId = execution.getVariable("msoRequestId")
+ String originalRequestorId = execution.getVariable("requestorId")
+ String errorSource = execution.getVariable("failedActivity")
+ String errorCode = execution.getVariable("errorCode")
+ String errorMessage = execution.getVariable("errorText")
+ String buildingBlockName = execution.getVariable("currentActivity")
+ String buildingBlockStep = execution.getVariable("workStep")
+ String validResponses = execution.getVariable("validResponses")
+
+ msoLogger.debug("Before creating task")
+
+ Map<String, String> taskVariables = new HashMap<String, String>()
+ taskVariables.put("type", type)
+ taskVariables.put("nfRole", nfRole)
+ taskVariables.put("subscriptionServiceType", subscriptionServiceType)
+ taskVariables.put("originalRequestId", originalRequestId)
+ taskVariables.put("originalRequestorId", originalRequestorId)
+ taskVariables.put("errorSource", errorSource)
+ taskVariables.put("errorCode", errorCode)
+ taskVariables.put("errorMessage", errorMessage)
+ taskVariables.put("buildingBlockName", buildingBlockName)
+ taskVariables.put("buildingBlockStep", buildingBlockStep)
+ taskVariables.put("validResponses", validResponses)
+ TaskService taskService = execution.getProcessEngineServices().getTaskService()
+
+
+ taskService.setVariables(taskId, taskVariables)
+ msoLogger.debug("successfully created task: "+ taskId)
+ } catch (BpmnError e) {
+ msoLogger.debug("BPMN exception: " + e.errorMessage)
+ throw e;
+ } catch (Exception ex){
+ msg = "Exception in createManualTask " + ex.getMessage()
+ msoLogger.debug(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
+ }
+ msoLogger.trace("Exit createManualTask of ManualHandling ")
+ }
+
+ public void completeTask (DelegateTask task) {
+
+ DelegateExecution execution = task.getExecution()
+
+ String msg = ""
+ msoLogger.trace("completeTask of ManualHandling ")
+ String taskId = task.getId()
+ msoLogger.debug("taskId is: " + taskId)
+
+ try {
+ TaskService taskService = execution.getProcessEngineServices().getTaskService()
+
+ Map<String, String> taskVariables = taskService.getVariables(taskId)
+ String responseValue = taskVariables.get("responseValue")
+
+ msoLogger.debug("Received responseValue on completion: "+ responseValue)
+ // Have to set the first letter of the response to upper case
+ String responseValueForRainyDay = responseValue.substring(0, 1).toUpperCase() + responseValue.substring(1)
+ msoLogger.debug("ResponseValue to RainyDayHandler: "+ responseValueForRainyDay)
+ execution.setVariable("responseValue", responseValueForRainyDay)
+
+ } catch (BpmnError e) {
+ msoLogger.debug("BPMN exception: " + e.errorMessage)
+ throw e;
+ } catch (Exception ex){
+ msg = "Exception in createManualTask " + ex.getMessage()
+ msoLogger.debug(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
+ }
+ msoLogger.trace("Exit completeTask of ManualHandling ")
+ }
+
+ public void prepareRequestsDBStatusUpdate (DelegateExecution execution, String requestStatus){
+
+ def method = getClass().getSimpleName() + '.prepareRequestsDBStatusUpdate(' +'execution=' + execution.getId() +')'
+ msoLogger.trace("prepareRequestsDBStatusUpdate of ManualHandling ")
+ try {
+ def requestId = execution.getVariable("msoRequestId")
+ String payload = """
+ <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:req="http://org.onap.so/requestsdb">
+ <soapenv:Header/>
+ <soapenv:Body>
+ <req:updateInfraRequest>
+ <requestId>${MsoUtils.xmlEscape(requestId)}</requestId>
+ <lastModifiedBy>ManualHandling</lastModifiedBy>
+ <requestStatus>${MsoUtils.xmlEscape(requestStatus)}</requestStatus>
+ </req:updateInfraRequest>
+ </soapenv:Body>
+ </soapenv:Envelope>
+ """
+
+ execution.setVariable("setUpdateDBstatusPayload", payload)
+ msoLogger.debug("Outgoing Update Mso Request Payload is: " + payload)
+ msoLogger.debug("setUpdateDBstatusPayload: " + payload)
+ } catch (BpmnError e) {
+ throw e;
+ } catch (Exception e) {
+ msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e);
+ exceptionUtil.buildAndThrowWorkflowException(execution, 2000, "Internal Error - Occured in" + method)
+ }
+
+ msoLogger.trace("Exit prepareRequestsDBStatusUpdate of ManualHandling ")
+ }
+
+ public void createAOTSTicket (DelegateExecution execution) {
+ String msg = ""
+ msoLogger.trace("createAOTSTicket of ManualHandling ")
+ def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
+ // This method will not be throwing an exception, but rather log the error
+
+ try {
+ execution.setVariable("prefix", Prefix)
+ setBasicDBAuthHeader(execution,isDebugLogEnabled)
+ // check for required input
+ String requestId = execution.getVariable("msoRequestId")
+ msoLogger.debug("requestId is: " + requestId)
+ def currentActivity = execution.getVariable("currentActivity")
+ msoLogger.debug("currentActivity is: " + currentActivity)
+ def workStep = execution.getVariable("workStep")
+ msoLogger.debug("workStep is: " + workStep)
+ def failedActivity = execution.getVariable("failedActivity")
+ msoLogger.debug("failedActivity is: " + failedActivity)
+ def errorCode = execution.getVariable("errorCode")
+ msoLogger.debug("errorCode is: " + errorCode)
+ def errorText = execution.getVariable("errorText")
+ msoLogger.debug("errorText is: " + errorText)
+ def vnfName = execution.getVariable("vnfName")
+ msoLogger.debug("vnfName is: " + vnfName)
+
+ String rubyRequestId = UUID.randomUUID()
+ msoLogger.debug("rubyRequestId: " + rubyRequestId)
+ String sourceName = vnfName
+ msoLogger.debug("sourceName: " + sourceName)
+ String reason = "VID Workflow failed at " + failedActivity + " " + workStep + " call with error " + errorCode
+ msoLogger.debug("reason: " + reason)
+ String workflowId = requestId
+ msoLogger.debug("workflowId: " + workflowId)
+ String notification = "Request originated from VID | Workflow fallout on " + vnfName + " | Workflow step failure: " + workStep + " failed | VID workflow ID: " + workflowId
+ msoLogger.debug("notification: " + notification)
+
+ msoLogger.debug("Creating AOTS Ticket request")
+
+ RubyClient rubyClient = new RubyClient()
+ rubyClient.rubyCreateTicketCheckRequest(rubyRequestId, sourceName, reason, workflowId, notification)
+
+ } catch (BpmnError e) {
+ msg = "BPMN error in createAOTSTicket " + ex.getMessage()
+ msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, msg, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "");
+ } catch (Exception ex){
+ msg = "Exception in createAOTSTicket " + ex.getMessage()
+ msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, msg, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "");
+ }
+ msoLogger.trace("Exit createAOTSTicket of ManualHandling ")
+ }
+
+
+
+}
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
new file mode 100644
index 0000000000..f9ddd0d430
--- /dev/null
+++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/MsoUtils.groovy
@@ -0,0 +1,999 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.so.bpmn.common.scripts
+
+import java.text.SimpleDateFormat
+
+import org.apache.commons.codec.binary.Base64
+import org.apache.commons.lang3.StringEscapeUtils
+import org.onap.so.bpmn.core.BPMNLogger
+import org.onap.so.bpmn.core.xml.XmlTool
+import org.onap.so.logger.MessageEnum
+import org.onap.so.logger.MsoLogger
+import org.onap.so.utils.CryptoUtils
+import org.slf4j.MDC
+import org.w3c.dom.Element
+
+import groovy.util.slurpersupport.NodeChild
+import groovy.xml.XmlUtil
+
+class MsoUtils {
+ private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, MsoUtils.class);
+
+ def initializeEndPoints(execution){
+ // use this placeholder to initialize end points, if called independently, this need to be set
+ execution.setVariable("AAIEndPoint","http://localhost:28080/SoapUIMocks")
+ }
+
+ /**
+ * Returns the unescaped contents of element
+ *
+ * @param xmlInput
+ * @param element
+ * @return
+ */
+ def getNodeText(xmlInput,element){
+ def rtn=null
+ if(xmlInput!=null){
+ def xml= new XmlSlurper().parseText(xmlInput)
+ rtn= xml.'**'.find{node->node.name()==element}
+ if (rtn != null){
+ rtn=rtn.text()
+ }
+ }
+ return rtn
+ }
+ def getMultNodes(xmlInput, element){
+ def nodes=null
+ if(xmlInput!=null){
+ def xml= new XmlSlurper().parseText(xmlInput)
+ nodes = xml.'**'.findAll{ node-> node.name() == element }*.text()
+ }
+ return nodes
+ }
+ /**
+ * Note: this uses XmlParser instead of XmlSlurper, thus it is not as
+ * efficient because it instantiates the whole DOM tree.
+ * @param xmlInput
+ * @param element
+ * @return a list of Nodes, or {@code null} if <i>xmlInput</i> is {@code null}
+ */
+ def getMultNodeObjects(xmlInput, element){
+ def nodes=null
+ if(xmlInput!=null){
+ def xml= new XmlParser().parseText(xmlInput)
+ nodes = xml.'**'.findAll{ node-> node.name() == element }
+ }
+ return nodes
+ }
+
+ def getNodeXml(xmlInput,element){
+ return getNodeXml(xmlInput, element, true)
+ }
+ def getNodeXml(xmlInput,element,incPreamble){
+ def fxml= new XmlSlurper().parseText(xmlInput)
+ NodeChild nodeToSerialize = fxml.'**'.find {it.name() == element}
+ if(nodeToSerialize==null){
+ return ""
+ }
+ def nodeAsText = XmlUtil.serialize(nodeToSerialize)
+ if (!incPreamble) {
+ nodeAsText = removeXmlPreamble(nodeAsText)
+ }
+
+ return unescapeNodeContents(nodeToSerialize, nodeAsText)
+ }
+
+ def unescapeNodeContents(NodeChild node, String text) {
+ if (!node.childNodes().hasNext()) {
+ return StringEscapeUtils.unescapeXml(text)
+ } else {
+ return text
+ }
+ }
+
+ def nodeExists(xmlInput,element){
+ try {
+ def fxml= new XmlSlurper().parseText(xmlInput)
+ def nodeToSerialize = fxml.'**'.find {it.name() == element}
+ return nodeToSerialize!=null
+ } catch(Exception e) {
+ return false
+ }
+ }
+
+
+ /***** Utilities when using XmlParser *****/
+
+ /**
+ * Convert a Node into a String by deserializing it and formatting it.
+ *
+ * @param node Node to be converted.
+ * @return the Node as a String.
+ */
+ def String nodeToString(Node node) {
+ def String nodeAsString = groovy.xml.XmlUtil.serialize(node)
+ nodeAsString = removeXmlPreamble(nodeAsString)
+ return formatXml(nodeAsString)
+ }
+
+ /**
+ * Get the specified child Node of the specified parent. If there are
+ * multiple children of the same name, only the first one is returned.
+ * If there are no children with the specified name, 'null' is returned.
+ *
+ * @param parent Parent Node in which to find a child.
+ * @param childNodeName Name of the child Node to get.
+ * @return the (first) child Node with the specified name or 'null'
+ * if a child Node with the specified name does not exist.
+ */
+ def Node getChildNode(Node parent, String childNodeName) {
+ def NodeList nodeList = getIdenticalChildren(parent, childNodeName)
+ if (nodeList.size() == 0) {
+ return null
+ } else {
+ return nodeList.get(0)
+ }
+ }
+
+ /**
+ * Get the textual value of the specified child Node of the specified parent.
+ * If there are no children with the specified name, 'null' is returned.
+ *
+ * @param parent Parent Node in which to find a child.
+ * @param childNodeName Name of the child Node whose value to get.
+ * @return the textual value of child Node with the specified name or 'null'
+ * if a child Node with the specified name does not exist.
+ */
+ def String getChildNodeText(Node parent, String childNodeName) {
+ def Node childNode = getChildNode(parent, childNodeName)
+ if (childNode == null) {
+ return null
+ } else {
+ return childNode.text()
+ }
+ }
+
+ /**
+ * Get all of the child nodes from the specified parent that have the
+ * specified name. The returned NodeList could be empty.
+ *
+ * @param parent Parent Node in which to find children.
+ * @param childNodeName Name of the children to get.
+ * @return a NodeList of all the children from the parent with the specified
+ * name. The list could be empty.
+ */
+ def NodeList getIdenticalChildren(Node parent, String childNodeName) {
+ return (NodeList) parent.get(childNodeName)
+ }
+
+ /***** End of Utilities when using XmlParser *****/
+
+
+ /** these are covered under the common function above**/
+ def getSubscriberName(xmlInput,element){
+ def rtn=null
+ if(xmlInput!=null){
+ def xml= new XmlSlurper().parseText(xmlInput)
+ rtn= xml.'**'.find{node->node.name()==element}.text()
+ }
+ return rtn
+ }
+ def getTenantInformation(xmlInput,element){
+ def xml= new XmlSlurper().parseText(xmlInput)
+ def nodeToSerialize = xml.'**'.find {it.name() == 'service-information'}
+ def nodeAsText = XmlUtil.serialize(nodeToSerialize)
+ return nodeAsText
+ }
+ def getServiceInstanceId(xmlInput,element){
+ def xml= new XmlSlurper().parseText(xmlInput)
+ return ( xml.'**'.find{node->node.name()==element}.text() )
+ }
+ //for aai tenant url
+ def searchResourceLink(xmlInput, resourceType){
+ def fxml= new XmlSlurper().parseText(xmlInput)
+ def element = fxml.'**'.find {it.'resource-type' == resourceType}
+ return (element == null) ? null : element.'resource-link'.text()
+ }
+
+ def searchMetaData(xmlInput, searchName, searchValue){
+ def fxml= new XmlSlurper().parseText(xmlInput)
+ def ret = fxml.'**'.find {it.metaname.text() == searchName && it.metaval.text() == searchValue}
+ if(ret != null){
+ return ret.parent().parent()
+ }
+ return ret
+ }
+
+ def searchMetaDataNode(fxml, searchName, searchValue){
+ def ret = fxml.'**'.find {it.metaname.text() == searchName && it.metaval.text() == searchValue}
+ if(ret != null){
+ return ret.parent().parent()
+ }
+ return ret
+ }
+
+ // for Trinity L3 add/delete bonding
+ def getPBGFList(isDebugLogEnabled, xmlInput){
+ log("DEBUG", "getPBGFList: xmlInput " + xmlInput,isDebugLogEnabled)
+ ArrayList myNodes = new ArrayList()
+ if(nodeExists(xmlInput,"nbnc-response-information")){
+ def respInfo=getNodeXml(xmlInput,"nbnc-response-information", false)
+ if(respInfo!=null){
+ def fxml= new XmlSlurper().parseText(respInfo)
+ fxml.'virtual-datacenter-list'.each { vdc ->
+ //we only want to add two BGF per VDC, BGF1 and BGF2
+ def routerList = vdc.'router-list'.first()
+ routerList.each{ myList ->
+ def physNodes = myList.'**'.findAll {it.'border-element-tangibility'.text() =~ /PHYSICAL/}
+ def nodeToAdd
+ physNodes.each{
+ if(nodeToAdd==null){
+ nodeToAdd = it
+ }else{
+ def beid = nodeToAdd.'border-element-id'.text() +
+ " " + nodeToAdd.'border-element-type'.text() +
+ " and " +
+ it.'border-element-id'.text() +
+ " " + it.'border-element-type'.text()
+ def mytag = nodeToAdd.'border-element-id'
+ mytag[0].replaceBody(beid)
+ }
+ }
+ def mytag = nodeToAdd.'vlan-id'
+ def ind = mytag.text().indexOf('.')
+ if(ind >= 0){
+ def vlan = mytag.text().substring(0,ind)
+ mytag[0].replaceBody(vlan)
+ }
+ myNodes.add(XmlUtil.serialize(nodeToAdd))
+ }
+
+ }
+ }
+
+ return myNodes
+ }else{
+ return null
+ }
+ }
+
+ def getPBGFList(xmlInput){
+ getPBGFList("false", xmlInput)
+ }
+
+ def getMetaVal(node, name){
+ try{
+ return node.'**'.find {it.metaname.text() == name}.metaval.text()
+ }catch(Exception e){
+ 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) {
+ msoLogger.info(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, logtxt, "BPMN", MsoLogger.getServiceName());
+ } else if ("WARN"==logmode) {
+ // to see the warning text displayed in the log entry, the text must also be passed as arg0 (2nd argument) to invoke the correct MsoLogger warn() method
+ msoLogger.warn (MessageEnum.BPMN_GENERAL_WARNING, logtxt, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, logtxt);
+ } else if ("ERROR"==logmode) {
+ // to see the error text displayed in the log entry, the text must also be passed as arg0 (2nd argument) to invoke the correct MsoLogger error() method
+ msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, logtxt, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, logtxt);
+
+ } else {
+ BPMNLogger.debug(isDebugLogEnabled, logtxt);
+ }
+ }
+
+ def logContext(requestId, serviceInstanceId){
+ msoLogger.setLogContext(requestId, serviceInstanceId);
+ }
+
+ def logMetrics(elapsedTime, logtxt){
+
+ msoLogger.recordMetricEvent (elapsedTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc,
+ logtxt, "BPMN", MsoLogger.getServiceName(), null);
+ }
+
+ def logAudit(logtxt){
+ long startTime = System.currentTimeMillis();
+
+ msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, logtxt);
+ }
+
+ // headers: header - name-value
+ def getHeaderNameValue(xmlInput, nameAttribute){
+ def rtn=null
+ if(xmlInput!=null){
+ def xml= new XmlSlurper().parseText(xmlInput)
+ rtn= xml.'**'.find {header->header.'@name'.text() == nameAttribute}.'@value'
+ }
+ return rtn
+ }
+
+ /**
+ * Gets the children of the specified element.
+ */
+ public String getChildNodes(xmlInput, element) {
+ def xml= new XmlSlurper().parseText(xmlInput)
+ def thisElement = xml.'**'.find {it.name() == element}
+ StringBuilder out = new StringBuilder()
+ if (thisElement != null) {
+ thisElement.children().each() {
+ String nodeAsText = removeXmlPreamble(XmlUtil.serialize(it))
+ if (out.length() > 0) {
+ out.append(System.lineSeparator())
+ }
+ out.append(nodeAsText)
+ }
+ }
+ return out.toString();
+ }
+
+ /**
+ * Encodes a value so it can be used inside an XML text element.
+ *
+ * <b>Will double encode</b>
+ * @param s the string to encode
+ * @return the encoded string
+ */
+ public static String xmlEscape(Object value) {
+ return XmlTool.encode(value)
+ }
+
+ /**
+ * Removes the preamble, if present, from an XML document.
+ * Also, for historical reasons, this also trims leading and trailing
+ * whitespace from the resulting document. TODO: remove the trimming
+ * and fix unit tests that depend on EXACT xml format.
+ * @param xml the XML document
+ * @return a possibly modified document
+ */
+ public String removeXmlPreamble(def xml) {
+ if (xml == null) {
+ return null
+ }
+
+ return XmlTool.removePreamble(xml).trim()
+ }
+
+ /**
+ * Removes namespaces and namespace declarations from an XML document.
+ * @param xml the XML document
+ * @return a possibly modified document
+ */
+ public String removeXmlNamespaces(def xml) {
+ return XmlTool.removeNamespaces(xml);
+ }
+
+ /**
+ * Use formatXml instead. Note: this method inserts an XML preamble.
+ */
+ @Deprecated
+ def formatXML(xmlInput) {
+ def parseXml = null
+ def formatXml = null
+ if (xmlInput !=null) {
+ parseXml = new XmlParser().parseText(xmlInput)
+ formatXml = XmlUtil.serialize(parseXml)
+ }
+ }
+
+ /**
+ * Reformats an XML document. The result will not contain an XML preamble
+ * or a trailing newline.
+ * @param xml the XML document
+ * @return a reformatted document
+ */
+ public String formatXml(def xml) {
+ return XmlTool.normalize(xml);
+ }
+
+ // build single elements
+ def buildElements(xmlInput, elementList, parentName) {
+ String var = ""
+ def xmlBuild = ""
+ if (parentName != "") {
+ xmlBuild += "<tns2:"+parentName+">"
+ }
+ if (xmlInput != null) {
+ for (element in elementList) {
+ def xml= new XmlSlurper().parseText(xmlInput)
+ var = xml.'**'.find {it.name() == element}
+ if (var != null) {
+ xmlBuild += "<tns2:"+element+">"+var.toString()+"</tns2:"+element+">"
+ }
+ }
+ }
+ if (parentName != "") {
+ xmlBuild += "</tns2:"+parentName+">"
+ }
+ return xmlBuild
+ }
+
+ // build the Unbounded elements
+ def buildElementsUnbounded(xmlInput, elementList, parentName) {
+ def varParents = ""
+ def var = ""
+ def xmlBuildUnbounded = ""
+ if (xmlInput != null) {
+ def xml= new XmlSlurper().parseText(xmlInput)
+ varParents = xml.'**'.findAll {it.name() == parentName}
+ //println " Unbounded ${parentName} - varParent.Size() - " + varParents.size()
+ for (i in 0..varParents.size()-1) {
+ if (parentName != "") {
+ xmlBuildUnbounded += "<tns2:"+parentName+">"
+ }
+ for (element in elementList) {
+ var = varParents[i].'*'.find {it.name() == element}
+ if (var != null) {
+ xmlBuildUnbounded += "<tns2:"+element+">"+var.toString()+"</tns2:"+element+">"
+ //println " i = " + i + ", element: " + element + " = " + var.toString()
+ }
+ }
+ if (parentName != "") {
+ xmlBuildUnbounded += "</tns2:"+parentName+">"
+ }
+ }
+ }
+ return xmlBuildUnbounded
+ }
+
+ // Build l2-homing-information
+ def buildL2HomingInformation(xmlInput) {
+ def elementsL2HomingList = ["evc-name", "topology", "preferred-aic-clli","aic-version"]
+ def rebuildL2Home = ''
+ if (xmlInput != null) {
+ rebuildL2Home = buildElements(xmlInput, elementsL2HomingList, "l2-homing-information")
+ }
+ return rebuildL2Home
+ }
+
+ // Build internet-evc-access-information
+ def buildInternetEvcAccessInformation(xmlInput) {
+ def elementsInternetEvcAccessInformationList = ["internet-evc-speed-value", "internet-evc-speed-units", "ip-version"]
+ def rebuildInternetEvcAccess = ''
+ if (xmlInput != null) {
+ rebuildInternetEvcAccess = buildElements(xmlInput, elementsInternetEvcAccessInformationList, "internet-evc-access-information")
+ }
+ return rebuildInternetEvcAccess
+ }
+
+ // Build ucpe-vms-service-information
+ def buildUcpeVmsServiceInformation(xmlInput) {
+ def rebuildUcpeVmsServiceInformation = ''
+ if (xmlInput != null) {
+ def ucpeVmsServiceInformation = getNodeXml(xmlInput, "ucpe-vms-service-information").drop(38).trim()
+ rebuildUcpeVmsServiceInformation = "<tns2:ucpe-vms-service-information>"
+ // transport-service-information
+ rebuildUcpeVmsServiceInformation += "<tns2:transport-service-information>"
+ def transportServiceInformation = getNodeXml(ucpeVmsServiceInformation, "transport-service-information").drop(38).trim()
+ def elementsTransportServiceInformationList = ["transport-service-type"]
+ rebuildUcpeVmsServiceInformation += buildElements(transportServiceInformation, elementsTransportServiceInformationList, "")
+ try { // optional
+ def accessCircuitInfoList = ["access-circuit-id", "dual-mode"]
+ rebuildUcpeVmsServiceInformation += buildElementsUnbounded(transportServiceInformation, accessCircuitInfoList, "access-circuit-info")
+ } catch (Exception e) {
+ log("ERROR", " Optional - Exception ACCESS-CIRCUIT-INFO - 'access-circuit-info' ")
+ }
+ rebuildUcpeVmsServiceInformation += "</tns2:transport-service-information>"
+ // ucpe-information
+ def elementsUcpeInformationList = ["ucpe-host-name", "ucpe-activation-code", "out-of-band-management-modem" ]
+ rebuildUcpeVmsServiceInformation += buildElements(ucpeVmsServiceInformation, elementsUcpeInformationList, "ucpe-information")
+ // vnf-list
+ rebuildUcpeVmsServiceInformation += "<tns2:vnf-list>"
+ def vnfListList = ["vnf-instance-id", "vnf-sequence-number", "vnf-type", "vnf-vendor", "vnf-model", "vnf-id", "prov-status", "operational-state", "orchestration-status", "equipment-role" ]
+ rebuildUcpeVmsServiceInformation += buildElementsUnbounded(ucpeVmsServiceInformation, vnfListList, "vnf-information")
+ rebuildUcpeVmsServiceInformation += "</tns2:vnf-list>"
+ rebuildUcpeVmsServiceInformation += "</tns2:ucpe-vms-service-information>"
+ }
+ log("DEBUG", " rebuildUcpeVmsServiceInformation - " + rebuildUcpeVmsServiceInformation)
+ return rebuildUcpeVmsServiceInformation
+ }
+
+ // Build internet-service-change-details
+ def buildInternetServiceChangeDetails(xmlInput) {
+ def rebuildInternetServiceChangeDetails = ""
+ if (xmlInput != null) {
+ try { // optional
+ def internetServiceChangeDetails = getNodeXml(xmlInput, "internet-service-change-details").drop(38).trim()
+ rebuildInternetServiceChangeDetails = "<tns:internet-service-change-details>"
+ rebuildInternetServiceChangeDetails += buildElements(internetServiceChangeDetails, ["internet-evc-speed-value"], "")
+ rebuildInternetServiceChangeDetails += buildElements(internetServiceChangeDetails, ["internet-evc-speed-units"], "")
+ rebuildInternetServiceChangeDetails += buildElements(internetServiceChangeDetails, ["v4-vr-lan-address"], "")
+ rebuildInternetServiceChangeDetails += buildElements(internetServiceChangeDetails, ["v4-vr-lan-prefix-length"], "")
+ try { // optional
+ def tProvidedV4LanPublicPrefixesChangesList = ["request-index", "v4-next-hop-address", "v4-lan-public-prefix", "v4-lan-public-prefix-length"]
+ rebuildInternetServiceChangeDetails += buildElementsUnbounded(internetServiceChangeDetails, tProvidedV4LanPublicPrefixesChangesList, "t-provided-v4-lan-public-prefixes")
+ } catch (Exception e) {
+ log("ERROR"," Optional - Exception in INTERNET-SERVICE-CHANGE-DETAILS 't-provided-v4-lan-public-prefixes ")
+ }
+ try { // optional
+ def tProvidedV6LanPublicPrefixesChangesList = ["request-index", "v6-next-hop-address", "v6-lan-public-prefix", "v6-lan-public-prefix-length"]
+ rebuildInternetServiceChangeDetails += buildElementsUnbounded(internetServiceChangeDetails, tProvidedV6LanPublicPrefixesChangesList, "t-provided-v6-lan-public-prefixes")
+ } catch (Exception e) {
+ log("ERROR"," Optional - Exception INTERNET-SERVICE-CHANGE-DETAILS 't-provided-v6-lan-public-prefixes ")
+ }
+ rebuildInternetServiceChangeDetails += "</tns:internet-service-change-details>"
+ } catch (Exception e) {
+ log("ERROR", " Optional - Exception INTERNET-SERVICE-CHANGE-DETAILS 'internet-service-change-details' ")
+ }
+ }
+ return rebuildInternetServiceChangeDetails
+ }
+
+ // Build vr-lan
+ def buildVrLan(xmlInput) {
+
+ def rebuildVrLan = ''
+ if (xmlInput != null) {
+
+ rebuildVrLan = "<tns2:vr-lan>"
+ def vrLan = getNodeXml(xmlInput, "vr-lan").drop(38).trim()
+ rebuildVrLan += buildElements(vrLan, ["routing-protocol"], "")
+
+ // vr-lan-interface
+ def rebuildVrLanInterface = "<tns2:vr-lan-interface>"
+ def vrLanInterface = getNodeXml(vrLan, "vr-lan-interface").drop(38).trim()
+ rebuildVrLanInterface += buildVrLanInterfacePartial(vrLanInterface)
+
+ // dhcp
+ def dhcp = getNodeXml(vrLan, "dhcp").drop(38).trim()
+ def rebuildDhcp = buildDhcp(dhcp)
+ rebuildVrLanInterface += rebuildDhcp
+
+ // pat
+ def pat = getNodeXml(vrLan, "pat").drop(38).trim()
+ def rebuildPat = buildPat(pat)
+ rebuildVrLanInterface += rebuildPat
+
+ // nat
+ def rebuildNat = ""
+ try { // optional
+ def nat = getNodeXml(vrLan, "nat").drop(38).trim()
+ rebuildNat = buildNat(nat)
+ } catch (Exception e) {
+ log("ERROR", " Optional - Exception 'nat' ")
+ }
+ rebuildVrLanInterface += rebuildNat
+
+ // firewall-lite
+ def firewallLite = getNodeXml(vrLan, "firewall-lite").drop(38).trim()
+ def rebuildFirewallLite = buildFirewallLite(firewallLite)
+ rebuildVrLanInterface += rebuildFirewallLite
+
+ // static-routes
+ def rebuildStaticRoutes = ""
+ try { // optional
+ def staticRoutes = getNodeXml(vrLan, "static-routes").drop(38).trim()
+ rebuildStaticRoutes = buildStaticRoutes(staticRoutes)
+ } catch (Exception e) {
+ log("ERROR", " Optional - Exception 'static-routes' ")
+ }
+ rebuildVrLanInterface += rebuildStaticRoutes
+
+ rebuildVrLan += rebuildVrLanInterface
+ rebuildVrLan += "</tns2:vr-lan-interface>"
+ rebuildVrLan += "</tns2:vr-lan>"
+
+ }
+ log("DEBUG", " rebuildVrLan - " + rebuildVrLan)
+ return rebuildVrLan
+ }
+
+ // Build vr-lan-interface
+ def buildVrLanInterfacePartial(xmlInput) {
+ def rebuildingVrLanInterface = ''
+ if (xmlInput != null) {
+ def vrLanInterfaceList = ["vr-designation", "v4-vr-lan-prefix", "v4-vr-lan-address", "v4-vr-lan-prefix-length", "v6-vr-lan-prefix", "v6-vr-lan-address", "v6-vr-lan-prefix-length", "v4-vce-loopback-address", "v6-vce-wan-address"]
+ rebuildingVrLanInterface += buildElements(xmlInput, vrLanInterfaceList, "")
+ rebuildingVrLanInterface += "<tns2:v4-public-lan-prefixes>"
+ try { // optional
+ def tProvidedV4LanPublicPrefixes = getNodeXml(xmlInput, "v4-public-lan-prefixes").drop(38).trim()
+ def tProvidedV4LanPublicPrefixesList = ["request-index", "v4-next-hop-address", "v4-lan-public-prefix", "v4-lan-public-prefix-length" ]
+ rebuildingVrLanInterface += buildElementsUnbounded(xmlInput, tProvidedV4LanPublicPrefixesList, "t-provided-v4-lan-public-prefixes")
+ } catch (Exception ex) {
+ log("ERROR", " Optional - Exception VR-LAN INTERFACE 'v4-public-lan-prefixes' ")
+ }
+ rebuildingVrLanInterface += "</tns2:v4-public-lan-prefixes>"
+ rebuildingVrLanInterface += "<tns2:v6-public-lan-prefixes>"
+ try { // optional
+ def tProvidedV6LanPublicPrefixes = getNodeXml(xmlInput, "v6-public-lan-prefixes").drop(38).trim()
+ def tProvidedV6LanPublicPrefixesList = ["request-index", "v6-next-hop-address", "v6-lan-public-prefix", "v6-lan-public-prefix-length" ]
+ rebuildingVrLanInterface += buildElementsUnbounded(xmlInput, tProvidedV6LanPublicPrefixesList, "t-provided-v6-lan-public-prefixes")
+ } catch (Exception e) {
+ log("ERROR", " Optional - Exception VR-LAN INTERFACE 'v6-public-lan-prefixes' ")
+ }
+ rebuildingVrLanInterface += "</tns2:v6-public-lan-prefixes>"
+ }
+ log("DEBUG", " rebuildingVrLanInterface - " + rebuildingVrLanInterface)
+ return rebuildingVrLanInterface
+ }
+
+ // Build dhcp
+ def buildDhcp(xmlInput) {
+ def rebuildingDhcp = ''
+ if (xmlInput != null) {
+ def dhcpData = new XmlSlurper().parseText(xmlInput)
+ rebuildingDhcp = "<tns2:dhcp>"
+ def dhcpList1 = ["v4-dhcp-server-enabled", "v6-dhcp-server-enabled", "use-v4-default-pool", "v4-dhcp-default-pool-prefix", "v4-dhcp-default-pool-prefix-length"]
+ rebuildingDhcp += buildElements(xmlInput, dhcpList1, "")
+ try { // optional
+ def excludedV4DhcpAddressesFromDefaultPoolList = ["excluded-v4-address"]
+ rebuildingDhcp += buildElementsUnbounded(xmlInput, excludedV4DhcpAddressesFromDefaultPoolList, "excluded-v4-dhcp-addresses-from-default-pool")
+ } catch (Exception e) {
+ log("ERROR", " Optional - Exception DHCP 'excluded-v4-dhcp-addresses-from-default-pool' ")
+ }
+ try { // optional
+ def v4DhcpPools = dhcpData.'**'.findAll {it.name() == "v4-dhcp-pools"}
+ def v4DhcpPoolsSize = v4DhcpPools.size()
+ // println " v4DhcpPoolsSize = " + v4DhcpPools.size()
+ for (i in 0..v4DhcpPoolsSize-1) {
+ def v4DhcpPool = v4DhcpPools[i]
+ def v4DhcpPoolXml = XmlUtil.serialize(v4DhcpPool)
+ rebuildingDhcp += "<tns2:v4-dhcp-pools>"
+ def v4DhcpPoolsList1 = ["v4-dhcp-pool-prefix", "v4-dhcp-pool-prefix-length" ]
+ rebuildingDhcp += buildElements(v4DhcpPoolXml, v4DhcpPoolsList1, "")
+ try { // optional
+ def excludedV4AddressesList = ["excluded-v4-address"]
+ rebuildingDhcp += buildElementsUnbounded(v4DhcpPoolXml, excludedV4AddressesList, "excluded-v4-addresses")
+ } catch (Exception e) {
+ log("ERROR", " Optional - Exception DHCP 'excluded-v4-addresses' ")
+ }
+ def v4DhcpPoolsList2 = ["v4-dhcp-relay-gateway-address", "v4-dhcp-relay-next-hop-address"]
+ rebuildingDhcp += buildElements(v4DhcpPoolXml, v4DhcpPoolsList2, "")
+ rebuildingDhcp += "</tns2:v4-dhcp-pools>"
+ }
+ } catch (Exception e) {
+ log("ERROR"," Optional - Exception DHCP 'v4-dhcp-pools' ")
+ }
+ def dhcpList2 = ["use-v6-default-pool", "v6-dhcp-default-pool-prefix", "v6-dhcp-default-pool-prefix-length"]
+ rebuildingDhcp += buildElements(xmlInput, dhcpList2, "")
+ try { // optional
+ def excludedV6DhcpAddressesFromDdefaultPoolList = ["excluded-v6-address"]
+ rebuildingDhcp += buildElementsUnbounded(xmlInput, excludedV6DhcpAddressesFromDdefaultPoolList, "excluded-v6-dhcp-addresses-from-default-pool")
+ } catch (Exception e) {
+ log("ERROR", " Optional - Exception DHCP 'excluded-v6-dhcp-addresses-from-default-pool' ")
+ }
+ try { // optional
+ def v6DhcpPools = dhcpData.'**'.findAll {it.name() == "v6-dhcp-pools"}
+ def v6DhcpPoolsSize = v6DhcpPools.size()
+ //println " v6DhcpPoolsSize = " + v6DhcpPools.size()
+ for (i in 0..v6DhcpPoolsSize-1) {
+ def v6DhcpPool = v6DhcpPools[i]
+ def v6DhcpPoolXml = XmlUtil.serialize(v6DhcpPool)
+ rebuildingDhcp += "<tns2:v6-dhcp-pools>"
+ def v6DhcpPoolsList1 = ["v6-dhcp-pool-prefix", "v6-dhcp-pool-prefix-length"]
+ rebuildingDhcp += buildElements(v6DhcpPoolXml, v6DhcpPoolsList1, "")
+ try { // optional
+ def excludedV6AddressesList = ["excluded-v6-address"]
+ rebuildingDhcp += buildElementsUnbounded(v6DhcpPoolXml, excludedV6AddressesList, "excluded-v6-addresses")
+ } catch (Exception e) {
+ log("ERROR", " Optional - Exception DHCP 'excluded-v6-addresses' ")
+ }
+ def v6DhcpPoolsList2 = ["v6-dhcp-relay-gateway-address", "v6-dhcp-relay-next-hop-address"]
+ rebuildingDhcp += buildElements(v6DhcpPoolXml, v6DhcpPoolsList2, "")
+ rebuildingDhcp += "</tns2:v6-dhcp-pools>"
+ }
+ } catch (Exception e) {
+ log("ERROR", " Optional - Exception DHCP 'v6-dhcp-pools' ")
+ }
+ rebuildingDhcp += "</tns2:dhcp>"
+ }
+ log("DEBUG", " rebuildingDhcp - " + rebuildingDhcp)
+ return rebuildingDhcp
+ }
+
+ // Build pat
+ def buildPat(xmlInput) {
+ def rebuildingPat = ''
+ if (xmlInput != null) {
+ rebuildingPat = "<tns2:pat>"
+ def patList = ["v4-pat-enabled", "use-v4-default-pool", "v4-pat-default-pool-prefix", "v4-pat-default-pool-prefix-length"]
+ rebuildingPat += buildElements(xmlInput, patList, "")
+ try { // optional
+ def v4PatPools = getNodeXml(xmlInput, "v4-pat-pools").drop(38).trim()
+ def v4PatPoolsList = ["v4-pat-pool-prefix", "v4-pat-pool-prefix-length", "v4-pat-pool-next-hop-address"]
+ rebuildingPat += buildElementsUnbounded(xmlInput, v4PatPoolsList, "v4-pat-pools")
+ } catch (Exception e) {
+ log("ERROR", " Optional - Exception 'v4-pat-pool-next-hop-address' ")
+ }
+ rebuildingPat += "</tns2:pat>"
+ }
+ log("DEBUG", " rebuildingPat - " + rebuildingPat)
+ return rebuildingPat
+ }
+
+ // Build nat
+ def buildNat(xmlInput) {
+ def rebuildingNat = ''
+ if (xmlInput != null) {
+ rebuildingNat = "<tns2:nat>"
+ rebuildingNat += buildElements(xmlInput, ["v4-nat-enabled"], "")
+ try { // optional
+ def v4NatMappingEntries = getNodeXml(xmlInput, "v4-nat-mapping-entries").drop(38).trim()
+ def v4NatMappingEntriesList = ["v4-nat-internal", "v4-nat-next-hop-address", "v4-nat-external"]
+ rebuildingNat += buildElementsUnbounded(xmlInput, v4NatMappingEntriesList, "v4-nat-mapping-entries")
+ } catch (Exception e) {
+ log("ERROR", " Optional - Exception 'v4-nat-external' ")
+ }
+ rebuildingNat += "</tns2:nat>"
+ }
+ log("DEBUG", " rebuildingNat - " + rebuildingNat)
+ return rebuildingNat
+ }
+
+ // Build firewall-lite
+ def buildFirewallLite(xmlInput) {
+ def rebuildingFirewallLite = ''
+
+ if (xmlInput != null) {
+
+ def firewallLiteData = new XmlSlurper().parseText(xmlInput)
+ rebuildingFirewallLite = "<tns2:firewall-lite>"
+ def firewallLiteList = ["stateful-firewall-lite-v4-enabled", "stateful-firewall-lite-v6-enabled"]
+ rebuildingFirewallLite += buildElements(xmlInput, firewallLiteList, "")
+
+ try { // optional
+ def v4FirewallPacketFilters = firewallLiteData.'**'.findAll {it.name() == "v4-firewall-packet-filters"}
+ def v4FirewallPacketFiltersSize = v4FirewallPacketFilters.size()
+ //println " v4FirewallPacketFiltersSize = " + v4FirewallPacketFilters.size()
+ for (i in 0..v4FirewallPacketFiltersSize-1) {
+ def v4FirewallPacketFilter = v4FirewallPacketFilters[i]
+ def v4FirewallPacketFilterXml = XmlUtil.serialize(v4FirewallPacketFilter)
+ rebuildingFirewallLite += "<tns2:v4-firewall-packet-filters>"
+ def v4FirewallPacketFiltersList = ["v4-firewall-prefix", "v4-firewall-prefix-length", "allow-icmp-ping"]
+ rebuildingFirewallLite += buildElements(v4FirewallPacketFilterXml, v4FirewallPacketFiltersList, "")
+ try { // optional
+ def udpPortsList = ["port-number"]
+ rebuildingFirewallLite += buildElementsUnbounded(v4FirewallPacketFilterXml, udpPortsList, "udp-ports")
+ } catch (Exception e) {
+ log("ERROR", " Optional - Exception FIREWALL-LITE v4 'udp-ports' ")
+ }
+ try { // optional
+ def tcpPortsList = ["port-number"]
+ rebuildingFirewallLite += buildElementsUnbounded(v4FirewallPacketFilterXml, tcpPortsList, "tcp-ports")
+ } catch (Exception e) {
+ log("ERROR", " Optional - Exception FIREWALL-LITE v4 'tcp-ports' ")
+ }
+ rebuildingFirewallLite += "</tns2:v4-firewall-packet-filters>"
+ }
+ } catch (Exception e) {
+ log("ERROR", " Optional - Exception FIREWALL-LITE 'v4-firewall-packet-filters' ")
+ }
+
+ try { // optional
+ def v6FirewallPacketFilters = firewallLiteData.'**'.findAll {it.name() == "v6-firewall-packet-filters"}
+ def v6FirewallPacketFiltersSize = v6FirewallPacketFilters.size()
+ //println " v6FirewallPacketFiltersSize = " + v6FirewallPacketFilters.size()
+ for (i in 0..v6FirewallPacketFiltersSize-1) {
+ def v6FirewallPacketFilter = v6FirewallPacketFilters[i]
+ def v6FirewallPacketFilterXml = XmlUtil.serialize(v6FirewallPacketFilter)
+ rebuildingFirewallLite += "<tns2:v6-firewall-packet-filters>"
+ def v6FirewallPacketFiltersList = ["v6-firewall-prefix", "v6-firewall-prefix-length", "allow-icmp-ping"]
+ rebuildingFirewallLite += buildElements(v6FirewallPacketFilterXml, v6FirewallPacketFiltersList, "")
+ try { // optional
+ def udpPortsList = ["port-number"]
+ rebuildingFirewallLite += buildElementsUnbounded(v6FirewallPacketFilterXml, udpPortsList, "udp-ports")
+ } catch (Exception e) {
+ log("ERROR", " Optional - Exception FIREWALL-LITE v6 'udp-ports' ")
+ }
+ try { // optional
+ def tcpPortsList = ["port-number"]
+ rebuildingFirewallLite += buildElementsUnbounded(v6FirewallPacketFilterXml, tcpPortsList, "tcp-ports")
+ } catch (Exception e) {
+ log("ERROR", " Optional - Exception FIREWALL-LITE v6 'tcp-ports' ")
+ }
+ rebuildingFirewallLite += "</tns2:v6-firewall-packet-filters>"
+ }
+ } catch (Exception e) {
+ log("ERROR", " Optional - Exception FIREWALL-LITE 'v6-firewall-packet-filters' ")
+ }
+ rebuildingFirewallLite+= "</tns2:firewall-lite>"
+ }
+ log("DEBUG", " rebuildingFirewallLite - " + rebuildingFirewallLite)
+ return rebuildingFirewallLite
+ }
+
+ def buildStaticRoutes(xmlInput) {
+ def rebuildingStaticRoutes = ''
+ if (xmlInput != null) {
+ rebuildingStaticRoutes = "<tns2:static-routes>"
+ def v4StaticRouteslist = ["v4-static-route-prefix","v4-static-route-prefix-length", "v4-next-hop-address"]
+ rebuildingStaticRoutes += buildElementsUnbounded(xmlInput, v4StaticRouteslist, "v4-static-routes")
+ def v6StaticRouteslist = ["v6-static-route-prefix","v6-static-route-prefix-length", "v6-next-hop-address"]
+ rebuildingStaticRoutes += buildElementsUnbounded(xmlInput, v6StaticRouteslist, "v6-static-routes")
+ rebuildingStaticRoutes += "</tns2:static-routes>"
+ }
+ log("DEBUG", " rebuildingStaticRoutes - " + rebuildingStaticRoutes)
+ return rebuildingStaticRoutes
+ }
+
+ public String generateCurrentTimeInUtc(){
+ final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
+ sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
+ final String utcTime = sdf.format(new Date());
+ return utcTime;
+ }
+
+ public String generateCurrentTimeInGMT(){
+ final SimpleDateFormat sdf = new SimpleDateFormat("E, d MMM yyyy h:m:s z");
+ sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
+ final String utcTime = sdf.format(new Date());
+ return utcTime;
+ }
+
+
+ /**
+ * @param encryptedAuth: encrypted credentials from urn properties
+ * @param msoKey: key to use to decrypt from urn properties
+ * @return base 64 encoded basic auth credentials
+ */
+ def getBasicAuth(encryptedAuth, msoKey){
+ if ((encryptedAuth == null || encryptedAuth.isEmpty()) || (msoKey == null || msoKey.isEmpty()))
+ return null
+ try {
+ def auth = decrypt(encryptedAuth, msoKey)
+ byte[] encoded = Base64.encodeBase64(auth.getBytes())
+ String encodedString = new String(encoded)
+ encodedString = "Basic " + encodedString
+ return encodedString
+ } catch (Exception ex) {
+ log("ERROR", "Unable to encode basic auth")
+ throw ex
+ }
+ }
+
+ def encrypt(toEncrypt, msokey){
+ try {
+ String result = CryptoUtils.encrypt(toEncrypt, msokey);
+ return result
+ }
+ catch (Exception e) {
+ log("ERROR", "Failed to encrypt credentials")
+ }
+ }
+
+ def decrypt(toDecrypt, msokey){
+ try {
+ String result = CryptoUtils.decrypt(toDecrypt, msokey);
+ return result
+ }
+ catch (Exception e) {
+ log("ERROR", "Failed to decrypt credentials")
+ throw e
+ }
+ }
+
+ /**
+ * Return URL with qualified host name (if any) or urn mapping
+ * @param String url from urn mapping
+ * @return String url with qualified host name
+ */
+ public String getQualifiedHostNameForCallback(String urnCallbackUrl) {
+ def callbackUrlToUse = urnCallbackUrl
+ try{
+ //swap host name with qualified host name from the jboss properties
+ def qualifiedHostName = System.getProperty("jboss.qualified.host.name")
+ if(qualifiedHostName!=null){
+ log("DEBUG", "qualifiedHostName:\n" + qualifiedHostName)
+ callbackUrlToUse = callbackUrlToUse.replaceAll("(http://)(.*)(:28080*)", {orig, first, torepl, last -> "${first}${qualifiedHostName}${last}"})
+ }
+ }catch(Exception e){
+ log("DEBUG", "unable to grab qualified host name, using what's in urn properties for callbackurl. Exception was: " + e.printStackTrace())
+ }
+ return callbackUrlToUse
+
+ }
+
+ /**
+ * Retrieves text context of the element if the element exists, returns empty string otherwise
+ * @param com.sun.org.apache.xerces.internal.dom.DeferredElementNSImpl element to parse
+ * param String tagName tagName
+ * @return String text content of the element
+ */
+ public String getElementText(Element element, String tagName) {
+ String text = ""
+ org.w3c.dom.NodeList nodeList = element.getElementsByTagNameNS("*", tagName)
+ if (nodeList != null && nodeList.length > 0) {
+ text = nodeList.item(0).getTextContent()
+ }
+ return text
+ }
+
+ /**
+ *
+ * Find the lowest unused module-index value in a given xml
+ */
+ public String getLowestUnusedIndex(String xml) {
+ if (xml == null || xml.isEmpty()) {
+ return "0"
+ }
+ def moduleIndexList = getMultNodes(xml, "module-index")
+ if (moduleIndexList == null || moduleIndexList.size() == 0) {
+ return "0"
+ }
+ def sortedModuleIndexList = moduleIndexList.sort { a, b -> a.compareTo b }
+
+ for (i in 0..sortedModuleIndexList.size()-1) {
+ if (Integer.parseInt(sortedModuleIndexList[i]) != i) {
+ return i.toString()
+ }
+ }
+ return sortedModuleIndexList.size().toString()
+ }
+ /**
+ * This utility checks if there is transaction id already present in MDC.
+ * If found, it returns same else creates new, sets in MDC for future use before returning
+ * @return String RequestId in UUID format.
+ */
+ public String getRequestID()
+ {
+ String requestId = MDC.get("RequestId")
+ if(requestId == null || requestId.isEmpty())
+ {
+ requestId = java.util.UUID.randomUUID()
+ MDC.put("RequestId",requestId)
+ log("DEBUG","MsoUtils - Created new RequestId: " + requestId)
+ }
+ else
+ {
+ log("DEBUG","MsoUtils - Using existing RequestId: " + requestId)
+ }
+
+ return requestId
+ }
+
+ /**
+ * Remove all the empty nodes and attributes from the within the given node
+ * @param node
+ * @return true if all empty nodes and attributes were removed.
+ */
+ public boolean cleanNode( Node node ) {
+ node.attributes().with { a ->
+ a.findAll { !it.value }.each { a.remove( it.key ) }
+ }
+ node.children().with { kids ->
+ kids.findAll { it instanceof Node ? !cleanNode( it ) : false }
+ .each { kids.remove( it ) }
+ }
+ node.attributes() || node.children() || node.text()
+ }
+
+ /**
+ *
+ * @param xml
+ * @return String representation of xml after removing the empty nodes and attributes
+ */
+ public String cleanNode(String xmlString) {
+ def xml = new XmlParser(false, false).parseText(xmlString)
+ cleanNode(xml)
+ return XmlUtil.serialize(xml)
+ }
+}
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
new file mode 100644
index 0000000000..2e5499c158
--- /dev/null
+++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/NetworkUtils.groovy
@@ -0,0 +1,1581 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.so.bpmn.common.scripts;
+
+import org.apache.commons.lang3.*
+
+import groovy.xml.XmlUtil
+import org.onap.so.bpmn.core.UrnPropertiesReader
+
+import javax.xml.parsers.DocumentBuilder
+import javax.xml.parsers.DocumentBuilderFactory
+import javax.xml.transform.Transformer
+import javax.xml.transform.TransformerFactory
+import javax.xml.transform.TransformerException
+import javax.xml.transform.dom.DOMSource
+import javax.xml.transform.stream.StreamResult
+
+import org.camunda.bpm.engine.delegate.BpmnError
+import org.camunda.bpm.engine.delegate.DelegateExecution
+import org.w3c.dom.Document
+import org.w3c.dom.Element
+
+import org.w3c.dom.NamedNodeMap
+import org.w3c.dom.Node
+import org.w3c.dom.NodeList;
+import org.xml.sax.InputSource
+import org.onap.so.logger.MsoLogger
+
+import org.onap.so.logger.MessageEnum
+
+
+import org.camunda.bpm.engine.delegate.BpmnError
+import org.camunda.bpm.engine.delegate.DelegateExecution
+import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor;
+import org.w3c.dom.Document
+import org.w3c.dom.Element
+import org.w3c.dom.NamedNodeMap
+import org.w3c.dom.Node
+import org.w3c.dom.NodeList;
+import org.xml.sax.InputSource
+
+
+/**
+ * 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
+
+ public NetworkUtils(AbstractServiceTaskProcessor taskProcessor) {
+ this.taskProcessor = taskProcessor
+ }
+
+ /**
+ * This method returns the string for Network request
+ * V2 for Contrail 3.x will populate cloud-region data in same cloudSiteId filed
+ * Network adapter will handle it properly
+ * @param requestId either 'request-id' or 'mso-request-id'
+ * @param requestInput the request in the process
+ * @param queryIdResponse the response of REST AAI query by Id
+ * @param routeCollection the collection
+ * @param policyFqdns the policy
+ * @param tableCollection the collection
+ * @param cloudRegionId the cloud-region-region
+ * @return String request
+ */
+ def CreateNetworkRequestV2(execution, requestId, messageId, requestInput, queryIdResponse, routeCollection, policyFqdns, tableCollection, cloudRegionId, backoutOnFailure, source) {
+ String createNetworkRequest = null
+ if(requestInput!=null && queryIdResponse!=null) {
+ String serviceInstanceId = ""
+ String sharedValue = ""
+ 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"
+ serviceInstanceId = utils.getNodeText(requestInput, "service-instance-id")
+
+ } else { // source = 'PORTAL'
+ sharedValue = getParameterValue(requestInput, "shared")
+ externalValue = getParameterValue(requestInput, "external")
+ serviceInstanceId = utils.getNodeText(requestInput, "service-instance-id") != null ? utils.getNodeText(requestInput, "service-instance-id") : ""
+ }
+
+ String networkParams = ""
+ if (utils.nodeExists(requestInput, "network-params")) {
+ String netParams = utils.getNodeXml(requestInput, "network-params", false).replace("tag0:","").replace(":tag0","")
+ networkParams = buildParams(netParams)
+ }
+
+ String failIfExists = "false"
+ // requestInput
+ String cloudRegion = cloudRegionId
+ String tenantId = utils.getNodeText(requestInput, "tenant-id")
+
+ String networkType = ""
+ String modelCustomizationUuid = ""
+ if (utils.nodeExists(requestInput, "networkModelInfo")) {
+ String networkModelInfo = utils.getNodeXml(requestInput, "networkModelInfo", false).replace("tag0:","").replace(":tag0","")
+ networkType = utils.getNodeText(networkModelInfo, "modelName")
+ modelCustomizationUuid = utils.getNodeText(networkModelInfo, "modelCustomizationUuid")
+ } else {
+ networkType = utils.getNodeText(queryIdResponse, "network-type")
+ 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")
+
+ // contrailNetwork - networkTechnology = 'Contrail' vs. 'AIC_SR_IOV')
+ String contrailNetwork = ""
+ if (networkTechnology.contains('Contrail') || networkTechnology.contains('contrail') || networkTechnology.contains('CONTRAIL')) {
+ contrailNetwork = """<contrailNetwork>
+ <shared>${MsoUtils.xmlEscape(sharedValue)}</shared>
+ <external>${MsoUtils.xmlEscape(externalValue)}</external>
+ ${routeCollection}
+ ${policyFqdns}
+ ${tableCollection}
+ </contrailNetwork>"""
+ networkTechnology = "CONTRAIL" // replace
+ }
+
+ // rebuild subnets
+ String subnets = ""
+ if (utils.nodeExists(queryIdResponse, "subnets")) {
+ def subnetsGroup = utils.getNodeXml(queryIdResponse, "subnets", false)
+ subnets = buildSubnets(subnetsGroup)
+ }
+
+ String physicalNetworkName = ""
+ physicalNetworkName = utils.getNodeText(queryIdResponse, "physical-network-name")
+
+ String vlansCollection = buildVlans(queryIdResponse)
+
+ String notificationUrl = "" //TODO - is this coming from URN? What variable/value to use?
+ //String notificationUrl = execution.getVariable("URN_?????") //TODO - is this coming from URN? What variable/value to use?
+
+ createNetworkRequest = """
+ <createNetworkRequest>
+ <cloudSiteId>${MsoUtils.xmlEscape(cloudRegion)}</cloudSiteId>
+ <tenantId>${MsoUtils.xmlEscape(tenantId)}</tenantId>
+ <networkId>${MsoUtils.xmlEscape(networkId)}</networkId>
+ <networkName>${MsoUtils.xmlEscape(networkName)}</networkName>
+ <networkType>${MsoUtils.xmlEscape(networkType)}</networkType>
+ <modelCustomizationUuid>${MsoUtils.xmlEscape(modelCustomizationUuid)}</modelCustomizationUuid>
+ <networkTechnology>${MsoUtils.xmlEscape(networkTechnology)}</networkTechnology>
+ <providerVlanNetwork>
+ <physicalNetworkName>${MsoUtils.xmlEscape(physicalNetworkName)}</physicalNetworkName >
+ ${vlansCollection}
+ </providerVlanNetwork>
+ ${contrailNetwork}
+ ${subnets}
+ <skipAAI>true</skipAAI>
+ <backout>${MsoUtils.xmlEscape(backoutOnFailure)}</backout>
+ <failIfExists>${MsoUtils.xmlEscape(failIfExists)}</failIfExists>
+ ${networkParams}
+ <msoRequest>
+ <requestId>${MsoUtils.xmlEscape(requestId)}</requestId>
+ <serviceInstanceId>${MsoUtils.xmlEscape(serviceInstanceId)}</serviceInstanceId>
+ </msoRequest>
+ <messageId>${MsoUtils.xmlEscape(messageId)}</messageId>
+ <notificationUrl>${MsoUtils.xmlEscape(notificationUrl)}</notificationUrl>
+ </createNetworkRequest>
+ """.trim()
+ }
+ return createNetworkRequest
+
+ }
+
+ /**
+ * This method returns the string for Network request
+ * V2 for Contrail 3.x will populate cloud-region data in same cloudSiteId filed
+ * Network adapter will handle it properly
+ * @param requestId either 'request-id' or 'mso-request-id'
+ * @param requestInput the request in the process
+ * @param queryIdResponse the response of REST AAI query by Id
+ * @param routeCollection the collection
+ * @param policyFqdns the policy
+ * @param cloudRegionId the cloud-region-region
+ * @return String request
+ */
+ def UpdateNetworkRequestV2(execution, requestId, messageId, requestInput, queryIdResponse, routeCollection, policyFqdns, tableCollection, cloudRegionId, backoutOnFailure, source) {
+ String updateNetworkRequest = null
+ if(requestInput!=null && queryIdResponse!=null) {
+ String serviceInstanceId = ""
+ String sharedValue = ""
+ 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"
+ serviceInstanceId = utils.getNodeText(requestInput, "service-instance-id")
+
+ } else { // source = 'PORTAL'
+ sharedValue = getParameterValue(requestInput, "shared")
+ externalValue = getParameterValue(requestInput, "external")
+ serviceInstanceId = utils.getNodeText(requestInput, "service-instance-id") != null ? utils.getNodeText(requestInput, "service-instance-id") : ""
+ }
+
+ String failIfExists = "false"
+ // requestInput
+ String cloudRegion = cloudRegionId
+ String tenantId = utils.getNodeText(requestInput, "tenant-id")
+
+ // queryIdResponse
+ String networkName = utils.getNodeText(queryIdResponse, "network-name")
+ String networkId = utils.getNodeText(queryIdResponse, "network-id")
+
+ String networkType = ""
+ String modelCustomizationUuid = ""
+ if (utils.nodeExists(requestInput, "networkModelInfo")) {
+ String networkModelInfo = utils.getNodeXml(requestInput, "networkModelInfo", false).replace("tag0:","").replace(":tag0","")
+ networkType = utils.getNodeText(networkModelInfo, "modelName")
+ modelCustomizationUuid = utils.getNodeText(networkModelInfo, "modelCustomizationUuid")
+ } else {
+ networkType = utils.getNodeText(queryIdResponse, "network-type")
+ modelCustomizationUuid = utils.getNodeText(requestInput, "modelCustomizationId")
+ }
+
+ // rebuild subnets
+ String subnets = ""
+ if (utils.nodeExists(queryIdResponse, "subnets")) {
+ def subnetsGroup = utils.getNodeXml(queryIdResponse, "subnets", false)
+ subnets = buildSubnets(subnetsGroup)
+ }
+
+ String networkParams = ""
+ if (utils.nodeExists(requestInput, "network-params")) {
+ String netParams = utils.getNodeXml(requestInput, "network-params", false).replace("tag0:","").replace(":tag0","")
+ networkParams = buildParams(netParams)
+ }
+
+ String networkStackId = utils.getNodeText(queryIdResponse, "heat-stack-id")
+ if (networkStackId == 'null' || networkStackId == "" || networkStackId == null) {
+ networkStackId = "force_update"
+ }
+
+ String physicalNetworkName = utils.getNodeText(queryIdResponse, "physical-network-name")
+ String vlansCollection = buildVlans(queryIdResponse)
+
+ updateNetworkRequest =
+ """<updateNetworkRequest>
+ <cloudSiteId>${MsoUtils.xmlEscape(cloudRegion)}</cloudSiteId>
+ <tenantId>${MsoUtils.xmlEscape(tenantId)}</tenantId>
+ <networkId>${MsoUtils.xmlEscape(networkId)}</networkId>
+ <networkStackId>${MsoUtils.xmlEscape(networkStackId)}</networkStackId>
+ <networkName>${MsoUtils.xmlEscape(networkName)}</networkName>
+ <networkType>${MsoUtils.xmlEscape(networkType)}</networkType>
+ <modelCustomizationUuid>${MsoUtils.xmlEscape(modelCustomizationUuid)}</modelCustomizationUuid>
+ <networkTypeVersion/>
+ <networkTechnology>CONTRAIL</networkTechnology>
+ <providerVlanNetwork>
+ <physicalNetworkName>${MsoUtils.xmlEscape(physicalNetworkName)}</physicalNetworkName>
+ ${vlansCollection}
+ </providerVlanNetwork>
+ <contrailNetwork>
+ <shared>${MsoUtils.xmlEscape(sharedValue)}</shared>
+ <external>${MsoUtils.xmlEscape(externalValue)}</external>
+ ${routeCollection}
+ ${policyFqdns}
+ ${tableCollection}
+ </contrailNetwork>
+ ${subnets}
+ <skipAAI>true</skipAAI>
+ <backout>${MsoUtils.xmlEscape(backoutOnFailure)}</backout>
+ <failIfExists>${MsoUtils.xmlEscape(failIfExists)}</failIfExists>
+ ${networkParams}
+
+ <msoRequest>
+ <requestId>${MsoUtils.xmlEscape(requestId)}</requestId>
+ <serviceInstanceId>${MsoUtils.xmlEscape(serviceInstanceId)}</serviceInstanceId>
+ </msoRequest>
+ <messageId>${MsoUtils.xmlEscape(messageId)}</messageId>
+ <notificationUrl></notificationUrl>
+ </updateNetworkRequest>""".trim()
+
+ }
+ return updateNetworkRequest
+
+ }
+
+ /**
+ * 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, tenantId, 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>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>att-aic</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
+ }
+
+ def String createCloudRegionVolumeRequest(groupId, volumeName, vnfType, vnfId, tenantId, 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>att-aic</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>
+ * <param name="external">0</external>
+ * </network-params>
+ *
+ * @param xmlInput the XML document
+ * @param paramName the param name (ex: 'shared')
+ * @return a param value for 'shared' (ex: '1')
+ */
+ def getParameterValue(xmlInput, paramName) {
+ def rtn=""
+ if(xmlInput!=null){
+ def xml= new XmlSlurper().parseText(xmlInput)
+ rtn= xml.'**'.find {param->param.'@name'.text() == paramName}
+ }
+ if (rtn==null) {
+ return ""
+ } else {
+ return rtn
+ }
+ }
+
+ /**
+ * 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>
+ * <param name="shared">1</param>
+ * <param name="external">0</external>
+ * </network-params>
+ *
+ * Sample result:
+ * <networkParams>
+ * <shared>1</shared>
+ * <external>0</external>
+ * </networkParams>
+ *
+ */
+
+ def buildParams(networkParams) {
+ def build = ""
+ def netParams = new XmlParser().parseText(networkParams)
+ try {
+ def paramsList = netParams.'**'.findAll {param->param.'@name'}.'@name'
+ if (paramsList.size() > 0) {
+ build += "<networkParams>"
+ for (i in 0..paramsList.size()-1) {
+ def name = netParams.'**'.find {param->param.'@name' == paramsList[i]}.'@name'
+ def value= netParams.'**'.find {param->param.'@name' == paramsList[i]}.text()
+ build += "<${name}>${MsoUtils.xmlEscape(value)}</${name}>"
+ }
+ build += "</networkParams>"
+ }
+
+ } catch (Exception ex) {
+ println ' buildParams error - ' + ex.getMessage()
+ build = ""
+ }
+ 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 != "") {
+ lcpCloudRegion = relatedLink.substring(relatedLink.indexOf("/att-aic/")+9, relatedLink.length())
+ if (lcpCloudRegion.contains('/')) {
+ lcpCloudRegion = relatedLink.substring(relatedLink.indexOf("/att-aic/")+9, relatedLink.length()-1)
+ }
+ }
+ }
+ }
+ }
+ }
+ 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
+ def buildNetworkElements(l3Network, createNetworkContrailResponse, networkList) {
+ def replaceNetworkId = ""
+ def replaceNeutronNetworkId = ""
+ def replaceContrailNetworkFqdn = ""
+ if (l3Network != null && createNetworkContrailResponse != null) {
+ if (utils.nodeExists(l3Network, 'heat-stack-id')) {
+ replaceNetworkId = utils.getNodeText(l3Network, 'heat-stack-id')
+ } else {
+ if (utils.nodeExists(createNetworkContrailResponse, 'networkStackId')) {
+ replaceNetworkId = utils.getNodeText(createNetworkContrailResponse, 'networkStackId')
+ }
+ }
+ if (utils.nodeExists(l3Network, 'neutron-network-id')) {
+ replaceNeutronNetworkId = utils.getNodeText(l3Network, 'neutron-network-id')
+ } else {
+ if (utils.nodeExists(createNetworkContrailResponse, 'neutronNetworkId')) {
+ replaceNeutronNetworkId = utils.getNodeText(createNetworkContrailResponse, 'neutronNetworkId')
+ }
+ }
+ if (utils.nodeExists(l3Network, 'contrail-network-fqdn')) {
+ replaceContrailNetworkFqdn = utils.getNodeText(l3Network, 'contrail-network-fqdn')
+ } else {
+ if (utils.nodeExists(createNetworkContrailResponse, 'networkFqdn')) {
+ replaceContrailNetworkFqdn = utils.getNodeText(createNetworkContrailResponse, 'networkFqdn')
+ }
+ }
+ }
+
+ String var = ""
+ def xmlNetwork = ""
+ if (l3Network != null) {
+ for (element in networkList) {
+ def xml= new XmlSlurper().parseText(l3Network)
+ var = xml.'**'.find {it.name() == element}
+ if (var == null) {
+ if (element=="orchestration-status") {
+ if (var.toString() == 'pending-create' || var.toString() == 'PendingCreate') {
+ xmlNetwork += "<"+element+">"+"Created"+"</"+element+">"
+ } else { //pending-update or PendingUpdate
+ xmlNetwork += "<"+element+">"+"Active"+"</"+element+">"
+ }
+ }
+ if (element=="heat-stack-id") {
+ if (replaceNetworkId != "") {
+ xmlNetwork += "<"+element+">"+replaceNetworkId+"</"+element+">"
+ }
+ }
+ if (element=="neutron-network-id") {
+ if (replaceNeutronNetworkId != "") {
+ xmlNetwork += "<"+element+">"+replaceNeutronNetworkId+"</"+element+">"
+ }
+ }
+ if (element=="contrail-network-fqdn") {
+ if (replaceContrailNetworkFqdn != "") {
+ xmlNetwork += "<"+element+">"+replaceContrailNetworkFqdn+"</"+element+">"
+ }
+ }
+
+ } else {
+ if (element=="orchestration-status") {
+ if (element=="orchestration-status") {
+ if (var.toString() == 'pending-create' || var.toString() == 'PendingCreate') {
+ xmlNetwork += "<"+element+">"+"Created"+"</"+element+">"
+ } else { //pending-update or PendingUpdate
+ xmlNetwork += "<"+element+">"+"Active"+"</"+element+">"
+ }
+ }
+ } else {
+ xmlNetwork += "<"+element+">"+var.toString()+"</"+element+">"
+ }
+ }
+ }
+ }
+ return xmlNetwork
+ }
+
+ def buildSubnets(requeryIdAAIResponse, createNetworkResponse) {
+ 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)
+ }
+
+ } 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>"
+ }
+ 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(subnetXml, elementList, parentName) {
+ def var = ""
+ def xmlBuild = ""
+ if (parentName != "") {
+ xmlBuild += "<"+parentName+">"
+ }
+ if (subnetXml != null) {
+ def networkStartAddress = ""
+ for (element in elementList) {
+ def xml= new XmlSlurper().parseText(subnetXml)
+ var = xml.'**'.find {it.name() == element}
+ if (element == "dhcp-start") {
+ xmlBuild += "<allocationPools>"
+ if (var.toString() == 'null') {
+ xmlBuild += "<start>"+""+"</start>"
+ } else {
+ xmlBuild += "<start>"+var.toString()+"</start>"
+ }
+ }
+ if (element == "dhcp-end") {
+ if (var.toString() == 'null') {
+ xmlBuild += "<end>"+""+"</end>"
+ } else {
+ xmlBuild += "<end>"+var.toString()+"</end>"
+ }
+ xmlBuild += "</allocationPools>"
+ }
+ if (element == "network-start-address" || element == "cidr-mask") {
+ if (element == "network-start-address") {
+ networkStartAddress = var.toString()
+ }
+ if (element == "cidr-mask") {
+ xmlBuild += "<cidr>"+networkStartAddress+"/"+var.toString()+"</cidr>"
+ }
+ }
+ if (element == "dhcp-enabled") {
+ xmlBuild += "<enableDHCP>"+var.toString()+"</enableDHCP>"
+ }
+ if (element == "gateway-address") {
+ xmlBuild += "<gatewayIp>"+var.toString()+"</gatewayIp>"
+ }
+ if (element == "ip-version") {
+ String ipVersion = getIpvVersion(var.toString())
+ xmlBuild += "<ipVersion>"+ipVersion+"</ipVersion>"
+ }
+ if (element == "subnet-id") {
+ xmlBuild += "<subnetId>"+var.toString()+"</subnetId>"
+ }
+ if ((element == "subnet-name") && (var != null)) {
+ xmlBuild += "<subnetName>"+var.toString()+"</subnetName>"
+ }
+ if ((element == "ip-assignment-direction") && (var != null)) {
+ xmlBuild += "<addrFromStart>"+var.toString()+"</addrFromStart>"
+ }
+ if (element == "host-routes") {
+ def routes = ""
+ if (subnetXml.contains("host-routes")) {
+ routes = buildHostRoutes(subnetXml)
+ }
+ xmlBuild += routes
+ }
+
+ }
+ }
+ if (parentName != "") {
+ xmlBuild += "</"+parentName+">"
+ }
+ return xmlBuild
+ }
+
+ // 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 = ""
+ 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>"
+ }
+ 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
+ }
+
+ 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'
+ }
+ }
+ }
+
+ }
+ 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 = ""
+ }
+
+ }
+ }
+ return nodeAsText
+
+ }
+
+//TODO: This method still needs to be tested before using.
+ /**
+ *
+ * This method is similar to the gennetwork:ContrailNetworUpdateCompletedObject
+ * BPEL method. It extracts all of the required subnet information
+ * for each subnet listed with an orch status equal to the one provided
+ * and puts the corresponding infomation with the appropriate node for
+ * updating aai. The method sets the orch status for each subnet to active
+ *
+ * @param subnetsXml the entire subnets xml
+ * @param requestInput the request in the process
+ * @param queryIdResponse the response of REST AAI query by Id
+ * @param queryVpnBindingResponse the response of REST AAI query by vpn binding
+ * @param routeCollection the collection of vpnBinding's 'global-route-target'
+ * @return String request
+ */
+ public String networkUpdateSubnetInfo(String subnetsXml, String networkResponseXml){
+
+ String subnets = ""
+ StringBuilder sb = new StringBuilder()
+ InputSource source = new InputSource(new StringReader(subnetsXml));
+ DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
+ docFactory.setNamespaceAware(true)
+ DocumentBuilder docBuilder = docFactory.newDocumentBuilder()
+ Document xml = docBuilder.parse(source)
+ NodeList nodeList = xml.getElementsByTagNameNS("*", "subnet")
+ for (int x = 0; x < nodeList.getLength(); x++) {
+ Node node = nodeList.item(x)
+ String subnet = ""
+ if (node.getNodeType() == Node.ELEMENT_NODE) {
+ Element eElement = (Element) node
+ String subnetOrchStatus = eElement.getElementsByTagNameNS("*", "orchestration-status").item(0).getTextContent()
+ if(subnetOrchStatus.equals("pending-create")){
+
+ String subnetId = eElement.getElementsByTagNameNS("*", "subnet-id").item(0).getTextContent()
+ def netAddress = eElement.getElementsByTagNameNS("*", "network-start-address").item(0).getTextContent()
+ def mask = eElement.getElementsByTagNameNS("*", "cidr-mask").item(0).getTextContent()
+ def dhcpEnabledSubnet = eElement.getElementsByTagNameNS("*", "dhcp-enabled").item(0).getTextContent()
+ def gatewayAddress = eElement.getElementsByTagNameNS("*", "gateway-address").item(0).getTextContent()
+ def ipVersion = eElement.getElementsByTagNameNS("*", "ip-version").item(0).getTextContent()
+ def relationshipList = eElement.getElementsByTagNameNS("*", "relationship-list").item(0).getTextContent() //TODO: test this
+ String neutronSubnetId = extractNeutSubId(networkResponseXml, subnetId)
+ subnet =
+ """<subnet>
+ <subnetId>${MsoUtils.xmlEscape(subnetId)}</subnetId>
+ <neutron-subnet-id>${MsoUtils.xmlEscape(neutronSubnetId)}</neutron-subnet-id>
+ <gateway-address>${MsoUtils.xmlEscape(gatewayAddress)}</gateway-address>
+ <network-start-address>${MsoUtils.xmlEscape(netAddress)}</network-start-address>
+ <cidr-mask>${MsoUtils.xmlEscape(mask)}</cidr-mask>
+ <ip-Version>${MsoUtils.xmlEscape(ipVersion)}</ip-Version>
+ <orchestration-status>active</orchestration-status>
+ <dhcp-enabled>${MsoUtils.xmlEscape(dhcpEnabledSubnet)}</dhcp-enabled>
+ <relationship-list>${relationshipList}</relationship-list>
+ </subnet>"""
+
+ }else if(subnetOrchStatus.equals("pending-delete")){
+ StringWriter writer = new StringWriter()
+ Transformer transformer = TransformerFactory.newInstance().newTransformer()
+ transformer.transform(new DOMSource(node), new StreamResult(writer))
+ subnet = writer.toString()
+
+ }else{
+ subnet = ""
+ }
+ }
+ subnets = sb.append(subnet)
+ }
+
+ subnets = utils.removeXmlPreamble(subnets)
+
+ String subnetsList =
+ """<subnets>
+ ${subnets}
+ </subnets>"""
+
+ return subnetsList
+ }
+
+
+ /**
+ *
+ * This method extracts the "value" node text for the the given subnet Id.
+ *
+ * @param String inputSource - xml that contains the subnet id key and value
+ * @param String subnetId - for which you want the value of
+
+ * @return String value - node text of node named value associated with the given subnet id
+ */
+ public String extractNeutSubId(String inputSource, String subnetId){
+
+ String value = ""
+ InputSource source = new InputSource(new StringReader(inputSource));
+ DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
+ docFactory.setNamespaceAware(true)
+ DocumentBuilder docBuilder = docFactory.newDocumentBuilder()
+ Document xml = docBuilder.parse(source)
+ NodeList nodeList = xml.getElementsByTagNameNS("*", "entry")
+ for (int x = 0; x < nodeList.getLength(); x++) {
+ Node node = nodeList.item(x)
+ String subnet = ""
+ if (node.getNodeType() == Node.ELEMENT_NODE) {
+ Element eElement = (Element) node
+ String key = eElement.getElementsByTagNameNS("*", "key").item(0).getTextContent()
+ if(key.equals(subnetId)){
+ value = eElement.getElementsByTagNameNS("*", "value").item(0).getTextContent()
+ }
+ }
+ }
+ return value
+ }
+
+ public boolean isRollbackEnabled (DelegateExecution execution, String payloadXml) {
+
+ def rollbackEnabled = false
+ def rollbackValueSet = false
+ if (utils.nodeExists(payloadXml, "backout-on-failure")) {
+ String backoutValue = utils.getNodeText(payloadXml, "backout-on-failure")
+ if (backoutValue != null && !backoutValue.isEmpty()) {
+ if (backoutValue.equalsIgnoreCase("false")) {
+ rollbackEnabled = false
+ }
+ else {
+ rollbackEnabled = true
+ }
+ rollbackValueSet = true;
+ }
+ }
+
+ if (!rollbackValueSet) {
+
+ if (UrnPropertiesReader.getVariable("mso.rollback", execution) != null) {
+ rollbackEnabled = UrnPropertiesReader.getVariable("mso.rollback", execution).toBoolean()
+ }
+ }
+ 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()) {
+ version = ipvVersion
+ } else {
+ version = ipvVersion.substring(ipvVersion.indexOf("ipv")+3)
+ if (!version.isNumber()) {
+ version = ipvVersion
+ }
+ }
+ } catch (Exception ex) {
+ 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
new file mode 100644
index 0000000000..c7fcc5c5d3
--- /dev/null
+++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/OofHoming.groovy
@@ -0,0 +1,348 @@
+/*
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+package org.onap.so.bpmn.common.scripts
+import org.onap.so.bpmn.core.UrnPropertiesReader
+import org.camunda.bpm.engine.delegate.BpmnError
+import org.camunda.bpm.engine.delegate.DelegateExecution
+
+import org.onap.so.bpmn.common.scripts.AaiUtil
+import org.onap.so.bpmn.common.scripts.ExceptionUtil
+import org.onap.so.bpmn.common.scripts.SDNCAdapterUtils
+import org.onap.so.bpmn.core.domain.CloudFlavor
+import org.onap.so.bpmn.core.domain.InventoryType
+import org.onap.so.bpmn.core.domain.Resource
+import org.onap.so.bpmn.core.domain.ResourceType
+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.logger.MsoLogger
+import org.onap.so.rest.APIResponse
+import org.onap.so.rest.RESTClient
+import org.onap.so.rest.RESTConfig
+import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor
+
+import org.json.JSONArray
+import org.json.JSONObject
+
+import static org.onap.so.bpmn.common.scripts.GenericUtils.*
+
+/**
+ * This class contains the scripts used
+ * by the OOF Homing Subflow building block. The
+ * subflow attempts to home the provided
+ * resources by calling OOF.
+ */
+class OofHoming extends AbstractServiceTaskProcessor {
+
+ private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, OofHoming.class);
+ ExceptionUtil exceptionUtil = new ExceptionUtil()
+ JsonUtils jsonUtil = new JsonUtils()
+ OofUtils oofUtils = new OofUtils(this)
+
+ /**
+ * This method validates the incoming variables.
+ * The method then prepares the OOF request
+ * and posts it to OOF's rest api.
+ *
+ * @param execution
+ */
+ public void callOof(DelegateExecution execution) {
+ def isDebugEnabled = execution.getVariable("isDebugLogEnabled")
+ execution.setVariable("prefix", "HOME_")
+ utils.log("DEBUG", "*** Started Homing Call OOF ***", isDebugEnabled)
+ try {
+ execution.setVariable("rollbackData", null)
+ execution.setVariable("rolledBack", false)
+
+ String requestId = execution.getVariable("msoRequestId")
+ utils.log("DEBUG", "Incoming Request Id is: " + requestId, isDebugEnabled)
+ String serviceInstanceId = execution.getVariable("serviceInstanceId")
+ utils.log("DEBUG", "Incoming Service Instance Id is: " + serviceInstanceId, isDebugEnabled)
+ String serviceInstanceName = execution.getVariable("serviceInstanceName")
+ utils.log("DEBUG", "Incoming Service Instance Name is: " + serviceInstanceName, isDebugEnabled)
+ ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition")
+ utils.log("DEBUG", "Incoming Service Decomposition is: " + serviceDecomposition, isDebugEnabled)
+ String subscriberInfo = execution.getVariable("subscriberInfo")
+ utils.log("DEBUG", "Incoming Subscriber Information is: " + subscriberInfo, isDebugEnabled)
+ Map customerLocation = execution.getVariable("customerLocation")
+ utils.log("DEBUG", "Incoming Customer Location is: " + customerLocation.toString(), isDebugEnabled)
+ String cloudOwner = execution.getVariable("cloudOwner")
+ utils.log("DEBUG", "Incoming cloudOwner is: " + cloudOwner, isDebugEnabled)
+ String cloudRegionId = execution.getVariable("cloudRegionId")
+ utils.log("DEBUG", "Incoming cloudRegionId is: " + cloudRegionId, isDebugEnabled)
+
+ if (isBlank(requestId) ||
+ isBlank(serviceInstanceId) ||
+ isBlank(serviceInstanceName) ||
+ isBlank(serviceDecomposition.toString()) ||
+ isBlank(customerLocation.toString())) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 4000,
+ "A required input variable is missing or null")
+ } else {
+ Subscriber subscriber = null
+ if (isBlank(subscriberInfo)) {
+ subscriber = new Subscriber("", "", "")
+ } else {
+ String subId = jsonUtil.getJsonValue(subscriberInfo, "globalSubscriberId")
+ String subName = jsonUtil.getJsonValue(subscriberInfo, "subscriberName")
+ String subCommonSiteId = ""
+ if (jsonUtil.jsonElementExist(subscriberInfo, "subscriberCommonSiteId")) {
+ subCommonSiteId = jsonUtil.getJsonValue(subscriberInfo, "subscriberCommonSiteId")
+ }
+ subscriber = new Subscriber(subId, subName, subCommonSiteId)
+ }
+
+ //Authentication
+ def authHeader = ""
+ String basicAuth = UrnPropertiesReader.getVariable("mso.oof.auth", execution)
+ String msokey = UrnPropertiesReader.getVariable("mso.msoKey", execution)
+
+
+
+
+ String basicAuthValue = utils.encrypt(basicAuth, msokey)
+ if (basicAuthValue != null) {
+ utils.log("DEBUG", "Obtained BasicAuth username and password for OOF Adapter: " + basicAuthValue,
+ isDebugEnabled)
+ try {
+ authHeader = utils.getBasicAuth(basicAuthValue, msokey)
+ execution.setVariable("BasicAuthHeaderValue", authHeader)
+ } catch (Exception ex) {
+ utils.log("DEBUG", "Unable to encode username and password string: " + ex, isDebugEnabled)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 401, "Internal Error - Unable to " +
+ "encode username and password string")
+ }
+ } else {
+ utils.log("DEBUG", "Unable to obtain BasicAuth - BasicAuth value null", isDebugEnabled)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 401, "Internal Error - BasicAuth " +
+ "value null")
+ }
+
+ //Prepare Callback
+ String timeout = execution.getVariable("timeout")
+ if (isBlank(timeout)) {
+ timeout = UrnPropertiesReader.getVariable("mso.oof.timeout", execution);
+ if (isBlank(timeout)) {
+ timeout = "PT30M"
+ }
+ }
+ utils.log("DEBUG", "Async Callback Timeout will be: " + timeout, isDebugEnabled)
+
+ execution.setVariable("timeout", timeout)
+ execution.setVariable("correlator", requestId)
+ execution.setVariable("messageType", "oofResponse")
+
+ //Build Request & Call OOF
+ String oofRequest = oofUtils.buildRequest(execution, requestId, serviceDecomposition,
+ subscriber, customerLocation)
+ execution.setVariable("oofRequest", oofRequest)
+ utils.log("DEBUG", "OOF Request is: " + oofRequest, isDebugEnabled)
+
+ String endpoint = UrnPropertiesReader.getVariable("mso.oof.service.agnostic.endpoint", execution);
+ String host = UrnPropertiesReader.getVariable("mso.oof.service.agnostic.host", execution);
+ String url = host + endpoint
+ utils.log("DEBUG", "Posting to OOF Url: " + url, 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)
+
+ 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)
+
+ if(responseCode != 202){
+ exceptionUtil.buildAndThrowWorkflowException(execution, responseCode, "Received a Bad Sync Response from OOF.")
+ }
+
+ utils.log("DEBUG", "*** Completed Homing Call OOF ***", isDebugEnabled)
+ }
+ } catch (BpmnError b) {
+ throw b
+ } catch (Exception e) {
+ msoLogger.error(e);
+ exceptionUtil.buildAndThrowWorkflowException(execution, 2500,
+ "Internal Error - Occured in Homing callOof: " + e.getMessage())
+ }
+ }
+
+ /**
+ * This method processes the callback response
+ * and the contained homing solution. It sets
+ * homing solution assignment and license
+ * information to the corresponding resources
+ *
+ * @param execution
+ */
+ public void processHomingSolution(DelegateExecution execution) {
+ def isDebugEnabled = execution.getVariable("isDebugLogEnabled")
+ utils.log("DEBUG", "*** Started Homing Process Homing Solution ***", isDebugEnabled)
+ try {
+ String response = execution.getVariable("asyncCallbackResponse")
+ utils.log("DEBUG", "OOF Async Callback Response is: " + response, isDebugEnabled)
+ utils.logAudit("OOF Async Callback Response is: " + response)
+
+ oofUtils.validateCallbackResponse(execution, response)
+ String placements = jsonUtil.getJsonValue(response, "solutions.placementSolutions")
+ utils.log("DEBUG", "****** Solution Placements: " + placements + " *****", isDebugEnabled)
+
+ ServiceDecomposition decomposition = execution.getVariable("serviceDecomposition")
+ utils.log("DEBUG", "Service Decomposition: " + decomposition, isDebugEnabled)
+
+ List<Resource> resourceList = decomposition.getServiceResources()
+ JSONArray arr = new JSONArray(placements)
+ for (int i = 0; i < arr.length(); i++) {
+ JSONArray arrSol = arr.getJSONArray(i)
+ for (int j = 0; j < arrSol.length(); j++) {
+ JSONObject placement = arrSol.getJSONObject(j)
+ utils.log("DEBUG", "****** Placement Solution is: " + placement + " *****", "true")
+ String jsonServiceResourceId = placement.getString("serviceResourceId")
+ String jsonResourceModuleName = placement.getString("resourceModuleName")
+ for (Resource resource : resourceList) {
+ String serviceResourceId = resource.getResourceId()
+ String resourceModuleName = ""
+ if (resource.getResourceType() == ResourceType.ALLOTTED_RESOURCE ||
+ resource.getResourceType() == ResourceType.VNF) {
+ resourceModuleName = resource.getNfFunction()
+ }
+ if (serviceResourceId.equalsIgnoreCase(jsonServiceResourceId) ||
+ resourceModuleName.equalsIgnoreCase(jsonResourceModuleName)) {
+ JSONObject solution = placement.getJSONObject("solution")
+ String solutionType = solution.getString("identifierType")
+ String inventoryType = ""
+ if (solutionType.equalsIgnoreCase("serviceInstanceId")) {
+ inventoryType = "service"
+ } else {
+ inventoryType = "cloud"
+ }
+ resource.getHomingSolution().setInventoryType(InventoryType.valueOf(inventoryType))
+
+ // TODO Deal with Placement Solutions & Assignment Info here
+ JSONArray assignmentArr = placement.getJSONArray("assignmentInfo")
+ Integer arrayIndex = 0
+ Integer flavorsIndex = null
+ Boolean foundFlavors = false
+ String flavors = null
+ Map<String, String> flavorsMap = null
+ ArrayList<CloudFlavor> flavorsArrayList = new ArrayList<CloudFlavor>()
+ assignmentArr.each { element ->
+ JSONObject jsonObject = new JSONObject(element.toString())
+ if (jsonUtil.getJsonRawValue(jsonObject.toString(), "key") == "flavors") {
+ flavors = jsonUtil.getJsonRawValue(jsonObject.toString(), "value")
+ foundFlavors = true
+ flavorsIndex = arrayIndex
+ } else {
+ arrayIndex += 1
+ }
+ }
+ if (foundFlavors) {
+ assignmentArr.remove(flavorsIndex)
+ flavorsMap = jsonUtil.jsonStringToMap(execution, flavors.toString())
+ flavorsMap.each { label, flavor ->
+ CloudFlavor cloudFlavor = new CloudFlavor(label, flavor)
+ flavorsArrayList.add(cloudFlavor)
+ }
+ }
+ Map<String, String> assignmentMap = jsonUtil.entryArrayToMap(execution,
+ assignmentArr.toString(), "key", "value")
+ String cloudOwner = assignmentMap.get("cloudOwner")
+ String cloudRegionId = assignmentMap.get("locationId")
+ resource.getHomingSolution().setCloudOwner(cloudOwner)
+ resource.getHomingSolution().setCloudRegionId(cloudRegionId)
+ if (flavorsArrayList != null && flavorsArrayList.size != 0) {
+ resource.getHomingSolution().setFlavors(flavorsArrayList)
+ execution.setVariable(cloudRegionId + "_flavorList", flavorsArrayList)
+ utils.log("DEBUG", "***** _flavorList is: " + flavorsArrayList.toString() +
+ " *****", "true")
+ }
+
+ if (inventoryType.equalsIgnoreCase("service")) {
+ resource.getHomingSolution().setRehome(assignmentMap.get("isRehome").toBoolean())
+ VnfResource vnf = new VnfResource()
+ vnf.setVnfHostname(assignmentMap.get("vnfHostName"))
+ resource.getHomingSolution().setVnf(vnf)
+ resource.getHomingSolution().setServiceInstanceId(solution.getJSONArray("identifiers")[0].toString())
+ }
+ }
+ }
+ }
+ if (JsonUtils.jsonElementExist(response, "solutions.licenseSolutions")) {
+ String licenseSolutions = jsonUtil.getJsonValue(response, "solutions.licenseSolutions")
+ JSONArray licenseArr = new JSONArray(licenseSolutions)
+ for (int l = 0; l < licenseArr.length(); l++) {
+ JSONObject license = licenseArr.getJSONObject(l)
+ String jsonServiceResourceId = license.getString("serviceResourceId")
+ for (Resource resource : resourceList) {
+ String serviceResourceId = resource.getResourceId()
+ if (serviceResourceId.equalsIgnoreCase(jsonServiceResourceId)) {
+ String jsonEntitlementPoolList = jsonUtil.getJsonValue(license.toString(), "entitlementPoolUUID")
+ List<String> entitlementPoolList = jsonUtil.StringArrayToList(execution, jsonEntitlementPoolList)
+ resource.getHomingSolution().getLicense().setEntitlementPoolList(entitlementPoolList)
+
+ String jsonLicenseKeyGroupList = jsonUtil.getJsonValue(license.toString(), "licenseKeyGroupUUID")
+ List<String> licenseKeyGroupList = jsonUtil.StringArrayToList(execution, jsonLicenseKeyGroupList)
+ resource.getHomingSolution().getLicense().setLicenseKeyGroupList(licenseKeyGroupList)
+ }
+ }
+ }
+ }
+ }
+ execution.setVariable("serviceDecomposition", decomposition)
+ execution.setVariable("homingSolution", placements) //TODO - can be removed as output variable
+
+ utils.log("DEBUG", "*** Completed Homing Process Homing Solution ***", isDebugEnabled)
+ } catch (BpmnError b) {
+ throw b
+ } catch (Exception e) {
+ msoLogger.error(e);
+ exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occurred in Homing ProcessHomingSolution")
+ }
+ }
+
+ /**
+ * This method logs the start of DHVCreateService
+ * to make debugging easier.
+ *
+ * @param - execution
+ */
+ public String logStart(DelegateExecution execution) {
+ def isDebugEnabled = execution.getVariable("isDebugLogEnabled")
+ String requestId = execution.getVariable("testReqId")
+ if (isBlank(requestId)) {
+ requestId = execution.getVariable("msoRequestId")
+ }
+ execution.setVariable("DHVCS_requestId", requestId)
+ utils.log("DEBUG", "***** STARTED Homing Subflow for request: " + requestId + " *****", "true")
+ utils.log("DEBUG", "****** Homing Subflow Global Debug Enabled: " + isDebugEnabled + " *****", "true")
+ utils.logAudit("***** STARTED Homing Subflow for request: " + requestId + " *****")
+ }
+
+ /**
+ * Auto-generated method stub
+ */
+ public void preProcessRequest(DelegateExecution execution) {}
+ // Not Implemented Method
+}
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
new file mode 100644
index 0000000000..7c5ffca4ab
--- /dev/null
+++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/OofUtils.groovy
@@ -0,0 +1,484 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ * Copyright (C) 2017 - 2018 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.so.bpmn.common.scripts
+
+import org.camunda.bpm.engine.delegate.DelegateExecution
+import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor
+import org.onap.so.bpmn.common.scripts.ExceptionUtil
+import org.onap.so.bpmn.common.scripts.MsoUtils
+import org.onap.so.bpmn.core.domain.HomingSolution
+import org.onap.so.bpmn.core.domain.ModelInfo
+import org.onap.so.bpmn.core.domain.Resource
+import org.onap.so.bpmn.core.domain.AllottedResource
+import org.onap.so.bpmn.core.domain.ServiceDecomposition
+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.logger.MsoLogger
+
+import java.lang.reflect.Array
+
+import static org.onap.so.bpmn.common.scripts.GenericUtils.*
+
+class OofUtils {
+ private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, OofUtils.class);
+ ExceptionUtil exceptionUtil = new ExceptionUtil()
+ JsonUtils jsonUtil = new JsonUtils()
+
+ private AbstractServiceTaskProcessor utils
+
+ public MsoUtils msoUtils = new MsoUtils()
+
+ public OofUtils(AbstractServiceTaskProcessor taskProcessor) {
+ this.utils = taskProcessor
+ }
+
+ /**
+ * This method builds the service-agnostic
+ * OOF json request to get a homing solution
+ * and license solution
+ *
+ * @param execution
+ * @param requestId
+ * @param decomposition - ServiceDecomposition object
+ * @param customerLocation -
+ * @param existingCandidates -
+ * @param excludedCandidates -
+ * @param requiredCandidates -
+ *
+ * @return request - OOF v1 payload - https://wiki.onap.org/pages/viewpage.action?pageId=25435066
+ */
+ String buildRequest(DelegateExecution execution,
+ String requestId,
+ ServiceDecomposition decomposition,
+ Subscriber subscriber = null,
+ Map customerLocation,
+ ArrayList existingCandidates = null,
+ ArrayList excludedCandidates = null,
+ ArrayList requiredCandidates = null) {
+ def isDebugEnabled = execution.getVariable("isDebugLogEnabled")
+ utils.log("DEBUG", "Started Building OOF Request", isDebugEnabled)
+ def callbackUrl = utils.createWorkflowMessageAdapterCallbackURL(execution, "oofResponse", requestId)
+ def transactionId = requestId
+ //ServiceInstance Info
+ ServiceInstance serviceInstance = decomposition.getServiceInstance()
+ def serviceInstanceId = ""
+ def serviceInstanceName = ""
+
+ serviceInstanceId = execution.getVariable("serviceInstanceId")
+ serviceInstanceName = execution.getVariable("serviceInstanceName")
+
+ if (serviceInstanceId == null || serviceInstanceId == "null") {
+ utils.log("DEBUG", "Unable to obtain Service Instance Id", isDebugEnabled)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 400, "Internal Error - Unable to " +
+ "obtain Service Instance Id, execution.getVariable(\"serviceInstanceName\") is null")
+ }
+ if (serviceInstanceName == null || serviceInstanceName == "null") {
+ utils.log("DEBUG", "Unable to obtain Service Instance Name", isDebugEnabled)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 400, "Internal Error - Unable to " +
+ "obtain Service Instance Name, execution.getVariable(\"serviceInstanceName\") is null")
+ }
+ //Model Info
+ ModelInfo model = decomposition.getModelInfo()
+ String modelType = model.getModelType()
+ String modelInvariantId = model.getModelInvariantUuid()
+ String modelVersionId = model.getModelUuid()
+ String modelName = model.getModelName()
+ String modelVersion = model.getModelVersion()
+ //Subscriber Info
+ String subscriberId = ""
+ String subscriberName = ""
+ String commonSiteId = ""
+ if (subscriber != null){
+ subscriberId = subscriber.getGlobalId()
+ subscriberName = subscriber.getName()
+ commonSiteId = subscriber.getCommonSiteId()
+ }
+
+ //Determine RequestType
+ //TODO Figure out better way to determine this
+ String requestType = "create"
+ List<Resource> resources = decomposition.getServiceResources()
+ for(Resource r:resources){
+ HomingSolution currentSolution = (HomingSolution) r.getCurrentHomingSolution()
+ if(currentSolution != null){
+ requestType = "speed changed"
+ }
+ }
+
+ //Demands
+ String placementDemands = ""
+ StringBuilder sb = new StringBuilder()
+ List<AllottedResource> allottedResourceList = decomposition.getAllottedResources()
+ List<VnfResource> vnfResourceList = decomposition.getVnfResources()
+
+ if (allottedResourceList == null || allottedResourceList.isEmpty() ) {
+ utils.log("DEBUG", "Allotted Resources List is empty - will try to get service VNFs instead.",
+ isDebugEnabled)
+ allottedResourceList = decomposition.getVnfResources()
+ }
+
+ if (allottedResourceList == null || allottedResourceList.isEmpty()) {
+ utils.log("DEBUG", "Resources List is Empty", isDebugEnabled)
+ } else {
+ for (AllottedResource resource : allottedResourceList) {
+ utils.log("DEBUG", "Allotted Resource: " + resource.toString(),
+ isDebugEnabled)
+ def serviceResourceId = resource.getResourceId()
+ def resourceModuleName = resource.getNfFunction()
+ utils.log("DEBUG", "resourceModuleName: " + resourceModuleName,
+ isDebugEnabled)
+ def resourceModelInvariantId = "no-resourceModelInvariantId"
+ def resourceModelVersionId = "no-resourceModelVersionId"
+
+ List modelIdLst = execution.getVariable("homingModelIds")
+ utils.log("DEBUG", "Incoming modelIdLst is: " + modelIdLst.toString(), isDebugEnabled)
+ for (Map modelId : modelIdLst )
+ if (resourceModuleName == modelId.resourceModuleName) {
+ resourceModelInvariantId = modelId.resourceModelInvariantId
+ resourceModelVersionId = modelId.resourceModelVersionId
+ }
+
+ def resourceModelName = "" //Optional
+ def resourceModelVersion = "" //Optional
+ def resourceModelType = "" //Optional
+ def tenantId = "" //Optional
+ def requiredCandidatesJson = ""
+
+ requiredCandidatesJson = createCandidateJson(
+ existingCandidates,
+ excludedCandidates,
+ requiredCandidates)
+
+ String demand =
+ " {\n" +
+ " \"resourceModuleName\": \"${resourceModuleName}\",\n" +
+ " \"serviceResourceId\": \"${serviceResourceId}\",\n" +
+ " \"tenantId\": \"${tenantId}\",\n" +
+ " \"resourceModelInfo\": {\n" +
+ " \"modelInvariantId\": \"${resourceModelInvariantId}\",\n" +
+ " \"modelVersionId\": \"${resourceModelVersionId}\",\n" +
+ " \"modelName\": \"${resourceModelName}\",\n" +
+ " \"modelType\": \"${resourceModelType}\",\n" +
+ " \"modelVersion\": \"${resourceModelVersion}\",\n" +
+ " \"modelCustomizationName\": \"\"\n" +
+ " }" + requiredCandidatesJson + "\n" +
+ " },"
+
+ placementDemands = sb.append(demand)
+ }
+ for (VnfResource vnfResource : vnfResourceList) {
+ utils.log("DEBUG", "VNF Resource: " + vnfResource.toString(),
+ isDebugEnabled)
+ ModelInfo vnfResourceModelInfo = vnfResource.getModelInfo()
+ def serviceResourceId = vnfResource.getResourceId()
+ def resourceModuleName = vnfResource.getNfFunction()
+ utils.log("DEBUG", "resourceModuleName: " + resourceModuleName,
+ isDebugEnabled)
+ def resourceModelInvariantId = vnfResourceModelInfo.getModelInvariantUuid()
+ def resourceModelName = vnfResourceModelInfo.getModelName()
+ def resourceModelVersion = vnfResourceModelInfo.getModelVersion()
+ def resourceModelVersionId = vnfResourceModelInfo.getModelUuid()
+ def resourceModelType = vnfResourceModelInfo.getModelType()
+ def tenantId = "" //Optional
+ def requiredCandidatesJson = ""
+
+
+ String placementDemand =
+ " {\n" +
+ " \"resourceModuleName\": \"${resourceModuleName}\",\n" +
+ " \"serviceResourceId\": \"${serviceResourceId}\",\n" +
+ " \"tenantId\": \"${tenantId}\",\n" +
+ " \"resourceModelInfo\": {\n" +
+ " \"modelInvariantId\": \"${resourceModelInvariantId}\",\n" +
+ " \"modelVersionId\": \"${resourceModelVersionId}\",\n" +
+ " \"modelName\": \"${resourceModelName}\",\n" +
+ " \"modelType\": \"${resourceModelType}\",\n" +
+ " \"modelVersion\": \"${resourceModelVersion}\",\n" +
+ " \"modelCustomizationName\": \"\"\n" +
+ " }" + requiredCandidatesJson + "\n" +
+ " },"
+
+ placementDemands = sb.append(placementDemand)
+ }
+ placementDemands = placementDemands.substring(0, placementDemands.length() - 1)
+ }
+
+ /* Commenting Out Licensing as OOF doesn't support for Beijing
+ String licenseDemands = ""
+ sb = new StringBuilder()
+ if (vnfResourceList.isEmpty() || vnfResourceList == null) {
+ utils.log("DEBUG", "Vnf Resources List is Empty", isDebugEnabled)
+ } else {
+ for (VnfResource vnfResource : vnfResourceList) {
+ ModelInfo vnfResourceModelInfo = vnfResource.getModelInfo()
+ def resourceInstanceType = vnfResource.getResourceType()
+ def serviceResourceId = vnfResource.getResourceId()
+ def resourceModuleName = vnfResource.getResourceType()
+ def resouceModelInvariantId = vnfResourceModelInfo.getModelInvariantUuid()
+ def resouceModelName = vnfResourceModelInfo.getModelName()
+ def resouceModelVersion = vnfResourceModelInfo.getModelVersion()
+ def resouceModelVersionId = vnfResourceModelInfo.getModelUuid()
+ def resouceModelType = vnfResourceModelInfo.getModelType()
+
+ // TODO Add Existing Licenses to demand
+ //"existingLicenses": {
+ //"entitlementPoolUUID": ["87257b49-9602-4ca1-9817-094e52bc873b",
+ // "43257b49-9602-4fe5-9337-094e52bc9435"],
+ //"licenseKeyGroupUUID": ["87257b49-9602-4ca1-9817-094e52bc873b",
+ // "43257b49-9602-4fe5-9337-094e52bc9435"]
+ //}
+
+ String licenseDemand =
+ "{\n" +
+ "\"resourceModuleName\": \"${resourceModuleName}\",\n" +
+ "\"serviceResourceId\": \"${serviceResourceId}\",\n" +
+ "\"resourceInstanceType\": \"${resourceInstanceType}\",\n" +
+ "\"resourceModelInfo\": {\n" +
+ " \"modelInvariantId\": \"${resouceModelInvariantId}\",\n" +
+ " \"modelVersionId\": \"${resouceModelVersionId}\",\n" +
+ " \"modelName\": \"${resouceModelName}\",\n" +
+ " \"modelType\": \"${resouceModelType}\",\n" +
+ " \"modelVersion\": \"${resouceModelVersion}\",\n" +
+ " \"modelCustomizationName\": \"\"\n" +
+ " }\n"
+ "},"
+
+ licenseDemands = sb.append(licenseDemand)
+ }
+ licenseDemands = licenseDemands.substring(0, licenseDemands.length() - 1)
+ }*/
+
+ String request =
+ "{\n" +
+ " \"requestInfo\": {\n" +
+ " \"transactionId\": \"${transactionId}\",\n" +
+ " \"requestId\": \"${requestId}\",\n" +
+ " \"callbackUrl\": \"${callbackUrl}\",\n" +
+ " \"sourceId\": \"so\",\n" +
+ " \"requestType\": \"${requestType}\"," +
+ " \"numSolutions\": 1,\n" +
+ " \"optimizers\": [\"placement\"],\n" +
+ " \"timeout\": 600\n" +
+ " },\n" +
+ " \"placementInfo\": {\n" +
+ " \"requestParameters\": {\n" +
+ " \"customerLatitude\": \"${customerLocation.customerLatitude}\",\n" +
+ " \"customerLongitude\": \"${customerLocation.customerLongitude}\",\n" +
+ " \"customerName\": \"${customerLocation.customerName}\"\n" +
+ " }," +
+ " \"subscriberInfo\": { \n" +
+ " \"globalSubscriberId\": \"${subscriberId}\",\n" +
+ " \"subscriberName\": \"${subscriberName}\",\n" +
+ " \"subscriberCommonSiteId\": \"${commonSiteId}\"\n" +
+ " },\n" +
+ " \"placementDemands\": [\n" +
+ " ${placementDemands}\n" +
+ " ]\n" +
+ " },\n" +
+ " \"serviceInfo\": {\n" +
+ " \"serviceInstanceId\": \"${serviceInstanceId}\",\n" +
+ " \"serviceName\": \"${serviceInstanceName}\",\n" +
+ " \"modelInfo\": {\n" +
+ " \"modelType\": \"${modelType}\",\n" +
+ " \"modelInvariantId\": \"${modelInvariantId}\",\n" +
+ " \"modelVersionId\": \"${modelVersionId}\",\n" +
+ " \"modelName\": \"${modelName}\",\n" +
+ " \"modelVersion\": \"${modelVersion}\",\n" +
+ " \"modelCustomizationName\": \"\"\n" +
+ " }\n" +
+ " }\n" +
+ "}"
+
+
+ utils.log("DEBUG", "Completed Building OOF Request", isDebugEnabled)
+ return request
+ }
+
+ /**
+ * This method validates the callback response
+ * from OOF. If the response contains an
+ * exception the method will build and throw
+ * a workflow exception.
+ *
+ * @param execution
+ * @param response - the async callback response from oof
+ */
+ Void validateCallbackResponse(DelegateExecution execution, String response) {
+ def isDebugEnabled = execution.getVariable("isDebugLogEnabled")
+ String placements = ""
+ if (isBlank(response)) {
+ exceptionUtil.buildAndThrowWorkflowException(execution, 5000, "OOF Async Callback Response is Empty")
+ } else {
+ if (JsonUtils.jsonElementExist(response, "solutions.placementSolutions")) {
+ placements = jsonUtil.getJsonValue(response, "solutions.placementSolutions")
+ if (isBlank(placements) || placements.equalsIgnoreCase("[]")) {
+ String statusMessage = jsonUtil.getJsonValue(response, "statusMessage")
+ if (isBlank(statusMessage)) {
+ utils.log("DEBUG", "Error Occurred in Homing: OOF Async Callback Response does " +
+ "not contain placement solution.", isDebugEnabled)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 400,
+ "OOF Async Callback Response does not contain placement solution.")
+ } else {
+ utils.log("DEBUG", "Error Occurred in Homing: " + statusMessage, isDebugEnabled)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 400, statusMessage)
+ }
+ } else {
+ return
+ }
+ } else if (response.contains("error") || response.contains("Error") ) {
+ String errorMessage = ""
+ if (response.contains("policyException")) {
+ String text = jsonUtil.getJsonValue(response, "requestError.policyException.text")
+ errorMessage = "OOF Async Callback Response contains a Request Error Policy Exception: " + text
+ } else if (response.contains("Unable to find any candidate for demand")) {
+ errorMessage = "OOF Async Callback Response contains error: Unable to find any candidate for " +
+ "demand *** Response: " + response.toString()
+ } else if (response.contains("serviceException")) {
+ String text = jsonUtil.getJsonValue(response, "requestError.serviceException.text")
+ errorMessage = "OOF Async Callback Response contains a Request Error Service Exception: " + text
+ } else {
+ errorMessage = "OOF Async Callback Response contains a Request Error. Unable to determine the Request Error Exception."
+ }
+ utils.log("DEBUG", "Error Occurred in Homing: " + errorMessage, isDebugEnabled)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 400, errorMessage)
+
+ } else {
+ utils.log("DEBUG", "Error Occurred in Homing: Received an Unknown Async Callback Response from OOF.", isDebugEnabled)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Received an Unknown Async Callback Response from OOF.")
+ }
+ }
+
+ }
+
+ /**
+ * This method creates candidates json for placement Demands.
+ *
+ * @param execution
+ * @param existingCandidates -
+ * @param excludedCandidates -
+ * @param requiredCandidates -
+ *
+ * @return candidatesJson - a JSON string with candidates
+ */
+ String createCandidateJson(ArrayList existingCandidates = null,
+ ArrayList excludedCandidates = null,
+ ArrayList requiredCandidates = null) {
+ def candidatesJson = ""
+ def type = ""
+ if (existingCandidates != null && existingCandidates != {}) {
+ sb = new StringBuilder()
+ sb.append(",\n" +
+ " \"existingCandidates\": [\n")
+ def existingCandidateJson = ""
+ existingCandidates.each { existingCandidate ->
+ type = existingCandidate.get('identifierType')
+ if (type == 'vimId') {
+ def cloudOwner = existingCandidate.get('cloudOwner')
+ def cloudRegionId = existingCandidate.get('identifiers')
+ existingCandidateJson = "{\n" +
+ " \"identifierType\": \"vimId\",\n" +
+ " \"cloudOwner\": \"${cloudOwner}\",\n" +
+ " \"identifiers\": [\"${cloudRegionId}\"]\n" +
+ " },"
+ sb.append(existingCandidateJson)
+ }
+ if (type == 'serviceInstanceId') {
+ def serviceInstanceId = existingCandidate.get('identifiers')
+ existingCandidateJson += "{\n" +
+ " \"identifierType\": \"serviceInstanceId\",\n" +
+ " \"identifiers\": [\"${serviceInstanceId}\"]\n" +
+ " },"
+ sb.append(existingCandidateJson)
+ }
+ }
+ if (existingCandidateJson != "") {
+ sb.setLength(sb.length() - 1)
+ candidatesJson = sb.append(",\n],")
+ }
+ }
+ if (excludedCandidates != null && excludedCandidates != {}) {
+ sb = new StringBuilder()
+ sb.append(",\n" +
+ " \"excludedCandidates\": [\n")
+ def excludedCandidateJson = ""
+ excludedCandidates.each { excludedCandidate ->
+ type = excludedCandidate.get('identifierType')
+ if (type == 'vimId') {
+ def cloudOwner = excludedCandidate.get('cloudOwner')
+ def cloudRegionId = excludedCandidate.get('identifiers')
+ excludedCandidateJson = "{\n" +
+ " \"identifierType\": \"vimId\",\n" +
+ " \"cloudOwner\": \"${cloudOwner}\",\n" +
+ " \"identifiers\": [\"${cloudRegionId}\"]\n" +
+ " },"
+ sb.append(excludedCandidateJson)
+ }
+ if (type == 'serviceInstanceId') {
+ def serviceInstanceId = excludedCandidate.get('identifiers')
+ excludedCandidateJson += "{\n" +
+ " \"identifierType\": \"serviceInstanceId\",\n" +
+ " \"identifiers\": [\"${serviceInstanceId}\"]\n" +
+ " },"
+ sb.append(excludedCandidateJson)
+ }
+ }
+ if (excludedCandidateJson != "") {
+ sb.setLength(sb.length() - 1)
+ candidatesJson = sb.append(",\n],")
+ }
+ }
+ if (requiredCandidates != null && requiredCandidates != {}) {
+ sb = new StringBuilder()
+ sb.append(",\n" +
+ " \"requiredCandidates\": [\n")
+ def requiredCandidatesJson = ""
+ requiredCandidates.each { requiredCandidate ->
+ type = requiredCandidate.get('identifierType')
+ if (type == 'vimId') {
+ def cloudOwner = requiredCandidate.get('cloudOwner')
+ def cloudRegionId = requiredCandidate.get('identifiers')
+ requiredCandidatesJson = "{\n" +
+ " \"identifierType\": \"vimId\",\n" +
+ " \"cloudOwner\": \"${cloudOwner}\",\n" +
+ " \"identifiers\": [\"${cloudRegionId}\"]\n" +
+ " },"
+ sb.append(requiredCandidatesJson)
+ }
+ if (type == 'serviceInstanceId') {
+ def serviceInstanceId = requiredCandidate.get('identifiers')
+ requiredCandidatesJson += "{\n" +
+ " \"identifierType\": \"serviceInstanceId\",\n" +
+ " \"identifiers\": [\"${serviceInstanceId}\"]\n" +
+ " },"
+ sb.append(requiredCandidatesJson)
+ }
+ }
+ if (requiredCandidatesJson != "") {
+ sb.setLength(sb.length() - 1)
+ candidatesJson = sb.append(",\n],")
+ }
+ }
+ if (candidatesJson != "") {candidatesJson = candidatesJson.substring(0, candidatesJson.length() - 1)}
+ return candidatesJson
+ }
+}
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
new file mode 100644
index 0000000000..a6f8ff469d
--- /dev/null
+++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/PrepareUpdateAAIVfModule.groovy
@@ -0,0 +1,366 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.so.bpmn.common.scripts
+
+import 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.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
+
+
+
+public class PrepareUpdateAAIVfModule extends VfModuleBase {
+ private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, PrepareUpdateAAIVfModule.class);
+
+
+ ExceptionUtil exceptionUtil = new ExceptionUtil()
+ private MsoUtils utils = new MsoUtils()
+ /**
+ * Initialize the flow's variables.
+ *
+ * @param execution The flow's execution instance.
+ */
+ public void initProcessVariables(DelegateExecution execution) {
+ execution.setVariable('prefix', 'PUAAIVfMod_')
+ execution.setVariable('PUAAIVfMod_vnfId', null)
+ execution.setVariable('PUAAIVfMod_vfModuleId', null)
+ execution.setVariable('PUAAIVfMod_vnfName', null)
+ execution.setVariable('PUAAIVfMod_orchestrationStatus', null)
+ execution.setVariable('PUAAIVfMod_vfModule', null)
+ execution.setVariable('PUAAIVfMod_vfModuleOK', false)
+ execution.setVariable('PUAAIVfMod_vfModuleValidationError', null)
+ execution.setVariable('PUAAIVfMod_getVnfResponseCode' ,null)
+ execution.setVariable('PUAAIVfMod_getVnfResponse', '')
+ execution.setVariable('PUAAIVfMod_updateVfModuleResponseCode', null)
+ execution.setVariable('PUAAIVfMod_updateVfModuleResponse', '')
+ execution.setVariable('PUAAIVfMod_outVfModule', null)
+ }
+
+ /**
+ * Check for missing elements in the received request.
+ *
+ * @param execution The flow's execution instance.
+ */
+ public void preProcessRequest(DelegateExecution execution) {
+ def method = getClass().getSimpleName() + '.preProcessRequest(' +
+ 'execution=' + execution.getId() +
+ ')'
+ msoLogger.trace('Entered ' + method)
+
+ try {
+ def xml = execution.getVariable('PrepareUpdateAAIVfModuleRequest')
+ msoLogger.debug('Received request xml:\n' + xml)
+ msoLogger.debug("PrepareUpdateAAIVfModule Request : " + xml)
+
+ initProcessVariables(execution)
+
+ def vnfId = getRequiredNodeText(execution, xml,'vnf-id')
+ execution.setVariable('PUAAIVfMod_vnfId', vnfId)
+
+ def vfModuleId = getRequiredNodeText(execution, xml,'vf-module-id')
+ execution.setVariable('PUAAIVfMod_vfModuleId', vfModuleId)
+
+ def orchestrationStatus = getRequiredNodeText(execution, xml,'orchestration-status')
+ execution.setVariable('PUAAIVfMod_orchestrationStatus', orchestrationStatus)
+
+ msoLogger.trace('Exited ' + method)
+ } catch (BpmnError e) {
+ throw e;
+ } catch (Exception e) {
+ msoLogger.error(e)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in preProcessRequest(): ' + e.getMessage())
+ }
+ }
+
+ /**
+ * Using the received vnfId, query AAI to get the corresponding Generic VNF.
+ * A 200 response is expected with the Generic VNF in the response body.
+ *
+ * @param execution The flow's execution instance.
+ */
+ public void getGenericVnf(DelegateExecution execution) {
+ def method = getClass().getSimpleName() + '.getGenericVnf(' +
+ 'execution=' + execution.getId() +
+ ')'
+ msoLogger.trace('Entered ' + method)
+
+ try {
+ def vnfId = execution.getVariable('PUAAIVfMod_vnfId')
+
+ AaiUtil aaiUriUtil = new AaiUtil(this)
+ def aai_uri = aaiUriUtil.getNetworkGenericVnfUri(execution)
+ msoLogger.debug('AAI URI is: ' + aai_uri)
+
+ String endPoint = UrnPropertiesReader.getVariable("aai.endpoint", execution) + "${aai_uri}/" + UriUtils.encode(vnfId, "UTF-8") + "?depth=1"
+
+ 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 = ''
+ String aaiRequestId = utils.getRequestID()
+ RESTClient client = new RESTClient(config).
+ addHeader('X-TransactionId', aaiRequestId).
+ addHeader('X-FromAppId', 'MSO').
+ addHeader('Content-Type', 'application/xml').
+ addHeader('Accept','application/xml');
+ if (basicAuthCred != null && !"".equals(basicAuthCred)) {
+ client.addAuthorizationHeader(basicAuthCred)
+ }
+ msoLogger.debug('sending GET to AAI endpoint \'' + endPoint + '\'')
+ APIResponse response = client.httpGet()
+ msoLogger.debug("PrepareUpdateAAIVfModule: - invoking httpGet to AAI")
+
+ responseData = response.getResponseBodyAsString()
+ execution.setVariable('PUAAIVfMod_getVnfResponseCode', response.getStatusCode())
+ execution.setVariable('PUAAIVfMod_getVnfResponse', responseData)
+
+ msoLogger.debug("PrepareUpdateAAIVfModule: AAI Response : " + responseData)
+ msoLogger.debug("PrepareUpdateAAIVfModule: AAI ResponseCode : " + response.getStatusCode())
+
+ msoLogger.debug('Response code:' + response.getStatusCode())
+ msoLogger.debug('Response:' + System.lineSeparator() + responseData)
+ } catch (Exception ex) {
+ msoLogger.error(ex);
+ msoLogger.debug('Exception occurred while executing AAI GET:' + ex.getMessage())
+ execution.setVariable('PUAAIVfMod_getVnfResponseCode', 500)
+ execution.setVariable('PUAAIVfMod_getVnfResponse', 'AAI GET Failed:' + ex.getMessage())
+ }
+ msoLogger.trace('Exited ' + method)
+ } catch (BpmnError e) {
+ throw e;
+ } catch (Exception e) {
+ msoLogger.error(e)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in getGenericVnf(): ' + e.getMessage())
+ }
+ }
+
+ /**
+ * Validate the VF Module. That is, confirm that a VF Module with the input VF Module ID
+ * exists in the retrieved Generic VNF. Then, check to make sure that if that VF Module
+ * is the base VF Module and it's not the only VF Module for this Generic VNF, that we're not
+ * attempting to delete it.
+ *
+ * @param execution The flow's execution instance.
+ */
+ public void validateVfModule(DelegateExecution execution) {
+ def method = getClass().getSimpleName() + '.validateVfModule(' +
+ 'execution=' + execution.getId() +
+ ')'
+ msoLogger.trace('Entered ' + method)
+
+ try {
+ def genericVnf = execution.getVariable('PUAAIVfMod_getVnfResponse')
+ def vnfId = execution.getVariable('PUAAIVfMod_vnfId')
+ def vfModuleId = execution.getVariable('PUAAIVfMod_vfModuleId')
+ def vnfName = getNodeTextForce(genericVnf, 'vnf-name')
+ execution.setVariable('PUAAIVfMod_vnfName', vnfName)
+ def VfModule vfModule = findVfModule(genericVnf, vfModuleId)
+ if (vfModule == null) {
+ def String msg = 'VF Module \'' + vfModuleId + '\' does not exist in Generic VNF \'' + vnfId + '\''
+ execution.setVariable('PUAAIVfMod_vfModuleValidationError', msg)
+ execution.setVariable('PUAAIVfMod_vfModuleOK', false)
+ } else {
+ def orchestrationStatus = execution.getVariable('PUAAIVfMod_orchestrationStatus')
+ msoLogger.debug('VF Module \'' + vfModuleId + '\': isBaseVfModule=' + vfModule.isBaseVfModule() +', isOnlyVfModule=' + vfModule.isOnlyVfModule() + ', new orchestration-status=' + orchestrationStatus)
+ if (vfModule.isBaseVfModule() && !vfModule.isOnlyVfModule() && orchestrationStatus.equals('pending-delete')) {
+ def String msg = 'Orchestration status for VF Module \'' + vfModuleId +
+ '\' cannot be set to \'pending-delete\' since it is the base VF Module and it\'s not the only VF Module in Generic VNF \'' + vnfId + '\''
+ execution.setVariable('PUAAIVfMod_vfModuleValidationError', msg)
+ execution.setVariable('PUAAIVfMod_vfModuleOK', false)
+ } else {
+ execution.setVariable('PUAAIVfMod_vfModule', vfModule)
+ execution.setVariable('PUAAIVfMod_vfModuleOK', true)
+ }
+ }
+
+ msoLogger.trace('Exited ' + method)
+ } catch (BpmnError e) {
+ throw e;
+ } catch (Exception e) {
+ msoLogger.error(e)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in validateVfModule(): ' + e.getMessage())
+ }
+ }
+
+ /**
+ * Construct and send a PATCH request to AAI to update the VF Module.
+ *
+ * @param execution The flow's execution instance.
+ */
+ public void updateVfModule(DelegateExecution execution) {
+ def method = getClass().getSimpleName() + '.updateVfModule(' +
+ 'execution=' + execution.getId() +
+ ')'
+ msoLogger.trace('Entered ' + method)
+
+ try {
+ // Construct payload
+ def VfModule vfModule = (VfModule) execution.getVariable('PUAAIVfMod_vfModule')
+ def Node newVfModuleNode = vfModule.getNode().clone()
+ def orchestrationStatus = execution.getVariable('PUAAIVfMod_orchestrationStatus')
+ def Node orchestrationStatusNode = utils.getChildNode(newVfModuleNode, 'orchestration-status')
+ if (orchestrationStatusNode == null) {
+ // Node doesn't exist, this should never happen, right?
+ new Node(newVfModuleNode, 'orchestration-status', orchestrationStatus)
+ } else {
+ // Node already exists, just give it a new value
+ orchestrationStatusNode.setValue(orchestrationStatus)
+ }
+ def VfModule newVfModule = new VfModule(newVfModuleNode, vfModule.isOnlyVfModule())
+ //def payload = utils.nodeToString(newVfModuleNode)
+
+ // Construct endpoint
+ def vnfId = execution.getVariable('PUAAIVfMod_vnfId')
+ def vfModuleId = execution.getVariable('PUAAIVfMod_vfModuleId')
+
+ def payload = """{
+ "vf-module-id": "${vfModuleId}",
+ "orchestration-status": "${orchestrationStatus}"
+ }"""
+
+ msoLogger.debug("VfModule payload : " + payload)
+
+ AaiUtil aaiUriUtil = new AaiUtil(this)
+ def aai_uri = aaiUriUtil.getNetworkGenericVnfUri(execution)
+ msoLogger.debug('AAI URI is: ' + aai_uri)
+
+ String endPoint = UrnPropertiesReader.getVariable("aai.endpoint", execution) + "${aai_uri}/" + UriUtils.encode(vnfId, "UTF-8") + "/vf-modules/vf-module/" + UriUtils.encode(vfModuleId, "UTF-8")
+ 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', newVfModule)
+ 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', newVfModule)
+ msoLogger.debug('Output PUAAIVfMod_outVfModule set for VF Module Id \'' + newVfModule.getElementText('vf-module-id') + '\'')
+ def heatStackId = newVfModule.getElementText('heat-stack-id')
+ 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) {
+ throw e;
+ } catch (Exception e) {
+ msoLogger.error(e)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in updateVfModule(): ' + e.getMessage())
+ }
+ }
+
+ /**
+ * Generates a WorkflowException if the AAI query returns a response code other than 200.
+ *
+ * @param execution The flow's execution instance.
+ */
+ public void handleVnfNotFound(DelegateExecution execution) {
+ def method = getClass().getSimpleName() + '.handleVnfNotFound(' +
+ 'execution=' + execution.getId() +
+ ')'
+ msoLogger.trace('Entered ' + method)
+
+ msoLogger.error('Error occurred attempting to query AAI, Response Code ' + execution.getVariable('PUAAIVfMod_getVnfResponseCode'));
+ String processKey = getProcessKey(execution);
+ WorkflowException exception = new WorkflowException(processKey, 5000,
+ execution.getVariable('PUAAIVfMod_getVnfResponse'))
+ execution.setVariable('WorkflowException', exception)
+
+ msoLogger.trace('Exited ' + method)
+ }
+
+ /**
+ * Generates a WorkflowException if the VF Module does not pass validation.
+ *
+ * @param execution The flow's execution instance.
+ */
+ public void handleVfModuleValidationError(DelegateExecution execution) {
+ def method = getClass().getSimpleName() + '.handleVfModuleValidationError(' +
+ 'execution=' + execution.getId() +
+ ')'
+ msoLogger.trace('Entered ' + method)
+
+ def String errorMsg = 'VF Module validation error: ' + execution.getVariable('PUAAIVfMod_vfModuleValidationError')
+ msoLogger.error(errorMsg);
+ msoLogger.debug("PrepareUpdateAAIVfModule: Error Message : " + errorMsg)
+
+ String processKey = getProcessKey(execution);
+ WorkflowException exception = new WorkflowException(processKey, 5000, errorMsg)
+ execution.setVariable('WorkflowException', exception)
+
+ 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('PUAAIVfMod_updateVfModuleResponseCode'));
+ String processKey = getProcessKey(execution);
+ WorkflowException exception = new WorkflowException(processKey, 5000,
+ execution.getVariable('PUAAIVfMod_updateVfModuleResponse'))
+ execution.setVariable('WorkflowException', exception)
+
+ msoLogger.trace('Exited ' + method)
+ }
+}
diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/RainyDayHandler.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/RainyDayHandler.groovy
new file mode 100644
index 0000000000..0d66b8f51b
--- /dev/null
+++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/RainyDayHandler.groovy
@@ -0,0 +1,190 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.so.bpmn.common.scripts;
+
+import static org.apache.commons.lang3.StringUtils.*;
+
+import org.apache.commons.lang3.*
+import org.camunda.bpm.engine.delegate.BpmnError
+import org.camunda.bpm.engine.delegate.DelegateExecution
+import org.onap.so.bpmn.core.UrnPropertiesReader;
+import org.onap.so.bpmn.core.json.JsonUtils
+import org.onap.so.client.policy.PolicyClient
+import org.onap.so.client.policy.PolicyClientImpl
+import org.onap.so.client.policy.entities.DictionaryData
+import org.onap.so.client.policy.entities.PolicyDecision
+import org.onap.so.client.policy.entities.Treatments
+import org.onap.so.logger.MsoLogger
+
+
+/**
+ * This groovy class supports the <class>RainyDayHandler.bpmn</class> process.
+ *
+ * @author
+ *
+ * Inputs:
+ * @param - msoRequestId
+ * @param - isDebugLogEnabled
+ * @param - serviceType
+ * @param - vnfType
+ * @param - currentActivity
+ * @param - workStep
+ * @param - failedActivity
+ * @param - errorCode
+ * @param - errorText
+ * @param - vnfName
+ *
+ * Outputs:
+ * @param - WorkflowException
+ * @param - handlingCode
+ *
+ */
+public class RainyDayHandler extends AbstractServiceTaskProcessor {
+ private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, RainyDayHandler.class);
+
+
+ String Prefix="RDH_"
+ ExceptionUtil exceptionUtil = new ExceptionUtil()
+
+ JsonUtils jsonUtils = new JsonUtils()
+
+ public void preProcessRequest (DelegateExecution execution) {
+ String msg = ""
+ msoLogger.trace("preProcessRequest of RainyDayHandler ")
+
+ try {
+ execution.setVariable("prefix", Prefix)
+ // check for required input
+ String requestId = execution.getVariable("msoRequestId")
+ msoLogger.debug("msoRequestId is: " + requestId)
+ def serviceType = execution.getVariable("serviceType")
+ msoLogger.debug("serviceType is: " + serviceType)
+ def vnfType = execution.getVariable("vnfType")
+ msoLogger.debug("vnftype is: " + vnfType)
+ def currentActivity = execution.getVariable("currentActivity")
+ msoLogger.debug("currentActivity is: " + currentActivity)
+ def workStep = execution.getVariable("workStep")
+ msoLogger.debug("workStep is: " + workStep)
+ def failedActivity = execution.getVariable("failedActivity")
+ msoLogger.debug("failedActivity is: " + failedActivity)
+ def errorCode = execution.getVariable("errorCode")
+ msoLogger.debug("errorCode is: " + errorCode)
+ def errorText = execution.getVariable("errorText")
+ msoLogger.debug("errorText is: " + errorText)
+ String defaultPolicyDisposition = (String) UrnPropertiesReader.getVariable("policy.default.disposition",execution)
+ msoLogger.debug("defaultPolicyDisposition is: " + defaultPolicyDisposition)
+ execution.setVariable('defaultPolicyDisposition', defaultPolicyDisposition)
+
+ } catch (BpmnError e) {
+ throw e;
+ } catch (Exception ex){
+ msg = "Exception in preProcessRequest " + ex.getMessage()
+ msoLogger.debug(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
+ }
+ msoLogger.trace("Exit preProcessRequest of RainyDayHandler ")
+ }
+
+ public void queryPolicy (DelegateExecution execution) {
+ String msg = ""
+ msoLogger.trace("queryPolicy of RainyDayHandler ")
+
+ try {
+
+ // check for input
+ String serviceType = execution.getVariable("serviceType")
+ String vnfType = execution.getVariable("vnfType")
+
+ msoLogger.debug("serviceType: " + serviceType)
+ msoLogger.debug("vnfType: " + vnfType)
+
+ def errorCode = execution.getVariable("errorCode")
+ def bbId = execution.getVariable("currentActivity")
+ def workStep = execution.getVariable("workStep")
+
+ msoLogger.debug("Before querying policy")
+
+ String decision = 'DENY'
+ String disposition = "Abort"
+ String defaultAllowedTreatments = "rollback, skip, manual, abort"
+
+ String defaultPolicyDisposition = (String) execution.getVariable('defaultPolicyDisposition')
+ if (defaultPolicyDisposition != null && !defaultPolicyDisposition.isEmpty()) {
+ msoLogger.debug("Setting disposition to the configured default instead of querying Policy: " + defaultPolicyDisposition)
+ disposition = defaultPolicyDisposition
+ msoLogger.debug("Setting default allowed treatments: " + defaultAllowedTreatments)
+ execution.setVariable("validResponses", defaultAllowedTreatments)
+ }
+ else {
+
+ PolicyDecision decisionObject = null
+
+ try {
+ PolicyClient policyClient = new PolicyClientImpl()
+ msoLogger.debug("Created policy client")
+ decisionObject = policyClient.getDecision(serviceType, vnfType, bbId, workStep, errorCode)
+ msoLogger.debug("Obtained decision object")
+ DictionaryData dictClient = policyClient.getAllowedTreatments(bbId, workStep)
+ Treatments treatments = dictClient.getTreatments()
+ String validResponses = treatments.getString()
+ if (validResponses != null) {
+ validResponses = validResponses.toLowerCase()
+ }
+ msoLogger.debug("Obtained validResponses: " + validResponses)
+ execution.setVariable("validResponses", validResponses)
+
+ } catch(Exception e) {
+ msg = "Exception in queryPolicy " + e.getMessage()
+ msoLogger.debug(msg)
+ }
+
+
+ if (decisionObject != null) {
+ decision = decisionObject.getDecision()
+ disposition = decisionObject.getDetails()
+ msoLogger.debug("Obtained disposition from policy engine: " + disposition)
+ }
+ else {
+ disposition = "Abort"
+ }
+ if (disposition == null) {
+ disposition = "Abort"
+ }
+ }
+ execution.setVariable("handlingCode", disposition)
+
+ msoLogger.debug("Disposition: "+ disposition)
+
+ } catch (BpmnError e) {
+ msoLogger.debug("BPMN exception: " + e.errorMessage)
+ throw e;
+ } catch (Exception ex){
+ msg = "Exception in queryPolicy " + ex.getMessage()
+ msoLogger.debug(msg)
+ //exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
+ }
+ msoLogger.trace("Exit queryPolicy of RainyDayHandler ")
+ }
+
+
+
+
+}
diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/ReceiveWorkflowMessage.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/ReceiveWorkflowMessage.groovy
new file mode 100644
index 0000000000..717d0df1ba
--- /dev/null
+++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/ReceiveWorkflowMessage.groovy
@@ -0,0 +1,133 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.so.bpmn.common.scripts;
+
+import groovy.json.*
+
+import org.apache.commons.lang3.*
+import org.camunda.bpm.engine.delegate.BpmnError
+import org.camunda.bpm.engine.delegate.DelegateExecution
+import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor
+import org.onap.so.bpmn.common.scripts.ExceptionUtil
+import org.onap.so.logger.MessageEnum
+import org.onap.so.logger.MsoLogger
+
+
+
+
+class ReceiveWorkflowMessage extends AbstractServiceTaskProcessor {
+ private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, ReceiveWorkflowMessage.class);
+
+
+ ExceptionUtil exceptionUtil = new ExceptionUtil()
+
+ /**
+ * Process the incoming variables.
+ *
+ * @param execution The flow's execution instance.
+ */
+public void preProcessRequest (DelegateExecution execution) {
+ def method = getClass().getSimpleName() + '.preProcessRequest(' +
+ 'execution=' + execution.getId() +
+ ')'
+ msoLogger.trace('Entered ' + method)
+
+ def prefix="RCVWFMSG_"
+ execution.setVariable("prefix", prefix)
+ setSuccessIndicator(execution, false)
+
+ try {
+
+ // Confirm that timeout value has been provided in 'RCVWFMSG_timeout'.
+ def timeout = execution.getVariable('RCVWFMSG_timeout')
+ msoLogger.debug('Timeout value is \'' + timeout + '\'')
+ if ((timeout == null) || (timeout.isEmpty())) {
+ String msg = getProcessKey(execution) + ': Missing or empty input variable \'RCVWFMSG_timeout\''
+ msoLogger.debug(msg)
+ msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, msg, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "");
+ exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg)
+ }
+
+ // Confirm that message type has been provided in 'RCVWFMSG_messageType'
+ def messageType = execution.getVariable('RCVWFMSG_messageType')
+ msoLogger.debug('Message type is \'' + messageType + '\'')
+ if ((messageType == null) || (messageType.isEmpty())) {
+ String msg = getProcessKey(execution) + ': Missing or empty input variable \'RCVWFMSG_messageType\''
+ msoLogger.debug(msg)
+ msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, msg, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "");
+ exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg)
+ }
+
+ // Confirm that correlator value has been provided in 'RCVWFMSG_correlator'
+ def correlator = execution.getVariable('RCVWFMSG_correlator')
+ msoLogger.debug('Correlator value is \'' + correlator + '\'')
+ if ((correlator == null) || (correlator.isEmpty())) {
+ String msg = getProcessKey(execution) + ': Missing or empty input variable \'RCVWFMSG_correlator\''
+ msoLogger.debug(msg)
+ msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, msg, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "");
+ exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg)
+ }
+ execution.setVariable(messageType + '_CORRELATOR', correlator)
+
+ msoLogger.trace('Exited ' + method)
+ } catch (BpmnError e) {
+ throw e
+ } catch (Exception e) {
+ String msg = 'Caught exception in ' + method + ": " + e
+ msoLogger.debug(msg)
+ msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, msg, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "");
+ exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg)
+ }
+ }
+
+ /**
+ * Process a received message.
+ *
+ * @param execution The flow's execution instance.
+ */
+ public void processReceivedMessage(DelegateExecution execution){
+ def method = getClass().getSimpleName() + '.processReceivedMessage(' +
+ 'execution=' + execution.getId() +
+ ')'
+ msoLogger.trace('Entered ' + method)
+
+ String messageType = null;
+ String receivedMessage = null;
+
+ try {
+ messageType = execution.getVariable('RCVWFMSG_messageType')
+ receivedMessage = execution.getVariable(messageType + '_MESSAGE')
+ msoLogger.debug(getProcessKey(execution) + ": received message:\n" + receivedMessage)
+
+ // The received message is made available to the calling flow in WorkflowResponse
+ execution.setVariable("WorkflowResponse", receivedMessage)
+
+ setSuccessIndicator(execution, true)
+
+ msoLogger.trace('Exited ' + method)
+ } catch (Exception e) {
+ receivedMessage = receivedMessage == null || String.valueOf(receivedMessage).isEmpty() ? "NONE" : receivedMessage
+ String msg = "Error processing received workflow message: " + receivedMessage
+ msoLogger.debug(getProcessKey(execution) + ': ' + msg)
+ exceptionUtil.buildWorkflowException(execution, 7020, msg)
+ }
+ }
+}
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
new file mode 100644
index 0000000000..852f8d75bd
--- /dev/null
+++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/SDNCAdapter.groovy
@@ -0,0 +1,327 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.so.bpmn.common.scripts;
+import org.onap.so.bpmn.core.UrnPropertiesReader;
+
+import java.text.SimpleDateFormat
+
+import org.camunda.bpm.engine.delegate.DelegateExecution
+import org.onap.so.bpmn.core.WorkflowException
+import org.onap.so.logger.MessageEnum
+import org.onap.so.logger.MsoLogger
+
+
+
+
+// SDNC Adapter Request/Response processing
+
+public class SDNCAdapter extends AbstractServiceTaskProcessor {
+ private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, SDNCAdapter.class);
+
+
+ def Prefix="SDNCA_"
+ ExceptionUtil exceptionUtil = new ExceptionUtil()
+
+ // Script Task: Process SDNC Workflow Request
+ // Params: Workflow DelegateExecution
+ // Assume: Received SDNCAdapterWorkflowRequest is in variable 'sdncAdapterWorkflowRequest'
+ // Put created SDNCAdapterRequest in variable 'sdncAdapterRequest'
+ public void preProcessRequest (DelegateExecution execution) {
+ try{
+
+ msoLogger.trace("Begin PreProcess SDNCAdapterRequestScript ")
+ msoLogger.debug("Incoming sdncAdapterWorkflowRequest:\n" + execution.getVariable("sdncAdapterWorkflowRequest"))
+
+ // Initialize some variables used throughout the flow
+ execution.setVariable("prefix", Prefix)
+ execution.setVariable("sdncAdapterResponse", "")
+ execution.setVariable("asynchronousResponseTimeout", false)
+ execution.setVariable("continueListening", false)
+ execution.setVariable("SDNCA_SuccessIndicator", false)
+ execution.setVariable("SDNCA_InterimNotify", false)
+
+ // Authorization Info
+ String basicAuthValue = UrnPropertiesReader.getVariable("mso.adapters.po.auth", execution)
+
+ try {
+ def encodedString = utils.getBasicAuth(basicAuthValue, UrnPropertiesReader.getVariable("mso.msoKey", execution))
+ execution.setVariable("BasicAuthHeaderValue",encodedString)
+ } catch (IOException ex) {
+ msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Unable to encode username password string", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "");
+ }
+
+ // TODO Use variables instead of passing xml request - Huh?
+
+ // Get original RequestHeader
+ def sdncwfreq= execution.getVariable("sdncAdapterWorkflowRequest")
+ def requestHeader = utils.getNodeXml(sdncwfreq, "RequestHeader")
+ requestHeader = requestHeader.replace("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n", "")
+
+ // Set Callback URL to use from URN Mapping or jBoss Property
+ def origCallbackUrl = utils.getNodeText(requestHeader, "CallbackUrl")
+ def callbackUrlToUse = UrnPropertiesReader.getVariable("mso.workflow.sdncadapter.callback", execution)
+ MsoUtils msoUtil = new MsoUtils()
+ def useQualifiedHostName = UrnPropertiesReader.getVariable("mso.use.qualified.host", execution)
+ if((useQualifiedHostName!=null) && (useQualifiedHostName.equals("true"))){
+ callbackUrlToUse = msoUtil.getQualifiedHostNameForCallback(callbackUrlToUse)
+ }
+ msoLogger.debug("Callback URL to use:\n" + callbackUrlToUse)
+ requestHeader = requestHeader.replace(origCallbackUrl, callbackUrlToUse)
+
+ // Get parameters from request header
+ def sdnca_svcInstanceId = utils.getNodeText(requestHeader, "SvcInstanceId") // optional
+ msoLogger.debug("SvcInstanceId: " + sdnca_svcInstanceId)
+ def sdnca_msoAction = utils.getNodeText(requestHeader, "MsoAction") // optional
+ msoLogger.debug("MsoAction: " + sdnca_msoAction)
+ def sdnca_svcAction = utils.getNodeText(requestHeader, "SvcAction")
+ msoLogger.debug("SvcAction: " + sdnca_svcAction)
+ def sdnca_svcOperation = utils.getNodeText(requestHeader, "SvcOperation")
+ msoLogger.debug("SvcOperation: " + sdnca_svcOperation)
+ def sdncRequestData = utils.getChildNodes(sdncwfreq, "SDNCRequestData")
+ sdncRequestData = sdncRequestData.replace("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n", "")
+ sdncRequestData = sdncRequestData.replaceAll('tag0:', '').replaceAll(':tag0', '')
+ msoLogger.debug("SDNCRequestData:\n" + sdncRequestData)
+ def sdnca_serviceType = ""
+ if (utils.nodeExists(sdncwfreq, "service-type")) {
+ sdnca_serviceType = utils.getNodeText(sdncwfreq, "service-type")
+ }
+ msoLogger.debug("service-type: " + sdnca_serviceType)
+ def serviceConfigActivate = false
+ def source = ''
+ if ((sdnca_svcAction == 'activate') && (sdnca_svcOperation == 'service-configuration-operation') && (sdnca_serviceType == 'uCPE-VMS')) {
+ serviceConfigActivate = true
+ if (utils.nodeExists(sdncwfreq, 'source')) {
+ source = utils.getNodeText(sdncwfreq, 'source')
+ }
+ }
+ execution.setVariable("serviceConfigActivate", serviceConfigActivate)
+ msoLogger.debug("serviceConfigActivate: " + serviceConfigActivate)
+ execution.setVariable("source", source)
+ 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)
+
+ // Prepare SDNC Request to the SDNC Adapter
+ String sdncAdapterRequest = """
+ <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
+ <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>"""
+
+ if (sdnca_svcInstanceId != null) {
+ sdncAdapterRequest += """
+ <sdncadapter:SvcInstanceId>${MsoUtils.xmlEscape(sdnca_svcInstanceId)}</sdncadapter:SvcInstanceId>"""
+ execution.setVariable("serviceInstanceId", sdnca_svcInstanceId)
+ }
+
+ sdncAdapterRequest += """
+ <sdncadapter:SvcAction>${MsoUtils.xmlEscape(sdnca_svcAction)}</sdncadapter:SvcAction>
+ <sdncadapter:SvcOperation>${MsoUtils.xmlEscape(sdnca_svcOperation)}</sdncadapter:SvcOperation>
+ <sdncadapter:CallbackUrl>${MsoUtils.xmlEscape(callbackUrlToUse)}</sdncadapter:CallbackUrl>"""
+
+ if (sdnca_msoAction != null) {
+ sdncAdapterRequest += """
+ <sdncadapter:MsoAction>${MsoUtils.xmlEscape(sdnca_msoAction)}</sdncadapter:MsoAction>"""
+ }
+
+ sdncAdapterRequest += """
+ </sdncadapter:RequestHeader>
+ <sdncadaptersc:RequestData>
+ ${sdncRequestData}
+ </sdncadaptersc:RequestData></aetgt:SDNCAdapterRequest></SOAP-ENV:Body></SOAP-ENV:Envelope>"""
+
+ msoLogger.debug("Outgoing SDNCAdapterRequest:\n" + sdncAdapterRequest)
+ execution.setVariable("sdncAdapterRequest", sdncAdapterRequest)
+
+ msoLogger.debug(UrnPropertiesReader.getVariable("mso.adapters.sdnc.endpoint", execution))
+ }catch(Exception e){
+ msoLogger.debug('Internal Error occured during PreProcess Method: ', e)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 9999, 'Internal Error occured during PreProcess Method') // TODO: what message and error code?
+ }
+ msoLogger.trace("End pre Process SDNCRequestScript ")
+ }
+
+ public void postProcessResponse (DelegateExecution execution) {
+
+ try{
+ msoLogger.trace("Begin POSTProcess SDNCAdapter ")
+ msoLogger.trace("Incoming sdncAdapterCallbackRequest:\n" + execution.getVariable("sdncAdapterCallbackRequest"))
+
+ // Check the sdnccallback request and get the responsecode
+ def sdnccallbackreq = execution.getVariable("sdncAdapterCallbackRequest")
+ def callbackRequestData = ""
+ def callbackHeader = ""
+
+ if(sdnccallbackreq != null){
+ callbackHeader = utils.getNodeXml(sdnccallbackreq, "CallbackHeader")
+ callbackRequestData = utils.getNodeXml(sdnccallbackreq, "RequestData")
+
+ 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)
+
+ String sdncAdapterWorkflowResponse ="""
+ <sdncadapterworkflow:SDNCAdapterWorkflowResponse xmlns:sdncadapterworkflow="http://org.onap/so/workflow/schema/v1">
+ <sdncadapterworkflow:response-data>
+ ${callbackHeader}
+ ${callbackRequestData}
+ </sdncadapterworkflow:response-data>
+ </sdncadapterworkflow:SDNCAdapterWorkflowResponse>"""
+
+
+ sdncAdapterWorkflowResponse = utils.formatXml(sdncAdapterWorkflowResponse)
+ execution.setVariable("sdncAdapterResponse", sdncAdapterWorkflowResponse)
+ // TODO: Should deprecate use of processKey+Response variable for the response. Will use "WorkflowResponse" instead
+ execution.setVariable("WorkflowResponse", sdncAdapterWorkflowResponse)
+
+ // Check final indicator to determine if we are to continue listening or not
+ def continueListening = false
+ if (utils.nodeExists(callbackRequestData, "ack-final-indicator")) {
+ if (utils.getNodeText(callbackRequestData, "ack-final-indicator") == 'N') {
+ continueListening = true
+ }
+ }
+ execution.setVariable("continueListening", continueListening)
+ msoLogger.debug("Continue Listening: " + continueListening)
+ execution.setVariable("asynchronousResponseTimeout", false)
+ }else{
+ // Timed out waiting for asynchronous message, build error response
+ exceptionUtil.buildWorkflowException(execution, 500, "SDNC Callback Timeout Error")
+ execution.setVariable("asynchronousResponseTimeout", true)
+ msoLogger.debug("Timed out waiting for asynchronous message")
+ }
+ }catch(Exception e){
+ msoLogger.debug('Internal Error occured during PostProcess Method: ' + e)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 9999, 'Internal Error occured during PostProcess Method') // TODO: what message and error code?
+ }
+ msoLogger.trace("End POSTProcess SDNCAdapter ")
+ }
+
+ public void callbackResponsecheck(DelegateExecution execution){
+
+ def sdnccallbackreq=execution.getVariable("sdncAdapterCallbackRequest")
+ msoLogger.debug("sdncAdapterCallbackRequest :" + sdnccallbackreq)
+ if (sdnccallbackreq==null){
+ execution.setVariable("callbackResponseReceived",false);
+ }else{
+ execution.setVariable("callbackResponseReceived",true);
+ }
+ }
+
+ public void resetCallbackRequest(DelegateExecution execution) {
+
+ msoLogger.trace("Begin Reset Callback Info SDNCAdapter ")
+
+ // Clear sdncAdapterCallbackRequest variable
+ execution.removeVariable("sdncAdapterCallbackRequest")
+
+ // Determine and set SDNC Timeout Value
+ def enhancedCallbackRequestData = execution.getVariable("enhancedCallbackRequestData")
+ msoLogger.debug("sdncAdapter - enhancedCallbackRequestData :" + enhancedCallbackRequestData)
+ def interim = false
+ if (enhancedCallbackRequestData != null) {
+ if (utils.nodeExists(enhancedCallbackRequestData, "ack-final-indicator")) {
+ if (utils.getNodeText(enhancedCallbackRequestData, "ack-final-indicator") == 'N') {
+ interim = true
+ }
+ }
+ }
+ def timeoutValue = UrnPropertiesReader.getVariable("mso.adapters.sdnc.timeout", execution)
+ if(timeoutValue==null)
+ timeoutValue="PT5M"
+ def sdncAdapterWorkflowRequest = execution.getVariable("sdncAdapterWorkflowRequest")
+ if (interim && utils.nodeExists(sdncAdapterWorkflowRequest, "InterimSDNCTimeOutValueInHours")) {
+ timeoutValue = "PT" + utils.getNodeText(sdncAdapterWorkflowRequest, "InterimSDNCTimeOutValueInHours") + "H"
+ } else if (utils.nodeExists(sdncAdapterWorkflowRequest, "SDNCTimeOutValueInMinutes")) {
+ timeoutValue = "PT" + utils.getNodeText(sdncAdapterWorkflowRequest, "SDNCTimeOutValueInMinutes") + "M"
+ }
+ execution.setVariable("sdncTimeoutValue", timeoutValue)
+ msoLogger.debug("Setting SDNC Timeout Value to " + timeoutValue)
+
+ msoLogger.trace("End Reset Callback Info SDNCAdapter ")
+ }
+
+
+ public void prepareDBMessage(DelegateExecution execution) {
+
+ msoLogger.trace("Begin Prepare DB Message SDNCAdapter ")
+
+ // Create DB Message
+ def dbRequestId = execution.getVariable("mso-request-id")
+ String dbUpdateInterimStageCompletion = """
+ <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
+ <SOAP-ENV:Body>
+ <DBAdapter:updateInterimStageCompletion xmlns:DBAdapter="http://org.onap.so/requestsdb">
+ <requestId>${MsoUtils.xmlEscape(dbRequestId)}</requestId>
+ <interimStageCompletion>1</interimStageCompletion>
+ <lastModifiedBy>BPEL</lastModifiedBy>
+ </DBAdapter:updateInterimStageCompletion>
+ </SOAP-ENV:Body>
+ </SOAP-ENV:Envelope>
+ """
+
+ execution.setVariable("dbUpdateInterimStageCompletion", dbUpdateInterimStageCompletion)
+ msoLogger.debug("sdncAdapter - dbUpdateInterimStageCompletion :" + dbUpdateInterimStageCompletion)
+ msoLogger.debug("DB UpdateInterimStageCompletion:\n" + dbUpdateInterimStageCompletion)
+ msoLogger.trace("End Prepare DB Message SDNCAdapter ")
+ }
+
+ public String generateCurrentTimeInUtc(){
+ final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
+ sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
+ final String utcTime = sdf.format(new Date());
+ return utcTime;
+ }
+
+ public void toggleSuccessIndicator(DelegateExecution execution){
+ execution.setVariable("SDNCA_SuccessIndicator", true)
+ msoLogger.debug("Setting SDNCA Success Indicator to True")
+ }
+
+ public void assignError(DelegateExecution execution){
+ msoLogger.trace("Started Assign Error ")
+ WorkflowException wf = execution.getVariable("WorkflowException")
+ if(wf == null){
+ exceptionUtil.buildWorkflowException(execution, 5000, "SDNCAdapter Encountered an Internal Error") // TODO: Not sure what message and error code we want here.....
+ }else{
+ execution.setVariable("WorkflowException", wf)
+ }
+
+ msoLogger.debug("Outgoing WorkflowException is: " + execution.getVariable("WorkflowException"))
+ msoLogger.trace("End Assign Error ")
+ }
+
+ public void setTimeout(DelegateExecution execution){
+ msoLogger.trace("Started SetTimeout ")
+ msoLogger.debug("Timer expired, telling correlation service to stop listening")
+ execution.setVariable("asynchronousResponseTimeout", true)
+
+ msoLogger.debug("Timed out branch sleeping for one second to give success branch a chance to complete if running")
+ Thread.sleep(1000)
+ msoLogger.trace("End SetTimeout ")
+ }
+}
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
new file mode 100644
index 0000000000..f610ea4782
--- /dev/null
+++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/SDNCAdapterRestV1.groovy
@@ -0,0 +1,381 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.so.bpmn.common.scripts
+
+import java.text.SimpleDateFormat
+import java.net.URLEncoder
+
+import org.apache.commons.codec.binary.Base64
+import org.apache.commons.lang3.*
+import org.camunda.bpm.engine.delegate.BpmnError
+import org.camunda.bpm.engine.delegate.DelegateExecution
+
+import groovy.json.*
+
+import org.json.JSONObject
+
+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.logger.MessageEnum
+import org.onap.so.logger.MsoLogger
+
+
+
+
+class SDNCAdapterRestV1 extends AbstractServiceTaskProcessor {
+ private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, SDNCAdapterRestV1.class);
+
+
+ ExceptionUtil exceptionUtil = new ExceptionUtil()
+ JsonUtils jsonUtil = new JsonUtils()
+
+ /**
+ * Processes the incoming request.
+ */
+ public void preProcessRequest (DelegateExecution execution) {
+ def method = getClass().getSimpleName() + '.preProcessRequest(' +
+ 'execution=' + execution.getId() +
+ ')'
+ msoLogger.trace('Entered ' + method)
+
+ def prefix="SDNCREST_"
+ execution.setVariable("prefix", prefix)
+ setSuccessIndicator(execution, false)
+
+ try {
+ // Determine the request type and log the request
+
+ String request = validateRequest(execution, "mso-request-id")
+ String requestType = jsonUtil.getJsonRootProperty(request)
+ execution.setVariable(prefix + 'requestType', requestType)
+ msoLogger.debug(getProcessKey(execution) + ': ' + prefix + 'requestType = ' + requestType)
+
+ // Determine the SDNCAdapter endpoint
+
+ String sdncAdapterEndpoint = UrnPropertiesReader.getVariable("mso.adapters.sdnc.rest.endpoint", execution)
+
+ if (sdncAdapterEndpoint == null || sdncAdapterEndpoint.isEmpty()) {
+ String msg = getProcessKey(execution) + ': mso:adapters:sdnc:rest:endpoint URN mapping is not defined'
+ msoLogger.debug(msg)
+ msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, msg, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "");
+ exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg)
+ }
+
+ while (sdncAdapterEndpoint.endsWith('/')) {
+ sdncAdapterEndpoint = sdncAdapterEndpoint.substring(0, sdncAdapterEndpoint.length()-1)
+ }
+
+ String sdncAdapterMethod = null
+ String sdncAdapterUrl = null
+ String sdncAdapterRequest = request
+
+ if ('SDNCServiceRequest'.equals(requestType)) {
+ // Get the sdncRequestId from the request
+
+ String sdncRequestId = jsonUtil.getJsonValue(request, requestType + ".sdncRequestId")
+
+ if (sdncRequestId == null || sdncRequestId.isEmpty()) {
+ String msg = getProcessKey(execution) + ': no sdncRequestId in ' + requestType
+ msoLogger.debug(msg)
+ msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, msg, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "");
+ exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg)
+ }
+
+ execution.setVariable('SDNCAResponse_CORRELATOR', sdncRequestId)
+ msoLogger.debug(getProcessKey(execution) + ': SDNCAResponse_CORRELATOR = ' + sdncRequestId)
+
+ // Get the bpNotificationUrl from the request (just to make sure it's there)
+
+ String bpNotificationUrl = jsonUtil.getJsonValue(request, requestType + ".bpNotificationUrl")
+
+ if (bpNotificationUrl == null || bpNotificationUrl.isEmpty()) {
+ String msg = getProcessKey(execution) + ': no bpNotificationUrl in ' + requestType
+ msoLogger.debug(msg)
+ msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, msg, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "");
+ exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg)
+ }
+
+ sdncAdapterMethod = 'POST'
+ sdncAdapterUrl = sdncAdapterEndpoint
+
+ RollbackData rollbackData = new RollbackData()
+ rollbackData.setRequestId(sdncRequestId)
+ rollbackData.getAdditionalData().put("service", jsonUtil.getJsonValue(request, requestType + ".sdncService"))
+ rollbackData.getAdditionalData().put("operation", jsonUtil.getJsonValue(request, requestType + ".sdncOperation"))
+ execution.setVariable("RollbackData", rollbackData)
+
+ } else {
+ String msg = getProcessKey(execution) + ': Unsupported request type: ' + requestType
+ msoLogger.debug(msg)
+ msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, msg, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "");
+ exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg)
+ }
+
+ execution.setVariable(prefix + 'sdncAdapterMethod', sdncAdapterMethod)
+ execution.setVariable(prefix + 'sdncAdapterUrl', sdncAdapterUrl)
+ execution.setVariable(prefix + 'sdncAdapterRequest', sdncAdapterRequest)
+
+ // Get the Basic Auth credentials for the SDNCAdapter (yes... we ARE using the PO adapters credentials)
+
+ String basicAuthValue = UrnPropertiesReader.getVariable("mso.adapters.po.auth", execution)
+
+ if (basicAuthValue == null || basicAuthValue.isEmpty()) {
+ msoLogger.debug(getProcessKey(execution) + ": mso:adapters:po:auth URN mapping is not defined")
+ msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, getProcessKey(execution) + ": mso:adapters:po:auth URN mapping is not defined", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "");
+ } else {
+ try {
+ def encodedString = utils.getBasicAuth(basicAuthValue, UrnPropertiesReader.getVariable("mso.msoKey", execution))
+ execution.setVariable(prefix + 'basicAuthHeaderValue', encodedString)
+ } catch (IOException ex) {
+ msoLogger.debug(getProcessKey(execution) + ": Unable to encode BasicAuth credentials for SDNCAdapter")
+ msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, getProcessKey(execution) + ": Unable to encode BasicAuth credentials for SDNCAdapter", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "");
+ }
+ }
+
+ // Set the timeout value, e.g. PT5M. It may be specified in the request as the
+ // bpTimeout value. If it's not in the request, use the URN mapping value.
+
+ String timeout = jsonUtil.getJsonValue(request, requestType + ".bpTimeout")
+
+ // in addition to null/empty, also need to verify that the timer value is a valid duration "P[n]T[n]H|M|S"
+ String timerRegex = "PT[0-9]+[HMS]";
+ if (timeout == null || timeout.isEmpty() || !timeout.matches(timerRegex)) {
+ msoLogger.debug(getProcessKey(execution) + ': preProcessRequest(): null/empty/invalid bpTimeout value. Using "mso.adapters.sdnc.timeout"')
+ timeout = UrnPropertiesReader.getVariable("mso.adapters.sdnc.timeout", execution)
+ }
+
+ // the timeout could still be null at this point if the config parm is missing/undefined
+ // forced to log (so OPs can fix the config) and temporarily use a hard coded value of 10 seconds
+ if (timeout == null) {
+ msoLogger.warnSimple('preProcessRequest()', 'property "mso.adapters.sdnc.timeout" is missing/undefined. Using "PT10S"')
+ timeout = "PT10S"
+ }
+
+ execution.setVariable(prefix + 'timeout', timeout)
+ msoLogger.debug(getProcessKey(execution) + ': ' + prefix + 'timeout = ' + timeout)
+ } catch (BpmnError e) {
+ throw e
+ } catch (Exception e) {
+ String msg = 'Caught exception in ' + method + ": " + e
+ msoLogger.debug(msg)
+ msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, msg, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "");
+ exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg)
+ }
+ }
+
+ /**
+ * Sends the request to the SDNC adapter.
+ */
+ public void sendRequestToSDNCAdapter(DelegateExecution execution) {
+ def method = getClass().getSimpleName() + '.sendRequestToSDNCAdapter(' +
+ 'execution=' + execution.getId() +
+ ')'
+ msoLogger.trace('Entered ' + method)
+
+ String prefix = execution.getVariable('prefix')
+
+ try {
+ String sdncAdapterMethod = execution.getVariable(prefix + 'sdncAdapterMethod')
+ msoLogger.debug("SDNC Method is: " + sdncAdapterMethod)
+ String sdncAdapterUrl = execution.getVariable(prefix + 'sdncAdapterUrl')
+ msoLogger.debug("SDNC Url is: " + sdncAdapterUrl)
+ 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"))
+
+ APIResponse response
+
+ if ("GET".equals(sdncAdapterMethod)) {
+ response = client.httpGet()
+ } else if ("PUT".equals(sdncAdapterMethod)) {
+ response = client.httpPut(sdncAdapterRequest)
+ } else if ("POST".equals(sdncAdapterMethod)) {
+ response = client.httpPost(sdncAdapterRequest)
+ } else if ("DELETE".equals(sdncAdapterMethod)) {
+ response = client.httpDelete(sdncAdapterRequest)
+ } else {
+ String msg = 'Unsupported HTTP method "' + sdncAdapterMethod + '" in ' + method + ": " + e
+ msoLogger.debug(msg)
+ msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, msg, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "");
+ exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg)
+ }
+
+ execution.setVariable(prefix + "sdncAdapterStatusCode", response.getStatusCode())
+ execution.setVariable(prefix + "sdncAdapterResponse", response.getResponseBodyAsString())
+ } catch (BpmnError e) {
+ throw e
+ } catch (Exception e) {
+ String msg = 'Caught exception in ' + method + ": " + e
+ msoLogger.debug(msg)
+ msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, msg, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "");
+ exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg)
+ }
+ }
+
+ /**
+ * Processes a callback.
+ */
+ public void processCallback(DelegateExecution execution){
+ def method = getClass().getSimpleName() + '.processCallback(' +
+ 'execution=' + execution.getId() +
+ ')'
+ msoLogger.trace('Entered ' + method)
+
+ String prefix = execution.getVariable('prefix')
+ String callback = execution.getVariable('SDNCAResponse_MESSAGE')
+ String requestId = execution.getVariable("mso-request-id");
+ String serviceInstanceId = execution.getVariable("mso-service-instance-id")
+ utils.logContext(requestId, serviceInstanceId)
+ msoLogger.debug("Incoming SDNC Rest Callback is: " + callback)
+
+ try {
+ int callbackNumber = 1
+ while (execution.getVariable(prefix + 'callback' + callbackNumber) != null) {
+ ++callbackNumber
+ }
+
+ execution.setVariable(prefix + 'callback' + callbackNumber, callback)
+ execution.removeVariable('SDNCAResponse_MESSAGE')
+
+ String responseType = jsonUtil.getJsonRootProperty(callback)
+
+ // Get the ackFinalIndicator and make sure it's either Y or N. Default to Y.
+ String ackFinalIndicator = jsonUtil.getJsonValue(callback, responseType + ".ackFinalIndicator")
+
+ if (!'N'.equals(ackFinalIndicator)) {
+ ackFinalIndicator = 'Y'
+ }
+
+ execution.setVariable(prefix + "ackFinalIndicator", ackFinalIndicator)
+
+ if (responseType.endsWith('Error')) {
+ sdncAdapterBuildWorkflowException(execution, callback)
+ }
+ } catch (Exception e) {
+ callback = callback == null || String.valueOf(callback).isEmpty() ? "NONE" : callback
+ String msg = "Received error from SDNCAdapter: " + callback
+ msoLogger.debug(getProcessKey(execution) + ': ' + msg)
+ exceptionUtil.buildWorkflowException(execution, 5300, msg)
+ }
+ }
+
+ /**
+ * Tries to parse the response as XML to extract the information to create
+ * a WorkflowException. If the response cannot be parsed, a more generic
+ * WorkflowException is created.
+ */
+ public void sdncAdapterBuildWorkflowException(DelegateExecution execution, String response) {
+ try {
+ String responseType = jsonUtil.getJsonRootProperty(response)
+ String responseCode = jsonUtil.getJsonValue(response, responseType + ".responseCode")
+ String responseMessage = jsonUtil.getJsonValue(response, responseType + ".responseMessage")
+
+ String info = ""
+
+ if (responseCode != null && !responseCode.isEmpty()) {
+ info += " responseCode='" + responseCode + "'"
+ }
+
+ if (responseMessage != null && !responseMessage.isEmpty()) {
+ info += " responseMessage='" + responseMessage + "'"
+ }
+
+ // Note: the mapping function handles a null or empty responseCode
+ int mappedResponseCode = Integer.parseInt(exceptionUtil.MapSDNCResponseCodeToErrorCode(responseCode));
+ exceptionUtil.buildWorkflowException(execution, mappedResponseCode, "Received " + responseType +
+ " from SDNCAdapter:" + info)
+ } catch (Exception e) {
+ response = response == null || String.valueOf(response).isEmpty() ? "NONE" : response
+ exceptionUtil.buildWorkflowException(execution, 5300, "Received error from SDNCAdapter: " + response)
+ }
+ }
+
+ /**
+ * Gets the last callback request from the execution, or null if there was no callback.
+ */
+ public String getLastCallback(DelegateExecution execution) {
+ def method = getClass().getSimpleName() + '.getLastCallback(' +
+ 'execution=' + execution.getId() +
+ ')'
+ msoLogger.trace('Entered ' + method)
+
+ String prefix = execution.getVariable('prefix')
+
+ try {
+ int callbackNumber = 1
+ String callback = null
+
+ while (true) {
+ String thisCallback = (String) execution.getVariable(prefix + 'callback' + callbackNumber)
+
+ if (thisCallback == null) {
+ break
+ }
+
+ callback = thisCallback
+ ++callbackNumber
+ }
+
+ return callback
+ } catch (Exception e) {
+ String msg = 'Caught exception in ' + method + ": " + e
+ msoLogger.debug(msg)
+ msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, msg, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "");
+ exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg)
+ }
+ }
+
+ /**
+ * Sets the timeout value to wait for the next notification.
+ */
+ public void setTimeoutValue(DelegateExecution execution) {
+ def method = getClass().getSimpleName() + '.setTimeoutValue(' +
+ 'execution=' + execution.getId() +
+ ')'
+ msoLogger.trace('Entered ' + method)
+
+ String prefix = execution.getVariable('prefix')
+
+ try {
+ def timeoutValue = UrnPropertiesReader.getVariable("mso.adapters.sdnc.timeout", execution)
+
+ if (execution.getVariable(prefix + 'callback1') != null) {
+ // Waiting for subsequent notifications
+ }
+ } catch (Exception e) {
+ String msg = 'Caught exception in ' + method + ": " + e
+ msoLogger.debug(msg)
+ 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
new file mode 100644
index 0000000000..967b9fa93f
--- /dev/null
+++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/SDNCAdapterRestV2.groovy
@@ -0,0 +1,286 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.so.bpmn.common.scripts
+
+import java.text.SimpleDateFormat
+import java.net.URLEncoder
+
+import org.apache.commons.codec.binary.Base64
+import org.apache.commons.lang3.*
+import org.camunda.bpm.engine.delegate.BpmnError
+import org.camunda.bpm.engine.delegate.DelegateExecution
+
+import groovy.json.*
+
+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
+
+
+
+/**
+ * This version of SDNCAdapterRest allows for interim notifications to be sent for
+ * any non-final response received from SDNC.
+ */
+class SDNCAdapterRestV2 extends SDNCAdapterRestV1 {
+ private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, SDNCAdapterRestV2.class);
+
+
+ ExceptionUtil exceptionUtil = new ExceptionUtil()
+ JsonUtils jsonUtil = new JsonUtils()
+
+ /**
+ * Processes the incoming request.
+ */
+ public void preProcessRequest (DelegateExecution execution) {
+ def method = getClass().getSimpleName() + '.preProcessRequest(' +
+ 'execution=' + execution.getId() +
+ ')'
+ msoLogger.trace('Entered ' + method)
+
+ def prefix="SDNCREST_"
+ execution.setVariable("prefix", prefix)
+ setSuccessIndicator(execution, false)
+
+ try {
+ // Determine the request type and log the request
+
+ String request = validateRequest(execution, "mso-request-id")
+ String requestType = jsonUtil.getJsonRootProperty(request)
+ execution.setVariable(prefix + 'requestType', requestType)
+ msoLogger.debug(getProcessKey(execution) + ': ' + prefix + 'requestType = ' + requestType)
+ msoLogger.debug('SDNCAdapterRestV2, request: ' + request)
+
+ // Determine the SDNCAdapter endpoint
+
+ String sdncAdapterEndpoint = UrnPropertiesReader.getVariable("mso.adapters.sdnc.rest.endpoint",execution)
+
+ if (sdncAdapterEndpoint == null || sdncAdapterEndpoint.isEmpty()) {
+ String msg = getProcessKey(execution) + ': mso:adapters:sdnc:rest:endpoint URN mapping is not defined'
+ msoLogger.debug(msg)
+ msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, msg, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "");
+ exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg)
+ }
+
+ while (sdncAdapterEndpoint.endsWith('/')) {
+ sdncAdapterEndpoint = sdncAdapterEndpoint.substring(0, sdncAdapterEndpoint.length()-1)
+ }
+
+ String sdncAdapterMethod = null
+ String sdncAdapterUrl = null
+ String sdncAdapterRequest = request
+
+ if ('SDNCServiceRequest'.equals(requestType)) {
+ // Get the sdncRequestId from the request
+
+ String sdncRequestId = jsonUtil.getJsonValue(request, requestType + ".sdncRequestId")
+
+ if (sdncRequestId == null || sdncRequestId.isEmpty()) {
+ String msg = getProcessKey(execution) + ': no sdncRequestId in ' + requestType
+ msoLogger.debug(msg)
+ msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, msg, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "");
+ exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg)
+ }
+
+ execution.setVariable('SDNCAResponse_CORRELATOR', sdncRequestId)
+ msoLogger.debug(getProcessKey(execution) + ': SDNCAResponse_CORRELATOR = ' + sdncRequestId)
+
+ // Get the bpNotificationUrl from the request (just to make sure it's there)
+
+ String bpNotificationUrl = jsonUtil.getJsonValue(request, requestType + ".bpNotificationUrl")
+
+ if (bpNotificationUrl == null || bpNotificationUrl.isEmpty()) {
+ String msg = getProcessKey(execution) + ': no bpNotificationUrl in ' + requestType
+ msoLogger.debug(msg)
+ msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, msg, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "");
+ exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg)
+ }
+
+ sdncAdapterMethod = 'POST'
+ sdncAdapterUrl = sdncAdapterEndpoint
+
+ } else {
+ String msg = getProcessKey(execution) + ': Unsupported request type: ' + requestType
+ msoLogger.debug(msg)
+ msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, msg, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "");
+ exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg)
+ }
+
+ execution.setVariable(prefix + 'sdncAdapterMethod', sdncAdapterMethod)
+ msoLogger.debug(getProcessKey(execution) + ': ' + prefix + 'sdncAdapterMethod = ' + sdncAdapterMethod)
+ execution.setVariable(prefix + 'sdncAdapterUrl', sdncAdapterUrl)
+ msoLogger.debug(getProcessKey(execution) + ': ' + prefix + 'sdncAdapterUrl = ' + sdncAdapterUrl)
+ execution.setVariable(prefix + 'sdncAdapterRequest', sdncAdapterRequest)
+ msoLogger.debug(getProcessKey(execution) + ': ' + prefix + 'sdncAdapterRequest = \n' + sdncAdapterRequest)
+
+ // Get the Basic Auth credentials for the SDNCAdapter (yes... we ARE using the PO adapters credentials)
+
+ String basicAuthValue = UrnPropertiesReader.getVariable("mso.adapters.po.auth",execution)
+
+ if (basicAuthValue == null || basicAuthValue.isEmpty()) {
+ msoLogger.debug(getProcessKey(execution) + ": mso:adapters:po:auth URN mapping is not defined")
+ msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, getProcessKey(execution) + ": mso:adapters:po:auth URN mapping is not defined", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "");
+ } else {
+ try {
+ def encodedString = utils.getBasicAuth(basicAuthValue, UrnPropertiesReader.getVariable("mso.msoKey", execution))
+ execution.setVariable(prefix + 'basicAuthHeaderValue', encodedString)
+ } catch (IOException ex) {
+ msoLogger.debug(getProcessKey(execution) + ": Unable to encode BasicAuth credentials for SDNCAdapter")
+ msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, getProcessKey(execution) + ": Unable to encode BasicAuth credentials for SDNCAdapter", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "");
+ }
+ }
+
+ // Set the timeout value, e.g. PT5M. It may be specified in the request as the
+ // bpTimeout value. If it's not in the request, use the URN mapping value.
+
+ String timeout = jsonUtil.getJsonValue(request, requestType + ".bpTimeout")
+
+ // in addition to null/empty, also need to verify that the timer value is a valid duration "P[n]T[n]H|M|S"
+ String timerRegex = "PT[0-9]+[HMS]";
+ if (timeout == null || timeout.isEmpty() || !timeout.matches(timerRegex)) {
+ msoLogger.debug(getProcessKey(execution) + ': preProcessRequest(): null/empty/invalid bpTimeout value. Using "mso.adapters.sdnc.timeout"')
+ timeout = UrnPropertiesReader.getVariable("mso.adapters.sdnc.timeout", execution)
+ }
+
+ // the timeout could still be null at this point if the config parm is missing/undefined
+ // forced to log (so OPs can fix the config) and temporarily use a hard coded value of 10 seconds
+ if (timeout == null) {
+ msoLogger.warnSimple('preProcessRequest()', 'property "mso.adapters.sdnc.timeout" is missing/undefined. Using "PT10S"')
+ timeout = "PT10S"
+ }
+
+ execution.setVariable(prefix + 'timeout', timeout)
+ msoLogger.debug(getProcessKey(execution) + ': ' + prefix + 'timeout = ' + timeout)
+ } catch (BpmnError e) {
+ throw e
+ } catch (Exception e) {
+ String msg = 'Caught exception in ' + method + ": " + e
+ msoLogger.debug(msg)
+ msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, msg, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "");
+ exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg)
+ }
+ }
+
+ /**
+ * Processes a callback. Check for possible interim notification.
+ */
+ public void processCallback(DelegateExecution execution){
+ def method = getClass().getSimpleName() + '.processCallback(' +
+ 'execution=' + execution.getId() +
+ ')'
+ msoLogger.trace('Entered ' + method)
+
+ String prefix = execution.getVariable('prefix')
+ String callback = execution.getVariable('SDNCAResponse_MESSAGE')
+ msoLogger.debug("Incoming SDNC Rest Callback is: " + callback)
+
+ try {
+ msoLogger.debug(getProcessKey(execution) + ": received callback:\n" + callback)
+
+ int callbackNumber = 1
+ while (execution.getVariable(prefix + 'callback' + callbackNumber) != null) {
+ ++callbackNumber
+ }
+
+ execution.setVariable(prefix + 'callback' + callbackNumber, callback)
+ execution.removeVariable('SDNCAResponse_MESSAGE')
+
+ String responseType = jsonUtil.getJsonRootProperty(callback)
+
+ // Get the ackFinalIndicator and make sure it's either Y or N. Default to Y.
+ String ackFinalIndicator = jsonUtil.getJsonValue(callback, responseType + ".ackFinalIndicator")
+
+ if (!'N'.equals(ackFinalIndicator)) {
+ ackFinalIndicator = 'Y'
+ }
+
+ execution.setVariable(prefix + "ackFinalIndicator", ackFinalIndicator)
+
+ if (responseType.endsWith('Error')) {
+ sdncAdapterBuildWorkflowException(execution, callback)
+ }
+
+ // Check for possible interim notification
+ execution.setVariable(prefix + "interimNotification", null)
+ execution.setVariable(prefix + "doInterimNotification", false)
+ if ('N'.equals(ackFinalIndicator)) {
+ def interimNotification = execution.getVariable(prefix + "InterimNotification" + callbackNumber)
+ if (interimNotification != null) {
+ execution.setVariable(prefix + "interimNotification", interimNotification)
+ execution.setVariable(prefix + "doInterimNotification", true)
+ }
+ }
+
+ } catch (Exception e) {
+ callback = callback == null || String.valueOf(callback).isEmpty() ? "NONE" : callback
+ String msg = "Received error from SDNCAdapter: " + callback
+ msoLogger.debug(getProcessKey(execution) + ': ' + msg)
+ 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
+ * variable/value definitions will be passed to the notification service.
+ */
+ public void prepareInterimNotification(DelegateExecution execution) {
+ def method = getClass().getSimpleName() + '.prepareInterimNotification(' +
+ '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")
+ execution.setVariable(variableName, variableValue)
+ msoLogger.debug("Setting "+ variableName + "=" + variableValue)
+ }
+ }
+
+ } catch (Exception e) {
+ String msg = "Error preparing interim notification"
+ msoLogger.debug(getProcessKey(execution) + ': ' + msg)
+ exceptionUtil.buildWorkflowException(execution, 5300, 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
new file mode 100644
index 0000000000..ba450c1b12
--- /dev/null
+++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/SDNCAdapterUtils.groovy
@@ -0,0 +1,1024 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.so.bpmn.common.scripts;
+
+import 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.bpmn.core.json.JsonUtils;
+import org.springframework.web.util.UriUtils
+import org.onap.so.bpmn.core.UrnPropertiesReader
+import org.onap.so.logger.MessageEnum
+import org.onap.so.logger.MsoLogger
+
+
+
+
+/**
+ * @version 1.0
+ *
+ */
+class SDNCAdapterUtils {
+ private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, SDNCAdapterUtils.class);
+
+
+ ExceptionUtil exceptionUtil = new ExceptionUtil()
+ JsonUtils jsonUtil = new JsonUtils()
+
+ private AbstractServiceTaskProcessor taskProcessor
+
+ public SDNCAdapterUtils(AbstractServiceTaskProcessor taskProcessor) {
+ this.taskProcessor = taskProcessor
+ }
+
+ String SDNCAdapterFeatureRequest(DelegateExecution execution, String requestName, String action, String callbackURL, String serviceOperation, String timeoutValueInMinutes) {
+ def utils=new MsoUtils()
+
+ def prefix = execution.getVariable('prefix')
+ def request = taskProcessor.getVariable(execution, requestName)
+ def requestInformation = utils.getNodeXml(request, 'request-information', false)
+ def serviceInformation = utils.getNodeXml(request, 'service-information', false)
+ def featureInformation = utils.getNodeXml(request, 'feature-information', false)
+ def featureParameters = utils.getNodeXml(request, 'feature-parameters', false)
+
+ def requestId = execution.getVariable('testReqId') // for junits
+ if(requestId==null){
+ requestId = execution.getVariable("mso-request-id") + "-" + System.currentTimeMillis()
+ }
+
+ def svcInstanceId = execution.getVariable("mso-service-instance-id")
+
+ def nnsRequestInformation = utils.removeXmlNamespaces(requestInformation)
+ def nnsServiceInformation = utils.removeXmlNamespaces(serviceInformation)
+ def nnsFeatureInformation = utils.removeXmlNamespaces(featureInformation)
+ def nnsFeatureParameters = utils.removeXmlNamespaces(featureParameters)
+
+ String sdncAdapterFeatureRequest = """
+ <sdncadapterworkflow:SDNCAdapterWorkflowRequest xmlns:sdncadapterworkflow="http://openecomp.com/mso/workflow/schema/v1"
+ xmlns:sdncadapter="http://domain2.openecomp.com/workflow/sdnc/adapter/schema/v1">
+ <sdncadapter:RequestHeader>
+ <sdncadapter:RequestId>${MsoUtils.xmlEscape(requestId)}</sdncadapter:RequestId>
+ <sdncadapter:SvcInstanceId>${MsoUtils.xmlEscape(svcInstanceId)}</sdncadapter:SvcInstanceId>
+ <sdncadapter:SvcAction>${MsoUtils.xmlEscape(action)}</sdncadapter:SvcAction>
+ <sdncadapter:SvcOperation>${MsoUtils.xmlEscape(serviceOperation)}</sdncadapter:SvcOperation>
+ <sdncadapter:CallbackUrl>${MsoUtils.xmlEscape(callbackURL)}</sdncadapter:CallbackUrl>
+ </sdncadapter:RequestHeader>
+ <sdncadapterworkflow:SDNCRequestData>
+ ${nnsRequestInformation}
+ ${nnsServiceInformation}
+ ${nnsFeatureInformation}
+ ${nnsFeatureParameters}
+ </sdncadapterworkflow:SDNCRequestData>
+ <sdncadapterworkflow:SDNCTimeOutValueInMinutes>${MsoUtils.xmlEscape(timeoutValueInMinutes)}</sdncadapterworkflow:SDNCTimeOutValueInMinutes>
+ </sdncadapterworkflow:SDNCAdapterWorkflowRequest>
+ """
+ sdncAdapterFeatureRequest = utils.removeXmlPreamble(utils.formatXML(sdncAdapterFeatureRequest))
+ return sdncAdapterFeatureRequest
+ }
+
+ String SDNCAdapterActivateVnfRequest(DelegateExecution execution, String action, String callbackURL, String serviceOperation, String msoAction, String timeoutValueInMinutes) {
+ def utils=new MsoUtils()
+
+ def prefix = execution.getVariable('prefix')
+ def request = taskProcessor.getVariable(execution, prefix+'Request')
+ def requestInformation = utils.getNodeXml(request, 'request-information', false)
+ def serviceInformation = utils.getNodeXml(request, 'service-information', false)
+ def vnfInformationList = utils.getNodeXml(request, 'vnf-information-list', false)
+
+ def requestId = execution.getVariable('testReqId') // for junits
+ if(requestId==null){
+ requestId = execution.getVariable("mso-request-id") + "-" + System.currentTimeMillis()
+ }
+
+ def svcInstanceId = execution.getVariable("mso-service-instance-id")
+
+ def nnsRequestInformation = utils.removeXmlNamespaces(requestInformation)
+ def nnsServiceInformation = utils.removeXmlNamespaces(serviceInformation)
+ def nnsVnfInformationList = utils.removeXmlNamespaces(vnfInformationList)
+
+ String sdncAdapterActivateVnfRequest = """
+ <sdncadapterworkflow:SDNCAdapterWorkflowRequest xmlns:sdncadapterworkflow="http://openecomp.com/mso/workflow/schema/v1"
+ xmlns:sdncadapter="http://domain2.openecomp.com/workflow/sdnc/adapter/schema/v1">
+ <sdncadapter:RequestHeader>
+ <sdncadapter:RequestId>${MsoUtils.xmlEscape(requestId)}</sdncadapter:RequestId>
+ <sdncadapter:SvcInstanceId>${MsoUtils.xmlEscape(svcInstanceId)}</sdncadapter:SvcInstanceId>
+ <sdncadapter:SvcAction>${MsoUtils.xmlEscape(action)}</sdncadapter:SvcAction>
+ <sdncadapter:SvcOperation>${MsoUtils.xmlEscape(serviceOperation)}</sdncadapter:SvcOperation>
+ <sdncadapter:CallbackUrl>${MsoUtils.xmlEscape(callbackURL)}</sdncadapter:CallbackUrl>
+ <sdncadapter:MsoAction>${MsoUtils.xmlEscape(msoAction)}</sdncadapter:MsoAction>
+ </sdncadapter:RequestHeader>
+ <sdncadapterworkflow:SDNCRequestData>
+ ${nnsRequestInformation}
+ ${nnsServiceInformation}
+ ${nnsVnfInformationList}
+ </sdncadapterworkflow:SDNCRequestData>
+ <sdncadapterworkflow:SDNCTimeOutValueInMinutes>${MsoUtils.xmlEscape(timeoutValueInMinutes)}</sdncadapterworkflow:SDNCTimeOutValueInMinutes>
+ </sdncadapterworkflow:SDNCAdapterWorkflowRequest>
+ """
+ sdncAdapterActivateVnfRequest = utils.removeXmlPreamble(utils.formatXML(sdncAdapterActivateVnfRequest))
+ return sdncAdapterActivateVnfRequest
+ }
+
+ String SDNCAdapterL3ToHigherLayerRequest(DelegateExecution execution, String action, String callbackURL, String serviceOperation, String timeoutValueInMinutes) {
+ def utils=new MsoUtils()
+
+ def prefix = execution.getVariable('prefix')
+ def request = taskProcessor.getVariable(execution, prefix+'Request')
+
+ def 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>
+ <notification-url>${MsoUtils.xmlEscape(execution.getVariable(prefix+"notificationUrl"))}</notification-url>
+ </request-information>"""
+
+ // Change the value of the 'request-information'.'request-action' element
+ def xml = new XmlSlurper().parseText(requestInformation)
+ if("assign".equalsIgnoreCase(action)){
+ xml.'request-action'.replaceBody('createTrinityBonding')
+ }else if("activate".equalsIgnoreCase(action)){
+ xml.'request-action'.replaceBody('activateTrinityBonding')
+ }else if("delete".equalsIgnoreCase(action)){
+ xml.'request-action'.replaceBody('deleteTrinityBonding')
+ }
+ requestInformation = utils.removeXmlPreamble(groovy.xml.XmlUtil.serialize(xml))
+ def nnsRequestInformation = utils.removeXmlNamespaces(requestInformation)
+
+ def requestId = execution.getVariable('testReqId') // for junits
+ if(requestId==null){
+ requestId = execution.getVariable("mso-request-id") + "-" + System.currentTimeMillis()
+ }
+
+ def svcInstanceId = execution.getVariable("mso-service-instance-id")
+
+ //Build Service Information
+ // Send serviceName from CANOPI to sdnc for service-type
+ def 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>
+ <subscriber-global-id>${MsoUtils.xmlEscape(execution.getVariable(prefix+"subscriberGlobalId"))}</subscriber-global-id>
+ </service-information>"""
+
+ //Build Additional Information - vpn or vni
+ // Send serviceType from CANOPI to SDNC for nbnc-request-information service-type
+ def service = execution.getVariable(prefix+"serviceType")
+ def customerId = execution.getVariable(prefix+"customerId")
+ def vpnId = execution.getVariable(prefix+"vpnId")
+ def vpnRt = execution.getVariable(prefix+"vpnRt")
+ def vpnService = execution.getVariable(prefix+"vpnService")
+ def vpnRegion = execution.getVariable(prefix+"vpnRegion")
+ def additionalInfo = ""
+ if("assign".equalsIgnoreCase(action)){
+ additionalInfo = """<vpn-data-list>
+ <vpn-id>${MsoUtils.xmlEscape(vpnId)}</vpn-id>
+ <vpn-rt>${MsoUtils.xmlEscape(vpnRt)}</vpn-rt>
+ <vpn-service>${MsoUtils.xmlEscape(vpnService)}</vpn-service>
+ <vpn-region>${MsoUtils.xmlEscape(vpnRegion)}</vpn-region>
+ </vpn-data-list>"""
+ }else if("activate".equalsIgnoreCase(action) || "delete".equalsIgnoreCase(action)){
+ def vniId = execution.getVariable(prefix+'vniId')
+ additionalInfo = "<vni-id>${MsoUtils.xmlEscape(vniId)}</vni-id>"
+ }
+
+ //Set Interface Status
+ def interfaceStatus = "DISABLE"
+ if("activate".equalsIgnoreCase(action)){
+ interfaceStatus = "ENABLE"
+ }
+
+ //Build SDNC Adapter Request
+ String sdncAdapterL3ToHLRequest = """
+ <sdncadapterworkflow:SDNCAdapterWorkflowRequest xmlns:sdncadapterworkflow="http://openecomp.com/mso/workflow/schema/v1"
+ xmlns:sdncadapter="http://domain2.openecomp.com/workflow/sdnc/adapter/schema/v1">
+ <sdncadapter:RequestHeader>
+ <sdncadapter:RequestId>${MsoUtils.xmlEscape(requestId)}</sdncadapter:RequestId>
+ <sdncadapter:SvcInstanceId>${MsoUtils.xmlEscape(svcInstanceId)}</sdncadapter:SvcInstanceId>
+ <sdncadapter:SvcAction>${MsoUtils.xmlEscape(action)}</sdncadapter:SvcAction>
+ <sdncadapter:SvcOperation>${MsoUtils.xmlEscape(serviceOperation)}</sdncadapter:SvcOperation>
+ <sdncadapter:CallbackUrl>${MsoUtils.xmlEscape(callbackURL)}</sdncadapter:CallbackUrl>
+ </sdncadapter:RequestHeader>
+ <sdncadapterworkflow:SDNCRequestData>
+ ${nnsRequestInformation}
+ ${serviceInformation}
+ <nbnc-request-information>
+ <service-type>${MsoUtils.xmlEscape(service)}</service-type>
+ <customer-id>${MsoUtils.xmlEscape(customerId)}</customer-id>
+ <interface-status>${MsoUtils.xmlEscape(interfaceStatus)}</interface-status>
+ ${additionalInfo}
+ </nbnc-request-information>
+ </sdncadapterworkflow:SDNCRequestData>
+ <sdncadapterworkflow:SDNCTimeOutValueInMinutes>${MsoUtils.xmlEscape(timeoutValueInMinutes)}</sdncadapterworkflow:SDNCTimeOutValueInMinutes>
+ </sdncadapterworkflow:SDNCAdapterWorkflowRequest>
+ """
+ sdncAdapterL3ToHLRequest = utils.removeXmlPreamble(utils.formatXML(sdncAdapterL3ToHLRequest))
+
+ return sdncAdapterL3ToHLRequest
+ }
+
+
+
+ private void SDNCAdapterActivateRequest(DelegateExecution execution, String resultVar, String svcAction,
+ String svcOperation, String additionalData) {
+ def utils=new MsoUtils()
+
+ def prefix = execution.getVariable('prefix')
+ def request = taskProcessor.getVariable(execution, prefix+'Request')
+ def requestInformation = utils.getNodeXml(request, 'request-information', false)
+ def serviceInformation = utils.getNodeXml(request, 'service-information', false)
+ def serviceParameters = utils.getNodeXml(request, 'service-parameters', false)
+
+ def requestId = execution.getVariable('testReqId') // for junits
+ if(requestId==null){
+ requestId = execution.getVariable("mso-request-id") + "-" + System.currentTimeMillis()
+ }
+
+ def svcInstanceId = execution.getVariable("mso-service-instance-id")
+ def msoAction = 'gammainternet'
+
+ def timeoutInMinutes = UrnPropertiesReader.getVariable('mso.sdnc.timeout.firewall.minutes',execution)
+
+ def callbackUrl = (String)UrnPropertiesReader.getVariable('mso.workflow.sdncadapter.callback',execution)
+ if (callbackUrl == null || callbackUrl.trim() == "") {
+ msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'mso:workflow:sdncadapter:callback URN is not set', "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "");
+ workflowException(execution, 'Internal Error', 9999) // TODO: what message and error code?
+ }
+
+ def l2HomingInformation = utils.getNodeXml(serviceParameters, 'l2-homing-information', false)
+ def internetEvcAccessInformation = utils.getNodeXml(serviceParameters, 'internet-evc-access-information', false)
+ def vrLan = utils.getNodeXml(serviceParameters, 'vr-lan', false)
+ def upceVmsServiceInformation = utils.getNodeXml(serviceParameters, 'ucpe-vms-service-information', false)
+
+
+ def nnsRequestInformation = utils.removeXmlNamespaces(requestInformation)
+ def nnsServiceInformation = utils.removeXmlNamespaces(serviceInformation)
+ def nnsl2HomingInformation = utils.removeXmlNamespaces(l2HomingInformation)
+ def nnsInternetEvcAccessInformation = utils.removeXmlNamespaces(internetEvcAccessInformation)
+ def nnsVrLan = utils.removeXmlNamespaces(vrLan)
+ def nnsUpceVmsServiceInformation = utils.removeXmlNamespaces(upceVmsServiceInformation)
+
+ if (additionalData == null) {
+ additionalData = ""
+ }
+
+ boolean isAic3 = execution.getVariable("isAic3")
+
+ if(isAic3) {
+ nnsl2HomingInformation = updateHomingInfo(nnsl2HomingInformation, "AIC3.0")
+ }
+ else {
+ nnsl2HomingInformation = updateHomingInfo(nnsl2HomingInformation, "AIC2.X")
+ }
+
+ String content = """
+ <sdncadapterworkflow:SDNCAdapterWorkflowRequest xmlns:sdncadapterworkflow="http://openecomp.com/mso/workflow/schema/v1"
+ xmlns:sdncadapter="http://domain2.openecomp.com/workflow/sdnc/adapter/schema/v1">
+ <sdncadapter:RequestHeader>
+ <sdncadapter:RequestId>${MsoUtils.xmlEscape(requestId)}</sdncadapter:RequestId>
+ <sdncadapter:SvcInstanceId>${MsoUtils.xmlEscape(svcInstanceId)}</sdncadapter:SvcInstanceId>
+ <sdncadapter:SvcAction>${MsoUtils.xmlEscape(svcAction)}</sdncadapter:SvcAction>
+ <sdncadapter:SvcOperation>${MsoUtils.xmlEscape(svcOperation)}</sdncadapter:SvcOperation>
+ <sdncadapter:CallbackUrl>${MsoUtils.xmlEscape(callbackUrl)}</sdncadapter:CallbackUrl>
+ <sdncadapter:MsoAction>${MsoUtils.xmlEscape(msoAction)}</sdncadapter:MsoAction>
+ </sdncadapter:RequestHeader>
+ <sdncadapterworkflow:SDNCRequestData>
+ ${additionalData}
+ ${nnsRequestInformation}
+ ${nnsServiceInformation}
+ ${nnsl2HomingInformation}
+ ${nnsInternetEvcAccessInformation}
+ ${nnsVrLan}
+ ${nnsUpceVmsServiceInformation}
+ </sdncadapterworkflow:SDNCRequestData>
+ <sdncadapterworkflow:SDNCTimeOutValueInMinutes>${MsoUtils.xmlEscape(timeoutInMinutes)}</sdncadapterworkflow:SDNCTimeOutValueInMinutes>
+ </sdncadapterworkflow:SDNCAdapterWorkflowRequest>
+ """
+
+ content = utils.removeXmlPreamble(utils.formatXML(content))
+ execution.setVariable(resultVar, content)
+ }
+
+ /**
+ * Builds an SDNC "reserve" request and stores it in the specified execution
+ * variable.
+ * @param execution the execution
+ * @param action the type of action: reserve, turnup, etc
+ * @param resultVar the execution variable in which the result will be stored
+ */
+ public void sdncReservePrep(DelegateExecution execution, String action, String resultVar) {
+ sdncReservePrep(execution, action, resultVar, false)
+ }
+
+ /**
+ * Builds an SDNC "reserve" request and stores it in the specified execution
+ * variable.
+ * @param execution the execution
+ * @param action the type of action: reserve, turnup, etc
+ * @param resultVar the execution variable in which the result will be stored
+ * @param isAic3 boolean to indicate whether request is for AIC3.0
+ */
+ public void sdncReservePrep(DelegateExecution execution, String action, String resultVar, boolean isAic3) {
+ sdncPrep(execution, resultVar, action , 'service-configuration-operation', null, isAic3, this.taskProcessor)
+ }
+
+ /**
+ * Builds a basic SDNC request and stores it in the specified execution variable.
+ * @param execution the execution
+ * @param resultVar the execution variable in which the result will be stored
+ * @param svcAction the svcAction element value
+ * @param svcOperation the svcOperation element value
+ * @param additionalData additional XML content to be inserted into the
+ * RequestData element (may be null)
+ */
+ public void sdncPrep(DelegateExecution execution, String resultVar, String svcAction,
+ String svcOperation, String additionalData, AbstractServiceTaskProcessor taskProcessor) {
+ sdncPrep(execution, resultVar, svcAction, svcOperation, additionalData, false, taskProcessor)
+ }
+
+ /**
+ * Builds a basic SDNC request and stores it in the specified execution variable.
+ * @param execution the execution
+ * @param resultVar the execution variable in which the result will be stored
+ * @param svcAction the svcAction element value
+ * @param svcOperation the svcOperation element value
+ * @param additionalData additional XML content to be inserted into the RequestData element (may be null)
+ * @param isAic3 boolean to indicate whether request is for AIC3.0
+ */
+ public void sdncPrep(DelegateExecution execution, String resultVar, String svcAction,
+ String svcOperation, String additionalData, boolean isAic3, AbstractServiceTaskProcessor taskProcessor) {
+ def method = getClass().getSimpleName() + '.sdncPrep(' +
+ 'execution=' + execution.getId() +
+ ', resultVar=' + resultVar +
+ ', svcAction=' + svcAction +
+ ', svcOperation=' + svcOperation +
+ ', additionalData=' + (additionalData == null ? "no" : "yes") +
+ ')'
+
+ msoLogger.trace('Entered ' + method)
+ MsoUtils utils = taskProcessor.utils
+ try {
+ def prefix = execution.getVariable('prefix')
+ def request = taskProcessor.getVariable(execution, prefix+'Request')
+ def requestInformation = utils.getNodeXml(request, 'request-information', false)
+ def serviceInformation = utils.getNodeXml(request, 'service-information', false)
+ def serviceParameters = utils.getChildNodes(request, 'service-parameters')
+ def requestAction = utils.getNodeText(request, 'request-action')
+
+ def timeoutInMinutes = UrnPropertiesReader.getVariable('mso.sdnc.timeout.firewall.minutes',execution)
+
+ def requestId = execution.getVariable('testReqId') // for junits
+ if(requestId==null){
+ requestId = execution.getVariable("mso-request-id") + "-" + System.currentTimeMillis()
+ }
+
+ def svcInstanceId = execution.getVariable("mso-service-instance-id")
+ def msoAction = 'gammainternet'
+
+ def callbackUrl = (String)UrnPropertiesReader.getVariable('mso.workflow.sdncadapter.callback',execution)
+ if (callbackUrl == null || callbackUrl.trim() == "") {
+ msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'mso:workflow:sdncadapter:callback URN is not set', "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "");
+ exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Internal Error - During PreProcess Request")
+ }
+
+ def l2HomingInformation = utils.getNodeXml(request, 'l2-homing-information', false)
+ def internetEvcAccessInformation = utils.getNodeXml(request, 'internet-evc-access-information', false)
+ def vrLan = utils.getNodeXml(request, 'vr-lan', false)
+ def upceVmsServiceInfo = utils.getNodeXml(request, 'ucpe-vms-service-information', false)
+ def vnfInformationList = utils.getNodeXml(request, 'vnf-information-list', false)
+
+ def nnsRequestInformation = utils.removeXmlNamespaces(requestInformation)
+ def nnsServiceInformation = utils.removeXmlNamespaces(serviceInformation)
+ def nnsl2HomingInformation = utils.removeXmlNamespaces(l2HomingInformation)
+ def nnsInternetEvcAccessInformation = utils.removeXmlNamespaces(internetEvcAccessInformation)
+ def nnsVrLan = utils.removeXmlNamespaces(vrLan)
+ def nnsUpceVmsServiceInfo = utils.removeXmlNamespaces(upceVmsServiceInfo)
+ def nnsVnfInformationList = utils.removeXmlNamespaces(vrLan)
+ def nnsinternetSvcChangeDetails = ""
+
+ if(requestAction!=null && requestAction.equals("ChangeLayer3ServiceProvRequest")){
+ def internetSvcChangeDetails = utils.removeXmlNamespaces(serviceParameters)
+ nnsinternetSvcChangeDetails = """<internet-service-change-details>
+ ${internetSvcChangeDetails}
+ </internet-service-change-details>"""
+ }
+
+ if (additionalData == null) {
+ additionalData = ""
+ }
+
+ if(isAic3) {
+ nnsl2HomingInformation = updateHomingInfo(nnsl2HomingInformation, "AIC3.0")
+ }
+ else {
+ nnsl2HomingInformation = updateHomingInfo(nnsl2HomingInformation, "AIC2.X")
+ }
+
+
+ String content = """
+ <sdncadapterworkflow:SDNCAdapterWorkflowRequest xmlns:sdncadapterworkflow="http://openecomp.com/mso/workflow/schema/v1"
+ xmlns:sdncadapter="http://domain2.openecomp.com/workflow/sdnc/adapter/schema/v1">
+ <sdncadapter:RequestHeader>
+ <sdncadapter:RequestId>${MsoUtils.xmlEscape(requestId)}</sdncadapter:RequestId>
+ <sdncadapter:SvcInstanceId>${MsoUtils.xmlEscape(svcInstanceId)}</sdncadapter:SvcInstanceId>
+ <sdncadapter:SvcAction>${MsoUtils.xmlEscape(svcAction)}</sdncadapter:SvcAction>
+ <sdncadapter:SvcOperation>${MsoUtils.xmlEscape(svcOperation)}</sdncadapter:SvcOperation>
+ <sdncadapter:CallbackUrl>${MsoUtils.xmlEscape(callbackUrl)}</sdncadapter:CallbackUrl>
+ <sdncadapter:MsoAction>${MsoUtils.xmlEscape(msoAction)}</sdncadapter:MsoAction>
+ </sdncadapter:RequestHeader>
+ <sdncadapterworkflow:SDNCRequestData>
+ ${additionalData}
+ ${nnsRequestInformation}
+ ${nnsServiceInformation}
+ ${nnsl2HomingInformation}
+ ${nnsInternetEvcAccessInformation}
+ ${nnsVrLan}
+ ${nnsUpceVmsServiceInfo}
+ ${nnsVnfInformationList}
+ ${nnsinternetSvcChangeDetails}
+ </sdncadapterworkflow:SDNCRequestData>
+ </sdncadapterworkflow:SDNCAdapterWorkflowRequest>
+ """
+
+ content = utils.removeXmlPreamble(utils.formatXML(content))
+ execution.setVariable(resultVar, content)
+ msoLogger.debug(resultVar + ' = ' + System.lineSeparator() + content)
+
+ msoLogger.trace('Exited ' + method)
+ } catch (BpmnError e) {
+ throw e;
+ } catch (Exception e) {
+ msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e);
+ exceptionUtil.buildAndThrowWorkflowException(execution, 5000, "Internal Error")
+ }
+ }
+
+ public String updateHomingInfo(String homingInfo, String aicVersion) {
+ String newHomingInfo
+ if(homingInfo == null || homingInfo.trim().length() == 0) {
+ newHomingInfo = "<l2-homing-information><aic-version>" + aicVersion + "</aic-version></l2-homing-information>"
+ }
+ else {
+ newHomingInfo = homingInfo.substring(0, homingInfo.indexOf("</l2-homing-information>")) + "<aic-version>" + aicVersion + "</aic-version></l2-homing-information>"
+ }
+ }
+
+ /**
+ * Builds a topology SDNC request and return String request.
+ * As V2 will use 1607-style request, region instead of aic clli code
+ * @param execution, the execution
+ * @param requestXML, the incoming request for the flow
+ * @param serviceInstanceId, the serviceIntance (if available)
+ * @param callbackUrl, the call back url
+ * @param action, the action element value
+ * @param requestAction the svcOperation element value
+ * @param cloudRegionId the aai's cloud-region-id
+ * @param networkId the aai's network-id
+ * @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) {
+ def utils=new MsoUtils()
+
+ // SNDC is expecting request Id for header as unique each call.
+ String hdrRequestId = ""
+ String testHdrRequestId = execution.getVariable("testMessageId") // for test purposes.
+ if (testHdrRequestId == null) {
+ hdrRequestId = UUID.randomUUID() // generate unique
+ } else {
+ hdrRequestId = testHdrRequestId
+ }
+
+ String requestId = ""
+ try {
+ requestId = execution.getVariable("mso-request-id")
+ } catch (Exception ex) {
+ requestId = utils.getNodeText(requestXML, "request-id")
+ }
+
+ String aicCloudRegion = cloudRegionId
+ String tenantId = ""
+ if (utils.nodeExists(requestXML, "tenant-id")) {
+ tenantId = utils.getNodeText(requestXML, "tenant-id")
+ }
+ String networkType = ""
+ if (utils.nodeExists(requestXML, "network-type")) {
+ networkType = utils.getNodeText(requestXML, "network-type")
+ }
+
+ // 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")
+ }
+
+ String serviceId = ""
+ if (utils.nodeExists(requestXML, "service-id")) {
+ serviceId = utils.getNodeText(requestXML, "service-id")
+ }
+ 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")
+ }
+ if (networkName.isEmpty() && utils.nodeExists(requestXML, "network-name")) {
+ networkName = utils.getNodeText(requestXML, "network-name")
+ }
+ String source = ""
+ if (utils.nodeExists(requestXML, "source")) {
+ source = utils.getNodeText(requestXML, "source")
+ }
+
+ // get resourceLink from subflow execution variable
+ String serviceType = ""
+ String subscriberName = ""
+ String siRelatedLink = execution.getVariable("GENGSI_siResourceLink")
+ if (siRelatedLink != null) {
+ // get service type
+ int serviceStart = siRelatedLink.indexOf("service-subscription/")
+ int serviceEnd = siRelatedLink.indexOf("/service-instances/")
+ serviceType = siRelatedLink.substring(serviceStart + 21, serviceEnd)
+ serviceType = UriUtils.decode(serviceType,"UTF-8")
+ // get subscriber name
+ int subscriberNameStart = siRelatedLink.indexOf("customers/customer/")
+ int subscriberNameEnd = siRelatedLink.indexOf("/service-subscriptions/")
+ subscriberName = siRelatedLink.substring(subscriberNameStart + 19, subscriberNameEnd)
+ subscriberName = UriUtils.decode(subscriberName,"UTF-8")
+ }
+
+ String content =
+ """<aetgt:SDNCAdapterWorkflowRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1"
+ xmlns:sdncadapterworkflow="http://org.onap/so/workflow/schema/v1"
+ xmlns:sdncadapter="http://org.onap.so/workflow/sdnc/adapter/schema/v1"
+ xmlns:ns5="http://org.onap/so/request/types/v1">
+ <sdncadapter:RequestHeader>
+ <sdncadapter:RequestId>${MsoUtils.xmlEscape(hdrRequestId)}</sdncadapter:RequestId>
+ <sdncadapter:SvcInstanceId>${MsoUtils.xmlEscape(serviceInstanceId)}</sdncadapter:SvcInstanceId>
+ <sdncadapter:SvcAction>${MsoUtils.xmlEscape(action)}</sdncadapter:SvcAction>
+ <sdncadapter:SvcOperation>network-topology-operation</sdncadapter:SvcOperation>
+ <sdncadapter:CallbackUrl>sdncCallback</sdncadapter:CallbackUrl>
+ </sdncadapter:RequestHeader>
+ <sdncadapterworkflow:SDNCRequestData>
+ <request-information>
+ <request-id>${MsoUtils.xmlEscape(requestId)}</request-id>
+ <request-action>${MsoUtils.xmlEscape(requestAction)}</request-action>
+ <source>${MsoUtils.xmlEscape(source)}</source>
+ <notification-url></notification-url>
+ <order-number></order-number>
+ <order-version></order-version>
+ </request-information>
+ <service-information>
+ <service-id>${MsoUtils.xmlEscape(serviceId)}</service-id>
+ <service-type>${MsoUtils.xmlEscape(serviceType)}</service-type>
+ <service-instance-id>${MsoUtils.xmlEscape(serviceInstanceId)}</service-instance-id>
+ <subscriber-name>${MsoUtils.xmlEscape(subscriberName)}</subscriber-name>
+ </service-information>
+ <network-request-information>
+ <network-id>${MsoUtils.xmlEscape(networkId)}</network-id>
+ <network-type>${MsoUtils.xmlEscape(networkType)}</network-type>
+ <network-name>${MsoUtils.xmlEscape(networkName)}</network-name>
+ <tenant>${MsoUtils.xmlEscape(tenantId)}</tenant>
+ <aic-cloud-region>${MsoUtils.xmlEscape(aicCloudRegion)}</aic-cloud-region>
+ </network-request-information>
+ </sdncadapterworkflow:SDNCRequestData>
+ </aetgt:SDNCAdapterWorkflowRequest>""".trim()
+
+ return content
+ }
+
+ /**
+ * Builds a topology SDNC request and return String request.
+ * As V2 will use 1607-style request, region instead of aic clli code
+ * @param execution, the execution
+ * @param requestXML, the incoming request for the flow
+ * @param serviceInstanceId, the serviceIntance (if available)
+ * @param callbackUrl, the call back url
+ * @param action, the action element value
+ * @param requestAction the svcOperation element value
+ * @param cloudRegionId the aai's cloud-region-id
+ * @param networkId the aai's network-id
+ * @param additionalData additional XML content to be inserted into the
+ * RequestData element (may be null)
+ */
+ public String sdncTopologyRequestRsrc (DelegateExecution execution, String requestXML, String serviceInstanceId, String callbackUrl, String action, String requestAction, String cloudRegionId, networkId, String additionalData) {
+ def utils=new MsoUtils()
+
+ // SNDC is expecting request Id for header as unique each call.
+ String hdrRequestId = ""
+ String testHdrRequestId = execution.getVariable("testMessageId") // for test purposes.
+ if (testHdrRequestId == null) {
+ hdrRequestId = UUID.randomUUID() // generate unique
+ } else {
+ hdrRequestId = testHdrRequestId
+ }
+
+ String requestId = ""
+ String testRequestId = execution.getVariable("testMessageId") // for test purposes.
+ if (testRequestId == null) {
+ requestId = execution.getVariable("mso-request-id")
+ if (requestId == null) {
+ requestId = execution.getVariable("msoRequestId")
+ }
+ } else {
+ requestId = testRequestId
+ }
+
+ String aicCloudRegion = cloudRegionId
+ String tenantId = ""
+ if (utils.nodeExists(requestXML, "tenant-id")) {
+ tenantId = utils.getNodeText(requestXML, "tenant-id")
+ }
+ String networkType = ""
+ if (utils.nodeExists(requestXML, "network-type")) {
+ networkType = utils.getNodeText(requestXML, "network-type")
+ }
+
+ String subscriptionServiceType = ""
+ if (utils.nodeExists(requestXML, "subscription-service-type")) {
+ subscriptionServiceType = utils.getNodeText(requestXML, "subscription-service-type")
+ }
+
+ String globalCustomerId = ""
+ if (utils.nodeExists(requestXML, "global-customer-id")) {
+ globalCustomerId = utils.getNodeText(requestXML, "global-customer-id")
+ }
+
+ String serviceId = ""
+ if (utils.nodeExists(requestXML, "service-id")) {
+ serviceId = utils.getNodeText(requestXML, "service-id")
+ }
+ String networkName = ""
+ if (utils.nodeExists(requestXML, "network-name")) {
+ networkName = utils.getNodeText(requestXML, "network-name")
+ }
+ String source = ""
+ if (utils.nodeExists(requestXML, "source")) {
+ source = utils.getNodeText(requestXML, "source")
+ }
+
+ // get resourceLink from subflow execution variable
+ String serviceType = ""
+ String subscriberName = ""
+ String siRelatedLink = execution.getVariable("GENGSI_siResourceLink")
+ if (siRelatedLink != null) {
+ // get service type
+ int serviceStart = siRelatedLink.indexOf("service-subscription/")
+ int serviceEnd = siRelatedLink.indexOf("/service-instances/")
+ serviceType = siRelatedLink.substring(serviceStart + 21, serviceEnd)
+ serviceType = UriUtils.decode(serviceType,"UTF-8")
+ // get subscriber name
+ int subscriberNameStart = siRelatedLink.indexOf("customers/customer/")
+ int subscriberNameEnd = siRelatedLink.indexOf("/service-subscriptions/")
+ subscriberName = siRelatedLink.substring(subscriberNameStart + 19, subscriberNameEnd)
+ subscriberName = UriUtils.decode(subscriberName,"UTF-8")
+ }
+
+ // network-information from 'networkModelInfo' // verify the DB Catalog response
+ String networkModelInfo = utils.getNodeXml(requestXML, "networkModelInfo", false).replace("tag0:","").replace(":tag0","")
+ String modelInvariantUuid = utils.getNodeText(networkModelInfo, "modelInvariantUuid") !=null ?
+ utils.getNodeText(networkModelInfo, "modelInvariantUuid") : ""
+ String modelCustomizationUuid = utils.getNodeText(networkModelInfo, "modelCustomizationUuid") !=null ?
+ utils.getNodeText(networkModelInfo, "modelCustomizationUuid") : ""
+ String modelUuid = utils.getNodeText(networkModelInfo, "modelUuid") !=null ?
+ utils.getNodeText(networkModelInfo, "modelUuid") : ""
+ String modelVersion = utils.getNodeText(networkModelInfo, "modelVersion") !=null ?
+ utils.getNodeText(networkModelInfo, "modelVersion") : ""
+ String modelName = utils.getNodeText(networkModelInfo, "modelName") !=null ?
+ utils.getNodeText(networkModelInfo, "modelName") : ""
+
+ // service-information from 'networkModelInfo' // verify the DB Catalog response
+ String serviceModelInfo = utils.getNodeXml(requestXML, "serviceModelInfo", false).replace("tag0:","").replace(":tag0","")
+ String serviceModelInvariantUuid = utils.getNodeText(serviceModelInfo, "modelInvariantUuid") !=null ?
+ utils.getNodeText(serviceModelInfo, "modelInvariantUuid") : ""
+ String serviceModelUuid = utils.getNodeText(serviceModelInfo, "modelUuid") !=null ?
+ utils.getNodeText(serviceModelInfo, "modelUuid") : ""
+ String serviceModelVersion = utils.getNodeText(serviceModelInfo, "modelVersion") !=null ?
+ utils.getNodeText(serviceModelInfo, "modelVersion") : ""
+ String serviceModelName = utils.getNodeText(serviceModelInfo, "modelName") !=null ?
+ utils.getNodeText(serviceModelInfo, "modelName") : ""
+
+
+ String content =
+ """<aetgt:SDNCAdapterWorkflowRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1"
+ xmlns:sdncadapter="http://org.onap.so/workflow/sdnc/adapter/schema/v1"
+ xmlns:sdncadapterworkflow="http://org.onap/so/workflow/schema/v1">
+ <sdncadapter:RequestHeader>
+ <sdncadapter:RequestId>${MsoUtils.xmlEscape(hdrRequestId)}</sdncadapter:RequestId>
+ <sdncadapter:SvcInstanceId>${MsoUtils.xmlEscape(serviceInstanceId)}</sdncadapter:SvcInstanceId>
+ <sdncadapter:SvcAction>${MsoUtils.xmlEscape(action)}</sdncadapter:SvcAction>
+ <sdncadapter:SvcOperation>network-topology-operation</sdncadapter:SvcOperation>
+ <sdncadapter:CallbackUrl>sdncCallback</sdncadapter:CallbackUrl>
+ <sdncadapter:MsoAction>generic-resource</sdncadapter:MsoAction>
+ </sdncadapter:RequestHeader>
+ <sdncadapterworkflow:SDNCRequestData>
+ <request-information>
+ <request-id>${MsoUtils.xmlEscape(requestId)}</request-id>
+ <request-action>${MsoUtils.xmlEscape(requestAction)}</request-action>
+ <source>${MsoUtils.xmlEscape(source)}</source>
+ <notification-url></notification-url>
+ <order-number></order-number>
+ <order-version></order-version>
+ </request-information>
+ <service-information>
+ <service-id>${MsoUtils.xmlEscape(serviceId)}</service-id>
+ <subscription-service-type>${MsoUtils.xmlEscape(subscriptionServiceType)}</subscription-service-type>
+ <onap-model-information>
+ <model-invariant-uuid>${MsoUtils.xmlEscape(serviceModelInvariantUuid)}</model-invariant-uuid>
+ <model-uuid>${MsoUtils.xmlEscape(serviceModelUuid)}</model-uuid>
+ <model-version>${MsoUtils.xmlEscape(serviceModelVersion)}</model-version>
+ <model-name>${MsoUtils.xmlEscape(serviceModelName)}</model-name>
+ </onap-model-information>
+ <service-instance-id>${MsoUtils.xmlEscape(serviceInstanceId)}</service-instance-id>
+ <global-customer-id>${MsoUtils.xmlEscape(globalCustomerId)}</global-customer-id>
+ <subscriber-name>${MsoUtils.xmlEscape(subscriberName)}</subscriber-name>
+ </service-information>
+ <network-information>
+ <network-id>${MsoUtils.xmlEscape(networkId)}</network-id>
+ <network-type>${MsoUtils.xmlEscape(networkType)}</network-type>
+ <onap-model-information>
+ <model-invariant-uuid>${MsoUtils.xmlEscape(modelInvariantUuid)}</model-invariant-uuid>
+ <model-customization-uuid>${MsoUtils.xmlEscape(modelCustomizationUuid)}</model-customization-uuid>
+ <model-uuid>${MsoUtils.xmlEscape(modelUuid)}</model-uuid>
+ <model-version>${MsoUtils.xmlEscape(modelVersion)}</model-version>
+ <model-name>${MsoUtils.xmlEscape(modelName)}</model-name>
+ </onap-model-information>
+ </network-information>
+ <network-request-input>
+ <network-name>${MsoUtils.xmlEscape(networkName)}</network-name>
+ <tenant>${MsoUtils.xmlEscape(tenantId)}</tenant>
+ <aic-cloud-region>${MsoUtils.xmlEscape(aicCloudRegion)}</aic-cloud-region>
+ <aic-clli></aic-clli>
+ <network-input-parameters/>
+ </network-request-input>
+ </sdncadapterworkflow:SDNCRequestData>
+ </aetgt:SDNCAdapterWorkflowRequest>""".trim()
+
+ return content
+ }
+
+ /**
+ * Validates a workflow response.
+ * @param execution the execution
+ * @param responseVar the execution variable in which the response is stored
+ * @param workflowException the WorkflowException Object returned from sdnc call
+ */
+ public void validateSDNCResponse(DelegateExecution execution, String response, WorkflowException workflowException, boolean successIndicator){
+ msoLogger.debug("SDNC Response is: " + response)
+ msoLogger.debug("SuccessIndicator is: " + successIndicator)
+
+ try {
+ def prefix = execution.getVariable('prefix')
+ execution.setVariable(prefix+'sdncResponseSuccess', false)
+ msoLogger.debug("Response" + ' = ' + (response == null ? "" : System.lineSeparator()) + response)
+
+ if (successIndicator){
+ if (response == null || response.trim().equals("")) {
+ msoLogger.debug(response + ' is empty');
+ exceptionUtil.buildAndThrowWorkflowException(execution, 500, "SDNCAdapter Workflow Response is Empty")
+ }else{
+
+ // we need to peer into the request data for error
+ def String sdncAdapterWorkflowResponse = taskProcessor.utils.getNodeXml(response, 'response-data', false)
+ def String decodedXml = sdncAdapterWorkflowResponse.replace('<?xml version="1.0" encoding="UTF-8"?>', "")
+ decodedXml = taskProcessor.utils.getNodeXml(response, 'RequestData')
+ msoLogger.debug("decodedXml:\n" + decodedXml)
+
+ int requestDataResponseCode = 200
+ def String requestDataResponseMessage = ''
+
+ try{
+ if (taskProcessor.utils.nodeExists(decodedXml, "response-message")) {
+ requestDataResponseMessage = taskProcessor.utils.getNodeText(decodedXml, "response-message")
+ } else if (taskProcessor.utils.nodeExists(sdncAdapterWorkflowResponse, "ResponseMessage")) {
+ requestDataResponseMessage = taskProcessor.utils.getNodeText(sdncAdapterWorkflowResponse, "ResponseMessage")
+ }
+ }catch(Exception e){
+ msoLogger.debug('Error caught while decoding resposne ' + e.getMessage())
+ }
+
+ if(taskProcessor.utils.nodeExists(decodedXml, "response-code")) {
+ msoLogger.debug("response-code node Exist ")
+ String code = taskProcessor.utils.getNodeText(decodedXml, "response-code")
+ if(code.isEmpty() || code.equals("")){
+ // if response-code is blank then Success
+ msoLogger.debug("response-code node is empty")
+ requestDataResponseCode = 0
+ }else{
+ requestDataResponseCode = code.toInteger()
+ msoLogger.debug("response-code is: " + requestDataResponseCode)
+ }
+ }else if(taskProcessor.utils.nodeExists(sdncAdapterWorkflowResponse, "ResponseCode")){
+ msoLogger.debug("ResponseCode node Exist ")
+ String code = taskProcessor.utils.getNodeText(sdncAdapterWorkflowResponse, "ResponseCode")
+ if(code.isEmpty() || code.equals("")){
+ // if ResponseCode blank then Success
+ msoLogger.debug("ResponseCode node is empty")
+ requestDataResponseCode = 0
+ }else{
+ requestDataResponseCode = code.toInteger()
+ msoLogger.debug("ResponseCode is: " + requestDataResponseCode)
+ }
+ }else{
+ msoLogger.debug("A Response Code DOES NOT Exist.")
+ // if a response code does not exist then Success
+ requestDataResponseCode = 0
+ }
+ try{
+
+ execution.setVariable(prefix+'sdncRequestDataResponseCode', requestDataResponseCode.toString())
+ // if a response code is 0 or 2XX then Success
+ if ((requestDataResponseCode >= 200 && requestDataResponseCode <= 299) || requestDataResponseCode == 0) {
+ execution.setVariable(prefix+'sdncResponseSuccess', true)
+ msoLogger.debug("Setting sdncResponseSuccess to True ")
+ msoLogger.debug("Exited ValidateSDNCResponse Method")
+ }else{
+ ExceptionUtil exceptionUtil = new ExceptionUtil()
+ String convertedCode = exceptionUtil.MapSDNCResponseCodeToErrorCode(requestDataResponseCode.toString())
+ int convertedCodeInt = Integer.parseInt(convertedCode)
+ exceptionUtil.buildAndThrowWorkflowException(execution, convertedCodeInt, "Received error from SDN-C: " + requestDataResponseMessage)
+ }
+
+ }catch(Exception e){
+ //TODO proper handling of new, non numerical response codes in 1607 and new error handling for common API
+ requestDataResponseCode = 500
+ }
+
+ msoLogger.debug("SDNC callback response-code: " + requestDataResponseCode)
+ msoLogger.debug("SDNC callback response-message: " + requestDataResponseMessage)
+ }
+
+ }else {
+ msoLogger.debug('SDNCAdapter Subflow did NOT complete Successfully. SuccessIndicator is False. ')
+ if(workflowException != null){
+ exceptionUtil.buildAndThrowWorkflowException(execution, workflowException.getErrorCode(), workflowException.getErrorMessage())
+ }else{
+ //TODO : what error code and error message use here
+ exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Internal Error - SDNCAdapter Subflow did NOT complete successfully.")
+ }
+ }
+
+ } catch (BpmnError e) {
+ throw e;
+ } catch (Exception e) {
+ msoLogger.debug('END of Validate SDNC Response')
+ exceptionUtil.buildAndThrowWorkflowException(execution, 500, 'Internal Error- Unable to validate SDNC Response ');
+ }
+ }
+
+ /**
+ * Validates a workflow response.
+ * @param execution the execution
+ * @param responseVar the execution variable in which the response is stored
+ * @param responseCodeVar the execution variable in which the response code is stored
+ * @param errorResponseVar the execution variable in which the error response is stored
+ */
+ public void validateL3BondingSDNCResp(DelegateExecution execution, String response, WorkflowException workflowException, boolean success) {
+ def method = getClass().getSimpleName() + '.validateL3BondingSDNCResp(' +
+ 'execution=' + execution.getId() +
+ ', response=' + response +
+ ')'
+ msoLogger.trace('Entered ' + method)
+ def prefix = execution.getVariable('prefix')
+ TrinityExceptionUtil trinityExceptionUtil = new TrinityExceptionUtil()
+
+ try {
+ execution.setVariable(prefix+'sdncResponseSuccess', false)
+
+ msoLogger.debug("sdncAdapter Success Indicator is: " + success)
+ if (success) {
+
+ // we need to look inside the request data for error
+ def String callbackRequestData = taskProcessor.utils.getNodeXml(response, 'RequestData', false)
+ def String decodedXml = callbackRequestData
+ msoLogger.debug("decodedXml:\n" + decodedXml)
+
+ def requestDataResponseCode = '200'
+ def requestDataResponseMessage = ''
+ int intDataResponseCode = 200
+
+ if (taskProcessor.utils.nodeExists(decodedXml, "response-code")) {
+
+ requestDataResponseCode = ((String) taskProcessor.utils.getNodeText(decodedXml, "response-code"))
+ if (taskProcessor.utils.nodeExists(decodedXml, "response-message")) {
+ requestDataResponseMessage = taskProcessor.utils.getNodeText(decodedXml, "response-message")
+ }
+ }else if(taskProcessor.utils.nodeExists(decodedXml, "ResponseCode")){
+ requestDataResponseCode = ((String) taskProcessor.utils.getNodeText(decodedXml, "ResponseCode")).toInteger()
+ }else if(taskProcessor.utils.nodeExists(response, "ResponseCode")){
+ requestDataResponseCode = ((String) taskProcessor.utils.getNodeText(response, "ResponseCode")).toInteger()
+ requestDataResponseMessage = taskProcessor.utils.getNodeText(response, "ResponseMessage")
+ }
+
+ msoLogger.debug("SDNC callback response-code: " + requestDataResponseCode)
+ msoLogger.debug("SDNC callback response-message: " + requestDataResponseMessage)
+
+ // Get the AAI Status to determine if rollback is needed on ASSIGN
+ def aai_status = ''
+ if (taskProcessor.utils.nodeExists(decodedXml, "aai-status")) {
+ aai_status = ((String) taskProcessor.utils.getNodeText(decodedXml, "aai-status"))
+ msoLogger.debug("SDNC sent AAI STATUS code: " + aai_status)
+ }
+ if (aai_status != null && !aai_status.equals("")) {
+ execution.setVariable(prefix+"AaiStatus",aai_status)
+ msoLogger.debug("Set variable " + prefix + "AaiStatus: " + execution.getVariable(prefix+"AaiStatus"))
+ }
+
+ // Get the result string to determine if rollback is needed on ASSIGN in Add Bonding flow only
+ def sdncResult = ''
+ if (taskProcessor.utils.nodeExists(decodedXml, "result")) {
+ sdncResult = ((String) taskProcessor.utils.getNodeText(decodedXml, "result"))
+ msoLogger.debug("SDNC sent result: " + sdncResult)
+ }
+ if (sdncResult != null && !sdncResult.equals("")) {
+ execution.setVariable(prefix+"SdncResult",sdncResult)
+ msoLogger.debug("Set variable " + prefix + "SdncResult: " + execution.getVariable(prefix+"SdncResult"))
+ }
+
+ try{
+ intDataResponseCode = Integer.parseInt(String.valueOf(requestDataResponseCode))
+ }catch(Exception e){
+ intDataResponseCode = 400
+ }
+
+ msoLogger.debug("intDataResponseCode " + intDataResponseCode )
+
+ // if response-code is not Success (200, 201, etc) we need to throw an exception
+ if ((intDataResponseCode < 200 || intDataResponseCode > 299) && intDataResponseCode != 0) {
+ execution.setVariable(prefix+'ResponseCode', intDataResponseCode)
+ execution.setVariable("L3HLAB_rollback", true)
+ def msg = trinityExceptionUtil.mapSDNCAdapterExceptionToErrorResponse(response, execution)
+ exceptionUtil.buildAndThrowWorkflowException(execution, intDataResponseCode, "Received error from SDN-C: " + msg)
+
+ }
+ }else {
+ msoLogger.warn(MessageEnum.BPMN_GENERAL_WARNING, 'sdncAdapter did not complete successfully, sdncAdapter Success Indicator was false ', "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, 'sdncAdapter did not complete successfully, sdncAdapter Success Indicator was false ');
+ execution.setVariable("L3HLAB_rollback", true)
+ def msg = trinityExceptionUtil.intDataResponseCode(response, execution)
+ exceptionUtil.buildAndThrowWorkflowException(execution, intDataResponseCode, msg)
+ }
+
+ if (response == null || response.trim().equals("")) {
+ msoLogger.warn(MessageEnum.BPMN_GENERAL_WARNING, 'sdncAdapter workflow response is empty', "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, 'sdncAdapter workflow response is empty');;
+ execution.setVariable("L3HLAB_rollback", true)
+ def msg = trinityExceptionUtil.buildException("Exception occurred while validating SDNC response " , execution)
+ exceptionUtil.buildAndThrowWorkflowException(execution, intResponseCode, msg)
+ }
+
+ execution.setVariable(prefix+'sdncResponseSuccess', true)
+ msoLogger.trace('Exited ' + method)
+ } catch (BpmnError e) {
+ throw e;
+ } catch (Exception e) {
+ msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e);
+ execution.setVariable(prefix+"ResponseCode",400)
+ execution.setVariable("L3HLAB_rollback", true)
+ def msg = trinityExceptionUtil.buildException("Exception occurred while validating SDNC response: " + e.getMessage(), execution)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 400, msg)
+ }
+ }
+
+ public String modelInfoToEcompModelInformation(String jsonModelInfo) {
+ String modelInvariantUuid = jsonUtil.getJsonValue(jsonModelInfo, "modelInvariantUuid")
+ String modelUuid = jsonUtil.getJsonValue(jsonModelInfo, "modelUuid")
+ if (modelUuid == null) {
+ modelUuid = ""
+ }
+ String modelCustomizationUuid = jsonUtil.getJsonValue(jsonModelInfo, "modelCustomizationUuid")
+ String modelCustomizationString = ""
+ if (modelCustomizationUuid != null) {
+ modelCustomizationString = "<model-customization-uuid>${MsoUtils.xmlEscape(modelCustomizationUuid)}</model-customization-uuid>"
+ }
+ String modelVersion = jsonUtil.getJsonValue(jsonModelInfo, "modelVersion")
+ if (modelVersion == null) {
+ modelVersion = ""
+ }
+ String modelName = jsonUtil.getJsonValue(jsonModelInfo, "modelName")
+ String ecompModelInformation =
+ """<onap-model-information>
+ <model-invariant-uuid>${MsoUtils.xmlEscape(modelInvariantUuid)}</model-invariant-uuid>
+ <model-uuid>${MsoUtils.xmlEscape(modelUuid)}</model-uuid>
+ ${modelCustomizationString}
+ <model-version>${MsoUtils.xmlEscape(modelVersion)}</model-version>
+ <model-name>${MsoUtils.xmlEscape(modelName)}</model-name>
+ </onap-model-information>"""
+
+ return ecompModelInformation
+ }
+} \ No newline at end of file
diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/ServiceTaskProcessor.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/ServiceTaskProcessor.groovy
new file mode 100644
index 0000000000..4e2ed0970f
--- /dev/null
+++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/ServiceTaskProcessor.groovy
@@ -0,0 +1,33 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.so.bpmn.common.scripts;
+
+import org.camunda.bpm.engine.delegate.DelegateExecution
+import org.camunda.bpm.engine.delegate.DelegateExecution
+
+
+/**
+ * @version 1.0
+ *
+ */
+public interface ServiceTaskProcessor {
+ public void preProcessRequest(DelegateExecution execution);
+}
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
new file mode 100644
index 0000000000..8d14ead6e0
--- /dev/null
+++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/SniroHomingV1.groovy
@@ -0,0 +1,260 @@
+/*
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.so.bpmn.common.scripts
+
+import org.camunda.bpm.engine.delegate.BpmnError
+import org.camunda.bpm.engine.delegate.DelegateExecution
+
+import org.onap.so.bpmn.common.scripts.AaiUtil
+import org.onap.so.bpmn.common.scripts.ExceptionUtil
+import org.onap.so.bpmn.common.scripts.SDNCAdapterUtils
+import org.onap.so.bpmn.core.UrnPropertiesReader
+import org.onap.so.bpmn.core.domain.InventoryType
+import org.onap.so.bpmn.core.domain.Resource
+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.bpmn.common.scripts.AbstractServiceTaskProcessor
+
+import org.json.JSONArray
+import org.json.JSONObject
+
+import static org.onap.so.bpmn.common.scripts.GenericUtils.*;
+import org.onap.so.logger.MessageEnum
+import org.onap.so.logger.MsoLogger
+
+
+/**
+ * This class is contains the scripts used
+ * by the Homing Subflow building block. The
+ * subflow attempts to home the provided
+ * resources by calling sniro.
+ *
+ * @author cb645j
+ *
+ */
+class SniroHomingV1 extends AbstractServiceTaskProcessor{
+
+ private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, SniroHomingV1.class);
+ ExceptionUtil exceptionUtil = new ExceptionUtil()
+ JsonUtils jsonUtil = new JsonUtils()
+ SniroUtils sniroUtils = new SniroUtils(this)
+
+ /**
+ * This method validates the incoming variables.
+ * The method then prepares the sniro request
+ * and posts it to sniro's rest api.
+ *
+ * @param execution
+ *
+ * @author cb645j
+ */
+ public void callSniro(DelegateExecution execution){
+ execution.setVariable("prefix","HOME_")
+ msoLogger.trace("Started Sniro Homing Call Sniro ")
+ try{
+ execution.setVariable("rollbackData", null)
+ execution.setVariable("rolledBack", false)
+
+ String requestId = execution.getVariable("msoRequestId")
+ msoLogger.debug("Incoming Request Id is: " + requestId)
+ String serviceInstanceId = execution.getVariable("serviceInstanceId")
+ msoLogger.debug("Incoming Service Instance Id is: " + serviceInstanceId)
+ ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition")
+ msoLogger.debug("Incoming Service Decomposition is: " + serviceDecomposition)
+ String subscriberInfo = execution.getVariable("subscriberInfo")
+ msoLogger.debug("Incoming Subscriber Information is: " + subscriberInfo)
+
+ if(isBlank(requestId) || isBlank(serviceInstanceId) || isBlank(serviceDecomposition.toString()) || isBlank(subscriberInfo)){
+ exceptionUtil.buildAndThrowWorkflowException(execution, 4000, "A required input variable is missing or null")
+ }else{
+ String subId = jsonUtil.getJsonValue(subscriberInfo, "globalSubscriberId")
+ String subName = jsonUtil.getJsonValue(subscriberInfo, "subscriberName")
+ String subCommonSiteId = ""
+ if(jsonUtil.jsonElementExist(subscriberInfo, "subscriberCommonSiteId")){
+ subCommonSiteId = jsonUtil.getJsonValue(subscriberInfo, "subscriberCommonSiteId")
+ }
+ Subscriber subscriber = new Subscriber(subId, subName, subCommonSiteId)
+
+ String cloudConfiguration = execution.getVariable("cloudConfiguration") // TODO Currently not being used
+ String homingParameters = execution.getVariable("homingParameters") // (aka. request parameters) Should be json format. TODO confirm its json format
+
+ //Authentication
+ String authHeader = UrnPropertiesReader.getVariable("sniro.manager.headers.auth", execution)
+ execution.setVariable("BasicAuthHeaderValue", authHeader)
+
+ //Prepare Callback
+ String timeout = execution.getVariable("timeout")
+ if(isBlank(timeout)){
+ timeout = UrnPropertiesReader.getVariable("sniro.manager.timeout", execution)
+ if(isBlank(timeout)) {
+ timeout = "PT30M";
+ }
+ }
+ msoLogger.debug("Async Callback Timeout will be: " + timeout)
+
+ execution.setVariable("timeout", timeout);
+ execution.setVariable("correlator", requestId);
+ execution.setVariable("messageType", "SNIROResponse");
+
+ //Build Request & Call Sniro
+ String sniroRequest = sniroUtils.buildRequest(execution, requestId, serviceDecomposition, subscriber, homingParameters)
+ execution.setVariable("sniroRequest", sniroRequest)
+ msoLogger.debug("SNIRO Request is: " + sniroRequest)
+
+ 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)
+
+ RESTConfig config = new RESTConfig(url);
+ RESTClient client = new RESTClient(config).addAuthorizationHeader(authHeader).addHeader("Content-Type", "application/json")
+ APIResponse response = client.httpPost(sniroRequest)
+
+ int responseCode = response.getStatusCode()
+ msoLogger.debug("Sniro sync response code is: " + responseCode)
+ msoLogger.debug("Sniro sync response is: " + response.getResponseBodyAsString())
+
+ if(responseCode != 202){
+ exceptionUtil.buildAndThrowWorkflowException(execution, responseCode, "Received a Bad Sync Response from Sniro.")
+ }
+ msoLogger.trace("Completed Sniro Homing Call Sniro")
+ }
+ }catch(BpmnError b){
+ throw b
+ }catch(Exception e){
+ msoLogger.debug("Error encountered within Homing CallSniro method: " + e)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured in Homing CallSniro: " + e.getMessage())
+ }
+ }
+
+ /**
+ * This method processes the callback response
+ * and the contained homing solution. It sets
+ * homing solution assignment and license
+ * information to the corresponding resources
+ *
+ * @param execution
+ *
+ * @author cb645j
+ */
+ public void processHomingSolution(DelegateExecution execution){
+ msoLogger.trace("Started Sniro Homing Process Homing Solution")
+ try{
+ String response = execution.getVariable("asyncCallbackResponse")
+ msoLogger.debug("Sniro Async Callback Response is: " + response)
+
+ sniroUtils.validateCallbackResponse(execution, response)
+
+ ServiceDecomposition decomposition = execution.getVariable("serviceDecomposition")
+ List<Resource> resourceList = decomposition.getServiceResources()
+
+ if(JsonUtils.jsonElementExist(response, "solutionInfo.placementInfo")){
+ String placements = jsonUtil.getJsonValue(response, "solutionInfo.placementInfo")
+ JSONArray arr = new JSONArray(placements)
+ for(int i = 0; i < arr.length(); i++){
+ JSONObject placement = arr.getJSONObject(i)
+ String jsonServiceResourceId = placement.getString("serviceResourceId")
+ for(Resource resource:resourceList){
+ String serviceResourceId = resource.getResourceId()
+ if(serviceResourceId.equalsIgnoreCase(jsonServiceResourceId)){
+ //match
+ String inventoryType = placement.getString("inventoryType")
+ resource.getHomingSolution().setInventoryType(InventoryType.valueOf(inventoryType))
+ resource.getHomingSolution().setCloudRegionId(placement.getString("cloudRegionId"))
+ resource.getHomingSolution().setRehome(placement.getBoolean("isRehome"))
+ JSONArray assignmentArr = placement.getJSONArray("assignmentInfo")
+ Map<String, String> assignmentMap = jsonUtil.entryArrayToMap(execution, assignmentArr.toString(), "variableName", "variableValue")
+ resource.getHomingSolution().setCloudOwner(assignmentMap.get("cloudOwner"))
+ resource.getHomingSolution().setAicClli(assignmentMap.get("aicClli"))
+ resource.getHomingSolution().setAicVersion(assignmentMap.get("aicVersion"))
+ if(inventoryType.equalsIgnoreCase("service")){
+ VnfResource vnf = new VnfResource()
+ vnf.setVnfHostname(assignmentMap.get("vnfHostName"))
+ resource.getHomingSolution().setVnf(vnf)
+ resource.getHomingSolution().setServiceInstanceId(placement.getString("serviceInstanceId"))
+ }
+ }
+ }
+ }
+ }
+
+ if(JsonUtils.jsonElementExist(response, "solutionInfo.licenseInfo")){
+ String licenseInfo = jsonUtil.getJsonValue(response, "solutionInfo.licenseInfo")
+ JSONArray licenseArr = new JSONArray(licenseInfo)
+ for(int l = 0; l < licenseArr.length(); l++){
+ JSONObject license = licenseArr.getJSONObject(l)
+ String jsonServiceResourceId = license.getString("serviceResourceId")
+ for(Resource resource:resourceList){
+ String serviceResourceId = resource.getResourceId()
+ if(serviceResourceId.equalsIgnoreCase(jsonServiceResourceId)){
+ //match
+ String jsonEntitlementPoolList = jsonUtil.getJsonValue(license.toString(), "entitlementPoolList")
+ List<String> entitlementPoolList = jsonUtil.StringArrayToList(execution, jsonEntitlementPoolList)
+ resource.getHomingSolution().getLicense().setEntitlementPoolList(entitlementPoolList)
+
+ String jsonLicenseKeyGroupList = jsonUtil.getJsonValue(license.toString(), "licenseKeyGroupList")
+ List<String> licenseKeyGroupList = jsonUtil.StringArrayToList(execution, jsonLicenseKeyGroupList)
+ resource.getHomingSolution().getLicense().setLicenseKeyGroupList(licenseKeyGroupList)
+ }
+ }
+ }
+ }
+ execution.setVariable("serviceDecomposition", decomposition)
+
+ msoLogger.trace("Completed Sniro Homing Process Homing Solution")
+ }catch(BpmnError b){
+ throw b
+ }catch(Exception e){
+ msoLogger.debug("Error encountered within Homing ProcessHomingSolution method: " + e)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured in Sniro Homing Process Solution")
+ }
+ }
+
+ /**
+ * This method logs the start of DHVCreateService
+ * to make debugging easier.
+ *
+ * @param - execution
+ * @author cb645j
+ */
+ public String logStart(DelegateExecution execution){
+ String requestId = execution.getVariable("testReqId")
+ if(isBlank(requestId)){
+ requestId = execution.getVariable("msoRequestId")
+ }
+ execution.setVariable("DHVCS_requestId", requestId)
+ msoLogger.trace("STARTED Homing Subflow for request: " + requestId + " ")
+ msoLogger.debug("****** Homing Subflow Global Debug Enabled: " + execution.getVariable("isDebugLogEnabled") + " *****")
+ msoLogger.trace("STARTED Homing Subflow for request: " + requestId + " ")
+ }
+
+
+ /**
+ * Auto-generated method stub
+ */
+ public void preProcessRequest(DelegateExecution execution){}
+
+}
diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/SniroUtils.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/SniroUtils.groovy
new file mode 100644
index 0000000000..fd4ab32215
--- /dev/null
+++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/SniroUtils.groovy
@@ -0,0 +1,353 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.so.bpmn.common.scripts
+
+import org.camunda.bpm.engine.delegate.BpmnError
+import org.camunda.bpm.engine.delegate.DelegateExecution
+import org.json.JSONArray
+import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor
+import org.onap.so.bpmn.common.scripts.ExceptionUtil
+import org.onap.so.bpmn.common.scripts.MsoUtils
+import org.onap.so.bpmn.core.domain.*
+import org.onap.so.bpmn.core.json.JsonUtils
+import org.apache.commons.lang3.StringUtils
+
+import static org.onap.so.bpmn.common.scripts.GenericUtils.*
+
+import java.time.Duration
+
+import org.onap.so.logger.MessageEnum
+import org.onap.so.logger.MsoLogger
+
+
+
+class SniroUtils{
+ private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, SniroUtils.class);
+
+
+ ExceptionUtil exceptionUtil = new ExceptionUtil()
+ JsonUtils jsonUtil = new JsonUtils()
+
+ private AbstractServiceTaskProcessor utils
+
+ public MsoUtils msoUtils = new MsoUtils()
+
+ public SniroUtils(AbstractServiceTaskProcessor taskProcessor) {
+ this.utils = taskProcessor
+ }
+
+ /**
+ * This method builds the service-agnostic
+ * sniro json request to get a homing solution
+ * and license solution
+ *
+ * @param execution
+ * @param requestId
+ * @param decomposition - ServiceDecomposition object
+ * @param subscriber - Subscriber information
+ * @param homingParams - Homing/Request parameters
+ *
+ * @return request - sniro v2 payload
+ *
+ * @author cb645j
+ */
+ public String buildRequest(DelegateExecution execution, String requestId, ServiceDecomposition decomposition, Subscriber subscriber, String homingParams){
+ msoLogger.debug("Started Building Sniro Request")
+ def callbackUrl = utils.createWorkflowMessageAdapterCallbackURL(execution, "SNIROResponse", requestId)
+ def transactionId = requestId
+ //ServiceInstance Info
+ ServiceInstance serviceInstance = decomposition.getServiceInstance()
+ def serviceInstanceId
+ if(serviceInstance == null){
+ msoLogger.debug("Unable to obtain Service Instance Id, ServiceInstance Object is null" )
+ exceptionUtil.buildAndThrowWorkflowException(execution, 400, "Internal Error - Unable to obtain Service Instance Id, ServiceInstance Object is null")
+ }else{
+ serviceInstanceId = serviceInstance.getInstanceId()
+ }
+ String type = decomposition.getServiceType()
+ String serviceType = ""
+ if(isNotBlank(type)){
+ serviceType = """ "serviceType": "${type}", """
+ }
+ //Model Info
+ ModelInfo model = decomposition.getModelInfo()
+ String modelType = model.getModelType()
+ String modelInvariantId = model.getModelInvariantUuid()
+ String modelVersionId = model.getModelUuid()
+ String modelName = model.getModelName()
+ String modelVersion = model.getModelVersion()
+ //Subscriber Info
+ String subscriberId = subscriber.getGlobalId()
+ String subscriberName = subscriber.getName()
+ String commonSiteId = subscriber.getCommonSiteId()
+ //OrderInfo
+ String orderInfo
+ if(!isBlank(homingParams)){
+ orderInfo = homingParams.replaceAll("\"", "\\\\\"").replaceAll("\n", "").replaceAll("\r", "")
+ orderInfo = StringUtils.normalizeSpace(orderInfo)
+ }
+
+ //Determine RequestType
+ //TODO Implement better way to determine this
+ String requestType = "initial"
+ List<Resource> resources = decomposition.getServiceResources()
+ for(Resource r:resources){
+ HomingSolution currentSolution = (HomingSolution) r.getCurrentHomingSolution()
+ if(currentSolution != null){
+ requestType = "speed changed"
+ }
+ }
+
+ String timeout = execution.getVariable("timeout")
+ Duration d = Duration.parse(timeout);
+ long timeoutSeconds = d.getSeconds();
+
+ //Demands
+ String placementDemands = ""
+ StringBuilder sb = new StringBuilder()
+ List<Resource> resourceList = decomposition.getAllottedResources()
+ List<VnfResource> vnfResourceList = decomposition.getVnfResources()
+
+ //TODO should be service agnostic so this is just a temp solution to all vnfs to be sent in placement container for adiod
+ if(resourceList.isEmpty() || resourceList == null){
+ search : {
+ for(VnfResource vnf : vnfResourceList){
+ if(StringUtils.containsIgnoreCase(vnf.getNfRole(), "vce") || StringUtils.containsIgnoreCase(vnf.getNfRole(), "vpe")){
+ resourceList = decomposition.getVnfResources()
+ break search
+ }
+ }
+ }
+ }
+
+ if(resourceList.isEmpty() || resourceList == null){
+ msoLogger.debug("Resources List is Empty")
+ }else{
+ for(Resource resource:resourceList){
+ ModelInfo resourceModelInfo = resource.getModelInfo()
+ ResourceInstance resourceInstance = resource.getResourceInstance()
+ def resourceInstanceType = resource.getResourceType()
+ def serviceResourceId = resource.getResourceId() //TODO - resourceId versus instanceId - should be what is put in AAI, whatever we put here will be what is in response, used to correlate
+ def resourceModuleName = resourceModelInfo.getModelInstanceName()
+ def resouceModelCustomizationId = resourceModelInfo.getModelCustomizationUuid()
+ def resouceModelInvariantId = resourceModelInfo.getModelInvariantUuid()
+ def resouceModelName = resourceModelInfo.getModelName()
+ def resouceModelVersion = resourceModelInfo.getModelVersion()
+ def resouceModelVersionId = resourceModelInfo.getModelUuid()
+ def resouceModelType = resourceModelInfo.getModelType()
+ def tenantId = "" //Optional
+ def tenantName = "" //Optional
+
+
+ String existingPlacement = ""
+ HomingSolution currentPlacement = resource.getCurrentHomingSolution()
+ if(currentPlacement != null){
+ String homedServiceInstanceId = currentPlacement.getServiceInstanceId()
+ existingPlacement =
+ ""","existingPlacement": {
+ "serviceInstanceId": "${homedServiceInstanceId}"
+ }"""
+ }
+
+
+ String demand =
+ """{
+ "resourceInstanceType": "${resourceInstanceType}",
+ "serviceResourceId": "${serviceResourceId}",
+ "resourceModuleName": "${resourceModuleName}",
+ "resourceModelInfo": {
+ "modelCustomizationId": "${resouceModelCustomizationId}",
+ "modelInvariantId": "${resouceModelInvariantId}",
+ "modelName": "${resouceModelName}",
+ "modelVersion": "${resouceModelVersion}",
+ "modelVersionId": "${resouceModelVersionId}",
+ "modelType": "${resouceModelType}"
+ },
+ "tenantId": "${tenantId}",
+ "tenantName": "${tenantName}"
+ ${existingPlacement}
+ },"""
+
+ placementDemands = sb.append(demand)
+ }
+ placementDemands = placementDemands.substring(0, placementDemands.length() - 1);
+ }
+
+ String licenseDemands = ""
+ sb = new StringBuilder()
+ if(vnfResourceList.isEmpty() || vnfResourceList == null){
+ msoLogger.debug("Vnf Resources List is Empty")
+ }else{
+ for(VnfResource vnfResource:vnfResourceList){
+ ModelInfo vnfResourceModelInfo = vnfResource.getModelInfo()
+ ResourceInstance vnfResourceInstance = vnfResource.getResourceInstance()
+ def resourceInstanceType = vnfResource.getResourceType()
+ def serviceResourceId = vnfResource.getResourceId()
+ def resourceModuleName = vnfResourceModelInfo.getModelInstanceName()
+ def resouceModelCustomizationId = vnfResourceModelInfo.getModelCustomizationUuid()
+ def resouceModelInvariantId = vnfResourceModelInfo.getModelInvariantUuid()
+ def resouceModelName = vnfResourceModelInfo.getModelName()
+ def resouceModelVersion = vnfResourceModelInfo.getModelVersion()
+ def resouceModelVersionId = vnfResourceModelInfo.getModelUuid()
+ def resouceModelType = vnfResourceModelInfo.getModelType()
+
+ String curentLicenseJson = ""
+ HomingSolution currentSol = vnfResource.getCurrentHomingSolution()
+ if(currentSol != null){
+ JSONArray entitlementPoolList = currentSol.getLicense().getEntitlementPoolListAsString()
+ JSONArray licenseKeyGroupList = currentSol.getLicense().getLicenseKeyGroupListAsString()
+ curentLicenseJson =
+ """ ,"existingLicense": {
+ "entitlementPoolUUID":
+ ${entitlementPoolList},
+ "licenseKeyGroupUUID":
+ ${licenseKeyGroupList}
+
+ }"""
+ }
+
+ String demand =
+ """{
+ "resourceInstanceType": "${resourceInstanceType}",
+ "serviceResourceId": "${serviceResourceId}",
+ "resourceModuleName": "${resourceModuleName}",
+ "resourceModelInfo": {
+ "modelCustomizationId": "${resouceModelCustomizationId}",
+ "modelInvariantId": "${resouceModelInvariantId}",
+ "modelName": "${resouceModelName}",
+ "modelVersion": "${resouceModelVersion}",
+ "modelVersionId": "${resouceModelVersionId}",
+ "modelType": "${resouceModelType}"
+ }
+ ${curentLicenseJson}
+ },"""
+
+ licenseDemands = sb.append(demand)
+ }
+ licenseDemands = licenseDemands.substring(0, licenseDemands.length() - 1);
+ }
+
+ String request =
+ """{
+ "requestInfo": {
+ "transactionId": "${transactionId}",
+ "requestId": "${requestId}",
+ "callbackUrl": "${callbackUrl}",
+ "sourceId": "mso",
+ "requestType": "${requestType}",
+ "optimizer": [
+ "placement",
+ "license"
+ ],
+ "numSolutions": 1,
+ "timeout": ${timeoutSeconds}
+ },
+ "placementInfo": {
+ ${serviceType}
+ "serviceModelInfo": {
+ "modelType": "${modelType}",
+ "modelInvariantId": "${modelInvariantId}",
+ "modelVersionId": "${modelVersionId}",
+ "modelName": "${modelName}",
+ "modelVersion": "${modelVersion}"
+ },
+ "subscriberInfo": {
+ "globalSubscriberId": "${subscriberId}",
+ "subscriberName": "${subscriberName}",
+ "subscriberCommonSiteId": "${commonSiteId}"
+ },
+ "demandInfo": {
+ "placementDemand": [
+ ${placementDemands}
+ ],
+ "licenseDemand": [
+ ${licenseDemands}
+ ]
+ },
+ "policyId": [],
+ "serviceInstanceId": "${serviceInstanceId}",
+ "orderInfo": "{\\\"requestParameters\\\": ${orderInfo}}"
+ }
+ }"""
+
+ msoLogger.debug("Completed Building Sniro Request")
+ return request
+ }
+
+ /**
+ * This method validates the async callback response from Sniro.
+ * If the response contains an exception the method will build
+ * and throw a workflow exception.
+ *
+ * @param execution
+ * @param response - sniro async response
+ *
+ * @author cb645j
+ */
+ //TODO needs updating per sniro changes
+ public void validateCallbackResponse(DelegateExecution execution, String response){
+ try{
+ String placements = ""
+ String licenses = ""
+ if(isBlank(response)){
+ exceptionUtil.buildAndThrowWorkflowException(execution, 5000, "Sniro Async Callback Response is Empty")
+ }else{
+ if(JsonUtils.jsonElementExist(response, "solutionInfo")){
+ if(JsonUtils.jsonElementExist(response, "solutionInfo.placementInfo")){
+ placements = jsonUtil.getJsonValue(response, "solutionInfo.placementInfo")
+ }
+ if(JsonUtils.jsonElementExist(response, "solutionInfo.licenseInfo")){
+ licenses = jsonUtil.getJsonValue(response, "solutionInfo.licenseInfo")
+ }
+ if((isBlank(placements) || placements.equalsIgnoreCase("[]")) && (isBlank(licenses) || licenses.equalsIgnoreCase("[]"))){
+ msoLogger.debug("Sniro Async Response does not contain: licenses or placements")
+ exceptionUtil.buildAndThrowWorkflowException(execution, 400, "Sniro Async Callback Response does not contain: licenses or placements")
+ }else{
+ return
+ }
+ }else if(JsonUtils.jsonElementExist(response, "requestError") == true){
+ String errorMessage = ""
+ if(response.contains("policyException")){
+ String text = jsonUtil.getJsonValue(response, "requestError.policyException.text")
+ errorMessage = "Sniro Async Response contains a policy error: " + text
+ }else if(response.contains("serviceException")){
+ String text = jsonUtil.getJsonValue(response, "requestError.serviceException.text")
+ errorMessage = "Sniro Async Response contains a service error: " + text
+ }else{
+ errorMessage = "Sniro Async Response contains an error: not provided"
+ }
+ msoLogger.debug("Sniro Async Response contains an error: " + errorMessage)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 400, errorMessage)
+
+ }else{
+ msoLogger.debug("Sniro Async Response contains an error: not provided")
+ exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Sniro Async Response contains an error: not provided")
+ }
+ }
+ }catch(BpmnError b){
+ throw b
+ }catch(Exception e){
+ msoLogger.debug("Error encountered within Homing validateCallbackResponse method: " + e)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured in Sniro Homing Validate Async Response")
+ }
+ }
+
+} \ No newline at end of file
diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/TrinityExceptionUtil.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/TrinityExceptionUtil.groovy
new file mode 100644
index 0000000000..3cf1edb8ca
--- /dev/null
+++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/TrinityExceptionUtil.groovy
@@ -0,0 +1,382 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.so.bpmn.common.scripts
+
+import org.camunda.bpm.engine.delegate.DelegateExecution
+import org.apache.commons.lang3.*
+import org.onap.so.logger.MessageEnum
+import org.onap.so.logger.MsoLogger
+
+
+
+class TrinityExceptionUtil {
+ private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, TrinityExceptionUtil.class);
+
+
+
+
+ public static enum Error {
+ SVC_GENERAL_SERVICE_ERROR("SVC0001","Internal Error"),
+ SVC_BAD_PARAMETER("SVC0002", "Invalid input value for message part %1"),
+ SVC_NO_SERVER_RESOURCES("SVC1000", "No server resources available to process the request"),
+ SVC_DETAILED_SERVICE_ERROR("SVC2000", "The following service error occurred: %1. Error code is %2."),
+ POL_GENERAL_POLICY_ERROR("POL0001", "A policy error occurred."),
+ POL_USER_NOT_PROVISIONED("POL1009", "User has not been provisioned for service"),
+ POL_USER_SUSPENDED("POL1010", "User has been suspended from service"),
+ POL_DETAILED_POLICY_ERROR("POL2000", "The following policy error occurred: %1. Error code is %2."),
+ POL_MSG_SIZE_EXCEEDS_LIMIT("POL9003", "Message content size exceeds the allowable limit")
+
+
+ private final String msgId
+ private final String msgTxt
+
+ private Error(String msgId, String msgTxt) {
+ this.msgId = msgId
+ this.msgTxt = msgTxt
+ }
+
+ public String getMsgId() {
+ return msgId
+ }
+
+ public String getMsgTxt() {
+ return msgTxt
+ }
+
+ }
+
+
+
+
+ String mapAdapterExecptionToCommonException(String response, DelegateExecution execution)
+ {
+ def utils=new MsoUtils()
+ def method = getClass().getSimpleName() + '.mapAdapterExecptionToCommonException(' +
+ 'execution=' + execution.getId() +
+ ')'
+
+ msoLogger.trace('Entered ' + method)
+
+
+ def errorCode
+
+
+ try {
+ errorCode = MapCategoryToErrorCode(utils.getNodeText(response, "category"))
+ execution.setVariable(prefix+"err",errorCode)
+ String message = buildException(response, execution)
+ msoLogger.trace("End MapAdapterExecptionToWorkflowException ")
+ return message
+ }catch (Exception ex) {
+ //Ignore the exception - cases include non xml payload
+ msoLogger.debug("error mapping error, ignoring: " + ex)
+ msoLogger.trace("End MapAdapterExecptionToWorkflowException ")
+ return buildException(response, execution)
+ }
+ }
+
+ /**
+ * @param response
+ * @param execution
+ * @return mapped exception
+ */
+ String mapAOTSExecptionToCommonException(String response, DelegateExecution execution)
+ {
+ def utils=new MsoUtils()
+
+ def prefix=execution.getVariable("prefix")
+ def method = getClass().getSimpleName() + '.mapAOTSExecptionToCommonException(' +
+ 'execution=' + execution.getId() +
+ ')'
+
+ msoLogger.trace('Entered ' + method)
+
+
+ try {
+ def errorCode = utils.getNodeText(response,"code")
+ def descr = utils.getNodeText(response, "description")
+ def mappedErr = mapErrorCodetoError(errorCode, descr)
+ if(mappedErr == Error.SVC_DETAILED_SERVICE_ERROR || mappedError == Error.POL_DETAILED_POLICY_ERROR){
+ ArrayList myVars = new ArrayList()
+ myVars.add(descr)
+ myVars.add(errorCode)
+ execution.setVariable(prefix+"errVariables", myVars)
+ }
+ execution.setVariable(prefix+"err",mappedErr)
+ def message = buildException("Received error from AOTS: " + descr, execution)
+ msoLogger.trace("End MapAOTSExecptionToCommonException ")
+ return message
+ }catch (Exception ex) {
+ //Ignore the exception - cases include non xml payload
+ msoLogger.debug("error mapping error, ignoring: " + ex)
+ msoLogger.trace("End MapAOTSExecptionToCommonException ")
+ return buildException(response, execution)
+ }
+ }
+
+ String mapSDNCAdapterExceptionToErrorResponse(String sdncAdapterCallbackRequest, DelegateExecution execution) {
+ def utils=new MsoUtils()
+ def prefix=execution.getVariable("prefix")
+ def method = getClass().getSimpleName() + '.mapSDNCAdapterExceptionToErrorResponse(' +
+ 'execution=' + execution.getId() +
+ ')'
+
+ msoLogger.trace('Entered ' + method)
+
+ def sdncResponseCode
+ String responseCode = execution.getVariable(prefix+"ResponseCode")
+ msoLogger.debug('responseCode to map: ' + responseCode)
+ def errorMessage
+
+ try {
+
+ if(utils.nodeExists(sdncAdapterCallbackRequest, "RequestData")) {
+ def reqDataXml = utils.getNodeXml(sdncAdapterCallbackRequest, "RequestData")
+ errorMessage = utils.getNodeText(reqDataXml, "response-message")
+ sdncResponseCode = utils.getNodeText(reqDataXml, "response-code")
+ }else{
+ errorMessage = utils.getNodeText(sdncAdapterCallbackRequest, "ResponseMessage")
+ sdncResponseCode = responseCode
+ }
+ def mappedErr = mapErrorCodetoError(responseCode, errorMessage)
+ errorMessage = errorMessage
+ def modifiedErrorMessage = "Received error from SDN-C: " + errorMessage
+ if(mappedErr == Error.SVC_DETAILED_SERVICE_ERROR || mappedErr == Error.POL_DETAILED_POLICY_ERROR){
+ ArrayList myVars = new ArrayList()
+ myVars.add(errorMessage)
+ myVars.add(sdncResponseCode)
+ execution.setVariable(prefix+"errVariables", myVars)
+ }
+ execution.setVariable(prefix+"err",mappedErr)
+ def message = buildException(modifiedErrorMessage, execution)
+
+
+ msoLogger.trace("End MapSDNCAdapterException ")
+ return message
+ }catch (Exception ex) {
+ //Ignore the exception - cases include non xml payload
+ msoLogger.debug("error mapping sdnc error, ignoring: " + ex)
+ msoLogger.trace("End MapSDNCAdapterException ")
+ return null
+ }
+
+ }
+
+ /**
+ * @param response message from called component (ex: AAI)
+ * @param execution
+ * @return an error response conforming to the common
+ */
+ String mapAAIExceptionTCommonException(String response, DelegateExecution execution)
+ {
+ def utils=new MsoUtils()
+ def prefix=execution.getVariable("prefix")
+ def method = getClass().getSimpleName() + '.mapAAIExceptionTCommonException(' +
+ 'execution=' + execution.getId() +
+ ')'
+
+ msoLogger.trace('Entered ' + method)
+ def variables
+ def message
+ String errorCode = 'SVC0001'
+ msoLogger.debug("response: " + response)
+ //they use the same format we do, pass their error along
+ //TODO add Received error from A&AI at beg of text
+ try {
+ message = utils.getNodeXml(response, "requestError")
+ message = utils.removeXmlNamespaces(message)
+ } catch (Exception ex) {
+ //Ignore the exception - cases include non xml payload
+ message = buildException("Received error from A&AI, unable to parse",execution)
+ msoLogger.debug("error mapping error, ignoring: " + ex)
+ }
+
+ if(message != null) {
+ execution.setVariable(prefix+"ErrorResponse",message)
+ msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Fault", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, execution.getVariable(prefix+"ErrorResponse"));
+ return message
+ } else {
+
+ return null
+
+ }
+ }
+
+ /**
+ * @param execution
+ * @return an error response conforming to the common API with default text msg
+ */
+ String buildException(execution){
+ return buildException(null, execution)
+ }
+
+ /**
+ * @param response message from called component (ex: AAI)
+ * @param execution
+ * @return an error response conforming to the common
+ */
+ String buildException(response, execution){
+ def utils=new MsoUtils()
+ def method = getClass().getSimpleName() + '.buildException(' +
+ 'execution=' + execution.getId() +
+ ')'
+
+ msoLogger.trace('Entered ' + method)
+ def prefix=execution.getVariable("prefix")
+ def responseCode = String.valueOf(execution.getVariable(prefix+"ResponseCode"))
+ def variables
+ msoLogger.debug("response: " + response)
+
+ try {
+ msoLogger.debug("formatting error message" )
+ def msgVars = execution.getVariable(prefix+"errVariables")
+ def myErr = execution.getVariable(prefix+"err")
+ def messageTxt = execution.getVariable(prefix+"errTxt")
+ def messageId = null
+
+ if(myErr == null){
+ msoLogger.debug("mapping response code: " + responseCode)
+ myErr = mapErrorCodetoError(responseCode, response)
+ if(myErr == null){
+ //not a service or policy error, just return error code
+ return ""
+ }
+ }
+ messageId = myErr.getMsgId()
+
+ if(messageTxt == null){
+ if(myErr!=null){
+ messageTxt = myErr.getMsgTxt()
+ }else{
+ messageTxt = response
+ }
+ }
+
+ if(msgVars==null && (myErr == Error.SVC_DETAILED_SERVICE_ERROR || myErr == Error.POL_DETAILED_POLICY_ERROR)){
+ msgVars = new ArrayList()
+ msgVars.add(response)
+ msgVars.add(responseCode)
+ }
+
+ def msgVarsXML=""
+ StringBuffer msgVarsBuff = new StringBuffer()
+ if(msgVars!=null){
+ for(String msgVar : msgVars){
+ msgVarsBuff.append(
+ """
+ <tns:variables>${MsoUtils.xmlEscape(msgVar)}</tns:variables>""")
+ }
+
+ }
+ def message = ""
+ if(messageId.startsWith("SVC")){
+ message = """<tns:requestError xmlns:tns="http://org.onap/so/request/types/v1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://org.onap/so/request/types/v1 MsoServiceInstanceTypesV1.xsd">
+ <tns:serviceException>
+ <tns:messageId>${MsoUtils.xmlEscape(messageId)}</tns:messageId>
+ <tns:text>${MsoUtils.xmlEscape(messageTxt)}</tns:text>${msgVarsBuff}
+ </tns:serviceException>
+</tns:requestError>"""
+ }else{
+ message ="""<tns:requestError xmlns:tns="http://org.onap/so/request/types/v1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://org.onap/so/request/types/v1 MsoServiceInstanceTypesV1.xsd">
+ <tns:policyException>
+ <tns:messageId>${MsoUtils.xmlEscape(messageId)}</tns:messageId>
+ <tns:text>${MsoUtils.xmlEscape(messageTxt)}</tns:text>${msgVarsBuff}
+ </tns:policyException>
+</tns:requestError>"""
+ }
+ msoLogger.debug("message " + message)
+ execution.setVariable(prefix+"ErrorResponse",message)
+ execution.setVariable(prefix+"err", myErr)
+ execution.setVariable(prefix+"errTxt", messageTxt)
+ execution.setVariable(prefix+"errVariables", msgVars)
+ msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Fault", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, execution.getVariable(prefix+"ErrorResponse"));
+ return message
+ }catch(Exception ex) {
+ msoLogger.debug("error mapping error, return null: " + ex)
+ return null
+ }
+
+ }
+
+ String parseError(DelegateExecution execution){
+ def utils=new MsoUtils()
+ def prefix=execution.getVariable("prefix")
+ def text = execution.getVariable(prefix+"errTxt")
+ def msgVars = execution.getVariable(prefix+"errVariables")
+ msoLogger.debug('parsing message: ' + text)
+ if(text == null){
+ return 'failed'
+ }
+ if(msgVars!=null && !msgVars.isEmpty()){
+ for(int i=0; i<msgVars.size(); i++){
+ text = text.replaceFirst("%"+(i+1), msgVars[i])
+ }
+ }
+ msoLogger.debug('parsed message is: ' + text)
+ return text
+ }
+
+
+
+ Error mapErrorCodetoError(responseCode, descr)
+ {
+
+ if(responseCode==null || responseCode=='0' || responseCode=='500' || responseCode =='408'){
+ return Error.SVC_NO_SERVER_RESOURCES
+ }else if(responseCode == '401' || responseCode == '405' || responseCode == '409' || responseCode == '503'){
+ return null
+ }else if(responseCode == '400'){
+ if(descr==null){
+ return Error.SVC_GENERAL_SERVICE_ERROR
+ }else{
+ return Error.SVC_DETAILED_SERVICE_ERROR
+ }
+ }else if(responseCode == '401'){
+ if(descr==null){
+ return Error.POL_GENERAL_POLICY_ERROR
+ }else{
+ return Error.POL_DETAILED_POLICY_ERROR
+ }
+ }else{
+ return Error.SVC_NO_SERVER_RESOURCES
+ }
+ }
+
+ String mapCategoryToErrorCode(String errorCategory)
+ {
+ if(errorCategory.equals('OPENSTACK'))
+ return Error.SVC_NO_SERVER_RESOURCES
+ else if (errorCategory.equals('IO'))
+ return Error.SVC_NO_SERVER_RESOURCES
+ else if (errorCategory.equals('INTERNAL'))
+ return Error.SVC_NO_SERVER_RESOURCES
+ else if (errorCategory.equals('USERDATA'))
+ return Error.SVC_GENERAL_SERVICE_ERROR
+ else
+ return Error.SVC_GENERAL_SERVICE_ERROR
+ }
+
+
+
+
+
+
+} \ No newline at end of file
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
new file mode 100644
index 0000000000..7d7b9e103f
--- /dev/null
+++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/UpdateAAIGenericVnf.groovy
@@ -0,0 +1,345 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.so.bpmn.common.scripts
+
+import 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.rest.APIResponse
+import org.springframework.web.util.UriUtils
+import org.onap.so.logger.MessageEnum
+import org.onap.so.logger.MsoLogger
+
+
+
+
+public class UpdateAAIGenericVnf extends AbstractServiceTaskProcessor {
+ private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, UpdateAAIGenericVnf.class);
+
+
+ private XmlParser xmlParser = new XmlParser()
+ ExceptionUtil exceptionUtil = new ExceptionUtil()
+
+ /**
+ * Initialize the flow's variables.
+ *
+ * @param execution The flow's execution instance.
+ */
+ public void initProcessVariables(DelegateExecution execution) {
+ execution.setVariable('prefix', 'UAAIGenVnf_')
+ execution.setVariable('UAAIGenVnf_vnfId', null)
+ execution.setVariable('UAAIGenVnf_personaModelId', null)
+ execution.setVariable('UAAIGenVnf_personaModelVersion', null)
+ execution.setVariable("UAAIGenVnf_ipv4OamAddress", null)
+ execution.setVariable('UAAIGenVnf_managementV6Address', null)
+ execution.setVariable('UAAIGenVnf_orchestrationStatus', null)
+ execution.setVariable('UAAIGenVnf_getGenericVnfResponseCode' ,null)
+ execution.setVariable('UAAIGenVnf_getGenericVnfResponse', '')
+ execution.setVariable('UAAIGenVnf_updateGenericVnfResponseCode', null)
+ execution.setVariable('UAAIGenVnf_updateGenericVnfResponse', '')
+ }
+
+ /**
+ * Check for missing elements in the received request.
+ *
+ * @param execution The flow's execution instance.
+ */
+ public void preProcessRequest(DelegateExecution execution) {
+ def method = getClass().getSimpleName() + '.preProcessRequest(' +
+ 'execution=' + execution.getId() +
+ ')'
+ msoLogger.trace('Entered ' + method)
+
+ try {
+ def xml = execution.getVariable('UpdateAAIGenericVnfRequest')
+ msoLogger.debug('Received request xml:\n' + xml)
+ msoLogger.debug("UpdateAAIGenericVnf Request XML: " + xml)
+ initProcessVariables(execution)
+
+ def vnfId = getRequiredNodeText(execution, xml,'vnf-id')
+ execution.setVariable('UAAIGenVnf_vnfId', vnfId)
+
+ def personaModelId = getNodeTextForce(xml,'persona-model-id')
+ if (personaModelId != null && !personaModelId.isEmpty()) {
+ execution.setVariable('UAAIGenVnf_personaModelId', personaModelId)
+ }
+
+ def personaModelVersion = getNodeTextForce(xml,'persona-model-version')
+ if (personaModelVersion != null && !personaModelVersion.isEmpty()) {
+ execution.setVariable('UAAIGenVnf_personaModelVersion', personaModelVersion)
+ }
+
+ def ipv4OamAddress = getNodeTextForce(xml, 'ipv4-oam-address')
+ if (ipv4OamAddress != null && !ipv4OamAddress.isEmpty()) {
+ execution.setVariable('UAAIGenVnf_ipv4OamAddress', ipv4OamAddress)
+ }
+
+ def managementV6Address = getNodeTextForce(xml, 'management-v6-address')
+ if (managementV6Address != null && !managementV6Address.isEmpty()) {
+ execution.setVariable('UAAIGenVnf_managementV6Address', managementV6Address)
+ }
+
+ def orchestrationStatus = getNodeTextForce(xml, 'orchestration-status')
+ if (orchestrationStatus != null && !orchestrationStatus.isEmpty()) {
+ execution.setVariable('UAAIGenVnf_orchestrationStatus', orchestrationStatus)
+ }
+
+ msoLogger.trace('Exited ' + method)
+ } catch (BpmnError e) {
+ throw e;
+ } catch (Exception e) {
+ msoLogger.error(e);
+ exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in preProcessRequest(): ' + e.getMessage())
+ }
+ }
+
+ /**
+ * Using the received vnfId, query AAI to get the corresponding Generic VNF.
+ * A 200 response is expected with the VF Module in the response body.
+ *
+ * @param execution The flow's execution instance.
+ */
+ public void getGenericVnf(DelegateExecution execution) {
+ def method = getClass().getSimpleName() + '.getGenericVnf(' +
+ 'execution=' + execution.getId() +
+ ')'
+ msoLogger.trace('Entered ' + method)
+
+ try {
+ def vnfId = execution.getVariable('UAAIGenVnf_vnfId')
+
+ // Construct endpoint
+ AaiUtil aaiUriUtil = new AaiUtil(this)
+ def aai_uri = aaiUriUtil.getNetworkGenericVnfUri(execution)
+ msoLogger.debug('AAI URI is: ' + aai_uri)
+ String endPoint = UrnPropertiesReader.getVariable("aai.endpoint", execution) + aai_uri + '/' + UriUtils.encode(vnfId, "UTF-8") + "?depth=1"
+
+ 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);
+ 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);
+ exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in getGenericVnf(): ' + e.getMessage())
+ }
+ }
+
+ /**
+ * Construct and send a PUT request to AAI to update the Generic VNF.
+ *
+ * @param execution The flow's execution instance.
+ */
+ public void updateGenericVnf(DelegateExecution execution) {
+ def method = getClass().getSimpleName() + '.updateGenericVnf(' +
+ 'execution=' + execution.getId() +
+ ')'
+ msoLogger.trace('Entered ' + method)
+
+ try {
+ def vnfId = execution.getVariable('UAAIGenVnf_vnfId')
+ def 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 = ""
+ 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)) {
+ 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, "");
+ throw new Exception(msg)
+ }
+
+ // Construct payload
+ personaModelVersionEntry = updateGenericVnfNode(origRequest, genericVnfNode, 'model-version-id')
+ }
+
+ // Handle ipv4-oam-address
+ def String ipv4OamAddress = execution.getVariable('UAAIGenVnf_ipv4OamAddress')
+ def String ipv4OamAddressEntry = ""
+ if (ipv4OamAddress != null) {
+ // Construct payload
+ ipv4OamAddressEntry = updateGenericVnfNode(origRequest, genericVnfNode, 'ipv4-oam-address')
+ }
+
+ // Handle management-v6-address
+ def String managementV6Address = execution.getVariable('UAAIGenVnf_managementV6Address')
+ def String managementV6AddressEntry = ""
+ if (managementV6Address != null) {
+ // Construct payload
+ managementV6AddressEntry = updateGenericVnfNode(origRequest, genericVnfNode, 'management-v6-address')
+ }
+
+ // Handle orchestration-status
+ def String orchestrationStatus = execution.getVariable('UAAIGenVnf_orchestrationStatus')
+ def String orchestrationStatusEntry = ""
+ if (orchestrationStatus != null) {
+ // Construct payload
+ orchestrationStatusEntry = updateGenericVnfNode(origRequest, genericVnfNode, 'orchestration-status')
+ }
+
+ def payload = """
+ { ${personaModelVersionEntry}
+ ${ipv4OamAddressEntry}
+ ${managementV6AddressEntry}
+ ${orchestrationStatusEntry}
+ "vnf-id": "${vnfId}"
+ }
+ """
+
+ // Construct endpoint
+ AaiUtil aaiUriUtil = new AaiUtil(this)
+ def aai_uri = aaiUriUtil.getNetworkGenericVnfUri(execution)
+ msoLogger.debug('AAI URI is: ' + aai_uri)
+ String endPoint = UrnPropertiesReader.getVariable("aai.endpoint", execution) + aai_uri + '/' + UriUtils.encode(vnfId, "UTF-8")
+
+ 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)
+ } catch (Exception ex) {
+ ex.printStackTrace()
+ msoLogger.debug('Exception occurred while executing AAI PATCH:' + ex.getMessage())
+ execution.setVariable('UAAIGenVnf_updateGenericVnfResponseCode', 500)
+ execution.setVariable('UAAIGenVnf_updateGenericVnfResponse', 'AAI PATCH Failed:' + ex.getMessage())
+ }
+ msoLogger.trace('Exited ' + method)
+ } catch (BpmnError e) {
+ throw e;
+ } catch (Exception e) {
+ msoLogger.error(e);
+ exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in updateGenericVnf(): ' + e.getMessage())
+ }
+ }
+
+ /**
+ * Sets up json attributes for PATCH request for Update
+ *
+ * @param origRequest Incoming update request with Generic VNF element(s) to be updated.
+ * @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) {
+
+ if (!utils.nodeExists(origRequest, elementName)) {
+ return ""
+ }
+ def elementValue = utils.getNodeText(origRequest, elementName)
+
+ if (elementValue.equals('DELETE')) {
+ // Set the element being deleted to null
+ return """"${elementName}": null,"""
+ }
+ else {
+ return """"${elementName}": "${elementValue}","""
+ }
+
+ }
+
+ /**
+ * Generates a WorkflowException if the AAI query returns a response code other than 200.
+ *
+ * @param execution The flow's execution instance.
+ */
+ public void handleAAIQueryFailure(DelegateExecution execution) {
+ def method = getClass().getSimpleName() + '.handleAAIQueryFailure(' +
+ 'execution=' + execution.getId() +
+ ')'
+ msoLogger.trace('Entered ' + method)
+
+ 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)
+
+ msoLogger.debug("Workflow Exception occurred when handling Quering AAI: " + 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 handleUpdateGenericVnfFailure(DelegateExecution execution) {
+ def method = getClass().getSimpleName() + '.handleUpdateGenericVnfFailure(' +
+ 'execution=' + execution.getId() +
+ ')'
+ msoLogger.trace('Entered ' + method)
+
+ msoLogger.error('Error occurred attempting to update Generic VNF in AAI, Response Code ' + execution.getVariable('UAAIGenVnf_updateGenericVnfResponseCode'));
+
+ String processKey = getProcessKey(execution);
+ WorkflowException exception = new WorkflowException(processKey, 5000,
+ execution.getVariable('UAAIGenVnf_updateGenericVnfResponse'))
+ execution.setVariable('WorkflowException', exception)
+
+ 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
new file mode 100644
index 0000000000..68b2df213a
--- /dev/null
+++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/UpdateAAIVfModule.groovy
@@ -0,0 +1,369 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.so.bpmn.common.scripts
+
+import 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.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);
+
+
+ private XmlParser xmlParser = new XmlParser()
+ ExceptionUtil exceptionUtil = new ExceptionUtil()
+
+ /**
+ * Initialize the flow's variables.
+ *
+ * @param execution The flow's execution instance.
+ */
+ public void initProcessVariables(DelegateExecution execution) {
+ execution.setVariable('prefix', 'UAAIVfMod_')
+ execution.setVariable('UAAIVfMod_vnfId', null)
+ execution.setVariable('UAAIVfMod_vfModuleId', null)
+ execution.setVariable('UAAIVfMod_orchestrationStatus', null)
+ execution.setVariable('UAAIVfMod_heatStackId', null)
+ execution.setVariable('UAAIVfMod_volumeGroupId', null)
+ execution.setVariable('UAAIVfMod_getVfModuleResponseCode' ,null)
+ execution.setVariable('UAAIVfMod_getVfModuleResponse', '')
+ execution.setVariable('UAAIVfMod_updateVfModuleResponseCode', null)
+ execution.setVariable('UAAIVfMod_updateVfModuleResponse', '')
+ }
+
+ /**
+ * Check for missing elements in the received request.
+ *
+ * @param execution The flow's execution instance.
+ */
+ public void preProcessRequest(DelegateExecution execution) {
+ def method = getClass().getSimpleName() + '.preProcessRequest(' +
+ 'execution=' + execution.getId() +
+ ')'
+ msoLogger.trace('Entered ' + method)
+
+ try {
+ def xml = execution.getVariable('UpdateAAIVfModuleRequest')
+ msoLogger.debug('Received request xml:\n' + xml)
+ initProcessVariables(execution)
+
+ def vnfId = getRequiredNodeText(execution, xml,'vnf-id')
+ execution.setVariable('UAAIVfMod_vnfId', vnfId)
+
+ def vfModuleId = getRequiredNodeText(execution, xml,'vf-module-id')
+ execution.setVariable('UAAIVfMod_vfModuleId', vfModuleId)
+
+ msoLogger.trace('Exited ' + method)
+ } catch (BpmnError e) {
+ throw e;
+ } catch (Exception e) {
+ msoLogger.error(e);
+ exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in preProcessRequest(): ' + e.getMessage())
+ }
+ }
+
+ /**
+ * Using the received vnfId and vfModuleId, query AAI to get the corresponding VF Module.
+ * A 200 response is expected with the VF Module in the response body.
+ *
+ * @param execution The flow's execution instance.
+ */
+ public void getVfModule(DelegateExecution execution) {
+ def method = getClass().getSimpleName() + '.getVfModule(' +
+ 'execution=' + execution.getId() +
+ ')'
+ msoLogger.trace('Entered ' + method)
+
+ try {
+ def vnfId = execution.getVariable('UAAIVfMod_vnfId')
+ def vfModuleId = execution.getVariable('UAAIVfMod_vfModuleId')
+
+ // Construct endpoint
+ AaiUtil aaiUriUtil = new AaiUtil(this)
+ def aai_uri = aaiUriUtil.getNetworkGenericVnfUri(execution)
+ msoLogger.debug('AAI URI is: ' + aai_uri)
+ String endPoint = UrnPropertiesReader.getVariable("aai.endpoint", execution) + aai_uri + '/' + UriUtils.encode(vnfId, "UTF-8") + '/vf-modules/vf-module/' + UriUtils.encode(vfModuleId, "UTF-8")
+
+ 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)
+ } 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) {
+ msoLogger.error(e);
+ exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in getVfModule(): ' + e.getMessage())
+ }
+ }
+
+ /**
+ * Construct and send a PATCH request to AAI to update the VF Module.
+ *
+ * @param execution The flow's execution instance.
+ */
+ public void updateVfModule(DelegateExecution execution) {
+ def method = getClass().getSimpleName() + '.updateVfModule(' +
+ 'execution=' + execution.getId() +
+ ')'
+ msoLogger.trace('Entered ' + method)
+
+ try {
+ def vnfId = execution.getVariable('UAAIVfMod_vnfId')
+ def vfModuleId = execution.getVariable('UAAIVfMod_vfModuleId')
+ def 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')
+ def String newPersonaModelVersion = utils.getNodeText(origRequest, 'persona-model-version')
+ if ((newPersonaModelId == null) || (newPersonaModelVersion == null)) {
+ doPersonaModelVersion = false
+ } else {
+ // Confirm "new" persona-model-id is same as "current" persona-model-id
+ def String currPersonaModelId = utils.getChildNodeText(vfModuleNode, 'model-invariant-id')
+ if (currPersonaModelId == null) {
+ // check the old attribute name
+ currPersonaModelId = utils.getChildNodeText(vfModuleNode, 'model-version-id')
+ }
+ if (currPersonaModelId == null) {
+ currPersonaModelId = ''
+ }
+ if (!newPersonaModelId.equals(currPersonaModelId)) {
+ def msg = 'Can\'t update VF Module ' + vfModuleId + ' since there is \'persona-model-id\' mismatch between the current and new values'
+ msoLogger.error(msg)
+ throw new Exception(msg)
+ }
+ }
+
+ // Construct payload
+ String orchestrationStatusEntry = updateVfModuleNode(origRequest, vfModuleNode, 'orchestration-status')
+ String heatStackIdEntry = updateVfModuleNode(origRequest, vfModuleNode, 'heat-stack-id')
+ String personaModelVersionEntry = ""
+ if (doPersonaModelVersion) {
+ personaModelVersionEntry = updateVfModuleNode(origRequest, vfModuleNode, 'persona-model-version')
+ }
+ String contrailServiceInstanceFqdnEntry = updateVfModuleNode(origRequest, vfModuleNode, 'contrail-service-instance-fqdn')
+ def payload = """
+ { ${orchestrationStatusEntry}
+ ${heatStackIdEntry}
+ ${personaModelVersionEntry}
+ ${contrailServiceInstanceFqdnEntry}
+ "vf-module-id": "${vfModuleId}"
+ }
+ """
+
+
+ // Construct endpoint
+ AaiUtil aaiUriUtil = new AaiUtil(this)
+ def aai_uri = aaiUriUtil.getNetworkGenericVnfUri(execution)
+ msoLogger.debug('AAI URI is: ' + aai_uri)
+ String endPoint = UrnPropertiesReader.getVariable("aai.endpoint", execution) + aai_uri + '/' + UriUtils.encode(vnfId, "UTF-8") + '/vf-modules/vf-module/' + UriUtils.encode(vfModuleId, "UTF-8")
+
+ try {
+ msoLogger.debug('sending PATCH to AAI endpoint \'' + endPoint + '\'' + 'with payload \n' + payload)
+ msoLogger.debug("Sending PATCH to AAI endpoint: " + endPoint)
+
+ APIResponse response = aaiUriUtil.executeAAIPatchCall(execution, endPoint, payload)
+ def responseData = response.getResponseBodyAsString()
+ execution.setVariable('UAAIVfMod_updateVfModuleResponseCode', response.getStatusCode())
+ execution.setVariable('UAAIVfMod_updateVfModuleResponse', responseData)
+ msoLogger.debug("UpdateAAIVfModule Response data: " + responseData)
+ msoLogger.debug('Response code:' + response.getStatusCode())
+ msoLogger.debug('Response:' + System.lineSeparator() + responseData)
+ } catch (Exception ex) {
+ ex.printStackTrace()
+ msoLogger.debug('Exception occurred while executing AAI PATCH:' + ex.getMessage())
+ execution.setVariable('UAAIVfMod_updateVfModuleResponseCode', 500)
+ execution.setVariable('UAAIVfMod_updateVfModuleResponse', 'AAI PATCH Failed:' + ex.getMessage())
+ }
+ msoLogger.trace('Exited ' + method)
+ } catch (BpmnError e) {
+ throw e;
+ } catch (Exception e) {
+ msoLogger.error(e);
+ exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in updateVfModule(): ' + e.getMessage())
+ }
+ }
+
+ /**
+ * 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) {
+
+ if (!utils.nodeExists(origRequest, elementName)) {
+ return ""
+ }
+ def elementValue = utils.getNodeText(origRequest, elementName)
+
+ if (elementValue.equals('DELETE')) {
+ // Set the element being deleted to null
+ return """"${elementName}": null,"""
+ }
+ else {
+ return """"${elementName}": "${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.
+ *
+ * @param execution The flow's execution instance.
+ */
+ public void handleAAIQueryFailure(DelegateExecution execution) {
+ def method = getClass().getSimpleName() + '.handleAAIQueryFailure(' +
+ 'execution=' + execution.getId() +
+ ')'
+ msoLogger.trace('Entered ' + method)
+
+ msoLogger.error( 'Error occurred attempting to query AAI, Response Code ' + execution.getVariable('UAAIVfMod_getVfModuleResponseCode'));
+ String processKey = getProcessKey(execution);
+ WorkflowException exception = new WorkflowException(processKey, 5000,
+ execution.getVariable('UAAIVfMod_getVfModuleResponse'))
+ execution.setVariable('WorkflowException', exception)
+ 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/VfModule.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/VfModule.groovy
new file mode 100644
index 0000000000..b20cc38b8b
--- /dev/null
+++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/VfModule.groovy
@@ -0,0 +1,93 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.so.bpmn.common.scripts;
+
+import org.apache.commons.lang3.*
+import org.onap.so.logger.MessageEnum
+import org.onap.so.logger.MsoLogger
+
+
+
+public class VfModule implements Serializable {
+ private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, VfModule.class);
+
+
+ /**
+ * Class representing a VF Module Node. Fields of this class include indicators
+ * as to whether the VF Module is the only VF Module in its containing Generic VNF
+ * and whether the VF Module is the base VF Module in its containing Generic VNF.
+ */
+
+ private Node node
+ private Boolean onlyVfModule
+ private Boolean baseVfModule
+
+ /**
+ * Constructor.
+ *
+ * @param node Node representing the VF Module xml.
+ * @param onlyVfModule Is this VF Module the only VF Module in its containing Generic VNF?
+ */
+ public VfModule(Node node, boolean onlyVfModule) {
+ this.node = node
+ this.onlyVfModule = onlyVfModule
+ this.baseVfModule = getElementText('is-base-vf-module').equals('true')
+ }
+
+ /**
+ * Get the Node representing the VF Module xml.
+ *
+ * @return the Node representing the VF Module xml.
+ */
+ public Node getNode() {
+ return node
+ }
+
+ public String getElementText(String childNodeName) {
+ def Node childNode = (new MsoUtils()).getChildNode(node, childNodeName)
+ if (childNode == null) {
+ return ''
+ } else {
+ return childNode.text()
+ }
+ }
+
+ /**
+ * Is this VF Module the only VF Module in its containing Generic VNF?
+ *
+ * @return true if this VF Module is the only VF Module in its containing Generic VNF;
+ * false otherwise.
+ */
+ public boolean isOnlyVfModule() {
+ return onlyVfModule
+ }
+
+ /**
+ * Is this VF Module the base VF Module in its containing Generic VNF?
+ *
+ * @return true if this VF Module is the base VF Module in its containing Generic VNF;
+ * false otherwise.
+ */
+ public boolean isBaseVfModule() {
+ return baseVfModule
+ }
+}
+
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
new file mode 100644
index 0000000000..fec140da33
--- /dev/null
+++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/VfModuleBase.groovy
@@ -0,0 +1,1285 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.so.bpmn.common.scripts;
+
+import 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
+import org.w3c.dom.NodeList
+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);
+
+
+ protected XmlParser xmlParser = new XmlParser()
+
+ /**
+ * Get the XmlParser.
+ *
+ * @return the XmlParser.
+ */
+ protected XmlParser getXmlParser() {
+ return xmlParser
+ }
+
+ /**
+ * Find the VF Module with specified ID in the specified Generic VF. If no such
+ * VF Module is found, null is returned.
+ *
+ * @param genericVnf The Generic VNF in which to search for the specified VF Moduel.
+ * @param vfModuleId The ID of the VF Module for which to search.
+ * @return a VFModule object for the found VF Module or null if no VF Module is found.
+ */
+ protected VfModule findVfModule(String genericVnf, String vfModuleId) {
+
+ def genericVnfNode = xmlParser.parseText(genericVnf)
+ def vfModulesNode = utils.getChildNode(genericVnfNode, 'vf-modules')
+ if (vfModulesNode == null) {
+ return null
+ }
+ def vfModuleList = utils.getIdenticalChildren(vfModulesNode, 'vf-module')
+ for (vfModuleNode in vfModuleList) {
+ def vfModuleIdNode = utils.getChildNode(vfModuleNode, 'vf-module-id')
+ if ((vfModuleIdNode != null) && (vfModuleIdNode.text().equals(vfModuleId))) {
+ return new VfModule(vfModuleNode, (vfModuleList.size() == 1))
+ }
+ }
+ return null
+ }
+
+ /**
+ * Transform all '*_network' parameter specifications from the incoming '*-params' root
+ * element to a corresponding list of 'vnf-networks' specifications (typically used when
+ * invoking the VNF Rest Adpater). Each element in '*-params' whose name attribute ends
+ * with '_network' is used to create an 'vnf-networks' element.
+ *
+ * @param paramsNode A Node representing a '*-params' element.
+ * @return a String of 'vnf-networks' elements, one for each 'param' element whose name
+ * attribute ends with '_network'.
+ */
+ protected String transformNetworkParamsToVnfNetworks(String paramsRootXml) {
+ if ((paramsRootXml == null) || (paramsRootXml.isEmpty())) {
+ return ''
+ }
+ def String vnfNetworks = ''
+ try {
+ paramsRootXml = utils.removeXmlNamespaces(paramsRootXml)
+ def paramsNode = xmlParser.parseText(paramsRootXml)
+ def params = utils.getIdenticalChildren(paramsNode, 'param')
+ for (param in params) {
+ def String attrName = (String) param.attribute('name')
+ if (attrName.endsWith('_network')) {
+ def networkRole = attrName.substring(0, (attrName.length()-'_network'.length()))
+ def networkName = param.text()
+ String vnfNetwork = """
+ <vnf-networks>
+ <network-role>${MsoUtils.xmlEscape(networkRole)}</network-role>
+ <network-name>${MsoUtils.xmlEscape(networkName)}</network-name>
+ </vnf-networks>
+ """
+ vnfNetworks = vnfNetworks + vnfNetwork
+ }
+ }
+ } catch (Exception e) {
+ msoLogger.warn(MessageEnum.BPMN_GENERAL_WARNING, 'Exception transforming network params to vnfNetworks', "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, 'Exception is: \n' + e);
+ }
+ return vnfNetworks
+ }
+
+ /**
+ * Transform the parameter specifications from the incoming '*-params' root element to
+ * a corresponding list of 'entry's (typically used when invoking the VNF Rest Adpater).
+ * Each element in '*-params' is used to create an 'entry' element.
+ *
+ * @param paramsNode A Node representing a '*-params' element.
+ * @return a String of 'entry' elements, one for each 'param' element.
+ */
+ protected String transformParamsToEntries(String paramsRootXml) {
+ if ((paramsRootXml == null) || (paramsRootXml.isEmpty())) {
+ return ''
+ }
+ def String entries = ''
+ try {
+ paramsRootXml = utils.removeXmlNamespaces(paramsRootXml)
+ def paramsNode = xmlParser.parseText(paramsRootXml)
+ def params = utils.getIdenticalChildren(paramsNode, 'param')
+ for (param in params) {
+ def key = (String) param.attribute('name')
+ if (key == null) {
+ key = ''
+ }
+ def value = (String) param.text()
+ String entry = """
+ <entry>
+ <key>${MsoUtils.xmlEscape(key)}</key>
+ <value>${MsoUtils.xmlEscape(value)}</value>
+ </entry>
+ """
+ entries = entries + entry
+ }
+ } catch (Exception e) {
+ msoLogger.warn(MessageEnum.BPMN_GENERAL_WARNING, 'Exception transforming params to entries', "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, 'Exception transforming params to entries', e);
+ }
+ return entries
+ }
+
+ /**
+ * Transform the parameter specifications from the incoming '*-params' root element to
+ * a corresponding list of 'entry's (typically used when invoking the VNF Rest Adpater).
+ * Each element in '*-params' is used to create an 'entry' element.
+ *
+ * @param paramsNode A Node representing a '*-params' element.
+ * @return a String of 'entry' elements, one for each 'param' element.
+ */
+ protected String transformVolumeParamsToEntries(String paramsRootXml) {
+ if ((paramsRootXml == null) || (paramsRootXml.isEmpty())) {
+ return ''
+ }
+ def String entries = ''
+ try {
+ paramsRootXml = utils.removeXmlNamespaces(paramsRootXml)
+ def paramsNode = xmlParser.parseText(paramsRootXml)
+ def params = utils.getIdenticalChildren(paramsNode, 'param')
+ for (param in params) {
+ def key = (String) param.attribute('name')
+ if (key == null) {
+ key = ''
+ }
+ if ( !(key in ['vnf_id', 'vnf_name', 'vf_module_id', 'vf_module_name'])) {
+ def value = (String) param.text()
+ String entry = """
+ <entry>
+ <key>${MsoUtils.xmlEscape(key)}</key>
+ <value>${MsoUtils.xmlEscape(value)}</value>
+ </entry>
+ """
+ entries = entries + entry
+ }
+ }
+ } catch (Exception e) {
+ msoLogger.warn(MessageEnum.BPMN_GENERAL_WARNING, 'Exception transforming params to entries', "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, 'Exception transforming params to entries', e);
+ }
+ 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.
+ * @param vnfParamsMap - map of VNF parameters passed in the request body
+ * @param sdncGetResponse - response string from SDNC GET topology request
+ * @param vnfId
+ * @param vnfName
+ * @param vfModuleId
+ * @param vfModuleName
+ * @param vfModuleIndex - can be null
+ * @return a String of key/value entries for vfModuleParams
+ */
+
+
+ protected String buildVfModuleParams(Map<String, String> vnfParamsMap, String sdncGetResponse, String vnfId, String vnfName,
+ String vfModuleId, String vfModuleName, String vfModuleIndex, String environmentContext, String workloadContext) {
+
+ //Get SDNC Response Data
+
+ String data = utils.getNodeXml(sdncGetResponse, "response-data")
+
+ String serviceData = utils.getNodeXml(data, "service-data")
+ serviceData = utils.removeXmlPreamble(serviceData)
+ serviceData = utils.removeXmlNamespaces(serviceData)
+ String vnfRequestInfo = utils.getNodeXml(serviceData, "vnf-request-information")
+ String oldVnfId = utils.getNodeXml(vnfRequestInfo, "vnf-id")
+ oldVnfId = utils.removeXmlPreamble(oldVnfId)
+ oldVnfId = utils.removeXmlNamespaces(oldVnfId)
+ serviceData = serviceData.replace(oldVnfId, "")
+ def vnfId1 = utils.getNodeText(serviceData, "vnf-id")
+
+ Map<String, String> paramsMap = new HashMap<String, String>()
+
+ if (vfModuleIndex != null) {
+ paramsMap.put("vf_module_index", "${vfModuleIndex}")
+ }
+
+ // Add-on data
+ paramsMap.put("vnf_id", "${vnfId}")
+ paramsMap.put("vnf_name", "${vnfName}")
+ paramsMap.put("vf_module_id", "${vfModuleId}")
+ paramsMap.put("vf_module_name", "${vfModuleName}")
+ paramsMap.put("environment_context", "${environmentContext}")
+ paramsMap.put("workload_context", "${workloadContext}")
+
+ InputSource source = new InputSource(new StringReader(data));
+ DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
+ docFactory.setNamespaceAware(true)
+ DocumentBuilder docBuilder = docFactory.newDocumentBuilder()
+ Document responseXml = docBuilder.parse(source)
+
+
+ // Availability Zones Data
+
+ NodeList aZonesList = responseXml.getElementsByTagNameNS("*", "availability-zones")
+ String aZonePosition = "0"
+ for (int z = 0; z < aZonesList.getLength(); z++) {
+ Node node = aZonesList.item(z)
+ if (node.getNodeType() == Node.ELEMENT_NODE) {
+ Element eElement = (Element) node
+ String aZoneValue = utils.getElementText(eElement, "availability-zone")
+ aZonePosition = z.toString()
+ paramsMap.put("availability_zone_${aZonePosition}", "${aZoneValue}")
+ }
+ }
+
+ // Map of network-roles and network-tags from vm-networks
+
+ NodeList vmNetworksListGlobal = responseXml.getElementsByTagNameNS("*", "vm-networks")
+ Map<String, String> networkRoleMap = new HashMap<String, String>()
+ for(int n = 0; n < vmNetworksListGlobal.getLength(); n++){
+ Node nodeNetworkKey = vmNetworksListGlobal.item(n)
+ if (nodeNetworkKey.getNodeType() == Node.ELEMENT_NODE) {
+ Element eElementNetworkKey = (Element) nodeNetworkKey
+ String networkRole = utils.getElementText(eElementNetworkKey, "network-role")
+ String networkRoleValue = utils.getElementText(eElementNetworkKey, "network-role-tag")
+ if (networkRoleValue.isEmpty()) {
+ networkRoleValue = networkRole
+ }
+ networkRoleMap.put(networkRole, networkRoleValue)
+ }
+ }
+
+ // VNF Networks Data
+
+ StringBuilder sbNet = new StringBuilder()
+
+ NodeList vnfNetworkList = responseXml.getElementsByTagNameNS("*", "vnf-networks")
+ for (int x = 0; x < vnfNetworkList.getLength(); x++) {
+ Node node = vnfNetworkList.item(x)
+ if (node.getNodeType() == Node.ELEMENT_NODE) {
+ Element eElement = (Element) node
+ String vnfNetworkKey = utils.getElementText(eElement, "network-role-tag")
+ String networkRole = utils.getElementText(eElement, "network-role")
+ if (vnfNetworkKey.isEmpty()) {
+ vnfNetworkKey = networkRoleMap.get(networkRole)
+ if (vnfNetworkKey == null || vnfNetworkKey.isEmpty()) {
+ vnfNetworkKey = networkRole
+ }
+ }
+ String vnfNetworkNeutronIdValue = utils.getElementText(eElement, "neutron-id")
+ String vnfNetworkNetNameValue = utils.getElementText(eElement, "network-name")
+ String vnfNetworkSubNetIdValue = utils.getElementText(eElement, "subnet-id")
+ String vnfNetworkV6SubNetIdValue = utils.getElementText(eElement, "ipv6-subnet-id")
+ String vnfNetworkNetFqdnValue = utils.getElementText(eElement, "contrail-network-fqdn")
+ paramsMap.put("${vnfNetworkKey}_net_id", "${vnfNetworkNeutronIdValue}")
+ paramsMap.put("${vnfNetworkKey}_net_name", "${vnfNetworkNetNameValue}")
+ paramsMap.put("${vnfNetworkKey}_subnet_id", "${vnfNetworkSubNetIdValue}")
+ paramsMap.put("${vnfNetworkKey}_v6_subnet_id", "${vnfNetworkV6SubNetIdValue}")
+ paramsMap.put("${vnfNetworkKey}_net_fqdn", "${vnfNetworkNetFqdnValue}")
+
+ NodeList sriovVlanFilterList = eElement.getElementsByTagNameNS("*","sriov-vlan-filter-list")
+ StringBuffer sriovFilterBuf = new StringBuffer()
+ String values = ""
+ for(int i = 0; i < sriovVlanFilterList.getLength(); i++){
+ Node node1 = sriovVlanFilterList.item(i)
+ if (node1.getNodeType() == Node.ELEMENT_NODE) {
+ Element eElement1 = (Element) node1
+ String value = utils.getElementText(eElement1, "sriov-vlan-filter")
+ if (i != sriovVlanFilterList.getLength() - 1) {
+ values = sriovFilterBuf.append(value + ",")
+ }
+ else {
+ values = sriovFilterBuf.append(value);
+ }
+ }
+ }
+ if (!values.isEmpty()) {
+ paramsMap.put("${vnfNetworkKey}_ATT_VF_VLAN_FILTER", "${values}")
+ }
+ }
+ }
+
+ // VNF-VMS Data
+
+ def key
+ def value
+ def networkKey
+ def networkValue
+ def floatingIPKey
+ def floatingIPKeyValue
+ def floatingIPV6Key
+ def floatingIPV6KeyValue
+ StringBuilder sb = new StringBuilder()
+
+ NodeList vmsList = responseXml.getElementsByTagNameNS("*","vnf-vms")
+ for (int x = 0; x < vmsList.getLength(); x++) {
+ Node node = vmsList.item(x)
+ if (node.getNodeType() == Node.ELEMENT_NODE) {
+ Element eElement = (Element) node
+ key = utils.getElementText(eElement, "vm-type")
+ String values
+ String position = "0"
+ StringBuilder sb1 = new StringBuilder()
+ NodeList valueList = eElement.getElementsByTagNameNS("*","vm-names")
+ NodeList vmNetworksList = eElement.getElementsByTagNameNS("*","vm-networks")
+ for(int i = 0; i < valueList.getLength(); i++){
+ Node node1 = valueList.item(i)
+ if (node1.getNodeType() == Node.ELEMENT_NODE) {
+ Element eElement1 = (Element) node1
+ value = utils.getElementText(eElement1, "vm-name")
+ if (i != valueList.getLength() - 1) {
+ values = sb1.append(value + ",")
+ }
+ else {
+ values = sb1.append(value);
+ }
+ position = i.toString()
+ paramsMap.put("${key}_name_${position}", "${value}")
+ }
+ }
+ for(int n = 0; n < vmNetworksList.getLength(); n++){
+ String floatingIpKeyValueStr = ""
+ String floatingIpV6KeyValueStr = ""
+ Node nodeNetworkKey = vmNetworksList.item(n)
+ if (nodeNetworkKey.getNodeType() == Node.ELEMENT_NODE) {
+ Element eElementNetworkKey = (Element) nodeNetworkKey
+ String ipAddressValues
+ String ipV6AddressValues
+ String networkPosition = "0"
+ StringBuilder sb2 = new StringBuilder()
+ StringBuilder sb3 = new StringBuilder()
+ StringBuilder sb4 = new StringBuilder()
+ networkKey = utils.getElementText(eElementNetworkKey, "network-role-tag")
+ if (networkKey.isEmpty()) {
+ networkKey = utils.getElementText(eElementNetworkKey, "network-role")
+ }
+ floatingIPKey = key + '_' + networkKey + '_floating_ip'
+ floatingIPKeyValue = utils.getElementText(eElementNetworkKey, "floating-ip")
+ if(!floatingIPKeyValue.isEmpty()){
+ paramsMap.put("$floatingIPKey", "$floatingIPKeyValue")
+ }
+ floatingIPV6Key = key + '_' + networkKey + '_floating_v6_ip'
+ floatingIPV6KeyValue = utils.getElementText(eElementNetworkKey, "floating-ip-v6")
+ if(!floatingIPV6KeyValue.isEmpty()){
+ paramsMap.put("$floatingIPV6Key", "$floatingIPV6KeyValue")
+ }
+ NodeList networkIpsList = eElementNetworkKey.getElementsByTagNameNS("*","network-ips")
+ for(int a = 0; a < networkIpsList.getLength(); a++){
+ Node ipAddress = networkIpsList.item(a)
+ if (ipAddress.getNodeType() == Node.ELEMENT_NODE) {
+ Element eElementIpAddress = (Element) ipAddress
+ String ipAddressValue = utils.getElementText(eElementIpAddress, "ip-address")
+ if (a != networkIpsList.getLength() - 1) {
+ ipAddressValues = sb2.append(ipAddressValue + ",")
+ }
+ else {
+ ipAddressValues = sb2.append(ipAddressValue);
+ }
+ networkPosition = a.toString()
+ paramsMap.put("${key}_${networkKey}_ip_${networkPosition}", "${ipAddressValue}")
+ }
+ }
+
+ paramsMap.put("${key}_${networkKey}_ips", "${ipAddressValues}")
+
+ NodeList interfaceRoutePrefixesList = eElementNetworkKey.getElementsByTagNameNS("*","interface-route-prefixes")
+ String interfaceRoutePrefixValues = sb3.append("[")
+
+ for(int a = 0; a < interfaceRoutePrefixesList.getLength(); a++){
+ Node interfaceRoutePrefix = interfaceRoutePrefixesList.item(a)
+ if (interfaceRoutePrefix.getNodeType() == Node.ELEMENT_NODE) {
+ Element eElementInterfaceRoutePrefix = (Element) interfaceRoutePrefix
+ String interfaceRoutePrefixValue = utils.getElementText(eElementInterfaceRoutePrefix, "interface-route-prefix-cidr")
+ if (interfaceRoutePrefixValue == null || interfaceRoutePrefixValue.isEmpty()) {
+ interfaceRoutePrefixValue = utils.getElementText(eElementInterfaceRoutePrefix, "interface-route-prefix")
+ }
+ if (a != interfaceRoutePrefixesList.getLength() - 1) {
+ interfaceRoutePrefixValues = sb3.append("{\"interface_route_table_routes_route_prefix\": \"" + interfaceRoutePrefixValue + "\"}" + ",")
+ }
+ else {
+ interfaceRoutePrefixValues = sb3.append("{\"interface_route_table_routes_route_prefix\": \"" + interfaceRoutePrefixValue + "\"}")
+ }
+ }
+ }
+ interfaceRoutePrefixValues = sb3.append("]")
+ if (interfaceRoutePrefixesList.getLength() > 0) {
+ paramsMap.put("${key}_${networkKey}_route_prefixes", "${interfaceRoutePrefixValues}")
+ }
+
+ NodeList networkIpsV6List = eElementNetworkKey.getElementsByTagNameNS("*","network-ips-v6")
+ for(int a = 0; a < networkIpsV6List.getLength(); a++){
+ Node ipV6Address = networkIpsV6List.item(a)
+ if (ipV6Address.getNodeType() == Node.ELEMENT_NODE) {
+ Element eElementIpV6Address = (Element) ipV6Address
+ String ipV6AddressValue = utils.getElementText(eElementIpV6Address, "ip-address-ipv6")
+ if (a != networkIpsV6List.getLength() - 1) {
+ ipV6AddressValues = sb4.append(ipV6AddressValue + ",")
+ }
+ else {
+ ipV6AddressValues = sb4.append(ipV6AddressValue);
+ }
+ networkPosition = a.toString()
+ paramsMap.put("${key}_${networkKey}_v6_ip_${networkPosition}", "${ipV6AddressValue}")
+ }
+ }
+ paramsMap.put("${key}_${networkKey}_v6_ips", "${ipV6AddressValues}")
+ }
+ }
+ paramsMap.put("${key}_names", "${values}")
+ }
+ }
+ //SDNC Response Params
+ String sdncResponseParams = ""
+ List<String> sdncResponseParamsToSkip = ["vnf_id", "vf_module_id", "vnf_name", "vf_module_name"]
+ String vnfParamsChildNodes = utils.getChildNodes(data, "vnf-parameters")
+ if(vnfParamsChildNodes == null || vnfParamsChildNodes.length() < 1){
+ // No SDNC params
+ }else{
+ NodeList paramsList = responseXml.getElementsByTagNameNS("*", "vnf-parameters")
+ for (int z = 0; z < paramsList.getLength(); z++) {
+ Node node = paramsList.item(z)
+ Element eElement = (Element) node
+ String vnfParameterName = utils.getElementText(eElement, "vnf-parameter-name")
+ if (!sdncResponseParamsToSkip.contains(vnfParameterName)) {
+ String vnfParameterValue = utils.getElementText(eElement, "vnf-parameter-value")
+ paramsMap.put("${vnfParameterName}", "${vnfParameterValue}")
+ }
+ }
+ }
+
+ // Parameters received from the request should overwrite any parameters received from SDNC
+ if (vnfParamsMap != null) {
+ for (Map.Entry<String, String> entry : vnfParamsMap.entrySet()) {
+ String vnfKey = entry.getKey()
+ String vnfValue = entry.getValue()
+ paramsMap.put("$vnfKey", "$vnfValue")
+ }
+ }
+
+ StringBuilder sbParams = new StringBuilder()
+ def vfModuleParams = ""
+ for (Map.Entry<String, String> entry : paramsMap.entrySet()) {
+ String paramsXml
+ String paramName = entry.getKey()
+ String paramValue = entry.getValue()
+ paramsXml =
+ """<entry>
+ <key>${MsoUtils.xmlEscape(paramName)}</key>
+ <value>${MsoUtils.xmlEscape(paramValue)}</value>
+ </entry>
+ """
+
+ vfModuleParams = sbParams.append(paramsXml)
+ }
+
+ return vfModuleParams
+
+ }
+
+
+ /*
+ * Parses VNF parameters passed in on the incoming requests and SDNC parameters returned from SDNC get response
+ * for both VNF and VF Module
+ * and puts them into the format expected by VNF adapter.
+ * @param vnfParamsMap - map of VNF parameters passed in the request body
+ * @param vnfSdncGetResponse - response string from SDNC GET VNF topology request
+ * @param vfmoduleSdncGetResponse - response string from SDNC GET VF Module topology request
+ * @param vnfId
+ * @param vnfName
+ * @param vfModuleId
+ * @param vfModuleName
+ * @param vfModuleIndex - can be null
+ * @return a String of key/value entries for vfModuleParams
+ */
+
+ protected String buildVfModuleParamsFromCombinedTopologies(Map<String, String> vnfParamsMap, String vnfSdncGetResponse, String vfmoduleSdncGetResponse, String vnfId, String vnfName,
+ String vfModuleId, String vfModuleName, String vfModuleIndex, String environmentContext, String workloadContext) {
+
+ // Set up initial parameters
+
+ Map<String, String> paramsMap = new HashMap<String, String>()
+
+ if (vfModuleIndex != null) {
+ paramsMap.put("vf_module_index", "${vfModuleIndex}")
+ }
+
+ // Add-on data
+ paramsMap.put("vnf_id", "${vnfId}")
+ paramsMap.put("vnf_name", "${vnfName}")
+ paramsMap.put("vf_module_id", "${vfModuleId}")
+ paramsMap.put("vf_module_name", "${vfModuleName}")
+ paramsMap.put("environment_context","${environmentContext}")
+ paramsMap.put("workload_context", "${workloadContext}")
+
+ //Get SDNC Response Data for VNF
+
+ String vnfData = utils.getNodeXml(vnfSdncGetResponse, "response-data")
+
+ String vnfTopology = utils.getNodeXml(vnfData, "vnf-topology")
+ vnfTopology = utils.removeXmlPreamble(vnfTopology)
+ vnfTopology = utils.removeXmlNamespaces(vnfTopology)
+
+ InputSource sourceVnf = new InputSource(new StringReader(vnfData));
+ DocumentBuilderFactory docFactoryVnf = DocumentBuilderFactory.newInstance();
+ docFactoryVnf.setNamespaceAware(true)
+ DocumentBuilder docBuilderVnf = docFactoryVnf.newDocumentBuilder()
+ Document responseXmlVnf = docBuilderVnf.parse(sourceVnf)
+
+ // Availability Zones Data
+
+ NodeList aZonesList = responseXmlVnf.getElementsByTagNameNS("*", "availability-zones")
+ String aZonePosition = "0"
+ for (int z = 0; z < aZonesList.getLength(); z++) {
+ Node node = aZonesList.item(z)
+ if (node.getNodeType() == Node.ELEMENT_NODE) {
+ Element eElement = (Element) node
+ String aZoneValue = utils.getElementText(eElement, "availability-zone")
+ aZonePosition = z.toString()
+ paramsMap.put("availability_zone_${aZonePosition}", "${aZoneValue}")
+ }
+ }
+
+ //Get SDNC Response Data for VF Module
+
+ String vfModuleData = utils.getNodeXml(vfmoduleSdncGetResponse, "response-data")
+
+ String vfModuleTopology = utils.getNodeXml(vfModuleData, "vf-module-topology")
+ vfModuleTopology = utils.removeXmlPreamble(vfModuleTopology)
+ vfModuleTopology = utils.removeXmlNamespaces(vfModuleTopology)
+ String vfModuleTopologyIdentifier = utils.getNodeXml(vfModuleTopology, "vf-module-topology-identifier")
+
+ InputSource sourceVfModule = new InputSource(new StringReader(vfModuleData));
+ DocumentBuilderFactory docFactoryVfModule = DocumentBuilderFactory.newInstance();
+ docFactoryVfModule.setNamespaceAware(true)
+ DocumentBuilder docBuilderVfModule = docFactoryVfModule.newDocumentBuilder()
+ Document responseXmlVfModule = docBuilderVfModule.parse(sourceVfModule)
+
+ // Map of network-roles and network-tags from vm-networks
+
+ NodeList vmNetworksListGlobal = responseXmlVfModule.getElementsByTagNameNS("*", "vm-networks")
+ Map<String, String> networkRoleMap = new HashMap<String, String>()
+ for(int n = 0; n < vmNetworksListGlobal.getLength(); n++){
+ Node nodeNetworkKey = vmNetworksListGlobal.item(n)
+ if (nodeNetworkKey.getNodeType() == Node.ELEMENT_NODE) {
+ Element eElementNetworkKey = (Element) nodeNetworkKey
+ String networkRole = utils.getElementText(eElementNetworkKey, "network-role")
+ String networkRoleValue = utils.getElementText(eElementNetworkKey, "network-role-tag")
+ if (networkRoleValue.isEmpty()) {
+ networkRoleValue = networkRole
+ }
+ networkRoleMap.put(networkRole, networkRoleValue)
+ }
+ }
+
+ // VNF Networks Data
+
+ StringBuilder sbNet = new StringBuilder()
+
+ NodeList vnfNetworkList = responseXmlVnf.getElementsByTagNameNS("*", "vnf-networks")
+ for (int x = 0; x < vnfNetworkList.getLength(); x++) {
+ Node node = vnfNetworkList.item(x)
+ if (node.getNodeType() == Node.ELEMENT_NODE) {
+ Element eElement = (Element) node
+ String vnfNetworkKey = utils.getElementText(eElement, "network-role-tag")
+ String networkRole = utils.getElementText(eElement, "network-role")
+ if (vnfNetworkKey.isEmpty()) {
+ vnfNetworkKey = networkRoleMap.get(networkRole)
+ if (vnfNetworkKey == null || vnfNetworkKey.isEmpty()) {
+ vnfNetworkKey = networkRole
+ }
+ }
+ String vnfNetworkNeutronIdValue = utils.getElementText(eElement, "neutron-id")
+ String vnfNetworkNetNameValue = utils.getElementText(eElement, "network-name")
+ String vnfNetworkSubNetIdValue = utils.getElementText(eElement, "subnet-id")
+ String vnfNetworkV6SubNetIdValue = utils.getElementText(eElement, "ipv6-subnet-id")
+ String vnfNetworkNetFqdnValue = utils.getElementText(eElement, "contrail-network-fqdn")
+ paramsMap.put("${vnfNetworkKey}_net_id", "${vnfNetworkNeutronIdValue}")
+ paramsMap.put("${vnfNetworkKey}_net_name", "${vnfNetworkNetNameValue}")
+ paramsMap.put("${vnfNetworkKey}_subnet_id", "${vnfNetworkSubNetIdValue}")
+ paramsMap.put("${vnfNetworkKey}_v6_subnet_id", "${vnfNetworkV6SubNetIdValue}")
+ paramsMap.put("${vnfNetworkKey}_net_fqdn", "${vnfNetworkNetFqdnValue}")
+
+ NodeList sriovVlanFilterList = eElement.getElementsByTagNameNS("*","sriov-vlan-filter-list")
+ StringBuffer sriovFilterBuf = new StringBuffer()
+ String values = ""
+ for(int i = 0; i < sriovVlanFilterList.getLength(); i++){
+ Node node1 = sriovVlanFilterList.item(i)
+ if (node1.getNodeType() == Node.ELEMENT_NODE) {
+ Element eElement1 = (Element) node1
+ String value = utils.getElementText(eElement1, "sriov-vlan-filter")
+ if (i != sriovVlanFilterList.getLength() - 1) {
+ values = sriovFilterBuf.append(value + ",")
+ }
+ else {
+ values = sriovFilterBuf.append(value);
+ }
+ }
+ }
+ if (!values.isEmpty()) {
+ paramsMap.put("${vnfNetworkKey}_ATT_VF_VLAN_FILTER", "${values}")
+ }
+ }
+ }
+
+
+
+ // VMS Data
+
+ def key
+ def value
+ def networkKey
+ def networkValue
+ def floatingIPKey
+ def floatingIPKeyValue
+ def floatingIPV6Key
+ def floatingIPV6KeyValue
+ StringBuilder sb = new StringBuilder()
+
+ NodeList vmsList = responseXmlVfModule.getElementsByTagNameNS("*","vm")
+ for (int x = 0; x < vmsList.getLength(); x++) {
+ Node node = vmsList.item(x)
+ if (node.getNodeType() == Node.ELEMENT_NODE) {
+ Element eElement = (Element) node
+ key = utils.getElementText(eElement, "vm-type")
+ String values
+ String position = "0"
+ StringBuilder sb1 = new StringBuilder()
+ NodeList valueList = eElement.getElementsByTagNameNS("*","vm-names")
+ NodeList vmNetworksList = eElement.getElementsByTagNameNS("*","vm-networks")
+ for(int i = 0; i < valueList.getLength(); i++){
+ Node node1 = valueList.item(i)
+ if (node1.getNodeType() == Node.ELEMENT_NODE) {
+ Element eElement1 = (Element) node1
+ value = utils.getElementText(eElement1, "vm-name")
+ if (i != valueList.getLength() - 1) {
+ values = sb1.append(value + ",")
+ }
+ else {
+ values = sb1.append(value);
+ }
+ position = i.toString()
+ paramsMap.put("${key}_name_${position}", "${value}")
+ }
+ }
+ for(int n = 0; n < vmNetworksList.getLength(); n++){
+ String floatingIpKeyValueStr = ""
+ String floatingIpV6KeyValueStr = ""
+ Node nodeNetworkKey = vmNetworksList.item(n)
+ if (nodeNetworkKey.getNodeType() == Node.ELEMENT_NODE) {
+ Element eElementNetworkKey = (Element) nodeNetworkKey
+ String ipAddressValues
+ String ipV6AddressValues
+ String networkPosition = "0"
+ StringBuilder sb2 = new StringBuilder()
+ StringBuilder sb3 = new StringBuilder()
+ StringBuilder sb4 = new StringBuilder()
+ networkKey = utils.getElementText(eElementNetworkKey, "network-role-tag")
+ if (networkKey.isEmpty()) {
+ networkKey = utils.getElementText(eElementNetworkKey, "network-role")
+ }
+ floatingIPKey = key + '_' + networkKey + '_floating_ip'
+ floatingIPKeyValue = utils.getElementText(eElementNetworkKey, "floating-ip")
+ if(!floatingIPKeyValue.isEmpty()){
+ paramsMap.put("$floatingIPKey", "$floatingIPKeyValue")
+ }
+ floatingIPV6Key = key + '_' + networkKey + '_floating_v6_ip'
+ floatingIPV6KeyValue = utils.getElementText(eElementNetworkKey, "floating-ip-v6")
+ if(!floatingIPV6KeyValue.isEmpty()){
+ paramsMap.put("$floatingIPV6Key", "$floatingIPV6KeyValue")
+ }
+ NodeList networkIpsList = eElementNetworkKey.getElementsByTagNameNS("*","network-ips")
+ for(int a = 0; a < networkIpsList.getLength(); a++){
+ Node ipAddress = networkIpsList.item(a)
+ if (ipAddress.getNodeType() == Node.ELEMENT_NODE) {
+ Element eElementIpAddress = (Element) ipAddress
+ String ipAddressValue = utils.getElementText(eElementIpAddress, "ip-address")
+ if (a != networkIpsList.getLength() - 1) {
+ ipAddressValues = sb2.append(ipAddressValue + ",")
+ }
+ else {
+ ipAddressValues = sb2.append(ipAddressValue);
+ }
+ networkPosition = a.toString()
+ paramsMap.put("${key}_${networkKey}_ip_${networkPosition}", "${ipAddressValue}")
+ }
+ }
+
+ paramsMap.put("${key}_${networkKey}_ips", "${ipAddressValues}")
+
+ NodeList interfaceRoutePrefixesList = eElementNetworkKey.getElementsByTagNameNS("*","interface-route-prefixes")
+ String interfaceRoutePrefixValues = sb3.append("[")
+
+ for(int a = 0; a < interfaceRoutePrefixesList.getLength(); a++){
+ Node interfaceRoutePrefix = interfaceRoutePrefixesList.item(a)
+ if (interfaceRoutePrefix.getNodeType() == Node.ELEMENT_NODE) {
+ Element eElementInterfaceRoutePrefix = (Element) interfaceRoutePrefix
+ String interfaceRoutePrefixValue = utils.getElementText(eElementInterfaceRoutePrefix, "interface-route-prefix-cidr")
+ if (interfaceRoutePrefixValue == null || interfaceRoutePrefixValue.isEmpty()) {
+ interfaceRoutePrefixValue = utils.getElementText(eElementInterfaceRoutePrefix, "interface-route-prefix")
+ }
+ if (a != interfaceRoutePrefixesList.getLength() - 1) {
+ interfaceRoutePrefixValues = sb3.append("{\"interface_route_table_routes_route_prefix\": \"" + interfaceRoutePrefixValue + "\"}" + ",")
+ }
+ else {
+ interfaceRoutePrefixValues = sb3.append("{\"interface_route_table_routes_route_prefix\": \"" + interfaceRoutePrefixValue + "\"}")
+ }
+ }
+ }
+ interfaceRoutePrefixValues = sb3.append("]")
+ if (interfaceRoutePrefixesList.getLength() > 0) {
+ paramsMap.put("${key}_${networkKey}_route_prefixes", "${interfaceRoutePrefixValues}")
+ }
+
+ NodeList networkIpsV6List = eElementNetworkKey.getElementsByTagNameNS("*","network-ips-v6")
+ for(int a = 0; a < networkIpsV6List.getLength(); a++){
+ Node ipV6Address = networkIpsV6List.item(a)
+ if (ipV6Address.getNodeType() == Node.ELEMENT_NODE) {
+ Element eElementIpV6Address = (Element) ipV6Address
+ String ipV6AddressValue = utils.getElementText(eElementIpV6Address, "ip-address-ipv6")
+ if (a != networkIpsV6List.getLength() - 1) {
+ ipV6AddressValues = sb4.append(ipV6AddressValue + ",")
+ }
+ else {
+ ipV6AddressValues = sb4.append(ipV6AddressValue);
+ }
+ networkPosition = a.toString()
+ paramsMap.put("${key}_${networkKey}_v6_ip_${networkPosition}", "${ipV6AddressValue}")
+ }
+ }
+ paramsMap.put("${key}_${networkKey}_v6_ips", "${ipV6AddressValues}")
+ }
+ }
+ paramsMap.put("${key}_names", "${values}")
+ }
+ }
+ //SDNC Response Params
+ List<String> sdncResponseParamsToSkip = ["vnf_id", "vf_module_id", "vnf_name", "vf_module_name"]
+
+ String vnfParamsChildNodes = utils.getChildNodes(vnfData, "param")
+ if(vnfParamsChildNodes == null || vnfParamsChildNodes.length() < 1){
+ // No SDNC params for VNF
+ }else{
+ NodeList paramsList = responseXmlVnf.getElementsByTagNameNS("*", "param")
+ for (int z = 0; z < paramsList.getLength(); z++) {
+ Node node = paramsList.item(z)
+ Element eElement = (Element) node
+ String vnfParameterName = utils.getElementText(eElement, "name")
+ if (!sdncResponseParamsToSkip.contains(vnfParameterName)) {
+ String vnfParameterValue = utils.getElementText(eElement, "value")
+ paramsMap.put("${vnfParameterName}", "${vnfParameterValue}")
+ }
+ }
+ }
+
+ String vfModuleParamsChildNodes = utils.getChildNodes(vfModuleData, "param")
+ if(vfModuleParamsChildNodes == null || vfModuleParamsChildNodes.length() < 1){
+ // No SDNC params for VF Module
+ }else{
+ NodeList paramsList = responseXmlVfModule.getElementsByTagNameNS("*", "param")
+ for (int z = 0; z < paramsList.getLength(); z++) {
+ Node node = paramsList.item(z)
+ Element eElement = (Element) node
+ String vnfParameterName = utils.getElementText(eElement, "name")
+ if (!sdncResponseParamsToSkip.contains(vnfParameterName)) {
+ String vnfParameterValue = utils.getElementText(eElement, "value")
+ paramsMap.put("${vnfParameterName}", "${vnfParameterValue}")
+ }
+ }
+ }
+
+ // Parameters received from the request should overwrite any parameters received from SDNC
+ if (vnfParamsMap != null) {
+ for (Map.Entry<String, String> entry : vnfParamsMap.entrySet()) {
+ String vnfKey = entry.getKey()
+ String vnfValue = entry.getValue()
+ paramsMap.put("$vnfKey", "$vnfValue")
+ }
+ }
+
+ StringBuilder sbParams = new StringBuilder()
+ def vfModuleParams = ""
+ for (Map.Entry<String, String> entry : paramsMap.entrySet()) {
+ String paramsXml
+ String paramName = entry.getKey()
+ String paramValue = entry.getValue()
+ paramsXml =
+ """<entry>
+ <key>${MsoUtils.xmlEscape(paramName)}</key>
+ <value>${MsoUtils.xmlEscape(paramValue)}</value>
+ </entry>
+ """
+
+ vfModuleParams = sbParams.append(paramsXml)
+ }
+
+ return vfModuleParams
+
+ }
+
+
+ /*
+ * VBNG specific method that 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.
+ * @param vnfParamsMap - map of VNF parameters passed in the request body
+ * @param sdncGetResponse - response string from SDNC GET topology request
+ * @param vnfId
+ * @param vnfName
+ * @param vfModuleId
+ * @param vfModuleName
+ * @return a String of key/value entries for vfModuleParams
+ */
+
+ protected String buildVfModuleParamsVbng(String vnfParams, String sdncGetResponse, String vnfId, String vnfName,
+ String vfModuleId, String vfModuleName) {
+
+ //Get SDNC Response Data
+
+ String data = utils.getNodeXml(sdncGetResponse, "response-data")
+
+
+
+ // Add-on data
+ String vnfInfo =
+ """<entry>
+ <key>vnf_id</key>
+ <value>${MsoUtils.xmlEscape(vnfId)}</value>
+ </entry>
+ <entry>
+ <key>vnf_name</key>
+ <value>${MsoUtils.xmlEscape(vnfName)}</value>
+ </entry>
+ <entry>
+ <key>vf_module_id</key>
+ <value>${MsoUtils.xmlEscape(vfModuleId)}</value>
+ </entry>
+ <entry>
+ <key>vf_module_name</key>
+ <value>${MsoUtils.xmlEscape(vfModuleName)}</value>
+ </entry>"""
+
+ msoLogger.debug("vnfInfo: " + vnfInfo)
+ InputSource source = new InputSource(new StringReader(data));
+ DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
+ docFactory.setNamespaceAware(true)
+ DocumentBuilder docBuilder = docFactory.newDocumentBuilder()
+ Document responseXml = docBuilder.parse(source)
+
+
+ // Availability Zones Data
+ String aZones = ""
+ StringBuilder sbAZone = new StringBuilder()
+ NodeList aZonesList = responseXml.getElementsByTagNameNS("*", "availability-zones")
+ String aZonePosition = "0"
+ for (int z = 0; z < aZonesList.getLength(); z++) {
+ Node node = aZonesList.item(z)
+ if (node.getNodeType() == Node.ELEMENT_NODE) {
+ Element eElement = (Element) node
+ String aZoneValue = utils.getElementText(eElement, "availability-zone")
+ aZonePosition = z.toString()
+ String aZoneXml =
+ """<entry>
+ <key>availability_zone_${MsoUtils.xmlEscape(aZonePosition)}</key>
+ <value>${MsoUtils.xmlEscape(aZoneValue)}</value>
+ </entry>"""
+ aZones = sbAZone.append(aZoneXml)
+ }
+ }
+
+ // Map of network-roles and network-tags from vm-networks
+
+ NodeList vmNetworksListGlobal = responseXml.getElementsByTagNameNS("*", "vm-networks")
+ Map<String, String> networkRoleMap = new HashMap<String, String>()
+ for(int n = 0; n < vmNetworksListGlobal.getLength(); n++){
+ Node nodeNetworkKey = vmNetworksListGlobal.item(n)
+ if (nodeNetworkKey.getNodeType() == Node.ELEMENT_NODE) {
+ Element eElementNetworkKey = (Element) nodeNetworkKey
+ String networkRole = utils.getElementText(eElementNetworkKey, "network-role")
+ String networkRoleValue = utils.getElementText(eElementNetworkKey, "network-role-tag")
+ if (networkRoleValue.isEmpty()) {
+ networkRoleValue = networkRole
+ }
+ networkRoleMap.put(networkRole, networkRoleValue)
+ }
+ }
+
+ // VNF Networks Data
+ String vnfNetworkNetId = ""
+ String vnfNetworkNetName = ""
+ String vnfNetworkSubNetId = ""
+ String vnfNetworkV6SubNetId = ""
+ String vnfNetworkNetFqdn = ""
+ String vnfNetworksSriovVlanFilters = ""
+ StringBuilder sbNet = new StringBuilder()
+ StringBuilder sbNet2 = new StringBuilder()
+ StringBuilder sbNet3 = new StringBuilder()
+ StringBuilder sbNet4 = new StringBuilder()
+ StringBuilder sbNet5 = new StringBuilder()
+ StringBuilder sbNet6 = new StringBuilder()
+ NodeList vnfNetworkList = responseXml.getElementsByTagNameNS("*", "vnf-networks")
+ for (int x = 0; x < vnfNetworkList.getLength(); x++) {
+ Node node = vnfNetworkList.item(x)
+ if (node.getNodeType() == Node.ELEMENT_NODE) {
+ Element eElement = (Element) node
+ String vnfNetworkKey = utils.getElementText(eElement, "network-role-tag")
+ String networkRole = utils.getElementText(eElement, "network-role")
+ if (vnfNetworkKey.isEmpty()) {
+ vnfNetworkKey = networkRoleMap.get(networkRole)
+ if (vnfNetworkKey == null || vnfNetworkKey.isEmpty()) {
+ vnfNetworkKey = networkRole
+ }
+ }
+ String vnfNetworkNeutronIdValue = utils.getElementText(eElement, "neutron-id")
+ String vnfNetworkNetNameValue = utils.getElementText(eElement, "network-name")
+ String vnfNetworkSubNetIdValue = utils.getElementText(eElement, "subnet-id")
+ String vnfNetworkV6SubNetIdValue = utils.getElementText(eElement, "ipv6-subnet-id")
+ String vnfNetworkNetFqdnValue = utils.getElementText(eElement, "contrail-network-fqdn")
+ String vnfNetworkNetIdXml =
+ """<entry>
+ <key>${MsoUtils.xmlEscape(vnfNetworkKey)}_net_id</key>
+ <value>${MsoUtils.xmlEscape(vnfNetworkNeutronIdValue)}</value>
+ </entry>"""
+ vnfNetworkNetId = sbNet.append(vnfNetworkNetIdXml)
+ String vnfNetworkNetNameXml =
+ """<entry>
+ <key>${MsoUtils.xmlEscape(vnfNetworkKey)}_net_name</key>
+ <value>${MsoUtils.xmlEscape(vnfNetworkNetNameValue)}</value>
+ </entry>"""
+ vnfNetworkNetName = sbNet2.append(vnfNetworkNetNameXml)
+ String vnfNetworkSubNetIdXml =
+ """<entry>
+ <key>${MsoUtils.xmlEscape(vnfNetworkKey)}_subnet_id</key>
+ <value>${MsoUtils.xmlEscape(vnfNetworkSubNetIdValue)}</value>
+ </entry>"""
+ vnfNetworkSubNetId = sbNet3.append(vnfNetworkSubNetIdXml)
+ String vnfNetworkV6SubNetIdXml =
+ """<entry>
+ <key>${MsoUtils.xmlEscape(vnfNetworkKey)}_v6_subnet_id</key>
+ <value>${MsoUtils.xmlEscape(vnfNetworkV6SubNetIdValue)}</value>
+ </entry>"""
+ vnfNetworkV6SubNetId = sbNet5.append(vnfNetworkV6SubNetIdXml)
+ String vnfNetworkNetFqdnXml =
+ """<entry>
+ <key>${MsoUtils.xmlEscape(vnfNetworkKey)}_net_fqdn</key>
+ <value>${MsoUtils.xmlEscape(vnfNetworkNetFqdnValue)}</value>
+ </entry>"""
+ vnfNetworkNetFqdn = sbNet4.append(vnfNetworkNetFqdnXml)
+
+ NodeList sriovVlanFilterList = eElement.getElementsByTagNameNS("*","sriov-vlan-filter-list")
+ StringBuffer sriovFilterBuf = new StringBuffer()
+ String values = ""
+ for(int i = 0; i < sriovVlanFilterList.getLength(); i++){
+ Node node1 = sriovVlanFilterList.item(i)
+ if (node1.getNodeType() == Node.ELEMENT_NODE) {
+ Element eElement1 = (Element) node1
+ String value = utils.getElementText(eElement1, "sriov-vlan-filter")
+ if (i != sriovVlanFilterList.getLength() - 1) {
+ values = sriovFilterBuf.append(value + ",")
+ }
+ else {
+ values = sriovFilterBuf.append(value);
+ }
+ }
+ }
+ if (!values.isEmpty()) {
+ String vnfNetworkSriovVlanFilterXml =
+ """<entry>
+ <key>${MsoUtils.xmlEscape(vnfNetworkKey)}_ATT_VF_VLAN_FILTER</key>
+ <value>${MsoUtils.xmlEscape(values)}</value>
+ </entry>"""
+ vnfNetworksSriovVlanFilters = sbNet6.append(vnfNetworkSriovVlanFilterXml)
+ }
+ }
+ }
+
+ // VNF-VMS Data
+ String vnfVMS = ""
+ String vnfVMSPositions = ""
+ String vmNetworks = ""
+ String vmNetworksPositions = ""
+ String vmNetworksPositionsV6 = ""
+ String interfaceRoutePrefixes = ""
+ def key
+ def value
+ def networkKey
+ def networkValue
+ def floatingIPKey
+ def floatingIPKeyValue
+ def floatingIPV6Key
+ def floatingIPV6KeyValue
+ StringBuilder sb = new StringBuilder()
+ StringBuilder sbPositions = new StringBuilder()
+ StringBuilder sbVmNetworks = new StringBuilder()
+ StringBuilder sbNetworksPositions = new StringBuilder()
+ StringBuilder sbInterfaceRoutePrefixes = new StringBuilder()
+ StringBuilder sbNetworksPositionsV6 = new StringBuilder()
+
+ NodeList vmsList = responseXml.getElementsByTagNameNS("*","vnf-vms")
+ for (int x = 0; x < vmsList.getLength(); x++) {
+ Node node = vmsList.item(x)
+ if (node.getNodeType() == Node.ELEMENT_NODE) {
+ Element eElement = (Element) node
+ key = utils.getElementText(eElement, "vm-type")
+ String values
+ String position = "0"
+ StringBuilder sb1 = new StringBuilder()
+ NodeList valueList = eElement.getElementsByTagNameNS("*","vm-names")
+ NodeList vmNetworksList = eElement.getElementsByTagNameNS("*","vm-networks")
+ for(int i = 0; i < valueList.getLength(); i++){
+ Node node1 = valueList.item(i)
+ if (node1.getNodeType() == Node.ELEMENT_NODE) {
+ Element eElement1 = (Element) node1
+ value = utils.getElementText(eElement1, "vm-name")
+ if (i != valueList.getLength() - 1) {
+ values = sb1.append(value + ",")
+ }
+ else {
+ values = sb1.append(value);
+ }
+ position = i.toString()
+ String vnfPositionXml =
+ """<entry>
+ <key>${MsoUtils.xmlEscape(key)}_name_${MsoUtils.xmlEscape(position)}</key>
+ <value>${MsoUtils.xmlEscape(value)}</value>
+ </entry>"""
+ nfVMSPositions = sbPositions.append(vnfPositionXml)
+ }
+ }
+ for(int n = 0; n < vmNetworksList.getLength(); n++){
+ String floatingIpKeyValueStr = ""
+ String floatingIpV6KeyValueStr = ""
+ Node nodeNetworkKey = vmNetworksList.item(n)
+ if (nodeNetworkKey.getNodeType() == Node.ELEMENT_NODE) {
+ Element eElementNetworkKey = (Element) nodeNetworkKey
+ String ipAddressValues
+ String ipV6AddressValues
+ String networkPosition = "0"
+ StringBuilder sb2 = new StringBuilder()
+ StringBuilder sb3 = new StringBuilder()
+ StringBuilder sb4 = new StringBuilder()
+ networkKey = utils.getElementText(eElementNetworkKey, "network-role-tag")
+ if (networkKey.isEmpty()) {
+ networkKey = utils.getElementText(eElementNetworkKey, "network-role")
+ }
+ floatingIPKey = key + '_' + networkKey + '_floating_ip'
+ floatingIPKeyValue = utils.getElementText(eElementNetworkKey, "floating-ip")
+ if(!floatingIPKeyValue.isEmpty()){
+ floatingIpKeyValueStr = """<entry>
+ <key>$floatingIPKey</key>
+ <value>$floatingIPKeyValue</value>
+ </entry>"""
+ }
+ floatingIPV6Key = key + '_' + networkKey + '_floating_v6_ip'
+ floatingIPV6KeyValue = utils.getElementText(eElementNetworkKey, "floating-ip-v6")
+ if(!floatingIPV6KeyValue.isEmpty()){
+ floatingIpV6KeyValueStr = """<entry>
+ <key>$floatingIPV6Key</key>
+ <value>$floatingIPV6KeyValue</value>
+ </entry>"""
+ }
+ NodeList networkIpsList = eElementNetworkKey.getElementsByTagNameNS("*","network-ips")
+ for(int a = 0; a < networkIpsList.getLength(); a++){
+ Node ipAddress = networkIpsList.item(a)
+ if (ipAddress.getNodeType() == Node.ELEMENT_NODE) {
+ Element eElementIpAddress = (Element) ipAddress
+ String ipAddressValue = utils.getElementText(eElementIpAddress, "ip-address")
+ if (a != networkIpsList.getLength() - 1) {
+ ipAddressValues = sb2.append(ipAddressValue + ",")
+ }
+ else {
+ ipAddressValues = sb2.append(ipAddressValue);
+ }
+ networkPosition = a.toString()
+ String vmNetworksPositionsXml =
+ """<entry>
+ <key>${MsoUtils.xmlEscape(key)}_${MsoUtils.xmlEscape(networkKey)}_ip_${MsoUtils.xmlEscape(networkPosition)}</key>
+ <value>${MsoUtils.xmlEscape(ipAddressValue)}</value>
+ </entry>"""
+ vmNetworksPositions = sbNetworksPositions.append(vmNetworksPositionsXml)
+ }
+ }
+ vmNetworksPositions = sbNetworksPositions.append(floatingIpKeyValueStr).append(floatingIpV6KeyValueStr)
+
+ String vmNetworksXml =
+ """<entry>
+ <key>${MsoUtils.xmlEscape(key)}_${MsoUtils.xmlEscape(networkKey)}_ips</key>
+ <value>${MsoUtils.xmlEscape(ipAddressValues)}</value>
+ </entry>"""
+ vmNetworks = sbVmNetworks.append(vmNetworksXml)
+
+ NodeList interfaceRoutePrefixesList = eElementNetworkKey.getElementsByTagNameNS("*","interface-route-prefixes")
+ String interfaceRoutePrefixValues = sb3.append("[")
+
+ for(int a = 0; a < interfaceRoutePrefixesList.getLength(); a++){
+ Node interfaceRoutePrefix = interfaceRoutePrefixesList.item(a)
+ if (interfaceRoutePrefix.getNodeType() == Node.ELEMENT_NODE) {
+ Element eElementInterfaceRoutePrefix = (Element) interfaceRoutePrefix
+ String interfaceRoutePrefixValue = utils.getElementText(eElementInterfaceRoutePrefix, "interface-route-prefix-cidr")
+ if (interfaceRoutePrefixValue == null || interfaceRoutePrefixValue.isEmpty()) {
+ interfaceRoutePrefixValue = utils.getElementText(eElementInterfaceRoutePrefix, "interface-route-prefix")
+ }
+ if (a != interfaceRoutePrefixesList.getLength() - 1) {
+ interfaceRoutePrefixValues = sb3.append("{\"interface_route_table_routes_route_prefix\": \"" + interfaceRoutePrefixValue + "\"}" + ",")
+ }
+ else {
+ interfaceRoutePrefixValues = sb3.append("{\"interface_route_table_routes_route_prefix\": \"" + interfaceRoutePrefixValue + "\"}")
+ }
+ }
+ }
+ interfaceRoutePrefixValues = sb3.append("]")
+ if (interfaceRoutePrefixesList.getLength() > 0) {
+ String interfaceRoutePrefixesXml =
+ """<entry>
+ <key>${MsoUtils.xmlEscape(key)}_${MsoUtils.xmlEscape(networkKey)}_route_prefixes</key>
+ <value>${MsoUtils.xmlEscape(interfaceRoutePrefixValues)}</value>
+ </entry>"""
+ interfaceRoutePrefixes = sbInterfaceRoutePrefixes.append(interfaceRoutePrefixesXml)
+ }
+
+ NodeList networkIpsV6List = eElementNetworkKey.getElementsByTagNameNS("*","network-ips-v6")
+ for(int a = 0; a < networkIpsV6List.getLength(); a++){
+ Node ipV6Address = networkIpsV6List.item(a)
+ if (ipV6Address.getNodeType() == Node.ELEMENT_NODE) {
+ Element eElementIpV6Address = (Element) ipV6Address
+ String ipV6AddressValue = utils.getElementText(eElementIpV6Address, "ip-address-ipv6")
+ if (a != networkIpsV6List.getLength() - 1) {
+ ipV6AddressValues = sb4.append(ipV6AddressValue + ",")
+ }
+ else {
+ ipV6AddressValues = sb4.append(ipV6AddressValue);
+ }
+ networkPosition = a.toString()
+ String vmNetworksPositionsV6Xml =
+ """<entry>
+ <key>${MsoUtils.xmlEscape(key)}_${MsoUtils.xmlEscape(networkKey)}_v6_ip_${MsoUtils.xmlEscape(networkPosition)}</key>
+ <value>${MsoUtils.xmlEscape(ipV6AddressValue)}</value>
+ </entry>"""
+ vmNetworksPositionsV6 = sbNetworksPositionsV6.append(vmNetworksPositionsV6Xml)
+ }
+ }
+ String vmNetworksV6Xml =
+ """<entry>
+ <key>${MsoUtils.xmlEscape(key)}_${MsoUtils.xmlEscape(networkKey)}_v6_ips</key>
+ <value>${MsoUtils.xmlEscape(ipV6AddressValues)}</value>
+ </entry>"""
+ vmNetworks = sbVmNetworks.append(vmNetworksV6Xml)
+ }
+ }
+ String vnfXml =
+ """<entry>
+ <key>${MsoUtils.xmlEscape(key)}_names</key>
+ <value>${MsoUtils.xmlEscape(values)}</value>
+ </entry>"""
+ vnfVMS = sb.append(vnfXml)
+ }
+ }
+ //SDNC Response Params
+ String sdncResponseParams = ""
+ List<String> sdncResponseParamsToSkip = ["vnf_id", "vf_module_id", "vnf_name", "vf_module_name"]
+ String vnfParamsChildNodes = utils.getChildNodes(data, "vnf-parameters")
+ if(vnfParamsChildNodes == null || vnfParamsChildNodes.length() < 1){
+ // No SDNC params
+ }else{
+ NodeList paramsList = responseXml.getElementsByTagNameNS("*", "vnf-parameters")
+ for (int z = 0; z < paramsList.getLength(); z++) {
+ Node node = paramsList.item(z)
+ Element eElement = (Element) node
+ String vnfParameterName = utils.getElementText(eElement, "vnf-parameter-name")
+ if (!sdncResponseParamsToSkip.contains(vnfParameterName)) {
+ String vnfParameterValue = utils.getElementText(eElement, "vnf-parameter-value")
+ String paraEntry =
+ """<entry>
+ <key>${MsoUtils.xmlEscape(vnfParameterName)}</key>
+ <value>${MsoUtils.xmlEscape(vnfParameterValue)}</value>
+ </entry>"""
+ sdncResponseParams = sb.append(paraEntry)
+ }
+ }
+ }
+
+
+ def vfModuleParams = """
+ ${vnfInfo}
+ ${aZones}
+ ${vnfNetworkNetId}
+ ${vnfNetworkNetName}
+ ${vnfNetworkSubNetId}
+ ${vnfNetworkV6SubNetId}
+ ${vnfNetworkNetFqdn}
+ ${vnfNetworksSriovVlanFilters}
+ ${vnfVMS}
+ ${vnfVMSPositions}
+ ${vmNetworks}
+ ${vmNetworksPositions}
+ ${vmNetworksPositionsV6}
+ ${interfaceRoutePrefixes}
+ ${vnfParams}
+ ${sdncResponseParams}"""
+
+ return vfModuleParams
+
+ }
+
+} \ No newline at end of file
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
new file mode 100644
index 0000000000..6e09837274
--- /dev/null
+++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/VidUtils.groovy
@@ -0,0 +1,553 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.so.bpmn.common.scripts
+
+import groovy.json.JsonBuilder
+import groovy.json.JsonSlurper
+
+import org.json.JSONObject
+import org.json.XML
+import org.onap.so.bpmn.core.xml.XmlTool
+import org.onap.so.logger.MsoLogger
+import org.onap.so.logger.MessageEnum
+
+
+class VidUtils {
+ private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, VidUtils.class);
+
+ public MsoUtils utils = new MsoUtils()
+ private AbstractServiceTaskProcessor taskProcessor
+
+ public VidUtils(AbstractServiceTaskProcessor taskProcessor) {
+ this.taskProcessor = taskProcessor
+ }
+
+ /**
+ * Create a volume-request XML using a JSON string
+ * @param jsonReq - JSON request from VID
+ * @param action
+ * @return
+ */
+ public String createXmlVolumeRequest(String jsonReq, String action, String serviceInstanceId) {
+ def jsonSlurper = new JsonSlurper()
+ try{
+ Map reqMap = jsonSlurper.parseText(jsonReq)
+ return createXmlVolumeRequest(reqMap, action, serviceInstanceId)
+ }
+ catch(Exception e) {
+ throw e
+ }
+ }
+
+ /**
+ * Create a volume-request XML using a map
+ * @param requestMap - map created from VID JSON
+ * @param action
+ * @param serviceInstanceId
+ * @return
+ */
+ public String createXmlVolumeRequest(Map requestMap, String action, String serviceInstanceId) {
+ createXmlVolumeRequest(requestMap, action, serviceInstanceId, '')
+ }
+
+
+ /**
+ * Create a volume-request XML using a map
+ * @param requestMap
+ * @param action
+ * @param serviceInstanceId
+ * @param volumeGroupId
+ * @return
+ */
+ public String createXmlVolumeRequest(Map requestMap, String action, String serviceInstanceId, String volumeGroupId) {
+ def vnfType = ''
+ def serviceName = ''
+ def modelCustomizationName = ''
+ def asdcServiceModelVersion = ''
+
+ def suppressRollback = requestMap.requestDetails.requestInfo.suppressRollback
+
+ def backoutOnFailure = ""
+ if(suppressRollback != null){
+ if ( suppressRollback == true) {
+ backoutOnFailure = "false"
+ } else if ( suppressRollback == false) {
+ backoutOnFailure = "true"
+ }
+ }
+
+ def volGrpName = requestMap.requestDetails.requestInfo?.instanceName ?: ''
+ def serviceId = requestMap.requestDetails.requestParameters?.serviceId ?: ''
+ def relatedInstanceList = requestMap.requestDetails.relatedInstanceList
+ relatedInstanceList.each {
+ if (it.relatedInstance.modelInfo?.modelType == 'service') {
+ serviceName = it.relatedInstance.modelInfo?.modelName
+ asdcServiceModelVersion = it.relatedInstance.modelInfo?.modelVersion
+ }
+ if (it.relatedInstance.modelInfo?.modelType == 'vnf') {
+ modelCustomizationName = it.relatedInstance.modelInfo?.modelInstanceName
+ }
+ }
+
+ vnfType = serviceName + '/' + modelCustomizationName
+
+ def userParams = requestMap.requestDetails?.requestParameters?.userParams
+ def userParamsNode = ''
+ if(userParams != null) {
+ userParamsNode = buildUserParams(userParams)
+ }
+ def modelCustomizationId = requestMap.requestDetails?.modelInfo?.modelCustomizationUuid ?: ''
+
+ def xmlReq = """
+ <volume-request xmlns="http://www.w3.org/2001/XMLSchema">
+ <request-info>
+ <action>${MsoUtils.xmlEscape(action)}</action>
+ <source>${MsoUtils.xmlEscape(requestMap.requestDetails.requestInfo.source)}</source>
+ <service-instance-id>${MsoUtils.xmlEscape(serviceInstanceId)}</service-instance-id>
+ </request-info>
+ <volume-inputs>
+ <volume-group-id>${MsoUtils.xmlEscape(volumeGroupId)}</volume-group-id>
+ <volume-group-name>${MsoUtils.xmlEscape(volGrpName)}</volume-group-name>
+ <vnf-type>${MsoUtils.xmlEscape(vnfType)}</vnf-type>
+ <vf-module-model-name>${MsoUtils.xmlEscape(requestMap.requestDetails.modelInfo.modelName)}</vf-module-model-name>
+ <asdc-service-model-version>${MsoUtils.xmlEscape(asdcServiceModelVersion)}</asdc-service-model-version>
+ <aic-cloud-region>${MsoUtils.xmlEscape(requestMap.requestDetails.cloudConfiguration.lcpCloudRegionId)}</aic-cloud-region>
+ <tenant-id>${MsoUtils.xmlEscape(requestMap.requestDetails.cloudConfiguration.tenantId)}</tenant-id>
+ <service-id>${MsoUtils.xmlEscape(serviceId)}</service-id>
+ <backout-on-failure>${MsoUtils.xmlEscape(backoutOnFailure)}</backout-on-failure>
+ <model-customization-id>${MsoUtils.xmlEscape(modelCustomizationId)}</model-customization-id>
+ </volume-inputs>
+ <volume-params>
+ $userParamsNode
+ </volume-params>
+ </volume-request>
+ """
+ // return a pretty-print of the volume-request xml without the preamble
+ return groovy.xml.XmlUtil.serialize(xmlReq.normalize().replaceAll("\t", "").replaceAll("\n", "")).replaceAll("(<\\?[^<]*\\?>\\s*[\\r\\n]*)?", "")
+ }
+
+ /**
+ * A common method that can be used to build volume-params node from a map.
+ * @param Map userParams
+ * @return
+ */
+ public String buildUserParams(userParams) {
+ if (userParams == null) return ""
+ def xml = ""
+ def key = ""
+ def value = ""
+ userParams.each {it ->
+ key = it.name.replaceAll(/\B[A-Z]/) { '_' + it }.toLowerCase()
+ value = it.value
+ xml += "<param name=\"${key}\">${MsoUtils.xmlEscape(value)}</param>"
+ }
+
+ return xml
+ }
+
+ /**
+ * A common method that can be used to extract 'requestDetails'
+ * @param String json
+ * @return String json requestDetails
+ */
+ @Deprecated
+ public getJsonRequestDetails(String jsonInput) {
+ String rtn = ""
+ if (jsonInput.isEmpty() || jsonInput == null) {
+ return rtn
+ } else {
+ def jsonMapObject = new JsonSlurper().parseText(jsonInput)
+ if (jsonMapObject instanceof Map) {
+ String jsonString = new JsonBuilder(jsonMapObject.requestDetails)
+ rtn = '{'+"requestDetails"+":"+jsonString+'}'
+ return rtn
+ } else {
+ return rtn
+ }
+ }
+ }
+
+ /**
+ * A common method that can be used to extract 'requestDetails' in Xml
+ * @param String json
+ * @return String xml requestDetails
+ */
+ @Deprecated
+ public getJsonRequestDetailstoXml(String jsonInput) {
+ String rtn = null
+ def jsonString = getJsonRequestDetails(jsonInput)
+ if (jsonString == null) {
+ return rtn
+ } else {
+ JSONObject jsonObj = new JSONObject(jsonString)
+ return XmlTool.normalize(XML.toString(jsonObj))
+ }
+ }
+
+ /**
+ * Create a network-request XML using a map
+ * @param execution
+ * @param xmlRequestDetails - requestDetails in xml
+ * @return
+ * Note: See latest version: createXmlNetworkRequestInstance()
+ */
+
+ public String createXmlNetworkRequestInfra(execution, def networkJsonIncoming) {
+
+ def requestId = execution.getVariable("requestId")
+ def serviceInstanceId = execution.getVariable("serviceInstanceId")
+ def requestAction = execution.getVariable("requestAction")
+ def networkId = (execution.getVariable("networkId")) != null ? execution.getVariable("networkId") : ""
+
+ def jsonSlurper = new JsonSlurper()
+ try {
+ Map reqMap = jsonSlurper.parseText(networkJsonIncoming)
+ def instanceName = reqMap.requestDetails.requestInfo.instanceName
+ def modelCustomizationId = reqMap.requestDetails.modelInfo.modelCustomizationId
+ if (modelCustomizationId == null) {
+ modelCustomizationId = reqMap.requestDetails.modelInfo.modelCustomizationUuid !=null ?
+ reqMap.requestDetails.modelInfo.modelCustomizationUuid : ""
+ }
+ def modelName = reqMap.requestDetails.modelInfo.modelName
+ def lcpCloudRegionId = reqMap.requestDetails.cloudConfiguration.lcpCloudRegionId
+ def tenantId = reqMap.requestDetails.cloudConfiguration.tenantId
+ def serviceId = reqMap.requestDetails.requestInfo.productFamilyId
+ def suppressRollback = reqMap.requestDetails.requestInfo.suppressRollback.toString()
+ def backoutOnFailure = "true"
+ if(suppressRollback != null){
+ if (suppressRollback == true || suppressRollback == "true") {
+ backoutOnFailure = "false"
+ } else if (suppressRollback == false || suppressRollback == "false") {
+ backoutOnFailure = "true"
+ }
+ }
+
+ //def userParams = reqMap.requestDetails.requestParameters.userParams
+ //def userParamsNode = buildUserParams(userParams)
+ def userParams = reqMap.requestDetails?.requestParameters?.userParams
+ def userParamsNode = ''
+ if(userParams != null) {
+ userParamsNode = buildUserParams(userParams)
+ }
+
+ //'sdncVersion' = current, '1610' (non-RPC SDNC) or '1702' (RPC SDNC)
+ def sdncVersion = execution.getVariable("sdncVersion")
+
+ def xmlReq = """
+ <network-request xmlns="http://www.w3.org/2001/XMLSchema">
+ <request-info>
+ <request-id>${MsoUtils.xmlEscape(requestId)}</request-id>
+ <action>${MsoUtils.xmlEscape(requestAction)}</action>
+ <source>VID</source>
+ <service-instance-id>${MsoUtils.xmlEscape(serviceInstanceId)}</service-instance-id>
+ </request-info>
+ <network-inputs>
+ <network-id>${MsoUtils.xmlEscape(networkId)}</network-id>
+ <network-name>${MsoUtils.xmlEscape(instanceName)}</network-name>
+ <network-type>${MsoUtils.xmlEscape(modelName)}</network-type>
+ <modelCustomizationId>${MsoUtils.xmlEscape(modelCustomizationId)}</modelCustomizationId>
+ <aic-cloud-region>${MsoUtils.xmlEscape(lcpCloudRegionId)}</aic-cloud-region>
+ <tenant-id>${MsoUtils.xmlEscape(tenantId)}</tenant-id>
+ <service-id>${MsoUtils.xmlEscape(serviceId)}</service-id>
+ <backout-on-failure>${MsoUtils.xmlEscape(backoutOnFailure)}</backout-on-failure>
+ <sdncVersion>${MsoUtils.xmlEscape(sdncVersion)}</sdncVersion>
+ </network-inputs>
+ <network-params>
+ ${userParamsNode}
+ </network-params>
+ </network-request>
+ """
+ // return a pretty-print of the volume-request xml without the preamble
+ return groovy.xml.XmlUtil.serialize(xmlReq.normalize().replaceAll("\t", "").replaceAll("\n", "")).replaceAll("(<\\?[^<]*\\?>\\s*[\\r\\n]*)?", "")
+
+ } catch(Exception e) {
+ msoLogger.debug("Error in Vid Utils",e.getCause())
+ e.printStackTrace();
+ throw e
+ }
+ }
+
+ /**
+ * Create a network-request XML using a map,
+ * @param execution
+ * @return
+ */
+ public String createXmlNetworkRequestInstance(execution) {
+
+ def networkModelUuid = ""
+ def networkModelName = ""
+ def networkModelVersion = ""
+ def networkModelCustomizationUuid = ""
+ def networkModelInvariantUuid = ""
+
+ // verify the DB Catalog response JSON structure
+ def networkModelInfo = execution.getVariable("networkModelInfo")
+ def jsonSlurper = new JsonSlurper()
+ if (networkModelInfo != null) {
+ try {
+ Map modelMap = jsonSlurper.parseText(networkModelInfo)
+ if (modelMap != null) {
+ if (networkModelInfo.contains("modelUuid")) {
+ networkModelUuid = modelMap.modelUuid !=null ? modelMap.modelUuid : ""
+ }
+ if (networkModelInfo.contains("modelName")) {
+ networkModelName = modelMap.modelName !=null ? modelMap.modelName : ""
+ }
+ if (networkModelInfo.contains("modelVersion")) {
+ networkModelVersion = modelMap.modelVersion !=null ? modelMap.modelVersion : ""
+ }
+ if (networkModelInfo.contains("modelCustomizationUuid")) {
+ networkModelCustomizationUuid = modelMap.modelCustomizationUuid !=null ? modelMap.modelCustomizationUuid : ""
+ }
+ if (networkModelInfo.contains("modelInvariantUuid")) {
+ networkModelInvariantUuid = modelMap.modelInvariantUuid !=null ? modelMap.modelInvariantUuid : ""
+ }
+ }
+ } catch (Exception ex) {
+ throw ex
+ }
+ }
+
+ def serviceModelUuid = ""
+ def serviceModelName = ""
+ def serviceModelVersion = ""
+ def serviceModelCustomizationUuid = ""
+ def serviceModelInvariantUuid = ""
+
+ // verify the DB Catalog response JSON structure
+ def serviceModelInfo = execution.getVariable("serviceModelInfo")
+ def jsonServiceSlurper = new JsonSlurper()
+ if (serviceModelInfo != null) {
+ try {
+ Map modelMap = jsonServiceSlurper.parseText(serviceModelInfo)
+ if (modelMap != null) {
+ if (serviceModelInfo.contains("modelUuid")) {
+ serviceModelUuid = modelMap.modelUuid !=null ? modelMap.modelUuid : ""
+ }
+ if (serviceModelInfo.contains("modelName")) {
+ serviceModelName = modelMap.modelName !=null ? modelMap.modelName : ""
+ }
+ if (serviceModelInfo.contains("modelVersion")) {
+ serviceModelVersion = modelMap.modelVersion !=null ? modelMap.modelVersion : ""
+ }
+ if (serviceModelInfo.contains("modelCustomizationUuid")) {
+ serviceModelCustomizationUuid = modelMap.modelCustomizationUuid !=null ? modelMap.modelCustomizationUuid : ""
+ }
+ if (serviceModelInfo.contains("modelInvariantUuid")) {
+ serviceModelInvariantUuid = modelMap.modelInvariantUuid !=null ? modelMap.modelInvariantUuid : ""
+ }
+ }
+ } catch (Exception ex) {
+ throw ex
+ }
+ }
+
+
+ def subscriptionServiceType = execution.getVariable("subscriptionServiceType") != null ? execution.getVariable("subscriptionServiceType") : ""
+ def globalSubscriberId = execution.getVariable("globalSubscriberId") != null ? execution.getVariable("globalSubscriberId") : ""
+ def requestId = execution.getVariable("msoRequestId")
+ def serviceInstanceId = execution.getVariable("serviceInstanceId") != null ? execution.getVariable("serviceInstanceId") : ""
+ def networkId = (execution.getVariable("networkId")) != null ? execution.getVariable("networkId") : "" // optional
+ def networkName = execution.getVariable("networkName") != null ? execution.getVariable("networkName") : "" // optional
+ def aicCloudReqion = execution.getVariable("lcpCloudRegionId") != null ? execution.getVariable("lcpCloudRegionId") : ""
+ def tenantId = execution.getVariable("tenantId") != null ? execution.getVariable("tenantId") : ""
+ def serviceId = execution.getVariable("productFamilyId") != null ? execution.getVariable("productFamilyId") : ""
+ def failIfExist = execution.getVariable("failIfExists") != null ? execution.getVariable("failIfExists") : ""
+ def suppressRollback = execution.getVariable("disableRollback")
+ def backoutOnFailure = "true"
+ if(suppressRollback != null){
+ if (suppressRollback == true || suppressRollback == "true") {
+ backoutOnFailure = "false"
+ } else if (suppressRollback == false || suppressRollback == "false") {
+ backoutOnFailure = "true"
+ }
+ }
+
+ //'sdncVersion' = current, '1610' (non-RPC SDNC) or '1702' (RPC SDNC)
+ def sdncVersion = execution.getVariable("sdncVersion")
+
+ def source = "VID"
+ def action = execution.getVariable("action")
+
+ def userParamsNode = ""
+ def userParams = execution.getVariable("networkInputParams")
+ if(userParams != null) {
+ userParamsNode = buildUserParams(userParams)
+ }
+
+ def xmlReq = """
+ <network-request xmlns="http://www.w3.org/2001/XMLSchema">
+ <request-info>
+ <request-id>${MsoUtils.xmlEscape(requestId)}</request-id>
+ <action>${MsoUtils.xmlEscape(action)}</action>
+ <source>${MsoUtils.xmlEscape(source)}</source>
+ <service-instance-id>${MsoUtils.xmlEscape(serviceInstanceId)}</service-instance-id>
+ </request-info>
+ <network-inputs>
+ <network-id>${MsoUtils.xmlEscape(networkId)}</network-id>
+ <network-name>${MsoUtils.xmlEscape(networkName)}</network-name>
+ <network-type>${MsoUtils.xmlEscape(networkModelName)}</network-type>
+ <subscription-service-type>${MsoUtils.xmlEscape(subscriptionServiceType)}</subscription-service-type>
+ <global-customer-id>${MsoUtils.xmlEscape(globalSubscriberId)}</global-customer-id>
+ <aic-cloud-region>${MsoUtils.xmlEscape(aicCloudReqion)}</aic-cloud-region>
+ <tenant-id>${MsoUtils.xmlEscape(tenantId)}</tenant-id>
+ <service-id>${MsoUtils.xmlEscape(serviceId)}</service-id>
+ <backout-on-failure>${MsoUtils.xmlEscape(backoutOnFailure)}</backout-on-failure>
+ <failIfExist>${MsoUtils.xmlEscape(failIfExist)}</failIfExist>
+ <networkModelInfo>
+ <modelName>${MsoUtils.xmlEscape(networkModelName)}</modelName>
+ <modelUuid>${MsoUtils.xmlEscape(networkModelUuid)}</modelUuid>
+ <modelInvariantUuid>${MsoUtils.xmlEscape(networkModelInvariantUuid)}</modelInvariantUuid>
+ <modelVersion>${MsoUtils.xmlEscape(networkModelVersion)}</modelVersion>
+ <modelCustomizationUuid>${MsoUtils.xmlEscape(networkModelCustomizationUuid)}</modelCustomizationUuid>
+ </networkModelInfo>
+ <serviceModelInfo>
+ <modelName>${MsoUtils.xmlEscape(serviceModelName)}</modelName>
+ <modelUuid>${MsoUtils.xmlEscape(serviceModelUuid)}</modelUuid>
+ <modelInvariantUuid>${MsoUtils.xmlEscape(serviceModelInvariantUuid)}</modelInvariantUuid>
+ <modelVersion>${MsoUtils.xmlEscape(serviceModelVersion)}</modelVersion>
+ <modelCustomizationUuid>${MsoUtils.xmlEscape(serviceModelCustomizationUuid)}</modelCustomizationUuid>
+
+ </serviceModelInfo>
+ <sdncVersion>${MsoUtils.xmlEscape(sdncVersion)}</sdncVersion>
+ </network-inputs>
+ <network-params>
+ ${userParamsNode}
+ </network-params>
+ </network-request>
+ """
+ // return a pretty-print of the volume-request xml without the preamble
+ return groovy.xml.XmlUtil.serialize(xmlReq.normalize().replaceAll("\t", "").replaceAll("\n", "")).replaceAll("(<\\?[^<]*\\?>\\s*[\\r\\n]*)?", "")
+
+ }
+
+ /**
+ * Create a vnf-request XML using a map
+ * @param requestMap - map created from VID JSON
+ * @param action
+ * @return
+ */
+ public String createXmlVfModuleRequest(execution, Map requestMap, String action, String serviceInstanceId) {
+
+ //def relatedInstanceList = requestMap.requestDetails.relatedInstanceList
+
+ //relatedInstanceList.each {
+ // if (it.relatedInstance.modelInfo.modelType == 'vnf') {
+ // vnfType = it.relatedInstance.modelInfo.modelName
+ // vnfId = it.relatedInstance.modelInfo.modelInvariantId
+ // }
+ //}
+
+ def vnfName = ''
+ def asdcServiceModelInfo = ''
+
+ def relatedInstanceList = requestMap.requestDetails?.relatedInstanceList
+
+
+ if (relatedInstanceList != null) {
+ relatedInstanceList.each {
+ if (it.relatedInstance.modelInfo?.modelType == 'service') {
+ asdcServiceModelInfo = it.relatedInstance.modelInfo?.modelVersion
+ }
+ if (it.relatedInstance.modelInfo.modelType == 'vnf') {
+ vnfName = it.relatedInstance.instanceName ?: ''
+ }
+ }
+ }
+
+ def vnfType = execution.getVariable('vnfType')
+ def vnfId = execution.getVariable('vnfId')
+
+ def vfModuleId = execution.getVariable('vfModuleId')
+ def volumeGroupId = execution.getVariable('volumeGroupId')
+ def userParams = requestMap.requestDetails?.requestParameters?.userParams
+
+
+ def userParamsNode = ''
+ if(userParams != null) {
+ userParamsNode = buildUserParams(userParams)
+ }
+
+ def isBaseVfModule = "false"
+ if (execution.getVariable('isBaseVfModule') == true) {
+ isBaseVfModule = "true"
+ }
+
+ def requestId = execution.getVariable("mso-request-id")
+ def vfModuleName = requestMap.requestDetails?.requestInfo?.instanceName ?: ''
+ def vfModuleModelName = requestMap.requestDetails?.modelInfo?.modelName ?: ''
+ def suppressRollback = requestMap.requestDetails?.requestInfo?.suppressRollback
+
+ def backoutOnFailure = ""
+ if(suppressRollback != null){
+ if ( suppressRollback == true) {
+ backoutOnFailure = "false"
+ } else if ( suppressRollback == false) {
+ backoutOnFailure = "true"
+ }
+ }
+
+ def serviceId = requestMap.requestDetails?.requestParameters?.serviceId ?: ''
+ def aicCloudRegion = requestMap.requestDetails?.cloudConfiguration?.lcpCloudRegionId ?: ''
+ def tenantId = requestMap.requestDetails?.cloudConfiguration?.tenantId ?: ''
+ def personaModelId = requestMap.requestDetails?.modelInfo?.modelInvariantUuid ?: ''
+ def personaModelVersion = requestMap.requestDetails?.modelInfo?.modelUuid ?: ''
+ def modelCustomizationId = requestMap.requestDetails?.modelInfo?.modelCustomizationUuid ?: ''
+
+ def xmlReq = """
+ <vnf-request>
+ <request-info>
+ <request-id>${MsoUtils.xmlEscape(requestId)}</request-id>
+ <action>${MsoUtils.xmlEscape(action)}</action>
+ <source>VID</source>
+ <service-instance-id>${MsoUtils.xmlEscape(serviceInstanceId)}</service-instance-id>
+ </request-info>
+ <vnf-inputs>
+ <!-- not in use in 1610 -->
+ <vnf-name>${MsoUtils.xmlEscape(vnfName)}</vnf-name>
+ <vnf-type>${MsoUtils.xmlEscape(vnfType)}</vnf-type>
+ <vnf-id>${MsoUtils.xmlEscape(vnfId)}</vnf-id>
+ <volume-group-id>${MsoUtils.xmlEscape(volumeGroupId)}</volume-group-id>
+ <vf-module-id>${MsoUtils.xmlEscape(vfModuleId)}</vf-module-id>
+ <vf-module-name>${MsoUtils.xmlEscape(vfModuleName)}</vf-module-name>
+ <vf-module-model-name>${MsoUtils.xmlEscape(vfModuleModelName)}</vf-module-model-name>
+ <model-customization-id>${MsoUtils.xmlEscape(modelCustomizationId)}</model-customization-id>
+ <is-base-vf-module>${MsoUtils.xmlEscape(isBaseVfModule)}</is-base-vf-module>
+ <asdc-service-model-version>${MsoUtils.xmlEscape(asdcServiceModelInfo)}</asdc-service-model-version>
+ <aic-cloud-region>${MsoUtils.xmlEscape(aicCloudRegion)}</aic-cloud-region>
+ <tenant-id>${MsoUtils.xmlEscape(tenantId)}</tenant-id>
+ <service-id>${MsoUtils.xmlEscape(serviceId)}</service-id>
+ <backout-on-failure>${MsoUtils.xmlEscape(backoutOnFailure)}</backout-on-failure>
+ <persona-model-id>${MsoUtils.xmlEscape(personaModelId)}</persona-model-id>
+ <persona-model-version>${MsoUtils.xmlEscape(personaModelVersion)}</persona-model-version>
+ </vnf-inputs>
+ <vnf-params>
+ $userParamsNode
+ </vnf-params>
+ </vnf-request>
+ """
+
+ // return a pretty-print of the volume-request xml without the preamble
+ return groovy.xml.XmlUtil.serialize(xmlReq.normalize().replaceAll("\t", "").replaceAll("\n", "")).replaceAll("(<\\?[^<]*\\?>\\s*[\\r\\n]*)?", "")
+ }
+
+
+}
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
new file mode 100644
index 0000000000..52f45c205c
--- /dev/null
+++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/VnfAdapterRestV1.groovy
@@ -0,0 +1,419 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.so.bpmn.common.scripts
+
+import 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.logger.MessageEnum
+import org.onap.so.logger.MsoLogger
+
+
+
+class VnfAdapterRestV1 extends AbstractServiceTaskProcessor {
+ private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, VnfAdapterRestV1.class);
+
+
+ ExceptionUtil exceptionUtil = new ExceptionUtil()
+
+ // VNF Response Processing
+ public void preProcessRequest (DelegateExecution execution) {
+ def method = getClass().getSimpleName() + '.preProcessRequest(' +
+ 'execution=' + execution.getId() +
+ ')'
+ msoLogger.trace('Entered ' + method)
+
+ def prefix="VNFREST_"
+ execution.setVariable("prefix", prefix)
+ setSuccessIndicator(execution, false)
+
+ try {
+ String request = validateRequest(execution, "mso-request-id")
+
+ // Get the request type (the name of the root element) from the request
+
+ Node root = new XmlParser().parseText(request)
+ String requestType = root.name()
+ execution.setVariable(prefix + 'requestType', requestType)
+ msoLogger.debug(getProcessKey(execution) + ': ' + prefix + 'requestType = ' + requestType)
+
+ msoLogger.debug('VnfAdapterRestV1, request: ' + request)
+ // Get the messageId from the request
+
+ String messageId = getChildText(root, 'messageId')
+
+ 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, "");
+ exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg)
+ }
+
+ execution.setVariable('VNFAResponse_CORRELATOR', messageId)
+ msoLogger.debug(getProcessKey(execution) + ': VNFAResponse_CORRELATOR = ' + messageId)
+
+ // Get the notificationUrl from the request
+
+ String notificationUrl = getChildText(root, 'notificationUrl')
+
+ if (notificationUrl == null || notificationUrl.isEmpty()) {
+ String msg = getProcessKey(execution) + ': no notificationUrl in ' + requestType
+ msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, msg, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "");
+ exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg)
+ }
+
+ execution.setVariable(prefix + 'notificationUrl', notificationUrl)
+ msoLogger.debug(getProcessKey(execution) + ': ' + prefix + 'notificationUrl = ' + notificationUrl)
+
+ // Determine the VnfAdapter endpoint
+
+ String vnfAdapterEndpoint = UrnPropertiesReader.getVariable("mso.adapters.vnf.rest.endpoint", execution)
+
+ if (vnfAdapterEndpoint == null || vnfAdapterEndpoint.isEmpty()) {
+ String msg = getProcessKey(execution) + ': mso:adapters:vnf:rest:endpoint URN mapping is not defined'
+ msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, msg, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "");
+ exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg)
+ }
+
+ while (vnfAdapterEndpoint.endsWith('/')) {
+ vnfAdapterEndpoint = vnfAdapterEndpoint.substring(0, vnfAdapterEndpoint.length()-1)
+ }
+
+ String vnfAdapterMethod = null
+ String vnfAdapterUrl = null
+ String vnfAdapterRequest = request
+
+ if ('createVfModuleRequest'.equals(requestType)) {
+ String vnfId = getChildText(root, 'vnfId')
+
+ if (vnfId == null || vnfId.isEmpty()) {
+ String msg = getProcessKey(execution) + ': no vnfId in ' + requestType
+ msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, msg, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "");
+ exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg)
+ }
+
+ vnfAdapterMethod = 'POST'
+ vnfAdapterUrl = vnfAdapterEndpoint + '/' + URLEncoder.encode(vnfId, 'UTF-8') + '/vf-modules'
+
+ } else if ('updateVfModuleRequest'.equals(requestType)) {
+ String vnfId = getChildText(root, 'vnfId')
+
+ if (vnfId == null || vnfId.isEmpty()) {
+ String msg = getProcessKey(execution) + ': no vnfId in ' + requestType
+ msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, msg, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "");
+ exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg)
+ }
+
+ String vfModuleId = getChildText(root, 'vfModuleId')
+
+ if (vfModuleId == null || vfModuleId.isEmpty()) {
+ String msg = getProcessKey(execution) + ': no vfModuleId in ' + requestType
+ msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, msg, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "");
+ exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg)
+ }
+
+ vnfAdapterMethod = 'PUT'
+ vnfAdapterUrl = vnfAdapterEndpoint + '/' + URLEncoder.encode(vnfId, 'UTF-8') +
+ '/vf-modules/' + URLEncoder.encode(vfModuleId, 'UTF-8')
+
+ } else if ('deleteVfModuleRequest'.equals(requestType)) {
+ String vnfId = getChildText(root, 'vnfId')
+
+ if (vnfId == null || vnfId.isEmpty()) {
+ String msg = getProcessKey(execution) + ': no vnfId in ' + requestType
+ msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, msg, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "");
+ exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg)
+ }
+
+ String vfModuleId = getChildText(root, 'vfModuleId')
+
+ if (vfModuleId == null || vfModuleId.isEmpty()) {
+ String msg = getProcessKey(execution) + ': no vfModuleId in ' + requestType
+ msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, msg, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "");
+ exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg)
+ }
+
+ vnfAdapterMethod = 'DELETE'
+ vnfAdapterUrl = vnfAdapterEndpoint + '/' + URLEncoder.encode(vnfId, 'UTF-8') +
+ '/vf-modules/' + URLEncoder.encode(vfModuleId, 'UTF-8')
+
+ } else if ('rollbackVfModuleRequest'.equals(requestType)) {
+ Node vfModuleRollbackNode = getChild(root, 'vfModuleRollback')
+
+ if (vfModuleRollbackNode == null) {
+ String msg = getProcessKey(execution) + ': no vfModuleRollback in ' + requestType
+ msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, msg, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "");
+ exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg)
+ }
+
+ String vnfId = getChildText(vfModuleRollbackNode, 'vnfId')
+
+ if (vnfId == null || vnfId.isEmpty()) {
+ String msg = getProcessKey(execution) + ': no vnfId in ' + requestType
+ msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, msg, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "");
+ exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg)
+ }
+
+ String vfModuleId = getChildText(vfModuleRollbackNode, 'vfModuleId')
+
+ if (vfModuleId == null || vfModuleId.isEmpty()) {
+ String msg = getProcessKey(execution) + ': no vfModuleId in ' + requestType
+ msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, msg, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "");
+ exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg)
+ }
+
+ vnfAdapterMethod = 'DELETE'
+ vnfAdapterUrl = vnfAdapterEndpoint + '/' + URLEncoder.encode(vnfId, 'UTF-8') +
+ '/vf-modules/' + URLEncoder.encode(vfModuleId, 'UTF-8') + '/rollback'
+
+ } else if ('createVolumeGroupRequest'.equals(requestType)) {
+ vnfAdapterMethod = 'POST'
+ if (vnfAdapterEndpoint.endsWith('v1/vnfs')) {
+ vnfAdapterEndpoint = vnfAdapterEndpoint.substring(0, (vnfAdapterEndpoint.length()-'/vnfs'.length()))
+ }
+ vnfAdapterUrl = vnfAdapterEndpoint + '/volume-groups'
+
+ } else if ('updateVolumeGroupRequest'.equals(requestType)) {
+ String volumeGroupId = getChildText(root, 'volumeGroupId')
+
+ if (volumeGroupId == null || volumeGroupId.isEmpty()) {
+ String msg = getProcessKey(execution) + ': no volumeGroupId in ' + requestType
+ msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, msg, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "");
+ exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg)
+ }
+
+ vnfAdapterMethod = 'PUT'
+ if (vnfAdapterEndpoint.endsWith('v1/vnfs')) {
+ vnfAdapterEndpoint = vnfAdapterEndpoint.substring(0, (vnfAdapterEndpoint.length()-'/vnfs'.length()))
+ }
+ vnfAdapterUrl = vnfAdapterEndpoint + '/volume-groups/' + URLEncoder.encode(volumeGroupId, 'UTF-8')
+
+ } else if ('deleteVolumeGroupRequest'.equals(requestType)) {
+ String volumeGroupId = getChildText(root, 'volumeGroupId')
+
+ if (volumeGroupId == null || volumeGroupId.isEmpty()) {
+ String msg = getProcessKey(execution) + ': no volumeGroupId in ' + requestType
+ msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, msg, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "");
+ exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg)
+ }
+
+ vnfAdapterMethod = 'DELETE'
+ if (vnfAdapterEndpoint.endsWith('v1/vnfs')) {
+ vnfAdapterEndpoint = vnfAdapterEndpoint.substring(0, (vnfAdapterEndpoint.length()-'/vnfs'.length()))
+ }
+ vnfAdapterUrl = vnfAdapterEndpoint + '/volume-groups/' + URLEncoder.encode(volumeGroupId, 'UTF-8')
+
+ } else if ('rollbackVolumeGroupRequest'.equals(requestType)) {
+ String volumeGroupId = getVolumeGroupIdFromRollbackRequest(root)
+
+ if (volumeGroupId == null || volumeGroupId.isEmpty()) {
+ String msg = getProcessKey(execution) + ': no volumeGroupId in ' + requestType
+ msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, msg, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "");
+ exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg)
+ }
+
+ vnfAdapterMethod = 'DELETE'
+ if (vnfAdapterEndpoint.endsWith('v1/vnfs')) {
+ vnfAdapterEndpoint = vnfAdapterEndpoint.substring(0, (vnfAdapterEndpoint.length()-'/vnfs'.length()))
+ }
+ vnfAdapterUrl = vnfAdapterEndpoint + '/volume-groups/' + URLEncoder.encode(volumeGroupId, 'UTF-8') + '/rollback'
+
+ } else {
+ String msg = getProcessKey(execution) + ': Unsupported request type: ' + requestType
+ msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, msg, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "");
+ exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg)
+ }
+
+ execution.setVariable(prefix + 'vnfAdapterMethod', vnfAdapterMethod)
+ msoLogger.debug(getProcessKey(execution) + ': ' + prefix + 'vnfAdapterMethod = ' + vnfAdapterMethod)
+ execution.setVariable(prefix + 'vnfAdapterUrl', vnfAdapterUrl)
+ msoLogger.debug(getProcessKey(execution) + ': ' + prefix + 'vnfAdapterUrl = ' + vnfAdapterUrl)
+ execution.setVariable(prefix + 'vnfAdapterRequest', vnfAdapterRequest)
+ msoLogger.debug(getProcessKey(execution) + ': ' + prefix + 'vnfAdapterRequest = \n' + vnfAdapterRequest)
+
+ // Get the Basic Auth credentials for the VnfAdapter
+
+ String basicAuthValue = UrnPropertiesReader.getVariable("mso.adapters.po.auth", execution)
+
+ if (basicAuthValue == null || basicAuthValue.isEmpty()) {
+ msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, getProcessKey(execution) + ": mso:adapters:po:auth URN mapping is not defined", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "");
+ } else {
+ try {
+ def encodedString = utils.getBasicAuth(basicAuthValue, UrnPropertiesReader.getVariable("mso.msoKey", execution))
+ execution.setVariable(prefix + 'basicAuthHeaderValue', encodedString)
+ } catch (IOException ex) {
+ msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, getProcessKey(execution) + ": Unable to encode BasicAuth credentials for VnfAdapter", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "");
+ }
+ }
+
+ } catch (BpmnError e) {
+ msoLogger.debug(" Rethrowing MSOWorkflowException")
+ throw e
+ } catch (Exception e) {
+ String msg = 'Caught exception in ' + method + ": " + e
+ msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, msg, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "");
+ msoLogger.debug(msg)
+ exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg)
+ }
+ }
+
+ public String getVolumeGroupIdFromRollbackRequest(Node root) {
+ return root.'volumeGroupRollback'.'volumeGroupId'.text()
+ }
+
+ 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.
+ */
+ public void sendRequestToVnfAdapter(DelegateExecution execution) {
+ def method = getClass().getSimpleName() + '.sendRequestToVnfAdapter(' +
+ 'execution=' + execution.getId() +
+ ')'
+ msoLogger.trace('Entered ' + method)
+
+ String prefix = execution.getVariable('prefix')
+
+ try {
+ String vnfAdapterMethod = execution.getVariable(prefix + 'vnfAdapterMethod')
+ 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"));
+
+ APIResponse response;
+
+ if ("GET".equals(vnfAdapterMethod)) {
+ response = client.httpGet()
+ } else if ("PUT".equals(vnfAdapterMethod)) {
+ response = client.httpPut(vnfAdapterRequest)
+ } else if ("POST".equals(vnfAdapterMethod)) {
+ response = client.httpPost(vnfAdapterRequest)
+ } else if ("DELETE".equals(vnfAdapterMethod)) {
+ response = client.httpDelete(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())
+ } catch (BpmnError e) {
+ throw e
+ } catch (Exception e) {
+ String msg = 'Caught exception in ' + method + ": " + e
+ msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, msg, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "");
+ exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg)
+ }
+ }
+
+ public void processCallback(DelegateExecution execution){
+ def method = getClass().getSimpleName() + '.processCallback(' +
+ 'execution=' + execution.getId() +
+ ')'
+ msoLogger.trace('Entered ' + method)
+
+ String callback = execution.getVariable('VNFAResponse_MESSAGE')
+
+ try {
+ msoLogger.debug(getProcessKey(execution) + ": received callback:\n" + callback)
+
+ // The XML callback is available to the calling flow in any case,
+ // even if a WorkflowException is generated.
+ execution.setVariable(getProcessKey(execution) + 'Response', callback)
+ // TODO: Should deprecate use of processKey+Response variable for the response. Will use "WorkflowResponse" instead.
+ execution.setVariable("WorkflowResponse", 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)
+ }
+ }
+
+ /**
+ * Tries to parse the response as XML to extract the information to create
+ * a WorkflowException. If the response cannot be parsed, a more generic
+ * WorkflowException is created.
+ */
+ public void vnfAdapterWorkflowException(DelegateExecution execution, Object response) {
+ try {
+ Node root = new XmlParser().parseText(response)
+ String category = getChildText(root, "category")
+ category = category == null || category.isEmpty() ? "" : " category='" + category + "'"
+ String message = getChildText(root, "message")
+ message = message == null || message.isEmpty() ? "" : " message='" + message + "'"
+ String rolledBack = getChildText(root, "rolledBack")
+ rolledBack = rolledBack == null || rolledBack.isEmpty() ? "" : " rolledBack='" + rolledBack + "'"
+ exceptionUtil.buildWorkflowException(execution, 7020, "Received " + root.name() +
+ " from VnfAdapter:" + category + message + rolledBack);
+ } catch (Exception e) {
+ response = response == null || String.valueOf(response).isEmpty() ? "NONE" : response
+ exceptionUtil.buildWorkflowException(execution, 7020, "Received error from VnfAdapter: " + response)
+ }
+ }
+
+ /**
+ * Gets the named child of the specified node.
+ * @param node the node
+ * @param name the child name
+ * @return the child node, or null if no such child exists
+ */
+ private Node getChild(Node node, String name) {
+ for (Node child : node.children()) {
+ if (child.name() == name) {
+ return child
+ }
+ }
+ return null
+ }
+
+ /**
+ * Gets the text of the named child of the specified node.
+ * @param node the node
+ * @param name the child name
+ * @return the child node text, or null if no such child exists
+ */
+ private String getChildText(Node node, String name) {
+ Node child = getChild(node, name)
+ return child == null ? null : child.text()
+ }
+}
diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/VnfAdapterUtils.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/VnfAdapterUtils.groovy
new file mode 100644
index 0000000000..8c979fca0b
--- /dev/null
+++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/VnfAdapterUtils.groovy
@@ -0,0 +1,90 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.so.bpmn.common.scripts
+
+import org.camunda.bpm.engine.delegate.BpmnError
+import org.camunda.bpm.engine.delegate.DelegateExecution;
+import org.onap.so.bpmn.core.WorkflowException
+import org.onap.so.logger.MessageEnum
+import org.onap.so.logger.MsoLogger
+
+
+
+class VnfAdapterUtils {
+ private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, VnfAdapterUtils.class);
+
+
+ private AbstractServiceTaskProcessor taskProcessor
+
+ public VnfAdapterUtils(AbstractServiceTaskProcessor taskProcessor) {
+ this.taskProcessor = taskProcessor
+ }
+
+ ExceptionUtil exceptionUtil = new ExceptionUtil()
+
+ public void validateVnfResponse(DelegateExecution execution, String responseVar, String responseCodeVar, String errorResponseVar) {
+ def method = getClass().getSimpleName() + '.validateVnfResponse(' +
+ 'execution=' + execution.getId() +
+ ', responseVar=' + responseVar +
+ ', responseCodeVar=' + responseCodeVar +
+ ', errorResponseVar=' + errorResponseVar +
+ ')'
+ msoLogger.trace('Entered ' + method)
+
+ try {
+ def prefix = execution.getVariable('prefix')
+
+ def response = execution.getVariable(responseVar)
+ def responseCode = execution.getVariable(responseCodeVar)
+ def errorResponse = execution.getVariable(errorResponseVar)
+
+ // The following if statement never appears to be true as any VNF Adapter error seems to be stored in 'errorResponse'.
+ // Also, the value is stored as a WorkflowException object, not a String. Added the else if to provide the proper
+ // functionality but leaving the original code in case it is hit under some circumstances.
+ if (response.contains("WorkflowException")) {
+ execution.setVariable(prefix + "ErrorResponse", response)
+ //execution.setVariable(prefix + "ResponseCode", responseCode)
+ msoLogger.debug(" Sub Vnf flow Error WorkflowException Response - " + "\n" + response)
+ throw new BpmnError("MSOWorkflowException")
+ } else if (errorResponse != null && errorResponse instanceof WorkflowException) {
+ // Not sure the variables with the associated prefix are still used
+ execution.setVariable(prefix + "ErrorResponse", errorResponse.getErrorMessage())
+ execution.setVariable(prefix + "ResponseCode", errorResponse.getErrorCode())
+ msoLogger.debug("Sub Vnf flow Error WorkflowException " + prefix + "ErrorResponse" + " - " + errorResponse.getErrorMessage())
+ // this is the important part to ensure we hit the Fallout Handler
+ throw new BpmnError("MSOWorkflowException")
+ } else if (errorResponse != null && errorResponse instanceof WorkflowException) {
+ // Not sure the variables with the associated prefix are still used
+ execution.setVariable(prefix + "ErrorResponse", errorResponse.getErrorMessage())
+ execution.setVariable(prefix + "ResponseCode", errorResponse.getErrorCode())
+ msoLogger.debug("Sub Vnf flow Error WorkflowException " + prefix + "ErrorResponse" + " - " + errorResponse.getErrorMessage())
+ // this is the important part to ensure we hit the Fallout Handler
+ throw new BpmnError("MSOWorkflowException")
+ }
+ } catch (BpmnError e) {
+ throw e;
+ } catch (Exception e) {
+ msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e);
+ exceptionUtil.buildAndThrowWorkflowException(execution, 5000, 'Internal Error- Unable to validate VNF Response ' + e.getMessage())
+ }
+ }
+
+}