From 94ee92559b051f2f82ed681f841f4f13016842ed Mon Sep 17 00:00:00 2001 From: "Determe, Sebastien (sd378r)" Date: Tue, 2 May 2017 03:53:18 -0700 Subject: [MSO-8] Second step of the rebase for MSO Second rebase containing additional features for MSO + total reworking of the BPMN structure + Notification flow can now be added at the end of some BPMN flows Change-Id: I7e937c7a0ba1593ca85e164a093f79c7e38b6ce0 Signed-off-by: Determe, Sebastien (sd378r) --- bpmn/MSOCockpit/pom.xml | 142 +- .../MSOCockpit/src/main/assembly/cockpit-build.xml | 180 +- bpmn/MSOCommonBPMN/pom.xml | 784 +-- .../mso/bpmn/common/scripts/AaiUtil.groovy | 1043 ++-- .../scripts/AbstractServiceTaskProcessor.groovy | 1684 +++--- .../mso/bpmn/common/scripts/CatalogDbUtils.groovy | 1481 +++-- .../bpmn/common/scripts/CompleteMsoProcess.groovy | 722 +-- .../common/scripts/ConfirmVolumeGroupName.groovy | 316 +- .../common/scripts/ConfirmVolumeGroupTenant.groovy | 388 +- .../bpmn/common/scripts/CreateAAIVfModule.groovy | 1243 ++-- .../scripts/CreateAAIVfModuleVolumeGroup.groovy | 666 +-- .../common/scripts/CreateGenericVNFUtils.groovy | 124 +- .../bpmn/common/scripts/DeleteAAIVfModule.groovy | 681 +-- .../mso/bpmn/common/scripts/ExceptionUtil.groovy | 997 ++-- .../mso/bpmn/common/scripts/FalloutHandler.groovy | 778 +-- .../common/scripts/GenerateVfModuleName.groovy | 332 +- .../common/scripts/GenericDeleteService.groovy | 611 +- .../bpmn/common/scripts/GenericDeleteVnf.groovy | 552 +- .../bpmn/common/scripts/GenericGetService.groovy | 766 +-- .../mso/bpmn/common/scripts/GenericGetVnf.groovy | 543 +- .../scripts/GenericNotificationService.groovy | 21 + .../mso/bpmn/common/scripts/GenericPutVnf.groovy | 344 +- .../mso/bpmn/common/scripts/MsoUtils.groovy | 1895 +++--- .../mso/bpmn/common/scripts/NetworkUtils.groovy | 2936 +++++----- .../common/scripts/PrepareUpdateAAIVfModule.groovy | 742 +-- .../mso/bpmn/common/scripts/SDNCAdapter.groovy | 654 ++- .../bpmn/common/scripts/SDNCAdapterRestV1.groovy | 343 ++ .../bpmn/common/scripts/SDNCAdapterUtils.groovy | 1891 +++--- .../common/scripts/ServiceTaskProcessor.groovy | 64 +- .../common/scripts/TrinityExceptionUtil.groovy | 382 ++ .../bpmn/common/scripts/UpdateAAIGenericVnf.groovy | 663 ++- .../bpmn/common/scripts/UpdateAAIVfModule.groovy | 763 ++- .../mso/bpmn/common/scripts/VfModule.groovy | 174 +- .../mso/bpmn/common/scripts/VfModuleBase.groovy | 1607 +++-- .../mso/bpmn/common/scripts/VidUtils.groovy | 1100 ++-- .../bpmn/common/scripts/VnfAdapterRestV1.groovy | 808 +-- .../mso/bpmn/common/scripts/VnfAdapterUtils.groovy | 164 +- .../mso/bpmn/common/MSOCommonApplication.java | 118 +- .../bpmn/common/adapter/sdnc/ObjectFactory.java | 182 +- .../bpmn/common/adapter/sdnc/RequestHeader.java | 446 +- .../common/adapter/sdnc/SDNCAdapterResponse.java | 102 +- .../common/adapter/vnf/DeleteVnfNotification.java | 396 +- .../common/adapter/vnf/MsoExceptionCategory.java | 122 +- .../mso/bpmn/common/adapter/vnf/MsoRequest.java | 228 +- .../common/adapter/vnf/QueryVnfNotification.java | 976 ++-- .../mso/bpmn/common/adapter/vnf/VnfStatus.java | 122 +- .../mso/bpmn/common/util/CryptoHandler.java | 114 +- .../mso/bpmn/common/util/CryptoUtils.java | 236 +- .../mso/bpmn/common/util/ICryptoHandler.java | 54 +- .../service/SDNCAdapterCallbackServiceImpl.java | 534 +- .../service/WorkflowAsyncCommonResource.java | 72 +- .../workflow/service/WorkflowAsyncResource.java | 582 +- .../workflow/service/WorkflowCallbackResponse.java | 104 +- .../common/workflow/service/WorkflowContext.java | 192 +- .../workflow/service/WorkflowContextHolder.java | 376 +- .../workflow/service/WorkflowMessageResource.java | 280 +- .../common/workflow/service/WorkflowResource.java | 1234 ++-- .../service/WorkflowResourceApplication.java | 114 +- .../common/workflow/service/WorkflowResponse.java | 138 +- .../src/main/resources/META-INF/persistence.xml | 74 +- .../MSOCommonBPMN/src/main/resources/processes.xml | 81 + .../resources/subprocess/CompleteMsoProcess.bpmn | 395 +- .../subprocess/ConfirmVolumeGroupTenant.bpmn | 362 +- .../resources/subprocess/CreateAAIVfModule.bpmn | 1036 ++-- .../resources/subprocess/DeleteAAIVfModule.bpmn | 918 +-- .../main/resources/subprocess/FalloutHandler.bpmn | 369 +- .../resources/subprocess/GenericDeleteService.bpmn | 599 +- .../resources/subprocess/GenericDeleteVnf.bpmn | 500 +- .../main/resources/subprocess/GenericGetVnf.bpmn | 396 +- .../subprocess/GenericNotificationService.bpmn | 48 + .../resources/subprocess/GenericPutService.bpmn | 402 +- .../main/resources/subprocess/GenericPutVnf.bpmn | 252 +- .../resources/subprocess/SDNCAdapterRestV1.bpmn | 470 ++ .../main/resources/subprocess/SDNCAdapterV1.bpmn | 290 +- .../resources/subprocess/VnfAdapterRestV1.bpmn | 882 +-- .../webapp/WEB-INF/jboss-deployment-structure.xml | 62 +- .../src/main/webapp/WEB-INF/jboss-web.xml | 52 +- bpmn/MSOCommonBPMN/src/main/webapp/WEB-INF/web.xml | 146 +- .../mso/bpmn/common/scripts/AaiUtilTest.groovy | 624 +- .../bpmn/common/scripts/ExceptionUtilTest.groovy | 256 +- .../bpmn/common/scripts/FalloutHandlerTest.groovy | 620 +- .../mso/bpmn/common/scripts/SDNCAdapterTest.groovy | 1894 +++--- .../common/scripts/TrinityExceptionUtilTest.groovy | 201 + .../org/openecomp/mso/bpmn/common/BPMNUtil.java | 428 +- .../mso/bpmn/common/CompleteMsoProcessTest.java | 424 +- .../mso/bpmn/common/CreateAAIVfModuleTest.java | 552 +- .../mso/bpmn/common/DeleteAAIVfModuleTest.java | 1286 ++-- .../mso/bpmn/common/FalloutHandlerTest.java | 456 +- .../bpmn/common/PrepareUpdateAAIVfModuleTest.java | 418 +- .../mso/bpmn/common/SDNCAdapterV1Test.java | 792 +-- .../mso/bpmn/common/UpdateAAIGenericVnfTest.java | 344 +- .../mso/bpmn/common/UpdateAAIVfModuleTest.java | 276 +- .../openecomp/mso/bpmn/common/WorkflowTest.java | 3592 ++++++------ .../mso/bpmn/common/WorkflowTestTransformer.java | 40 +- .../__files/CRTGVNF_queryAAIResponseVolume.xml | 42 +- .../CRTGVNF_queryAAIResponseVolume_idsNotMatch.xml | 42 +- ..._genericQueryByInstanceName_AAIResponse_200.xml | 24 +- .../__files/GENDSI_getServiceInstanceResponse.xml | 68 +- .../GenericFlows/getGenericVnfByNameResponse.xml | 44 +- .../__files/GenericFlows/getGenericVnfResponse.xml | 178 +- .../getGenericVnfResponse_hasRelationships.xml | 178 +- .../__files/GenericFlows/getSIUrlById.xml | 10 +- .../__files/GenericFlows/getSIUrlByName.xml | 10 +- .../__files/GenericFlows/getServiceInstance.xml | 58 +- .../GenericFlows/getServiceSubscription.xml | 66 +- .../__files/GenericFlows/getVceByNameResponse.xml | 192 +- .../__files/GenericFlows/getVceResponse.xml | 192 +- .../sdncadaptercallbackrequest.xml | 698 +-- .../updateNetwork_queryInstance_Success.xml | 6 +- ...ueryNetworkId_AAIResponse_NoPayload_Success.xml | 146 +- ...k_queryNetworkTableRef1_AAIResponse_Success.xml | 38 +- ...k_queryNetworkTableRef2_AAIResponse_Success.xml | 38 +- .../AddNetworkPolicy_AAIResponse_Success.xml | 40 +- .../resources/__files/VfModularity/GenericVnf.xml | 76 +- .../QueryNetworkPolicy_AAIResponse_Success.xml | 40 +- .../VfModularity/SDNCTopologyQueryCallback.xml | 630 +- .../SDNCTopologyQueryCallbackVfModule.xml | 282 +- .../__files/VfModularity/VfModule-lukewarm.xml | 18 +- .../__files/VfModularity/VfModule-new.xml | 16 +- .../__files/VfModularity/VfModule-supercool.xml | 52 +- .../resources/__files/VfModularity/VolumeGroup.xml | 48 +- .../resources/__files/aai-volume-group-id-info.xml | 56 +- .../src/test/resources/mso.bpmn.urn.properties | 170 +- .../test/resources/sdncCallbackErrorResponse.xml | 2 +- .../src/test/resources/sdncDeleteResponse.xml | 422 +- .../test/resources/sdncadaptercallbackrequest.xml | 684 +-- .../sdncadaptercallbackrequest_404CallBack.xml | 24 +- .../openecomp/mso/bpmn/core/XQueryScriptTask.java | 484 +- .../openecomp/mso/bpmn/core/json/JsonUtils.java | 1660 +++--- .../WebContent/META-INF/MANIFEST.MF | 6 +- bpmn/MSOInfrastructureBPMN/pom.xml | 776 +-- .../CreateGenericMacroServiceNetworkVnf.groovy | 1499 ++--- .../scripts/CreateNetworkInstance.groovy | 92 +- .../scripts/CreateServiceInstance.groovy | 522 +- .../scripts/CreateVfModuleInfra.groovy | 264 +- .../scripts/CreateVfModuleVolumeInfraV1.groovy | 608 +- .../scripts/DelServiceInstance.groovy | 706 +-- .../DeleteGenericMacroServiceNetworkVnf.groovy | 942 ++- .../scripts/DeleteNetworkInstance.groovy | 834 +-- .../scripts/DeleteVfModuleInfra.groovy | 122 +- .../scripts/DeleteVfModuleVolumeInfraV1.groovy | 1120 ++-- .../scripts/DoCreateNetworkInstance.groovy | 89 +- .../scripts/DoCreateNetworkInstanceRollback.groovy | 774 +-- .../scripts/DoCreateServiceInstance.groovy | 115 +- .../scripts/DoCreateServiceInstanceRollback.groovy | 462 +- .../infrastructure/scripts/DoCreateVfModule.groovy | 461 +- .../scripts/DoCreateVfModuleRollback.groovy | 292 +- .../bpmn/infrastructure/scripts/DoCreateVnf.groovy | 804 +-- .../scripts/DoCreateVnfAndModules.groovy | 526 +- .../scripts/DoCreateVnfAndModulesRollback.groovy | 153 + .../scripts/DoDeleteNetworkInstance.groovy | 111 +- .../scripts/DoDeleteNetworkInstanceRollback.groovy | 670 +-- .../scripts/DoDeleteServiceInstance.groovy | 840 +-- .../infrastructure/scripts/DoDeleteVfModule.groovy | 118 +- .../bpmn/infrastructure/scripts/DoDeleteVnf.groovy | 272 +- .../scripts/DoDeleteVnfAndModules.groovy | 256 + .../scripts/DoUpdateNetworkInstance.groovy | 1399 +++++ .../scripts/DoUpdateNetworkInstanceRollback.groovy | 304 + .../infrastructure/scripts/DoUpdateVfModule.groovy | 1708 +++--- .../scripts/HealchCheckActivate.groovy | 108 +- .../scripts/UpdateNetworkInstance.groovy | 452 ++ .../scripts/UpdateNetworkInstanceInfra.groovy | 148 +- .../infrastructure/scripts/UpdateVfModule.groovy | 132 +- .../scripts/UpdateVfModuleInfra.groovy | 132 +- .../scripts/UpdateVfModuleVolume.groovy | 169 +- .../scripts/UpdateVfModuleVolumeInfraV1.groovy | 1098 ++-- .../MSOInfrastructureApplication.java | 116 +- .../WorkflowAsyncInfrastructureResource.java | 100 +- .../service/WorkflowResourceApplication.java | 114 +- .../src/main/resources/META-INF/persistence.xml | 74 +- .../src/main/resources/META-INF/processes.xml | 162 +- .../src/main/resources/logback.xml | 318 +- .../CreateGenericMacroServiceNetworkVnf.bpmn | 2406 ++++---- .../resources/process/CreateNetworkInstance.bpmn | 3 +- .../resources/process/CreateServiceInstance.bpmn | 2 +- .../resources/process/CreateVfModuleInfra.bpmn | 335 +- .../process/CreateVfModuleVolumeInfraV1.bpmn | 341 +- .../src/main/resources/process/CreateVnfInfra.bpmn | 6 +- .../main/resources/process/DelServiceInstance.bpmn | 2 +- .../DeleteGenericMacroServiceNetworkVnf.bpmn | 1542 ++--- .../resources/process/DeleteNetworkInstance.bpmn | 741 +-- .../resources/process/DeleteVfModuleInfra.bpmn | 3 +- .../process/DeleteVfModuleVolumeInfraV1.bpmn | 1 - .../src/main/resources/process/DeleteVnfInfra.bpmn | 4 +- .../resources/process/UpdateNetworkInstance.bpmn | 372 ++ .../process/UpdateNetworkInstanceInfra.bpmn | 688 ++- .../process/UpdateVfModuleVolumeInfraV1.bpmn | 1 - .../subprocess/DoCreateNetworkInstance.bpmn | 139 +- .../subprocess/DoCreateServiceInstance.bpmn | 780 +-- .../DoCreateServiceInstanceRollback.bpmn | 676 +-- .../resources/subprocess/DoCreateVfModule.bpmn | 2171 +++---- .../subprocess/DoCreateVfModuleRollback.bpmn | 29 +- .../src/main/resources/subprocess/DoCreateVnf.bpmn | 95 +- .../subprocess/DoCreateVnfAndModules.bpmn | 145 +- .../subprocess/DoCreateVnfAndModulesRollback.bpmn | 282 + .../subprocess/DoDeleteNetworkInstance.bpmn | 30 +- .../DoDeleteNetworkInstanceRollback.bpmn | 2 +- .../subprocess/DoDeleteServiceInstance.bpmn | 664 +-- .../subprocess/DoDeleteVnfAndModules.bpmn | 263 + .../subprocess/DoUpdateNetworkInstance.bpmn | 847 +++ .../DoUpdateNetworkInstanceRollback.bpmn | 373 ++ .../src/main/resources/urn.properties | 58 +- .../webapp/WEB-INF/jboss-deployment-structure.xml | 62 +- .../src/main/webapp/WEB-INF/jboss-web.xml | 52 +- .../src/main/webapp/WEB-INF/web.xml | 146 +- .../scripts/DoCreateVfModuleVolumeV1Test.groovy | 436 +- .../scripts/UpdateNetworkInstanceInfraTest.groovy | 6149 ++++++++++---------- .../scripts/UpdateVfModuleVolumeInfraV1Test.groovy | 186 +- .../infrastructure/CreateVfModuleInfraTest.java | 492 +- .../infrastructure/DeleteVfModuleInfraTest.java | 1156 ++-- .../DoCreateVfModuleRollbackTest.java | 317 +- .../bpmn/infrastructure/DoCreateVfModuleTest.java | 299 +- .../bpmn/infrastructure/DoDeleteVfModuleTest.java | 1110 ++-- .../bpmn/infrastructure/DoUpdateVfModuleTest.java | 231 +- .../infrastructure/UpdateVfModuleInfraTest.java | 289 +- .../cloudRegion25_AAIResponse_Success.xml | 40 +- .../cloudRegion30_AAIResponse_Success.xml | 40 +- .../createNetwork_queryInstance_Success.xml | 6 +- ...reateNetwork_queryName2_AAIResponse_Success.xml | 124 +- ...Network_queryNameActive_AAIResponse_Success.xml | 148 +- ...createNetwork_queryName_AAIResponse_Success.xml | 124 +- ...ueryNetworkId_AAIResponse_NoPayload_Success.xml | 146 +- ...eNetwork_queryNetworkId_AAIResponse_Success.xml | 188 +- ...work_queryNetworkPolicy_AAIResponse_Success.xml | 40 +- ...k_queryNetworkTableRef1_AAIResponse_Success.xml | 38 +- ...k_queryNetworkTableRef2_AAIResponse_Success.xml | 38 +- ...Network_queryVpnBinding_AAIResponse_Success.xml | 90 +- .../CreateVfModuleVolumeInfraV1/GenericVnf.xml | 74 +- ...Volume_createVolumeName_AAIResponse_Success.xml | 98 +- ...oduleVolume_queryVolumeName_AAIResponse_404.xml | 62 +- ...eVolume_queryVolumeName_AAIResponse_Success.xml | 98 +- .../CreateVfModuleVolumeInfraV1/getSIUrlById.xml | 10 +- .../DeleteGenericVNFV1/sdncAdapterResponse.xml | 12 +- .../queryVolumeId_AAIResponse_Success.xml | 82 +- .../DoCreateVfModuleRollback/GenericVnf.xml | 50 +- .../GenericVnfVfModule.xml | 50 +- .../DoCreateVfModuleVolumeV1/GenericVnf.xml | 74 +- ...Volume_createVolumeName_AAIResponse_Success.xml | 98 +- ...eVolume_queryVolumeName_AAIResponse_Success.xml | 98 +- .../queryVolumeId_AAIResponse_Success.xml | 86 +- .../vf_module_aai_response.xml | 56 +- .../resources/__files/VfModularity/VolumeGroup.xml | 48 +- .../src/test/resources/camunda.cfg.xml | 122 +- .../src/test/resources/mso.bpmn.urn.properties | 168 +- .../openecomp/mso/bpmn/mock/StubResponseAAI.java | 1563 ++--- .../src/main/resources/__files/sdncSimResponse.xml | 38 +- bpmn/MSORESTClient/pom.xml | 102 +- bpmn/MSOURN-plugin/pom.xml | 140 +- .../camunda/bpmn/plugin/urnmap/URNMapPlugin.java | 106 +- .../urnmap/db/MyBatisExtendedSessionFactory.java | 178 +- .../urnmap/db/MyBatisQueryCommandExecutor.java | 88 +- .../camunda/bpmn/plugin/urnmap/db/URNData.java | 94 +- .../camunda/bpmn/plugin/urnmap/db/URNService.java | 96 +- .../urnmap/resources/ProcessInstanceResource.java | 192 +- .../urnmap/resources/URNMapPluginRootResource.java | 84 +- .../bpmn/plugin/urnmap/resources/URNResource.java | 410 +- bpmn/MSOURN-plugin/src/main/resources/mappings.xml | 64 +- .../bpmn/plugin/urnmap/URNMapPluginESTest.java | 86 +- .../urnmap/URNMapPluginESTestscaffolding.java | 182 +- .../bpmn/plugin/urnmap/db/URNDataESTest.java | 176 +- .../plugin/urnmap/db/URNDataESTestscaffolding.java | 156 +- .../bpmn/plugin/urnmap/db/URNServiceESTest.java | 72 +- .../urnmap/db/URNServiceESTestscaffolding.java | 194 +- .../resources/ProcessInstanceResourceESTest.java | 176 +- .../ProcessInstanceResourceESTestscaffolding.java | 188 +- .../resources/URNMapPluginRootResourceESTest.java | 84 +- .../URNMapPluginRootResourceESTestscaffolding.java | 238 +- .../plugin/urnmap/resources/URNResourceESTest.java | 330 +- .../resources/URNResourceESTestscaffolding.java | 800 +-- 269 files changed, 60572 insertions(+), 53044 deletions(-) create mode 100644 bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/GenericNotificationService.groovy create mode 100644 bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/SDNCAdapterRestV1.groovy create mode 100644 bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/TrinityExceptionUtil.groovy create mode 100644 bpmn/MSOCommonBPMN/src/main/resources/processes.xml create mode 100644 bpmn/MSOCommonBPMN/src/main/resources/subprocess/GenericNotificationService.bpmn create mode 100644 bpmn/MSOCommonBPMN/src/main/resources/subprocess/SDNCAdapterRestV1.bpmn create mode 100644 bpmn/MSOCommonBPMN/src/test/groovy/org/openecomp/mso/bpmn/common/scripts/TrinityExceptionUtilTest.groovy create mode 100644 bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/DoCreateVnfAndModulesRollback.groovy create mode 100644 bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/DoDeleteVnfAndModules.groovy create mode 100644 bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/DoUpdateNetworkInstance.groovy create mode 100644 bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/DoUpdateNetworkInstanceRollback.groovy create mode 100644 bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/UpdateNetworkInstance.groovy create mode 100644 bpmn/MSOInfrastructureBPMN/src/main/resources/process/UpdateNetworkInstance.bpmn create mode 100644 bpmn/MSOInfrastructureBPMN/src/main/resources/subprocess/DoCreateVnfAndModulesRollback.bpmn create mode 100644 bpmn/MSOInfrastructureBPMN/src/main/resources/subprocess/DoDeleteVnfAndModules.bpmn create mode 100644 bpmn/MSOInfrastructureBPMN/src/main/resources/subprocess/DoUpdateNetworkInstance.bpmn create mode 100644 bpmn/MSOInfrastructureBPMN/src/main/resources/subprocess/DoUpdateNetworkInstanceRollback.bpmn (limited to 'bpmn') diff --git a/bpmn/MSOCockpit/pom.xml b/bpmn/MSOCockpit/pom.xml index a985dc91b1..165c528812 100644 --- a/bpmn/MSOCockpit/pom.xml +++ b/bpmn/MSOCockpit/pom.xml @@ -1,72 +1,72 @@ - - - org.openecomp.mso - bpmn + + + org.openecomp.mso + bpmn 1.1.0-SNAPSHOT - - - 4.0.0 - org.openecomp.mso - MSOCockpit - pom - MSOCockpit - Builds the Camunda cockpit webapp for MSO - - - - - org.apache.maven.plugins - maven-assembly-plugin - - - - - src/main/assembly/cockpit-build.xml - - false - - cockpit-build - package - - single - - - - - - - - - - - org.camunda.bpm.webapp - camunda-webapp-jboss-standalone - ${camunda.version} - war - - - - org.openecomp.mso - common - ${project.version} - - - org.openecomp.mso - cockpit-urnmap-plugin - ${project.version} - - - org.openecomp.mso - MSOCoreBPMN - ${project.version} - - - org.evosuite - evosuite-standalone-runtime - ${evosuiteVersion} - test - - - - + + + 4.0.0 + org.openecomp.mso + MSOCockpit + pom + MSOCockpit + Builds the Camunda cockpit webapp for MSO + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + src/main/assembly/cockpit-build.xml + + false + + cockpit-build + package + + single + + + + + + + + + + + org.camunda.bpm.webapp + camunda-webapp-jboss-standalone + ${camunda.version} + war + + + + org.openecomp.mso + common + ${project.version} + + + org.openecomp.mso + cockpit-urnmap-plugin + ${project.version} + + + org.openecomp.mso + MSOCoreBPMN + ${project.version} + + + org.evosuite + evosuite-standalone-runtime + ${evosuiteVersion} + test + + + + diff --git a/bpmn/MSOCockpit/src/main/assembly/cockpit-build.xml b/bpmn/MSOCockpit/src/main/assembly/cockpit-build.xml index d623aa585a..b84a84df8a 100644 --- a/bpmn/MSOCockpit/src/main/assembly/cockpit-build.xml +++ b/bpmn/MSOCockpit/src/main/assembly/cockpit-build.xml @@ -1,91 +1,89 @@ - - - - cockpit-build - - - war - - - false - - - - / - - org.camunda.bpm.webapp:camunda-webapp-jboss-standalone - - true - - - WEB-INF/applicationContext.xml - WEB-INF/web.xml - WEB-INF/jboss-deployment-structure.xml - - - runtime - false - - - - - - /WEB-INF/lib - - - - - - org.openecomp.mso:logger - ch.qos.logback:logback-core - ch.qos.logback:logback-classic - com.att.eelf:eelf-core - - - org.openecomp.mso:MSOCoreBPMN - - false - runtime - false - - - - - - - - src/main/resources/WEB-INF/applicationContext.xml - /WEB-INF - - - src/main/resources/WEB-INF/web.xml - /WEB-INF - - - src/main/resources/WEB-INF/jboss-deployment-structure.xml - /WEB-INF - - - + + + + cockpit-build + + + war + + + false + + + + / + + org.camunda.bpm.webapp:camunda-webapp-jboss-standalone + + true + + + WEB-INF/applicationContext.xml + WEB-INF/web.xml + WEB-INF/jboss-deployment-structure.xml + + + runtime + false + + + + + + /WEB-INF/lib + + + + org.openecomp.mso:logger + ch.qos.logback:logback-core + ch.qos.logback:logback-classic + com.att.eelf:eelf-core + + + org.openecomp.mso:MSOCoreBPMN + + false + runtime + false + + + + + + + + src/main/resources/WEB-INF/applicationContext.xml + /WEB-INF + + + src/main/resources/WEB-INF/web.xml + /WEB-INF + + + src/main/resources/WEB-INF/jboss-deployment-structure.xml + /WEB-INF + + + diff --git a/bpmn/MSOCommonBPMN/pom.xml b/bpmn/MSOCommonBPMN/pom.xml index ee84d82f8f..e35c874a4e 100644 --- a/bpmn/MSOCommonBPMN/pom.xml +++ b/bpmn/MSOCommonBPMN/pom.xml @@ -1,392 +1,392 @@ - - - 4.0.0 - - org.openecomp.mso - bpmn - 1.1.0-SNAPSHOT - - MSOCommonBPMN - MSOCommonBPMN - war - - - - - org.apache.maven.plugins - maven-compiler-plugin - - - test-compile - compile - - testCompile - - - false - - - - - - - org.apache.maven.plugins - maven-jar-plugin - 2.6 - - - - default-jar - package - - jar - - - - org/openecomp/mso/bpmn/common/MSOCommonApplication.class - META-INF/ - - - - - - test-jar - - - true - false - - - - - - org.codehaus.mojo - build-helper-maven-plugin - 3.0.0 - - - - attach-artifact - - package - - - - ${project.build.directory}/${project.artifactId}-${project.version}.jar - jar - - - - - - - - - org.apache.maven.plugins - maven-war-plugin - 2.3 - - false - - - - org.apache.cxf - cxf-codegen-plugin - 2.5.2 - - - org.apache.maven.plugins - maven-eclipse-plugin - 2.8 - - - org.eclipse.jdt.groovy.core.groovyNature - - - **/*.groovy - - - - - maven-antrun-plugin - - - compile - compile - - - - - - - - - - - - - - run - - - - test-compile - test-compile - - - - - - - - - - - - - - run - - - - - - - - - - org.eclipse.m2e - lifecycle-mapping - 1.0.0 - - - - - - - org.apache.maven.plugins - - - maven-antrun-plugin - - - [1.3,) - - - run - - - - - - - - - - - - - - - - - - - org.camunda.bpm - camunda-engine - compile - - - org.slf4j - slf4j-api - - - - - - - org.camunda.bpm - camunda-engine-cdi - - - - - org.camunda.bpm.extension - camunda-bpm-assert - 1.2 - test - - - org.mockito - mockito-all - 1.10.19 - test - - - - org.camunda.bpm.workbench - camunda-workbench-dist-embeddable - 1.0.0-alpha8 - test - - - - - org.camunda.spin - camunda-spin-dataformat-all - compile - - - org.camunda.bpm - camunda-engine-plugin-spin - compile - - - - org.camunda.bpm - camunda-engine-plugin-connect - compile - - - - - org.webjars - bootstrap - 2.3.2 - - - - org.jboss.resteasy - resteasy-client - 3.0.19.Final - provided - - - org.apache.httpcomponents - httpclient - - - - - - - com.h2database - h2 - test - - - - com.fasterxml.uuid - java-uuid-generator - - - org.codehaus.groovy - groovy-all - - - org.apache.commons - commons-lang3 - 3.4 - - - org.openecomp.mso - MSOCoreBPMN - ${project.version} - - - - org.openecomp.mso - MSOCoreBPMN - ${project.version} - tests - test - - - javax.ws.rs - javax.ws.rs-api - 2.0 - - - - org.springframework - spring-web - 4.3.2.RELEASE - - - org.openecomp.mso - MSOMockServer - ${project.version} - classes - test - - - org.openecomp.mso - MSORESTClient - ${project.version} - - - - javax.servlet - javax.servlet-api - 3.0.1 - provided - - - - com.github.tomakehurst - wiremock - 1.56 - test - standalone - - - org.mortbay.jetty - jetty - - - com.google.guava - guava - - - com.fasterxml.jackson.core - jackson-core - - - com.fasterxml.jackson.core - jackson-annotations - - - com.fasterxml.jackson.core - jackson-databind - - - org.apache.httpcomponents - httpclient - - - org.skyscreamer - jsonassert - - - xmlunit - xmlunit - - - com.jayway.jsonpath - json-path - - - net.sf.jopt-simple - jopt-simple - - - - - + + + 4.0.0 + + org.openecomp.mso + bpmn + 1.1.0-SNAPSHOT + + MSOCommonBPMN + MSOCommonBPMN + war + + + + + org.apache.maven.plugins + maven-compiler-plugin + + + test-compile + compile + + testCompile + + + false + + + + + + + org.apache.maven.plugins + maven-jar-plugin + 2.6 + + + + default-jar + package + + jar + + + + org/openecomp/mso/bpmn/common/MSOCommonApplication.class + + + + + + + test-jar + + + true + false + + + + + + org.codehaus.mojo + build-helper-maven-plugin + 3.0.0 + + + + attach-artifact + + package + + + + ${project.build.directory}/${project.artifactId}-${project.version}.jar + jar + + + + + + + + + org.apache.maven.plugins + maven-war-plugin + 2.3 + + false + + + + org.apache.cxf + cxf-codegen-plugin + 2.5.2 + + + org.apache.maven.plugins + maven-eclipse-plugin + 2.8 + + + org.eclipse.jdt.groovy.core.groovyNature + + + **/*.groovy + + + + + maven-antrun-plugin + + + compile + compile + + + + + + + + + + + + + + run + + + + test-compile + test-compile + + + + + + + + + + + + + + run + + + + + + + + + + org.eclipse.m2e + lifecycle-mapping + 1.0.0 + + + + + + + org.apache.maven.plugins + + + maven-antrun-plugin + + + [1.3,) + + + run + + + + + + + + + + + + + + + + + + + org.camunda.bpm + camunda-engine + compile + + + org.slf4j + slf4j-api + + + + + + + org.camunda.bpm + camunda-engine-cdi + + + + + org.camunda.bpm.extension + camunda-bpm-assert + 1.2 + test + + + org.mockito + mockito-all + 1.10.19 + test + + + + org.camunda.bpm.workbench + camunda-workbench-dist-embeddable + 1.0.0-alpha8 + test + + + + + org.camunda.spin + camunda-spin-dataformat-all + compile + + + org.camunda.bpm + camunda-engine-plugin-spin + compile + + + + org.camunda.bpm + camunda-engine-plugin-connect + compile + + + + + org.webjars + bootstrap + 2.3.2 + + + + org.jboss.resteasy + resteasy-client + 3.0.19.Final + provided + + + org.apache.httpcomponents + httpclient + + + + + + + com.h2database + h2 + test + + + + com.fasterxml.uuid + java-uuid-generator + + + org.codehaus.groovy + groovy-all + + + org.apache.commons + commons-lang3 + 3.4 + + + org.openecomp.mso + MSOCoreBPMN + ${project.version} + + + + org.openecomp.mso + MSOCoreBPMN + ${project.version} + tests + test + + + javax.ws.rs + javax.ws.rs-api + 2.0 + + + + org.springframework + spring-web + 4.3.2.RELEASE + + + org.openecomp.mso + MSOMockServer + ${project.version} + classes + test + + + org.openecomp.mso + MSORESTClient + ${project.version} + + + + javax.servlet + javax.servlet-api + 3.0.1 + provided + + + + com.github.tomakehurst + wiremock + 1.56 + test + standalone + + + org.mortbay.jetty + jetty + + + com.google.guava + guava + + + com.fasterxml.jackson.core + jackson-core + + + com.fasterxml.jackson.core + jackson-annotations + + + com.fasterxml.jackson.core + jackson-databind + + + org.apache.httpcomponents + httpclient + + + org.skyscreamer + jsonassert + + + xmlunit + xmlunit + + + com.jayway.jsonpath + json-path + + + net.sf.jopt-simple + jopt-simple + + + + + diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/AaiUtil.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/AaiUtil.groovy index 01e25a5741..95a577c946 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/AaiUtil.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/AaiUtil.groovy @@ -1,483 +1,562 @@ -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - MSO - * ================================================================================ - * 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.openecomp.mso.bpmn.common.scripts -import org.camunda.bpm.engine.delegate.BpmnError -import org.camunda.bpm.engine.runtime.Execution -import org.openecomp.mso.bpmn.common.scripts.AbstractServiceTaskProcessor; -import org.openecomp.mso.rest.APIResponse; -import org.openecomp.mso.rest.RESTClient -import org.openecomp.mso.rest.RESTConfig - -class AaiUtil { - - public MsoUtils utils = new MsoUtils() - public static final String AAI_NAMESPACE_STRING = 'http://org.openecomp.aai.inventory/' - public static final String DEFAULT_VERSION_KEY = 'URN_mso_workflow_global_default_aai_version' - - private AbstractServiceTaskProcessor taskProcessor - - public AaiUtil(AbstractServiceTaskProcessor taskProcessor) { - this.taskProcessor = taskProcessor - } - - public String getNetworkGenericVnfEndpoint(Execution execution) { - def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') - String endpoint = execution.getVariable("URN_aai_endpoint") - def uri = getNetworkGenericVnfUri(execution) - taskProcessor.logDebug('AaiUtil.getNetworkGenericVnfEndpoint() - AAI endpoint: ' + endpoint + uri, isDebugLogEnabled) - return endpoint + uri - } - - public String getNetworkGenericVnfUri(Execution execution) { - def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') - def uri = getUri(execution, 'generic_vnf') - taskProcessor.logDebug('AaiUtil.getNetworkGenericVnfUri() - AAI URI: ' + uri, isDebugLogEnabled) - return uri - } - - public String getNetworkVpnBindingUri(Execution execution) { - def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') - def uri = getUri(execution, 'vpn_binding') - taskProcessor.logDebug('AaiUtil.getNetworkVpnBindingUri() - AAI URI: ' + uri, isDebugLogEnabled) - return uri - } - - public String getNetworkPolicyUri(Execution execution) { - def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') - def uri = getUri(execution, 'network_policy') - taskProcessor.logDebug('AaiUtil.getNetworkPolicyUri() - AAI URI: ' + uri, isDebugLogEnabled) - return uri - } - - public String getNetworkTableReferencesUri(Execution execution) { - def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') - def uri = getUri(execution, 'route_table_reference') - taskProcessor.logDebug('AaiUtil.getNetworkTableReferencesUri() - AAI URI: ' + uri, isDebugLogEnabled) - return uri - } - - public String getNetworkVceUri(Execution execution) { - def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') - def uri = getUri(execution, 'vce') - taskProcessor.logDebug('AaiUtil.getNetworkVceUri() - AAI URI: ' + uri, isDebugLogEnabled) - return uri - } - - public String getNetworkL3NetworkUri(Execution execution) { - def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') - def uri = getUri(execution, 'l3_network') - taskProcessor.logDebug('AaiUtil.getNetworkL3NetworkUri() - AAI URI: ' + uri, isDebugLogEnabled) - return uri - } - - public String getBusinessCustomerUri(Execution execution) { - def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') - def uri = getUri(execution, 'customer') - taskProcessor.logDebug('AaiUtil.getBusinessCustomerUri() - AAI URI: ' + uri, isDebugLogEnabled) - return uri - } - - //public String getBusinessCustomerUriv7(Execution execution) { - // def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') - // //def uri = getUri(execution, BUSINESS_CUSTOMERV7) - // def uri = getUri(execution, 'Customer') - // taskProcessor.logDebug('AaiUtil.getBusinessCustomerUriv7() - AAI URI: ' + uri, isDebugLogEnabled) - // return uri - //} - - public String getCloudInfrastructureCloudRegionEndpoint(Execution execution) { - def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') - String endpoint = execution.getVariable("URN_aai_endpoint") - def uri = getCloudInfrastructureCloudRegionUri(execution) - taskProcessor.logDebug('AaiUtil.getCloudInfrastructureCloudRegionEndpoint() - AAI endpoint: ' + endpoint + uri, isDebugLogEnabled) - return endpoint + uri - } - - public String getCloudInfrastructureCloudRegionUri(Execution execution) { - def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') - def uri = getUri(execution, 'cloud_region') - taskProcessor.logDebug('AaiUtil.getCloudInfrastructureCloudRegionUri() - AAI URI: ' + uri, isDebugLogEnabled) - return uri - } - - public String getCloudInfrastructureVolumeGroupUri(Execution execution) { - def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') - def uri = getUri(execution, 'volume_group') - taskProcessor.logDebug('AaiUtil.getCloudInfrastructureVolumeGroupUri() - AAI URI: ' + uri, isDebugLogEnabled) - return uri - } - - public String getCloudInfrastructureTenantUri(Execution execution) { - def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') - def uri = getUri(execution, 'tenant') - taskProcessor.logDebug('AaiUtil.getCloudInfrastructureTenantUri() - AAI URI: ' + uri, isDebugLogEnabled) - return uri - } - - public String getSearchNodesQueryUri(Execution execution) { - def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') - def uri = getUri(execution, 'nodes_query') - taskProcessor.logDebug('AaiUtil.getSearchNodesQueryUri() - AAI URI: ' + uri, isDebugLogEnabled) - return uri - } - - public String getSearchNodesQueryEndpoint(Execution execution) { - def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') - String endpoint = execution.getVariable("URN_aai_endpoint") - def uri = getSearchNodesQueryUri(execution) - taskProcessor.logDebug('AaiUtil.getSearchNodesQueryEndpoint() - AAI endpoint: ' + endpoint + uri, isDebugLogEnabled) - return endpoint + uri - } - - public String getSearchGenericQueryUri(Execution execution) { - def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') - def uri = getUri(execution, 'generic_query') - taskProcessor.logDebug('AaiUtil.getSearchGenericQueryUri() - AAI URI: ' + uri, isDebugLogEnabled) - return uri - } - - public String getVersion(Execution execution, resourceName, processKey) { - def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') - - resourceName = resourceName.replaceAll('-', '_') - - def versionWithResourceKey = "URN_mso_workflow_default_aai_${resourceName}_version" - def versionWithProcessKey = "URN_mso_workflow_custom_${processKey}_aai_version" - - def version = execution.getVariable(versionWithProcessKey) - if (version) { - taskProcessor.logDebug("AaiUtil.getVersion() - using flow specific ${versionWithProcessKey}=${version}", isDebugLogEnabled) - return version - } - - version = execution.getVariable(versionWithResourceKey) - if (version) { - taskProcessor.logDebug("AaiUtil.getVersion() - using resource specific ${versionWithResourceKey}=${version}", isDebugLogEnabled) - return version - } - - version = execution.getVariable(DEFAULT_VERSION_KEY) - if (version) { - taskProcessor.logDebug("AaiUtil.getVersion() - using default version ${DEFAULT_VERSION_KEY}=${version}", isDebugLogEnabled) - 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(Execution execution, resourceName) { - - def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') - def processKey = taskProcessor.getMainProcessKey(execution) - - resourceName = resourceName.replaceAll('-', '_') - - // Check for flow+resource specific first - def key = "URN_mso_workflow_${processKey}_aai_${resourceName}_uri" - def uri = execution.getVariable(key) - if(uri) { - taskProcessor.logDebug("AaiUtil.getUri() - using flow+resource specific key: ${key}=${uri}", isDebugLogEnabled) - return uri - } - - // Check for versioned key - def version = getVersion(execution, resourceName, processKey) - key = "URN_mso_workflow_default_aai_v${version}_${resourceName}_uri" - uri = execution.getVariable(key) - - if(uri) { - taskProcessor.logDebug("AaiUtil.getUri() - using versioned URI key: ${key}=${uri}", isDebugLogEnabled) - return uri - } - - (new ExceptionUtil()).buildAndThrowWorkflowException(execution, 9999, 'Internal Error: AAI URI entry for ' + key + ' not defined in the MSO URN properties file') - } - - public String getNamespaceFromUri(String uri) { - String namespace = AAI_NAMESPACE_STRING - if(uri!=null){ - return namespace + uri.substring(uri.indexOf("v"), uri.indexOf("v")+2) - }else{ - return namespace - } - } - - - - /** - * 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(Execution execution, String url){ - def isDebugEnabled = execution.getVariable("isDebugLogEnabled") - taskProcessor.logDebug(" ======== STARTED Execute AAI Get Process ======== ", isDebugEnabled) - try{ - String uuid = UUID.randomUUID() - taskProcessor.logDebug( "Generated uuid is: " + uuid, isDebugEnabled) - taskProcessor.logDebug( "URL to be used is: " + url, isDebugEnabled) - - String basicAuthCred = utils.getBasicAuth(execution.getVariable("URN_aai_auth"),execution.getVariable("URN_mso_msoKey")) - - RESTConfig config = new RESTConfig(url); - RESTClient client = new RESTClient(config).addHeader("X-FromAppId", "MSO").addHeader("X-TransactionId", uuid).addHeader("Accept","application/xml"); - - if (basicAuthCred != null && !"".equals(basicAuthCred)) { - client.addAuthorizationHeader(basicAuthCred) - } - - APIResponse apiResponse = client.get() - return apiResponse - - }catch(Exception e){ - taskProcessor.logDebug("Exception occured while executing AAI Get Call. Exception is: \n" + e, isDebugEnabled) - return e - } - taskProcessor.logDebug( "======== COMPLETED Execute AAI Get Process ======== ", isDebugEnabled) - } - - /** - * 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(Execution execution, String url, String payload){ - def isDebugEnabled = execution.getVariable("isDebugLogEnabled") - taskProcessor.logDebug( " ======== Started Execute AAI Put Process ======== ", isDebugEnabled) - try{ - String uuid = UUID.randomUUID() - taskProcessor.logDebug( "Generated uuid is: " + uuid, isDebugEnabled) - taskProcessor.logDebug( "URL to be used is: " + url, isDebugEnabled) - - String basicAuthCred = utils.getBasicAuth(execution.getVariable("URN_aai_auth"),execution.getVariable("URN_mso_msoKey")) - - RESTConfig config = new RESTConfig(url); - RESTClient client = new RESTClient(config).addHeader("X-FromAppId", "MSO").addHeader("X-TransactionId", uuid).addHeader("Content-Type", "application/xml").addHeader("Accept","application/xml"); - if (basicAuthCred != null && !"".equals(basicAuthCred)) { - client.addAuthorizationHeader(basicAuthCred) - } - APIResponse apiResponse = client.httpPut(payload) - - return apiResponse - }catch(Exception e){ - taskProcessor.utils.log("ERROR", "Exception occured while executing AAI Put Call. Exception is: \n" + e, isDebugEnabled) - return e - } - taskProcessor.logDebug( "======== Completed Execute AAI Put Process ======== ", isDebugEnabled) - } - - - /** - * 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(Execution execution, String url){ - def isDebugEnabled = execution.getVariable("isDebugLogEnabled") - taskProcessor.logDebug( " ======== Started Execute AAI Delete Process ======== ", isDebugEnabled) - try{ - String uuid = UUID.randomUUID() - taskProcessor.logDebug( "Generated uuid is: " + uuid, isDebugEnabled) - taskProcessor.logDebug( "URL to be used is: " + url, isDebugEnabled) - - String basicAuthCred = utils.getBasicAuth(execution.getVariable("URN_aai_auth"),execution.getVariable("URN_mso_msoKey")) - - RESTConfig config = new RESTConfig(url); - RESTClient client = new RESTClient(config).addHeader("X-FromAppId", "MSO").addHeader("X-TransactionId", uuid).addHeader("Accept","application/xml"); - if (basicAuthCred != null && !"".equals(basicAuthCred)) { - client.addAuthorizationHeader(basicAuthCred) - } - APIResponse apiResponse = client.delete() - - return apiResponse - - }catch(Exception e){ - taskProcessor.utils.log("ERROR", "Exception occured while executing AAI Delete Call. Exception is: \n" + e, isDebugEnabled) - return e - } - taskProcessor.logDebug( "======== Completed Execute AAI Delete Process ======== ", isDebugEnabled) - } - - /** - * 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(Execution execution, String url, String payload, String authHeader){ - def isDebugEnabled = execution.getVariable("isDebugLogEnabled") - taskProcessor.logDebug( " ======== Started Execute AAI Delete Process ======== ", isDebugEnabled) - try{ - String uuid = UUID.randomUUID() - taskProcessor.logDebug( "Generated uuid is: " + uuid, isDebugEnabled) - taskProcessor.logDebug( "URL to be used is: " + url, isDebugEnabled) - - String basicAuthCred = utils.getBasicAuth(execution.getVariable("URN_aai_auth"),execution.getVariable("URN_mso_msoKey")) - RESTConfig config = new RESTConfig(url); - RESTClient client = new RESTClient(config).addHeader("X-FromAppId", "MSO").addHeader("X-TransactionId", uuid).addHeader("Accept","application/xml").addAuthorizationHeader(authHeader); - if (basicAuthCred != null && !"".equals(basicAuthCred)) { - client.addAuthorizationHeader(basicAuthCred) - } - - APIResponse apiResponse = client.httpDelete(payload) - - return apiResponse - - }catch(Exception e){ - taskProcessor.utils.log("ERROR", "Exception occured while executing AAI Delete Call. Exception is: \n" + e, isDebugEnabled) - return e - } - taskProcessor.logDebug( "======== Completed Execute AAI Delete Process ======== ", isDebugEnabled) - } - - /** - * This reusable method can be used for making AAI Post 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 executeAAIPostCall(Execution execution, String url, String payload){ - def isDebugEnabled = execution.getVariable("isDebugLogEnabled") - taskProcessor.logDebug( " ======== Started Execute AAI Post Process ======== ", isDebugEnabled) - try{ - String uuid = UUID.randomUUID() - taskProcessor.logDebug( "Generated uuid is: " + uuid, isDebugEnabled) - taskProcessor.logDebug( "URL to be used is: " + url, isDebugEnabled) - - String basicAuthCred = utils.getBasicAuth(execution.getVariable("URN_aai_auth"),execution.getVariable("URN_mso_msoKey")) - RESTConfig config = new RESTConfig(url); - RESTClient client = new RESTClient(config).addHeader("X-FromAppId", "MSO").addHeader("X-TransactionId", uuid).addHeader("Accept","application/xml"); - if (basicAuthCred != null && !"".equals(basicAuthCred)) { - client.addAuthorizationHeader(basicAuthCred) - } - APIResponse apiResponse = client.httpPost(payload) - - return apiResponse - - }catch(Exception e){ - taskProcessor.utils.log("ERROR", "Exception occured while executing AAI Post Call. Exception is: \n" + e, isDebugEnabled) - return e - } - taskProcessor.logDebug( "======== Completed Execute AAI Post Process ======== ", isDebugEnabled) - } - - /** Utilitty 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). - */ - - //TODO: We should refactor this method to return WorkflowException instead of Error. Also to throw MSOWorkflowException which the calling flow will then catch. - - public String getAAICloudReqion(Execution execution, String url, String backend, inputCloudRegion){ - def isDebugEnabled = execution.getVariable("isDebugLogEnabled") - - try { - APIResponse apiResponse = executeAAIGetCall(execution, url) - String returnCode = apiResponse.getStatusCode() - String aaiResponseAsString = apiResponse.getResponseBodyAsString() - taskProcessor.utils.log("DEBUG", "Call AAI Cloud Region Return code: " + returnCode, isDebugEnabled) - execution.setVariable(execution.getVariable("prefix")+"queryCloudRegionReturnCode", returnCode) - //taskProcessor.utils.log("DEBUG", "Call AAI Cloud Region Response: " + aaiResponseAsString, isDebugEnabled) - //execution.setVariable(execution.getVariable("prefix")+"queryCloudRegionResponse", aaiResponseAsString) - String regionId = "" - if (returnCode == "200") { - taskProcessor.utils.log("DEBUG", "Call AAI Cloud Region is Successful.", isDebugEnabled) - try { - String regionVersion = taskProcessor.utils.getNodeText(aaiResponseAsString, "cloud-region-version") - taskProcessor.utils.log("DEBUG", "Cloud Region Version from AAI for " + backend + " is: " + regionVersion, isDebugEnabled) - 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") - } - } - - taskProcessor.utils.log("DEBUG", "Cloud Region Id from AAI " + backend + " is: " + regionId, isDebugEnabled) - return regionId - - } catch (Exception e) { - taskProcessor.utils.log("ERROR", "Exception occured while getting the Cloud Reqion. Exception is: \n" + e, isDebugEnabled) - return "ERROR" - } - } else { // not 200 - if (returnCode == "404") { - if (backend == "PO") { - regionId = inputCloudRegion - } else { // backend not "PO" - regionId = "AAIAIC25" - } - taskProcessor.utils.log("DEBUG", "Cloud Region value for code='404' of " + backend + " is: " + regionId, isDebugEnabled) - return regionId - } else { - taskProcessor.utils.log("ERROR", "Call AAI Cloud Region is NOT Successful.", isDebugEnabled) - return "ERROR" - } - } - }catch(Exception e) { - taskProcessor.utils.log("ERROR", "Exception occured while getting the Cloud Reqion. Exception is: \n" + e, isDebugEnabled) - return "ERROR" - } - } - - /* 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 - } +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.bpmn.common.scripts +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.runtime.Execution +import org.openecomp.mso.bpmn.common.scripts.AbstractServiceTaskProcessor; +import org.openecomp.mso.rest.APIResponse; +import org.openecomp.mso.rest.RESTClient +import org.openecomp.mso.rest.RESTConfig + +class AaiUtil { + + public MsoUtils utils = new MsoUtils() + public static final String AAI_NAMESPACE_STRING = 'http://org.openecomp.aai.inventory/' + public static final String DEFAULT_VERSION_KEY = 'URN_mso_workflow_global_default_aai_version' + + private AbstractServiceTaskProcessor taskProcessor + + public AaiUtil(AbstractServiceTaskProcessor taskProcessor) { + this.taskProcessor = taskProcessor + } + + public String getNetworkGenericVnfEndpoint(Execution execution) { + def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') + String endpoint = execution.getVariable("URN_aai_endpoint") + def uri = getNetworkGenericVnfUri(execution) + taskProcessor.logDebug('AaiUtil.getNetworkGenericVnfEndpoint() - AAI endpoint: ' + endpoint + uri, isDebugLogEnabled) + return endpoint + uri + } + + public String getNetworkGenericVnfUri(Execution execution) { + def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') + def uri = getUri(execution, 'generic_vnf') + taskProcessor.logDebug('AaiUtil.getNetworkGenericVnfUri() - AAI URI: ' + uri, isDebugLogEnabled) + return uri + } + + public String getNetworkVpnBindingUri(Execution execution) { + def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') + def uri = getUri(execution, 'vpn_binding') + taskProcessor.logDebug('AaiUtil.getNetworkVpnBindingUri() - AAI URI: ' + uri, isDebugLogEnabled) + return uri + } + + public String getNetworkPolicyUri(Execution execution) { + def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') + def uri = getUri(execution, 'network_policy') + taskProcessor.logDebug('AaiUtil.getNetworkPolicyUri() - AAI URI: ' + uri, isDebugLogEnabled) + return uri + } + + public String getNetworkTableReferencesUri(Execution execution) { + def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') + def uri = getUri(execution, 'route_table_reference') + taskProcessor.logDebug('AaiUtil.getNetworkTableReferencesUri() - AAI URI: ' + uri, isDebugLogEnabled) + return uri + } + + public String getNetworkVceUri(Execution execution) { + def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') + def uri = getUri(execution, 'vce') + taskProcessor.logDebug('AaiUtil.getNetworkVceUri() - AAI URI: ' + uri, isDebugLogEnabled) + return uri + } + + public String getNetworkL3NetworkUri(Execution execution) { + def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') + def uri = getUri(execution, 'l3_network') + taskProcessor.logDebug('AaiUtil.getNetworkL3NetworkUri() - AAI URI: ' + uri, isDebugLogEnabled) + return uri + } + + public String getBusinessCustomerUri(Execution execution) { + def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') + def uri = getUri(execution, 'customer') + taskProcessor.logDebug('AaiUtil.getBusinessCustomerUri() - AAI URI: ' + uri, isDebugLogEnabled) + return uri + } + + //public String getBusinessCustomerUriv7(Execution execution) { + // def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') + // //def uri = getUri(execution, BUSINESS_CUSTOMERV7) + // def uri = getUri(execution, 'Customer') + // taskProcessor.logDebug('AaiUtil.getBusinessCustomerUriv7() - AAI URI: ' + uri, isDebugLogEnabled) + // return uri + //} + + public String getCloudInfrastructureCloudRegionEndpoint(Execution execution) { + def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') + String endpoint = execution.getVariable("URN_aai_endpoint") + def uri = getCloudInfrastructureCloudRegionUri(execution) + taskProcessor.logDebug('AaiUtil.getCloudInfrastructureCloudRegionEndpoint() - AAI endpoint: ' + endpoint + uri, isDebugLogEnabled) + return endpoint + uri + } + + public String getCloudInfrastructureCloudRegionUri(Execution execution) { + def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') + def uri = getUri(execution, 'cloud_region') + taskProcessor.logDebug('AaiUtil.getCloudInfrastructureCloudRegionUri() - AAI URI: ' + uri, isDebugLogEnabled) + return uri + } + + public String getCloudInfrastructureTenantUri(Execution execution) { + def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') + def uri = getUri(execution, 'tenant') + taskProcessor.logDebug('AaiUtil.getCloudInfrastructureTenantUri() - AAI URI: ' + uri, isDebugLogEnabled) + return uri + } + + public String getSearchNodesQueryUri(Execution execution) { + def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') + def uri = getUri(execution, 'nodes_query') + taskProcessor.logDebug('AaiUtil.getSearchNodesQueryUri() - AAI URI: ' + uri, isDebugLogEnabled) + return uri + } + + public String getSearchNodesQueryEndpoint(Execution execution) { + def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') + String endpoint = execution.getVariable("URN_aai_endpoint") + def uri = getSearchNodesQueryUri(execution) + taskProcessor.logDebug('AaiUtil.getSearchNodesQueryEndpoint() - AAI endpoint: ' + endpoint + uri, isDebugLogEnabled) + return endpoint + uri + } + + public String getSearchGenericQueryUri(Execution execution) { + def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') + def uri = getUri(execution, 'generic_query') + taskProcessor.logDebug('AaiUtil.getSearchGenericQueryUri() - AAI URI: ' + uri, isDebugLogEnabled) + return uri + } + + public String getVersion(Execution execution, resourceName, processKey) { + def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') + + resourceName = resourceName.replaceAll('-', '_') + + def versionWithResourceKey = "URN_mso_workflow_default_aai_${resourceName}_version" + def versionWithProcessKey = "URN_mso_workflow_custom_${processKey}_aai_version" + + def version = execution.getVariable(versionWithProcessKey) + if (version) { + taskProcessor.logDebug("AaiUtil.getVersion() - using flow specific ${versionWithProcessKey}=${version}", isDebugLogEnabled) + return version + } + + version = execution.getVariable(versionWithResourceKey) + if (version) { + taskProcessor.logDebug("AaiUtil.getVersion() - using resource specific ${versionWithResourceKey}=${version}", isDebugLogEnabled) + return version + } + + version = execution.getVariable(DEFAULT_VERSION_KEY) + if (version) { + taskProcessor.logDebug("AaiUtil.getVersion() - using default version ${DEFAULT_VERSION_KEY}=${version}", isDebugLogEnabled) + 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(Execution execution, resourceName) { + + def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') + def processKey = taskProcessor.getMainProcessKey(execution) + + resourceName = resourceName.replaceAll('-', '_') + + // Check for flow+resource specific first + def key = "URN_mso_workflow_${processKey}_aai_${resourceName}_uri" + def uri = execution.getVariable(key) + if(uri) { + taskProcessor.logDebug("AaiUtil.getUri() - using flow+resource specific key: ${key}=${uri}", isDebugLogEnabled) + return uri + } + + // Check for versioned key + def version = getVersion(execution, resourceName, processKey) + key = "URN_mso_workflow_default_aai_v${version}_${resourceName}_uri" + uri = execution.getVariable(key) + + if(uri) { + taskProcessor.logDebug("AaiUtil.getUri() - using versioned URI key: ${key}=${uri}", isDebugLogEnabled) + return uri + } + + (new ExceptionUtil()).buildAndThrowWorkflowException(execution, 9999, 'Internal Error: AAI URI entry for ' + key + ' not defined in the MSO URN properties file') + } + + public String getNamespaceFromUri(String uri) { + String namespace = AAI_NAMESPACE_STRING + if(uri!=null){ + return namespace + uri.substring(uri.indexOf("v"), uri.indexOf("v")+2) + }else{ + return namespace + } + } + + + + /** + * 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(Execution execution, String url){ + def isDebugEnabled = execution.getVariable("isDebugLogEnabled") + taskProcessor.logDebug(" ======== STARTED Execute AAI Get Process ======== ", isDebugEnabled) + try{ + String uuid = UUID.randomUUID() + taskProcessor.logDebug( "Generated uuid is: " + uuid, isDebugEnabled) + taskProcessor.logDebug( "URL to be used is: " + url, isDebugEnabled) + + String basicAuthCred = utils.getBasicAuth(execution.getVariable("URN_aai_auth"),execution.getVariable("URN_mso_msoKey")) + + RESTConfig config = new RESTConfig(url); + RESTClient client = new RESTClient(config).addHeader("X-FromAppId", "MSO").addHeader("X-TransactionId", uuid).addHeader("Accept","application/xml"); + + if (basicAuthCred != null && !"".equals(basicAuthCred)) { + client.addAuthorizationHeader(basicAuthCred) + } + + APIResponse apiResponse = client.get() + return apiResponse + + }catch(Exception e){ + taskProcessor.logDebug("Exception occured while executing AAI Get Call. Exception is: \n" + e, isDebugEnabled) + return e + } + taskProcessor.logDebug( "======== COMPLETED Execute AAI Get Process ======== ", isDebugEnabled) + } + + /** + * 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(Execution execution, String url, String payload){ + def isDebugEnabled = execution.getVariable("isDebugLogEnabled") + taskProcessor.logDebug( " ======== Started Execute AAI Put Process ======== ", isDebugEnabled) + try{ + String uuid = UUID.randomUUID() + taskProcessor.logDebug( "Generated uuid is: " + uuid, isDebugEnabled) + taskProcessor.logDebug( "URL to be used is: " + url, isDebugEnabled) + + String basicAuthCred = utils.getBasicAuth(execution.getVariable("URN_aai_auth"),execution.getVariable("URN_mso_msoKey")) + + RESTConfig config = new RESTConfig(url); + RESTClient client = new RESTClient(config).addHeader("X-FromAppId", "MSO").addHeader("X-TransactionId", uuid).addHeader("Content-Type", "application/xml").addHeader("Accept","application/xml"); + if (basicAuthCred != null && !"".equals(basicAuthCred)) { + client.addAuthorizationHeader(basicAuthCred) + } + APIResponse apiResponse = client.httpPut(payload) + + return apiResponse + }catch(Exception e){ + taskProcessor.utils.log("ERROR", "Exception occured while executing AAI Put Call. Exception is: \n" + e, isDebugEnabled) + return e + } + taskProcessor.logDebug( "======== Completed Execute AAI Put Process ======== ", isDebugEnabled) + } + + /** + * 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(Execution execution, String url, String payload){ + def isDebugEnabled = execution.getVariable("isDebugLogEnabled") + taskProcessor.logDebug( " ======== Started Execute AAI Patch Process ======== ", isDebugEnabled) + try{ + String uuid = UUID.randomUUID() + taskProcessor.logDebug( "Generated uuid is: " + uuid, isDebugEnabled) + + taskProcessor.logDebug( "URL to be used is: " + url, isDebugEnabled) + + String basicAuthCred = utils.getBasicAuth(execution.getVariable("URN_aai_auth"),execution.getVariable("URN_mso_msoKey")) + + RESTConfig config = new RESTConfig(url); + RESTClient client = new RESTClient(config).addHeader("X-FromAppId", "MSO").addHeader("X-TransactionId", uuid).addHeader("Content-Type", "application/merge-patch+json").addHeader("Accept","application/json"); + if (basicAuthCred != null && !"".equals(basicAuthCred)) { + client.addAuthorizationHeader(basicAuthCred) + } + APIResponse apiResponse = client.httpPatch(payload) + + return apiResponse + }catch(Exception e){ + taskProcessor.utils.log("ERROR", "Exception occured while executing AAI Patch Call. Exception is: \n" + e, isDebugEnabled) + return e + } + taskProcessor.logDebug( "======== Completed Execute AAI Patch Process ======== ", isDebugEnabled) + } + + + /** + * 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(Execution execution, String url){ + def isDebugEnabled = execution.getVariable("isDebugLogEnabled") + taskProcessor.logDebug( " ======== Started Execute AAI Delete Process ======== ", isDebugEnabled) + try{ + String uuid = UUID.randomUUID() + taskProcessor.logDebug( "Generated uuid is: " + uuid, isDebugEnabled) + taskProcessor.logDebug( "URL to be used is: " + url, isDebugEnabled) + + String basicAuthCred = utils.getBasicAuth(execution.getVariable("URN_aai_auth"),execution.getVariable("URN_mso_msoKey")) + + RESTConfig config = new RESTConfig(url); + RESTClient client = new RESTClient(config).addHeader("X-FromAppId", "MSO").addHeader("X-TransactionId", uuid).addHeader("Accept","application/xml"); + if (basicAuthCred != null && !"".equals(basicAuthCred)) { + client.addAuthorizationHeader(basicAuthCred) + } + APIResponse apiResponse = client.delete() + + return apiResponse + + }catch(Exception e){ + taskProcessor.utils.log("ERROR", "Exception occured while executing AAI Delete Call. Exception is: \n" + e, isDebugEnabled) + return e + } + taskProcessor.logDebug( "======== Completed Execute AAI Delete Process ======== ", isDebugEnabled) + } + + /** + * 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(Execution execution, String url, String payload, String authHeader){ + def isDebugEnabled = execution.getVariable("isDebugLogEnabled") + taskProcessor.logDebug( " ======== Started Execute AAI Delete Process ======== ", isDebugEnabled) + try{ + String uuid = UUID.randomUUID() + taskProcessor.logDebug( "Generated uuid is: " + uuid, isDebugEnabled) + taskProcessor.logDebug( "URL to be used is: " + url, isDebugEnabled) + + String basicAuthCred = utils.getBasicAuth(execution.getVariable("URN_aai_auth"),execution.getVariable("URN_mso_msoKey")) + RESTConfig config = new RESTConfig(url); + RESTClient client = new RESTClient(config).addHeader("X-FromAppId", "MSO").addHeader("X-TransactionId", uuid).addHeader("Accept","application/xml").addAuthorizationHeader(authHeader); + if (basicAuthCred != null && !"".equals(basicAuthCred)) { + client.addAuthorizationHeader(basicAuthCred) + } + + APIResponse apiResponse = client.httpDelete(payload) + + return apiResponse + + }catch(Exception e){ + taskProcessor.utils.log("ERROR", "Exception occured while executing AAI Delete Call. Exception is: \n" + e, isDebugEnabled) + return e + } + taskProcessor.logDebug( "======== Completed Execute AAI Delete Process ======== ", isDebugEnabled) + } + + /** + * This reusable method can be used for making AAI Post 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 executeAAIPostCall(Execution execution, String url, String payload){ + def isDebugEnabled = execution.getVariable("isDebugLogEnabled") + taskProcessor.logDebug( " ======== Started Execute AAI Post Process ======== ", isDebugEnabled) + try{ + String uuid = UUID.randomUUID() + taskProcessor.logDebug( "Generated uuid is: " + uuid, isDebugEnabled) + taskProcessor.logDebug( "URL to be used is: " + url, isDebugEnabled) + + String basicAuthCred = utils.getBasicAuth(execution.getVariable("URN_aai_auth"),execution.getVariable("URN_mso_msoKey")) + RESTConfig config = new RESTConfig(url); + RESTClient client = new RESTClient(config).addHeader("X-FromAppId", "MSO").addHeader("X-TransactionId", uuid).addHeader("Accept","application/xml"); + if (basicAuthCred != null && !"".equals(basicAuthCred)) { + client.addAuthorizationHeader(basicAuthCred) + } + APIResponse apiResponse = client.httpPost(payload) + + return apiResponse + + }catch(Exception e){ + taskProcessor.utils.log("ERROR", "Exception occured while executing AAI Post Call. Exception is: \n" + e, isDebugEnabled) + return e + } + taskProcessor.logDebug( "======== Completed Execute AAI Post Process ======== ", isDebugEnabled) + } + + /** Utilitty 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). + */ + + //TODO: We should refactor this method to return WorkflowException instead of Error. Also to throw MSOWorkflowException which the calling flow will then catch. + + public String getAAICloudReqion(Execution execution, String url, String backend, inputCloudRegion){ + def isDebugEnabled = execution.getVariable("isDebugLogEnabled") + + try { + APIResponse apiResponse = executeAAIGetCall(execution, url) + String returnCode = apiResponse.getStatusCode() + String aaiResponseAsString = apiResponse.getResponseBodyAsString() + taskProcessor.utils.log("DEBUG", "Call AAI Cloud Region Return code: " + returnCode, isDebugEnabled) + execution.setVariable(execution.getVariable("prefix")+"queryCloudRegionReturnCode", returnCode) + //taskProcessor.utils.log("DEBUG", "Call AAI Cloud Region Response: " + aaiResponseAsString, isDebugEnabled) + //execution.setVariable(execution.getVariable("prefix")+"queryCloudRegionResponse", aaiResponseAsString) + String regionId = "" + if (returnCode == "200") { + taskProcessor.utils.log("DEBUG", "Call AAI Cloud Region is Successful.", isDebugEnabled) + try { + String regionVersion = taskProcessor.utils.getNodeText(aaiResponseAsString, "cloud-region-version") + taskProcessor.utils.log("DEBUG", "Cloud Region Version from AAI for " + backend + " is: " + regionVersion, isDebugEnabled) + 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") + } + } + + taskProcessor.utils.log("DEBUG", "Cloud Region Id from AAI " + backend + " is: " + regionId, isDebugEnabled) + return regionId + + } catch (Exception e) { + taskProcessor.utils.log("ERROR", "Exception occured while getting the Cloud Reqion. Exception is: \n" + e, isDebugEnabled) + return "ERROR" + } + } else { // not 200 + if (returnCode == "404") { + if (backend == "PO") { + regionId = inputCloudRegion + } else { // backend not "PO" + regionId = "AAIAIC25" + } + taskProcessor.utils.log("DEBUG", "Cloud Region value for code='404' of " + backend + " is: " + regionId, isDebugEnabled) + return regionId + } else { + taskProcessor.utils.log("ERROR", "Call AAI Cloud Region is NOT Successful.", isDebugEnabled) + return "ERROR" + } + } + }catch(Exception e) { + taskProcessor.utils.log("ERROR", "Exception occured while getting the Cloud Reqion. Exception is: \n" + e, isDebugEnabled) + return "ERROR" + } + } + + /* 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(Execution execution, String aaiVnfResponse, String key, String value) { + def isDebugEnabled = execution.getVariable("isDebugLogEnabled") + if (aaiVnfResponse != null) { + String vfModulesText = taskProcessor.utils.getNodeXml(aaiVnfResponse, "vf-modules") + if (vfModulesText == null || vfModulesText.isEmpty()) { + taskProcessor.utils.log("DEBUG", "There are no VF modules in this VNF yet", isDebugEnabled) + 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 = "" + 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 + "" + taskProcessor.utils.log("DEBUG", "Matching VF Modules: " + matchingVfModules, isDebugEnabled) + 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/openecomp/mso/bpmn/common/scripts/AbstractServiceTaskProcessor.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/AbstractServiceTaskProcessor.groovy index 5a23d17da0..d7aa97906c 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/AbstractServiceTaskProcessor.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/AbstractServiceTaskProcessor.groovy @@ -1,964 +1,720 @@ -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - MSO - * ================================================================================ - * 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.openecomp.mso.bpmn.common.scripts; - -import groovy.json.JsonSlurper - -import org.camunda.bpm.engine.delegate.BpmnError -import org.camunda.bpm.engine.runtime.Execution -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.openecomp.mso.bpmn.common.workflow.service.WorkflowCallbackResponse -import org.openecomp.mso.bpmn.common.workflow.service.WorkflowContextHolder -import org.openecomp.mso.bpmn.core.WorkflowException -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 INFO level. - * @param message the message - */ - public void logInfo(String message) { - log('INFO', message, null, "true") - } - - /** - * Logs a message at the INFO level. - * @param message the message - * @param cause the cause (stracktrace will be included in the output) - */ - public void logInfo(String message, Throwable cause) { - log('INFO', 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(Execution 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(Execution execution, String variable) { - if (variable == null) { - throw new NullPointerException(); - } - - execution.setVariable(variable, execution.getVariable("WorkflowException")) - execution.setVariable("WorkflowException", null) - } - - /** - * Builds a success response from the specified message content and numeric - * response code. The response code may be an integer or a string representation - * of an integer. The response is stored in the execution where it may be - * picked up by the Workflow service. - *

- * IMPORTANT: the activity that executes this method should have an - * asynchronous continuation after it to ensure the execution variables - * are persisted to the database. - * @param execution the execution - * @param content the message content - * @param responseCode the message response code - */ - @Deprecated - public void buildResponse(Execution execution, String content, Object responseCode) { - buildResponse(execution, content, responseCode, true) - } - - /** - * Builds a standard error response containing the specified error message and - * numeric response code. The response code may be an integer or a string - * representation of an integer. The response is stored in the execution where - * it may be picked up by the Workflow service. - *

- * IMPORTANT: the activity that executes this method should have an - * asynchronous continuation after it to ensure the execution variables - * are persisted to the database. - * @param execution the execution - * @param content the message content - * @param errorCode the message response code - */ - @Deprecated - public void buildErrorResponse(Execution execution, String errorMessage, Object errorCode) { - - def encErrorMessage = errorMessage.replace("&", "&").replace("<", "<").replace(">", ">") - - def content = """ - - ${encErrorMessage} - ${errorCode} - - """ - - buildResponse(execution, content, errorCode, false) - } - - // BEGIN LEGACY SUPPORT. TODO: REMOVE THIS CODE - /** - * Builds a standard error response containing the specified error message - * and a numeric response code. The response code is obtained from the - * prefix+"ResponseCode" execution variable. The response is stored in the - * execution where it may be picked up by the Workflow service. - *

- * IMPORTANT: the activity that executes this method should have an - * asynchronous continuation after it to ensure the execution variables - * are persisted to the database. - *

- * This method is deprecated. Methods that accept a response code should - * be used instead. - * @param execution the execution - * @param errorMessage the error message for the error response - */ - @Deprecated - public void buildErrorResponse(Execution execution, String errorMessage) { - buildErrorResponse(execution, errorMessage, null) - } - // END LEGACY SUPPORT. TODO: REMOVE THIS CODE - - /** - * Builds a response from the specified message content and numeric response - * code. The response code may be an integer or a string representation of - * an integer. The response is stored in the execution where it may be - * picked up by the Workflow service. - *

- * IMPORTANT: the activity that executes this method should have an - * asynchronous continuation after it to ensure the execution variables - * are persisted to the database. - * @param execution the execution - * @param content the message content - * @param responseCode the message response code - * @param isSuccess true if this is a success response - */ - @Deprecated - protected void buildResponse(Execution execution, String content, Object responseCode, - boolean isSuccess) { - def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') - - String processKey = getProcessKey(execution); - logDebug("Building " + processKey + " response", isDebugLogEnabled) - - Map responseMap = new HashMap() - - if (isSuccess) { - responseMap.put("Status", "Success") - } else { - responseMap.put("Status", "Fail") - } - - // BEGIN LEGACY SUPPORT. TODO: REMOVE THIS CODE - def prefix = execution.getVariable("prefix") - - if (responseCode == null) { - responseCode = execution.getVariable(prefix+"ResponseCode") - } else { - execution.setVariable(prefix+"ResponseCode", String.valueOf(responseCode)) - } - // END LEGACY SUPPORT. TODO: REMOVE THIS CODE - - responseMap.put("ResponseCode", String.valueOf(responseCode)) - - if (isSuccess) { - responseMap.put("Status", "Success") - // TODO: Should deprecate use of processKey+Response variable for the response. Will use "WorkflowResponse" instead - execution.setVariable("WorkflowResponse", content) - // BEGIN LEGACY SUPPORT. TODO: REMOVE THIS CODE - execution.setVariable(processKey+"Response", content) - execution.setVariable(prefix+"ErrorResponse", null) - // END LEGACY SUPPORT. TODO: REMOVE THIS CODE - } else { - responseMap.put("Status", "Fail") - // BEGIN LEGACY SUPPORT. TODO: REMOVE THIS CODE - execution.setVariable(prefix+"ErrorResponse", content) - execution.setVariable(prefix+"Response", null) - // END LEGACY SUPPORT. TODO: REMOVE THIS CODE - } - - responseMap.put("Response", content) - - logDebug(processKey - + " ResponseCode=" + responseMap.get("ResponseCode") - + " Status=" + responseMap.get("Status") - + " Response=\n" + responseMap.get("Response"), - isDebugLogEnabled) - - execution.setVariable(processKey + "ResponseMap", responseMap) - } - - /** - * Builds an error response (if one has not already been built) and throws - * a BpmnError of type "MSOWorkflowException" that can be caught as a - * boundary event. - * @param execution the execution - * @param errorMessage the error message for the error response - * @param responseCode the message response code - */ - @Deprecated - public void workflowException(Execution execution, String errorMessage, Object responseCode) { - String processKey = getProcessKey(execution); - - buildErrorResponse(execution, errorMessage, responseCode) - throw new BpmnError("MSOWorkflowException") - } - - /** - * Puts a WorkflowException into the execution - * @param execution the execution - * @param errorCode the error code (normally a 4-digit number) - * @param errorMessage the error message - */ - @Deprecated - public void newWorkflowException(Execution execution, int errorCode, String errorMessage) { - def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') - String processKey = getProcessKey(execution); - logDebug("Building a " + processKey + " WorkflowException", isDebugLogEnabled) - - if (errorCode < 1000) { - throw new IllegalArgumentException("ErrorCode must be a number greater than 1000"); - } - - WorkflowException exception = new WorkflowException(processKey, errorCode, errorMessage); - execution.setVariable("WorkflowException", exception); - } - - /** - * Puts a WorkflowException into the execution and throws an MSOWorkflowException event. - * @param execution the execution - * @param errorCode the error code (normally a 4-digit number) - * @param errorMessage the error message - */ - // TODO: rename this method to be throwWorkflowException - @Deprecated - public void createWorkflowException(Execution execution, int errorCode, String errorMessage) { - newWorkflowException(execution, errorCode, errorMessage) - throw new BpmnError("MSOWorkflowException", "errorCode:" + errorCode + ", errorMessage:" + errorMessage) - } - - /** - * Puts a WorkflowException into the execution and throws an MSOWorkflowException event. - * @param execution the execution - * @param errorCode the error code (normally a 4-digit number) - * @param errorMessage the error message - */ - @Deprecated - public void commonWorkflowException(Execution execution, int errorCode, String errorMessage) { - def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') - String processKey = getProcessKey(execution); - logDebug("Building a " + processKey + " WorkflowException", isDebugLogEnabled) - logError(errorMessage) - WorkflowException exception = new WorkflowException(processKey, errorCode, errorMessage); - execution.setVariable("WorkflowException", exception); - throw new BpmnError("MSOWorkflowException","errorCode:" + errorCode + ",errorMessage:" + errorMessage) - } - - /** - * Puts a WorkflowException into the execution and throws an MSOWorkflowException event. - * @param execution the execution - * @param errorCode the error code (normally a 4-digit number) - * @param errorMessage the error message - */ - @Deprecated - public void commonWorkflowException(Execution execution, String errorCode, String errorMessage) { - int intRespCode - try{ - intRespCode = Integer.parseInt(errorCode) - }catch (Exception e){ - intRespCode = 400 - } - commonWorkflowException(execution, intRespCode, errorMessage) - } - - - - /** - * 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(Execution 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 allRequiredVariables = new ArrayList() - 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(Execution 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(Execution 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(Execution 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(Execution 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(Execution execution) { - Execution exec = execution - - while (true) { - Execution 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(Execution execution, String xml, String elementName) { - def element = utils.getNodeXml(xml, elementName, false) - if (element.trim().isEmpty()) { - def msg = 'Required element \'' + elementName + '\' is missing or empty' - logError(msg) - createWorkflowException(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 value of the element, if found in the xml. - */ - protected String getRequiredNodeText(Execution execution, String xml, String elementName) { - def elementText = utils.getNodeText1(xml, elementName) - if (elementText == null) { - def msg = 'Required element \'' + elementName + '\' is missing or empty' - logError(msg) - createWorkflowException(execution, 2000, msg) - } else { - return elementText - } - } - - /** - * 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) { - def nodeText = utils.getNodeText1(xml, elementName) - return (nodeText == null) ? '' : nodeText - } - - /** - * Sends the empty, synchronous response back to the API Handler. - * @param execution the execution - */ - @Deprecated - public void sendResponse(Execution execution) { - def method = getClass().getSimpleName() + '.sendResponse(' + - 'execution=' + execution.getId() + - ')' - def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') - logDebug('Entered ' + method, isDebugLogEnabled) - - try { - buildResponse(execution, "", 200) - logDebug('Exited ' + method, isDebugLogEnabled) - } catch (BpmnError e) { - throw e; - } catch (Exception e) { - logError('Caught exception in ' + method, e) - workflowException(execution, 'Internal Error', 9999) // TODO: what message and error code? - } - } - - /** - *Store the variable as typed with java serialization type - *@param execution - *@param name - *@param value - */ - public void setVariable(Execution 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(Execution 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: - *

-	 *     def statusCode = getStatusCode()
-	 *     isOneOf(statusCode, 200, 201, 204)
-	 * 
- * @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 - } - - public void setSuccessIndicator(Execution 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) - } - - - public void sendSyncError(Execution 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) - } - } - - /** - * Create a WorkflowException - uses ExceptionUtil to build a WorkflowException - * @param execution - * @param errorCode - * @param errorMessage - * @param isDebugEnabled - */ - public void buildWorkflowException(Execution execution, int errorCode, String errorMessage, boolean isDebugEnabled) { - (new ExceptionUtil()).buildWorkflowException(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 - Execution execution = (Execution) 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 - } - - /** - * - *This method gets and decodes SDNC Response's "RequestData". - * - *@param response - the sdnc response - * - *@return data - the response "RequestData" decoded - * - */ - public String getRequestDataDecoded(String response){ - String data = utils.getNodeText1(response, "RequestData") - if(data != null){ - data = data.replaceAll("<", "<") - data = data.replaceAll(">", ">") - } - - return data - } - - - /** - * Constructs a workflow message callback URL for the specified message type and correlator. - * @param messageType the message type (e.g. SDNCAResponse or VNFAResponse) - * @param correlator the correlator value (e.g. a request ID) - */ - public String createCallbackURL(Execution execution, String messageType, String correlator) { - String endpoint = (String) execution.getVariable('URN_mso_workflow_message_endpoint') - - 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') - } - -} +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.bpmn.common.scripts; + +import groovy.json.JsonSlurper + +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.runtime.Execution +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.openecomp.mso.bpmn.common.workflow.service.WorkflowCallbackResponse +import org.openecomp.mso.bpmn.common.workflow.service.WorkflowContextHolder +import org.openecomp.mso.bpmn.core.WorkflowException +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(Execution 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(Execution 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(Execution 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 allRequiredVariables = new ArrayList() + 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(Execution 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(Execution 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(Execution 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(Execution 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(Execution execution) { + Execution exec = execution + + while (true) { + Execution 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(Execution 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(Execution execution, String xml, String elementName) { + ExceptionUtil exceptionUtil = new ExceptionUtil() + def elementText = utils.getNodeText1(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.getNodeText1(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(Execution 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(Execution 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: + *
+	 *     def statusCode = getStatusCode()
+	 *     isOneOf(statusCode, 200, 201, 204)
+	 * 
+ * @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(Execution 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(Execution 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) + } + } + + /** + * Create a WorkflowException - uses ExceptionUtil to build a WorkflowException + * @param execution + * @param errorCode + * @param errorMessage + * @param isDebugEnabled + */ + public void buildWorkflowException(Execution execution, int errorCode, String errorMessage, boolean isDebugEnabled) { + (new ExceptionUtil()).buildWorkflowException(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 + Execution execution = (Execution) 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 + } + + /** + * + *This method gets and decodes SDNC Response's "RequestData". + * + *@param response - the sdnc response + * + *@return data - the response "RequestData" decoded + * + */ + public String getRequestDataDecoded(String response){ + String data = utils.getNodeText1(response, "RequestData") + if(data != null){ + data = data.replaceAll("<", "<") + data = data.replaceAll(">", ">") + } + + return data + } + + + /** + * Constructs a workflow message callback URL for the specified message type and correlator. + * @param messageType the message type (e.g. SDNCAResponse or VNFAResponse) + * @param correlator the correlator value (e.g. a request ID) + */ + public String createCallbackURL(Execution execution, String messageType, String correlator) { + String endpoint = (String) execution.getVariable('URN_mso_workflow_message_endpoint') + + 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') + } +} \ No newline at end of file diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/CatalogDbUtils.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/CatalogDbUtils.groovy index f74717b510..488535024b 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/CatalogDbUtils.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/CatalogDbUtils.groovy @@ -1,550 +1,931 @@ -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - MSO - * ================================================================================ - * 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.openecomp.mso.bpmn.common.scripts - -import org.json.JSONObject; -import org.json.JSONArray; -import org.json.XML; -import org.springframework.web.util.UriUtils; - -import org.openecomp.mso.bpmn.core.json.JsonUtils - - -import groovy.json.JsonBuilder -import groovy.json.JsonSlurper -import groovy.util.slurpersupport.GPathResult -import groovy.xml.QName; - -import org.openecomp.mso.logger.MsoLogger; -import org.openecomp.mso.rest.APIResponse; -import org.openecomp.mso.rest.RESTClient -import org.openecomp.mso.rest.RESTConfig - - -/*** - * Utilities for accessing Catalog DB Adapter to retrieve Networks, VNF/VFModules, AllottedResources and complete ServiceResources information - * - */ - -class CatalogDbUtils { - - MsoUtils utils = new MsoUtils() - JsonUtils jsonUtils = new JsonUtils() - MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL); - - public JSONArray getAllNetworksByServiceModelUuid(String catalogDbEndpoint, String serviceModelUuid) { - JSONArray networksList = null - String endPoint = catalogDbEndpoint + "/v1/serviceNetworks?serviceModelUuid=" + UriUtils.encode(serviceModelUuid, "UTF-8") - try { - String catalogDbResponse = getResponseFromCatalogDb(endPoint) - - if (catalogDbResponse != null) { - networksList = parseNetworksJson(catalogDbResponse, "serviceNetworks") - } - - } - catch (Exception e) { - utils.log("ERROR", "Exception in Querying Catalog DB: " + e.message) - } - - return networksList - } - - public JSONArray getAllNetworksByServiceModelInvariantUuid(String catalogDbEndpoint, String serviceModelInvariantUuid) { - JSONArray networksList = null - String endPoint = catalogDbEndpoint + "/v1/serviceNetworks?serviceModelInvariantUuid=" + UriUtils.encode(serviceModelInvariantUuid, "UTF-8") - try { - String catalogDbResponse = getResponseFromCatalogDb(endPoint) - - if (catalogDbResponse != null) { - networksList = parseNetworksJson(catalogDbResponse, "serviceNetworks") - } - - } - catch (Exception e) { - utils.log("ERROR", "Exception in Querying Catalog DB: " + e.message) - } - - return networksList - } - - public JSONArray getAllNetworksByServiceModelInvariantUuidAndServiceModelVersion(String catalogDbEndpoint, String serviceModelInvariantUuid, String serviceModelVersion) { - JSONArray networksList = null - String endPoint = catalogDbEndpoint + "/v1/serviceNetworks?serviceModelInvariantUuid=" + UriUtils.encode(serviceModelInvariantUuid, "UTF-8") + "&serviceModelVersion=" + UriUtils.encode(serviceModelVersion, "UTF-8") - try { - String catalogDbResponse = getResponseFromCatalogDb(endPoint) - - if (catalogDbResponse != null) { - networksList = parseNetworksJson(catalogDbResponse, "serviceNetworks") - } - - } - catch (Exception e) { - utils.log("ERROR", "Exception in Querying Catalog DB: " + e.message) - } - - return networksList - } - - public JSONArray getAllNetworksByNetworkModelCustomizationUuid(String catalogDbEndpoint, String networkModelCustomizationUuid) { - JSONArray networksList = null - String endPoint = catalogDbEndpoint + "/v1/serviceNetworks?networkModelCustomizationUuid=" + UriUtils.encode(networkModelCustomizationUuid, "UTF-8") - try { - String catalogDbResponse = getResponseFromCatalogDb(endPoint) - - if (catalogDbResponse != null) { - networksList = parseNetworksJson(catalogDbResponse, "serviceNetworks") - } - - } - catch (Exception e) { - utils.log("ERROR", "Exception in Querying Catalog DB: " + e.message) - } - - return networksList - } - - public JSONArray getAllNetworksByNetworkType(String catalogDbEndpoint, String networkType) { - JSONArray networksList = null - String endPoint = catalogDbEndpoint + "/v1/serviceNetworks?networkType=" + UriUtils.encode(networkType, "UTF-8") - try { - String catalogDbResponse = getResponseFromCatalogDb(endPoint) - - if (catalogDbResponse != null) { - networksList = parseNetworksJson(catalogDbResponse, "serviceNetworks") - } - - } - catch (Exception e) { - utils.log("ERROR", "Exception in Querying Catalog DB: " + e.message) - } - - return networksList - } - - - public JSONArray getAllVnfsByServiceModelUuid(String catalogDbEndpoint, String serviceModelUuid) { - JSONArray vnfsList = null - String endPoint = catalogDbEndpoint + "/v1/serviceVnfs?serviceModelUuid=" + UriUtils.encode(serviceModelUuid, "UTF-8") - try { - msoLogger.debug("ENDPOINT: " + endPoint) - String catalogDbResponse = getResponseFromCatalogDb(endPoint) - - if (catalogDbResponse != null) { - vnfsList = parseVnfsJson(catalogDbResponse, "serviceVnfs") - } - - } - catch (Exception e) { - utils.log("ERROR", "Exception in Querying Catalog DB: " + e.message) - } - - return vnfsList - } - - public JSONArray getAllVnfsByServiceModelInvariantUuid(String catalogDbEndpoint, String serviceModelInvariantUuid) { - JSONArray vnfsList = null - String endPoint = catalogDbEndpoint + "/v1/serviceVnfs?serviceModelInvariantUuid=" + UriUtils.encode(serviceModelInvariantUuid, "UTF-8") - try { - msoLogger.debug("ENDPOINT: " + endPoint) - String catalogDbResponse = getResponseFromCatalogDb(endPoint) - - if (catalogDbResponse != null) { - vnfsList = parseVnfsJson(catalogDbResponse, "serviceVnfs") - } - - } - catch (Exception e) { - utils.log("ERROR", "Exception in Querying Catalog DB: " + e.message) - } - - return vnfsList - } - - public JSONArray getAllVnfsByServiceModelInvariantUuidAndServiceModelVersion(String catalogDbEndpoint, String serviceModelInvariantUuid, String serviceModelVersion) { - JSONArray vnfsList = null - String endPoint = catalogDbEndpoint + "/v1/serviceVnfs?serviceModelInvariantUuid=" + UriUtils.encode(serviceModelInvariantUuid, "UTF-8") + "&serviceModelVersion=" + UriUtils.encode(serviceModelVersion, "UTF-8") - try { - msoLogger.debug("ENDPOINT: " + endPoint) - String catalogDbResponse = getResponseFromCatalogDb(endPoint) - - if (catalogDbResponse != null) { - vnfsList = parseVnfsJson(catalogDbResponse, "serviceVnfs") - } - - } - catch (Exception e) { - utils.log("ERROR", "Exception in Querying Catalog DB: " + e.message) - } - - return vnfsList - } - - public JSONArray getAllVnfsByVnfModelCustomizationUuid(String catalogDbEndpoint, String vnfModelCustomizationUuid) { - JSONArray vnfsList = null - String endPoint = catalogDbEndpoint + "/v1/serviceVnfs?vnfModelCustomizationUuid=" + UriUtils.encode(vnfModelCustomizationUuid, "UTF-8") - try { - msoLogger.debug("ENDPOINT: " + endPoint) - String catalogDbResponse = getResponseFromCatalogDb(endPoint) - - if (catalogDbResponse != null) { - vnfsList = parseVnfsJson(catalogDbResponse, "serviceVnfs") - } - - } - catch (Exception e) { - utils.log("ERROR", "Exception in Querying Catalog DB: " + e.message) - } - - return vnfsList - } - - - public JSONArray getAllottedResourcesByServiceModelUuid(String catalogDbEndpoint, String serviceModelUuid) { - JSONArray vnfsList = null - String endPoint = catalogDbEndpoint + "/v1/ServiceAllottedResources?serviceModelUuid=" + UriUtils.encode(serviceModelUuid, "UTF-8") - try { - String catalogDbResponse = getResponseFromCatalogDb(endPoint) - - if (catalogDbResponse != null) { - vnfsList = parseAllottedResourcesJson(catalogDbResponse, "serviceAllottedResources") - } - - } - catch (Exception e) { - utils.log("ERROR", "Exception in Querying Catalog DB: " + e.message) - } - - return vnfsList - } - - public JSONArray getAllottedResourcesByServiceModelInvariantUuid(String catalogDbEndpoint, String serviceModelInvariantUuid) { - JSONArray vnfsList = null - String endPoint = catalogDbEndpoint + "/v1/serviceAllottedResources?serviceModelInvariantUuid=" + UriUtils.encode(serviceModelInvariantUuid, "UTF-8") - try { - String catalogDbResponse = getResponseFromCatalogDb(endPoint) - - if (catalogDbResponse != null) { - vnfsList = parseAllottedResourcesJson(catalogDbResponse, "serviceAllottedResources") - } - - } - catch (Exception e) { - utils.log("ERROR", "Exception in Querying Catalog DB: " + e.message) - } - - return vnfsList - } - - public JSONArray getAllottedResourcesByServiceModelInvariantUuidAndServiceModelVersion(String catalogDbEndpoint, String serviceModelInvariantUuid, String serviceModelVersion) { - JSONArray vnfsList = null - String endPoint = catalogDbEndpoint + "/v1/serviceAllottedResources?serviceModelInvariantUuid=" + UriUtils.encode(serviceModelInvariantUuid, "UTF-8") + "&serviceModelVersion=" + UriUtils.encode(serviceModelVersion, "UTF-8") - try { - String catalogDbResponse = getResponseFromCatalogDb(endPoint) - - if (catalogDbResponse != null) { - vnfsList = parseAllottedResourcesJson(catalogDbResponse, "serviceAllottedResources") - } - - } - catch (Exception e) { - utils.log("ERROR", "Exception in Querying Catalog DB: " + e.message) - } - - return vnfsList - } - - public JSONArray getAllottedResourcesByArModelCustomizationUuid(String catalogDbEndpoint, String arModelCustomizationUuid) { - JSONArray vnfsList = null - String endPoint = catalogDbEndpoint + "/v1/serviceAllottedResources?serviceModelCustomizationUuid=" + UriUtils.encode(arModelCustomizationUuid, "UTF-8") - try { - String catalogDbResponse = getResponseFromCatalogDb(endPoint) - - if (catalogDbResponse != null) { - vnfsList = parseAllottedResourcesJson(catalogDbResponse, "serviceAllottedResources") - } - - } - catch (Exception e) { - utils.log("ERROR", "Exception in Querying Catalog DB: " + e.message) - } - - return vnfsList - } - - public JSONObject getServiceResourcesByServiceModelInvariantUuid(String catalogDbEndpoint, String serviceModelInvariantUuid) { - JSONObject resources = null - String endPoint = catalogDbEndpoint + "/v1/serviceResources?serviceModelInvariantUuid=" + UriUtils.encode(serviceModelInvariantUuid, "UTF-8") - try { - String catalogDbResponse = getResponseFromCatalogDb(endPoint) - - if (catalogDbResponse != null) { - resources = parseServiceResourcesJson(catalogDbResponse) - } - - } - catch (Exception e) { - utils.log("ERROR", "Exception in Querying Catalog DB: " + e.message) - } - - return resources - } - - public JSONObject getServiceResourcesByServiceModelInvariantUuidAndServiceModelVersion(String catalogDbEndpoint, String serviceModelInvariantUuid, String serviceModelVersion) { - JSONObject resources = null - String endPoint = catalogDbEndpoint + "/v1/serviceResources?serviceModelInvariantUuid=" + UriUtils.encode(serviceModelInvariantUuid, "UTF-8") + "&serviceModelVersion=" + UriUtils.encode(serviceModelVersion, "UTF-8") - try { - String catalogDbResponse = getResponseFromCatalogDb(endPoint) - - if (catalogDbResponse != null) { - resources = parseServiceResourcesJson(catalogDbResponse) - } - - } - catch (Exception e) { - utils.log("ERROR", "Exception in Querying Catalog DB: " + e.message) - } - - return resources - } - - - - private JSONArray parseNetworksJson (String catalogDbResponse, String arrayName) { - JSONArray modelInfos = null - - 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 modelInfo = buildModelInfo("network", network) - JSONObject modelJson = new JSONObject() - modelJson.put("modelInfo", modelInfo) - String networkType = jsonUtils.getJsonValueForKey(network, "networkType") - modelJson.put("networkType", networkType) - modelInfos.put(modelJson) - } - - String modelInfosString = modelInfos.toString() - msoLogger.debug("Returning networks JSON: " + modelInfosString) - - } catch (Exception e) { - utils.log("ERROR", "Exception in parsing Catalog DB Response: " + e.message) - } - - return modelInfos - } - - private JSONArray parseVnfsJson (String catalogDbResponse, String arrayName) { - JSONArray modelInfos = null - - 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) - JSONObject modelJson = new JSONObject() - modelJson.put("modelInfo", modelInfo) - - 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) - JSONObject vfModuleModelJson = new JSONObject() - vfModuleModelJson.put("modelInfo", vfModuleModelInfo) - String vfModuleType = jsonUtils.getJsonValueForKey(vfModule, "type") - vfModuleModelJson.put("vfModuleType", vfModuleType) - Integer isBase = jsonUtils.getJsonIntValueForKey(vfModule, "isBase") - if (isBase.intValue() == 1) { - vfModuleModelJson.put("isBase", "true") - } - else { - vfModuleModelJson.put("isBase", "false") - } - 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) { - utils.log("ERROR", "Exception in parsing Catalog DB Response: " + e.message) - } - - return modelInfos - } - - private JSONArray parseAllottedResourcesJson (String catalogDbResponse, String arrayName) { - JSONArray modelInfos = null - - 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) - JSONObject modelJson = new JSONObject() - modelJson.put("modelInfo", modelInfo) - modelInfos.put(modelJson) - } - - String modelInfosString = modelInfos.toString() - msoLogger.debug("Returning allottedResources JSON: " + modelInfosString) - - } catch (Exception e) { - utils.log("ERROR", "Exception in parsing Catalog DB Response: " + e.message) - } - - return modelInfos - } - - private JSONObject parseServiceResourcesJson (String catalogDbResponse) { - JSONObject serviceResources = new JSONObject() - - try { - // Create array of jsons - - JSONObject responseJson = new JSONObject(catalogDbResponse) - JSONObject serviceResourcesRoot = responseJson.getJSONObject("serviceResources") - JSONArray vnfsArray = parseVnfsJson(serviceResourcesRoot.toString(), "vnfResources") - serviceResources.put("vnfs", vnfsArray) - JSONArray networksArray = parseNetworksJson(serviceResourcesRoot.toString(), "networkResourceCustomization") - serviceResources.put("networks", networksArray) - JSONArray allottedResourcesArray = parseAllottedResourcesJson(serviceResourcesRoot.toString(), "allottedResourceCustomization") - serviceResources.put("allottedResources", allottedResourcesArray) - - String serviceResourcesString = serviceResources.toString() - msoLogger.debug("Returning serviceResources JSON: " + serviceResourcesString) - - } catch (Exception e) { - utils.log("ERROR", "Exception in parsing Catalog DB Response: " + e.message) - } - - return serviceResources - } - - private JSONObject buildModelInfo(String modelType, JSONObject modelFromDb) { - 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")){ - String modelInstanceName = jsonUtils.getJsonValueForKey(modelFromDb, "modelInstanceName") - modelInfo.put("modelInstanceName", modelInstanceName) - } - if (!"vfModule".equals(modelType) && !"vnf".equals(modelType)) { - 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") - modelInfo.put("modelCustomizationId", modelCustomizationId) - JSONObject modelJson = new JSONObject() - modelJson.put("modelInfo", modelInfo) - } - catch (Exception e) { - utils.log("ERROR", "Exception while parsing model information: " + e.message) - } - return modelInfo - } - - private String getResponseFromCatalogDb (String endPoint) { - try { - RESTConfig config = new RESTConfig(endPoint); - 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'); - 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) - return null - } - - } -} +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.bpmn.common.scripts + +import org.json.JSONObject; +import org.json.JSONArray; +import org.json.XML; +import org.springframework.web.util.UriUtils; + +import org.openecomp.mso.bpmn.core.json.JsonUtils + + +import groovy.json.JsonBuilder +import groovy.json.JsonSlurper +import groovy.util.slurpersupport.GPathResult +import groovy.xml.QName; + +import org.openecomp.mso.logger.MsoLogger; +import org.openecomp.mso.rest.APIResponse; +import org.openecomp.mso.rest.RESTClient +import org.openecomp.mso.rest.RESTConfig + + +/*** + * Utilities for accessing Catalog DB Adapter to retrieve Networks, VNF/VFModules, AllottedResources and complete ServiceResources information + * + */ + +class CatalogDbUtils { + + MsoUtils utils = new MsoUtils() + JsonUtils jsonUtils = new JsonUtils() + MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL); + static private String defaultDbAdapterVersion = "v2" + + public JSONArray getAllNetworksByServiceModelUuid(String catalogDbEndpoint, String serviceModelUuid) { + JSONArray networksList = null + String endPoint = catalogDbEndpoint + "/" + defaultDbAdapterVersion + "/serviceNetworks?serviceModelUuid=" + UriUtils.encode(serviceModelUuid, "UTF-8") + try { + String catalogDbResponse = getResponseFromCatalogDb(endPoint) + + if (catalogDbResponse != null) { + networksList = parseNetworksJson(catalogDbResponse, "serviceNetworks", "v1") + } + + } + catch (Exception e) { + utils.log("ERROR", "Exception in Querying Catalog DB: " + e.message) + } + + return networksList + } + + public JSONArray getAllNetworksByServiceModelUuid(String catalogDbEndpoint, String serviceModelUuid, String catalogUtilsVersion) { + JSONArray networksList = null + String endPoint = catalogDbEndpoint + "/" + defaultDbAdapterVersion + "/serviceNetworks?serviceModelUuid=" + UriUtils.encode(serviceModelUuid, "UTF-8") + try { + String catalogDbResponse = getResponseFromCatalogDb(endPoint) + + if (catalogDbResponse != null) { + networksList = parseNetworksJson(catalogDbResponse, "serviceNetworks", catalogUtilsVersion) + + } + + } + catch (Exception e) { + utils.log("ERROR", "Exception in Querying Catalog DB: " + e.message) + } + + return networksList + } + + public JSONArray getAllNetworksByServiceModelInvariantUuid(String catalogDbEndpoint, String serviceModelInvariantUuid) { + JSONArray networksList = null + String endPoint = catalogDbEndpoint + "/" + defaultDbAdapterVersion + "/serviceNetworks?serviceModelInvariantUuid=" + UriUtils.encode(serviceModelInvariantUuid, "UTF-8") + try { + String catalogDbResponse = getResponseFromCatalogDb(endPoint) + + if (catalogDbResponse != null) { + networksList = parseNetworksJson(catalogDbResponse, "serviceNetworks", "v1") + } + + } + catch (Exception e) { + utils.log("ERROR", "Exception in Querying Catalog DB: " + e.message) + } + + return networksList + } + + public JSONArray getAllNetworksByServiceModelInvariantUuid(String catalogDbEndpoint, String serviceModelInvariantUuid, String catalogUtilsVersion) { + JSONArray networksList = null + String endPoint = catalogDbEndpoint + "/" + defaultDbAdapterVersion + "/serviceNetworks?serviceModelInvariantUuid=" + UriUtils.encode(serviceModelInvariantUuid, "UTF-8") + + try { + String catalogDbResponse = getResponseFromCatalogDb(endPoint) + + if (catalogDbResponse != null) { + networksList = parseNetworksJson(catalogDbResponse, "serviceNetworks", catalogUtilsVersion) + } + + } + catch (Exception e) { + utils.log("ERROR", "Exception in Querying Catalog DB: " + e.message) + } + + return networksList + } + + public JSONArray getAllNetworksByServiceModelInvariantUuidAndServiceModelVersion(String catalogDbEndpoint, String serviceModelInvariantUuid, String serviceModelVersion) { + JSONArray networksList = null + String endPoint = catalogDbEndpoint + "/" + defaultDbAdapterVersion + "/serviceNetworks?serviceModelInvariantUuid=" + UriUtils.encode(serviceModelInvariantUuid, "UTF-8") + "&serviceModelVersion=" + UriUtils.encode(serviceModelVersion, "UTF-8") + try { + String catalogDbResponse = getResponseFromCatalogDb(endPoint) + + if (catalogDbResponse != null) { + networksList = parseNetworksJson(catalogDbResponse, "serviceNetworks", "v1") + } + + } + catch (Exception e) { + utils.log("ERROR", "Exception in Querying Catalog DB: " + e.message) + } + + return networksList + } + + public JSONArray getAllNetworksByServiceModelInvariantUuidAndServiceModelVersion(String catalogDbEndpoint, String serviceModelInvariantUuid, String serviceModelVersion, String catalogUtilsVersion) { + JSONArray networksList = null + String endPoint = catalogDbEndpoint + "/" + defaultDbAdapterVersion + "/serviceNetworks?serviceModelInvariantUuid=" + UriUtils.encode(serviceModelInvariantUuid, "UTF-8") + "&serviceModelVersion=" + UriUtils.encode(serviceModelVersion, "UTF-8") + + try { + String catalogDbResponse = getResponseFromCatalogDb(endPoint) + + if (catalogDbResponse != null) { + networksList = parseNetworksJson(catalogDbResponse, "serviceNetworks", catalogUtilsVersion) + } + + } + catch (Exception e) { + utils.log("ERROR", "Exception in Querying Catalog DB: " + e.message) + } + + return networksList + } + + public JSONArray getAllNetworksByNetworkModelCustomizationUuid(String catalogDbEndpoint, String networkModelCustomizationUuid) { + JSONArray networksList = null + String endPoint = catalogDbEndpoint + "/" + defaultDbAdapterVersion + "/serviceNetworks?networkModelCustomizationUuid=" + UriUtils.encode(networkModelCustomizationUuid, "UTF-8") + try { + String catalogDbResponse = getResponseFromCatalogDb(endPoint) + + if (catalogDbResponse != null) { + networksList = parseNetworksJson(catalogDbResponse, "serviceNetworks", "v1") + } + + } + catch (Exception e) { + utils.log("ERROR", "Exception in Querying Catalog DB: " + e.message) + } + + return networksList + } + + public JSONArray getAllNetworksByNetworkModelCustomizationUuid(String catalogDbEndpoint, String networkModelCustomizationUuid, String catalogUtilsVersion) { + JSONArray networksList = null + String endPoint = catalogDbEndpoint + "/" + defaultDbAdapterVersion + "/serviceNetworks?networkModelCustomizationUuid=" + UriUtils.encode(networkModelCustomizationUuid, "UTF-8") + + try { + String catalogDbResponse = getResponseFromCatalogDb(endPoint) + + if (catalogDbResponse != null) { + networksList = parseNetworksJson(catalogDbResponse, "serviceNetworks", catalogUtilsVersion) + } + + } + catch (Exception e) { + utils.log("ERROR", "Exception in Querying Catalog DB: " + e.message) + } + + return networksList + } + + public JSONArray getAllNetworksByNetworkType(String catalogDbEndpoint, String networkType) { + JSONArray networksList = null + String endPoint = catalogDbEndpoint + "/" + defaultDbAdapterVersion + "/serviceNetworks?networkType=" + UriUtils.encode(networkType, "UTF-8") + try { + String catalogDbResponse = getResponseFromCatalogDb(endPoint) + + if (catalogDbResponse != null) { + networksList = parseNetworksJson(catalogDbResponse, "serviceNetworks", "v1") + } + + } + catch (Exception e) { + utils.log("ERROR", "Exception in Querying Catalog DB: " + e.message) + } + + return networksList + } + + public JSONArray getAllNetworksByNetworkType(String catalogDbEndpoint, String networkType, String catalogUtilsVersion) { + JSONArray networksList = null + String endPoint = catalogDbEndpoint + "/" + defaultDbAdapterVersion + "/serviceNetworks?networkType=" + UriUtils.encode(networkType, "UTF-8") + try { + String catalogDbResponse = getResponseFromCatalogDb(endPoint) + + if (catalogDbResponse != null) { + networksList = parseNetworksJson(catalogDbResponse, "serviceNetworks", catalogUtilsVersion) + + } + + } + catch (Exception e) { + utils.log("ERROR", "Exception in Querying Catalog DB: " + e.message) + } + + return networksList + } + + + public JSONArray getAllVnfsByServiceModelUuid(String catalogDbEndpoint, String serviceModelUuid) { + JSONArray vnfsList = null + String endPoint = catalogDbEndpoint + "/" + defaultDbAdapterVersion + "/serviceVnfs?serviceModelUuid=" + UriUtils.encode(serviceModelUuid, "UTF-8") + try { + msoLogger.debug("ENDPOINT: " + endPoint) + String catalogDbResponse = getResponseFromCatalogDb(endPoint) + + if (catalogDbResponse != null) { + vnfsList = parseVnfsJson(catalogDbResponse, "serviceVnfs", "v1") + } + + } + catch (Exception e) { + utils.log("ERROR", "Exception in Querying Catalog DB: " + e.message) + } + + return vnfsList + } + + public JSONArray getAllVnfsByServiceModelUuid(String catalogDbEndpoint, String serviceModelUuid, String catalogUtilsVersion) { + JSONArray vnfsList = null + String endPoint = catalogDbEndpoint + "/" + defaultDbAdapterVersion + "/serviceVnfs?serviceModelUuid=" + UriUtils.encode(serviceModelUuid, "UTF-8") + try { + msoLogger.debug("ENDPOINT: " + endPoint) + String catalogDbResponse = getResponseFromCatalogDb(endPoint) + + if (catalogDbResponse != null) { + vnfsList = parseVnfsJson(catalogDbResponse, "serviceVnfs", catalogUtilsVersion) + + } + + } + catch (Exception e) { + utils.log("ERROR", "Exception in Querying Catalog DB: " + e.message) + } + + return vnfsList + } + + public JSONArray getAllVnfsByServiceModelInvariantUuid(String catalogDbEndpoint, String serviceModelInvariantUuid) { + JSONArray vnfsList = null + String endPoint = catalogDbEndpoint + "/" + defaultDbAdapterVersion + "/serviceVnfs?serviceModelInvariantUuid=" + UriUtils.encode(serviceModelInvariantUuid, "UTF-8") + try { + msoLogger.debug("ENDPOINT: " + endPoint) + String catalogDbResponse = getResponseFromCatalogDb(endPoint) + + if (catalogDbResponse != null) { + vnfsList = parseVnfsJson(catalogDbResponse, "serviceVnfs", "v1") + } + + } + catch (Exception e) { + utils.log("ERROR", "Exception in Querying Catalog DB: " + e.message) + } + + return vnfsList + } + + public JSONArray getAllVnfsByServiceModelInvariantUuid(String catalogDbEndpoint, String serviceModelInvariantUuid, String catalogUtilsVersion) { + JSONArray vnfsList = null + String endPoint = catalogDbEndpoint + "/" + defaultDbAdapterVersion + "/serviceVnfs?serviceModelInvariantUuid=" + UriUtils.encode(serviceModelInvariantUuid, "UTF-8") + try { + msoLogger.debug("ENDPOINT: " + endPoint) + String catalogDbResponse = getResponseFromCatalogDb(endPoint) + + if (catalogDbResponse != null) { + vnfsList = parseVnfsJson(catalogDbResponse, "serviceVnfs", catalogUtilsVersion) + + } + + } + catch (Exception e) { + utils.log("ERROR", "Exception in Querying Catalog DB: " + e.message) + } + + return vnfsList + } + + public JSONArray getAllVnfsByServiceModelInvariantUuidAndServiceModelVersion(String catalogDbEndpoint, String serviceModelInvariantUuid, String serviceModelVersion) { + JSONArray vnfsList = null + String endPoint = catalogDbEndpoint + "/" + defaultDbAdapterVersion + "/serviceVnfs?serviceModelInvariantUuid=" + UriUtils.encode(serviceModelInvariantUuid, "UTF-8") + "&serviceModelVersion=" + UriUtils.encode(serviceModelVersion, "UTF-8") + try { + msoLogger.debug("ENDPOINT: " + endPoint) + String catalogDbResponse = getResponseFromCatalogDb(endPoint) + + if (catalogDbResponse != null) { + vnfsList = parseVnfsJson(catalogDbResponse, "serviceVnfs", "v1") + } + + } + catch (Exception e) { + utils.log("ERROR", "Exception in Querying Catalog DB: " + e.message) + } + + return vnfsList + } + + public JSONArray getAllVnfsByServiceModelInvariantUuidAndServiceModelVersion(String catalogDbEndpoint, String serviceModelInvariantUuid, String serviceModelVersion, String catalogUtilsVersion) { + JSONArray vnfsList = null + String endPoint = catalogDbEndpoint + "/" + defaultDbAdapterVersion + "/serviceVnfs?serviceModelInvariantUuid=" + UriUtils.encode(serviceModelInvariantUuid, "UTF-8") + "&serviceModelVersion=" + UriUtils.encode(serviceModelVersion, "UTF-8") + try { + msoLogger.debug("ENDPOINT: " + endPoint) + String catalogDbResponse = getResponseFromCatalogDb(endPoint) + + if (catalogDbResponse != null) { + vnfsList = parseVnfsJson(catalogDbResponse, "serviceVnfs", catalogUtilsVersion) + + } + + } + catch (Exception e) { + utils.log("ERROR", "Exception in Querying Catalog DB: " + e.message) + } + + return vnfsList + } + + public JSONArray getAllVnfsByVnfModelCustomizationUuid(String catalogDbEndpoint, String vnfModelCustomizationUuid) { + JSONArray vnfsList = null + String endPoint = catalogDbEndpoint + "/" + defaultDbAdapterVersion + "/serviceVnfs?vnfModelCustomizationUuid=" + UriUtils.encode(vnfModelCustomizationUuid, "UTF-8") + try { + msoLogger.debug("ENDPOINT: " + endPoint) + String catalogDbResponse = getResponseFromCatalogDb(endPoint) + + if (catalogDbResponse != null) { + vnfsList = parseVnfsJson(catalogDbResponse, "serviceVnfs", "v1") + } + + } + catch (Exception e) { + utils.log("ERROR", "Exception in Querying Catalog DB: " + e.message) + } + + return vnfsList + } + + public JSONArray getAllVnfsByVnfModelCustomizationUuid(String catalogDbEndpoint, String vnfModelCustomizationUuid, String catalogUtilsVersion) { + JSONArray vnfsList = null + String endPoint = catalogDbEndpoint + "/" + defaultDbAdapterVersion + "/serviceVnfs?vnfModelCustomizationUuid=" + UriUtils.encode(vnfModelCustomizationUuid, "UTF-8") + try { + msoLogger.debug("ENDPOINT: " + endPoint) + String catalogDbResponse = getResponseFromCatalogDb(endPoint) + + if (catalogDbResponse != null) { + vnfsList = parseVnfsJson(catalogDbResponse, "serviceVnfs", catalogUtilsVersion) + + } + + } + catch (Exception e) { + utils.log("ERROR", "Exception in Querying Catalog DB: " + e.message) + } + + return vnfsList + } + + + public JSONArray getAllottedResourcesByServiceModelUuid(String catalogDbEndpoint, String serviceModelUuid) { + JSONArray vnfsList = null + String endPoint = catalogDbEndpoint + "/" + defaultDbAdapterVersion + "/ServiceAllottedResources?serviceModelUuid=" + UriUtils.encode(serviceModelUuid, "UTF-8") + try { + String catalogDbResponse = getResponseFromCatalogDb(endPoint) + + if (catalogDbResponse != null) { + vnfsList = parseAllottedResourcesJson(catalogDbResponse, "serviceAllottedResources", "v1") + } + + } + catch (Exception e) { + utils.log("ERROR", "Exception in Querying Catalog DB: " + e.message) + } + + return vnfsList + } + + public JSONArray getAllottedResourcesByServiceModelUuid(String catalogDbEndpoint, String serviceModelUuid, String catalogUtilsVersion) { + JSONArray vnfsList = null + String endPoint = catalogDbEndpoint + "/" + defaultDbAdapterVersion + "/ServiceAllottedResources?serviceModelUuid=" + UriUtils.encode(serviceModelUuid, "UTF-8") + + try { + String catalogDbResponse = getResponseFromCatalogDb(endPoint) + + if (catalogDbResponse != null) { + vnfsList = parseAllottedResourcesJson(catalogDbResponse, "serviceAllottedResources", catalogUtilsVersion) + } + + } + catch (Exception e) { + utils.log("ERROR", "Exception in Querying Catalog DB: " + e.message) + } + + return vnfsList + } + + public JSONArray getAllottedResourcesByServiceModelInvariantUuid(String catalogDbEndpoint, String serviceModelInvariantUuid) { + JSONArray vnfsList = null + String endPoint = catalogDbEndpoint + "/" + defaultDbAdapterVersion + "/serviceAllottedResources?serviceModelInvariantUuid=" + UriUtils.encode(serviceModelInvariantUuid, "UTF-8") + try { + String catalogDbResponse = getResponseFromCatalogDb(endPoint) + + if (catalogDbResponse != null) { + vnfsList = parseAllottedResourcesJson(catalogDbResponse, "serviceAllottedResources", "v1") + } + + } + catch (Exception e) { + utils.log("ERROR", "Exception in Querying Catalog DB: " + e.message) + } + + return vnfsList + } + + public JSONArray getAllottedResourcesByServiceModelInvariantUuid(String catalogDbEndpoint, String serviceModelInvariantUuid, String catalogUtilsVersion) { + JSONArray vnfsList = null + String endPoint = catalogDbEndpoint + "/" + defaultDbAdapterVersion + "/serviceAllottedResources?serviceModelInvariantUuid=" + UriUtils.encode(serviceModelInvariantUuid, "UTF-8") + try { + String catalogDbResponse = getResponseFromCatalogDb(endPoint) + + if (catalogDbResponse != null) { + vnfsList = parseAllottedResourcesJson(catalogDbResponse, "serviceAllottedResources", catalogUtilsVersion) + } + + } + catch (Exception e) { + utils.log("ERROR", "Exception in Querying Catalog DB: " + e.message) + } + + return vnfsList + } + + public JSONArray getAllottedResourcesByServiceModelInvariantUuidAndServiceModelVersion(String catalogDbEndpoint, String serviceModelInvariantUuid, String serviceModelVersion) { + JSONArray vnfsList = null + String endPoint = catalogDbEndpoint + "/" + defaultDbAdapterVersion + "/serviceAllottedResources?serviceModelInvariantUuid=" + UriUtils.encode(serviceModelInvariantUuid, "UTF-8") + "&serviceModelVersion=" + UriUtils.encode(serviceModelVersion, "UTF-8") + try { + String catalogDbResponse = getResponseFromCatalogDb(endPoint) + + if (catalogDbResponse != null) { + vnfsList = parseAllottedResourcesJson(catalogDbResponse, "serviceAllottedResources", "v1") + } + + } + catch (Exception e) { + utils.log("ERROR", "Exception in Querying Catalog DB: " + e.message) + } + + return vnfsList + } + + public JSONArray getAllottedResourcesByServiceModelInvariantUuidAndServiceModelVersion(String catalogDbEndpoint, String serviceModelInvariantUuid, String serviceModelVersion, String catalogUtilsVersion) { + JSONArray vnfsList = null + String endPoint = catalogDbEndpoint + "/" + defaultDbAdapterVersion + "/serviceAllottedResources?serviceModelInvariantUuid=" + UriUtils.encode(serviceModelInvariantUuid, "UTF-8") + "&serviceModelVersion=" + UriUtils.encode(serviceModelVersion, "UTF-8") + + try { + String catalogDbResponse = getResponseFromCatalogDb(endPoint) + + if (catalogDbResponse != null) { + vnfsList = parseAllottedResourcesJson(catalogDbResponse, "serviceAllottedResources", catalogUtilsVersion) + } + + } + catch (Exception e) { + utils.log("ERROR", "Exception in Querying Catalog DB: " + e.message) + } + + return vnfsList + } + + public JSONArray getAllottedResourcesByArModelCustomizationUuid(String catalogDbEndpoint, String arModelCustomizationUuid) { + JSONArray vnfsList = null + String endPoint = catalogDbEndpoint + "/" + defaultDbAdapterVersion + "/serviceAllottedResources?serviceModelCustomizationUuid=" + UriUtils.encode(arModelCustomizationUuid, "UTF-8") + try { + String catalogDbResponse = getResponseFromCatalogDb(endPoint) + + if (catalogDbResponse != null) { + vnfsList = parseAllottedResourcesJson(catalogDbResponse, "serviceAllottedResources", "v1") + } + + } + catch (Exception e) { + utils.log("ERROR", "Exception in Querying Catalog DB: " + e.message) + } + + return vnfsList + } + + public JSONArray getAllottedResourcesByArModelCustomizationUuid(String catalogDbEndpoint, String arModelCustomizationUuid, String catalogUtilsVersion) { + JSONArray vnfsList = null + String endPoint = catalogDbEndpoint + "/" + defaultDbAdapterVersion + "/serviceAllottedResources?serviceModelCustomizationUuid=" + UriUtils.encode(arModelCustomizationUuid, "UTF-8") + try { + String catalogDbResponse = getResponseFromCatalogDb(endPoint) + + if (catalogDbResponse != null) { + vnfsList = parseAllottedResourcesJson(catalogDbResponse, "serviceAllottedResources", catalogUtilsVersion) + } + + } + catch (Exception e) { + utils.log("ERROR", "Exception in Querying Catalog DB: " + e.message) + } + + return vnfsList + } + + public JSONObject getServiceResourcesByServiceModelInvariantUuid(String catalogDbEndpoint, String serviceModelInvariantUuid) { + JSONObject resources = null + String endPoint = catalogDbEndpoint + "/" + defaultDbAdapterVersion + "/serviceResources?serviceModelInvariantUuid=" + UriUtils.encode(serviceModelInvariantUuid, "UTF-8") + + try { + String catalogDbResponse = getResponseFromCatalogDb(endPoint) + + if (catalogDbResponse != null) { + resources = parseServiceResourcesJson(catalogDbResponse, "v1") + } + + } + catch (Exception e) { + utils.log("ERROR", "Exception in Querying Catalog DB: " + e.message) + } + + return resources + } + + public JSONObject getServiceResourcesByServiceModelInvariantUuid(String catalogDbEndpoint, String serviceModelInvariantUuid, String catalogUtilsVersion) { + JSONObject resources = null + String endPoint = catalogDbEndpoint + "/" + defaultDbAdapterVersion + "/serviceResources?serviceModelInvariantUuid=" + UriUtils.encode(serviceModelInvariantUuid, "UTF-8") + try { + String catalogDbResponse = getResponseFromCatalogDb(endPoint) + + if (catalogDbResponse != null) { + resources = parseServiceResourcesJson(catalogDbResponse, catalogUtilsVersion) + } + + } + catch (Exception e) { + utils.log("ERROR", "Exception in Querying Catalog DB: " + e.message) + } + + return resources + } + + + public JSONObject getServiceResourcesByServiceModelInvariantUuidAndServiceModelVersion(String catalogDbEndpoint, String serviceModelInvariantUuid, String serviceModelVersion) { + JSONObject resources = null + String endPoint = catalogDbEndpoint + "/" + defaultDbAdapterVersion + "/serviceResources?serviceModelInvariantUuid=" + UriUtils.encode(serviceModelInvariantUuid, "UTF-8") + "&serviceModelVersion=" + UriUtils.encode(serviceModelVersion, "UTF-8") + try { + String catalogDbResponse = getResponseFromCatalogDb(endPoint) + + if (catalogDbResponse != null) { + resources = parseServiceResourcesJson(catalogDbResponse) + } + + } + catch (Exception e) { + utils.log("ERROR", "Exception in Querying Catalog DB: " + e.message) + } + + return resources + } + + public JSONObject getServiceResourcesByServiceModelInvariantUuidAndServiceModelVersion(String catalogDbEndpoint, String serviceModelInvariantUuid, String serviceModelVersion, String catalogUtilsVersion) { + JSONObject resources = null + String endPoint = catalogDbEndpoint + "/" + defaultDbAdapterVersion + "/serviceResources?serviceModelInvariantUuid=" + UriUtils.encode(serviceModelInvariantUuid, "UTF-8") + "&serviceModelVersion=" + UriUtils.encode(serviceModelVersion, "UTF-8") + try { + String catalogDbResponse = getResponseFromCatalogDb(endPoint) + + if (catalogDbResponse != null) { + resources = parseServiceResourcesJson(catalogDbResponse, catalogUtilsVersion) + } + + } + catch (Exception e) { + utils.log("ERROR", "Exception in Querying Catalog DB: " + e.message) + } + + 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) { + utils.log("ERROR", "Exception in parsing Catalog DB Response: " + 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("nfCode", nfCode) + break + } + + JSONObject vnfJson = vnf.getJSONObject("vnf") + JSONArray vfModules = null + try { + vfModules = vnfJson.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": + 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) { + utils.log("ERROR", "Exception in parsing Catalog DB Response: " + e.message) + } + + return modelInfos + } + + 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 parentServiceModelUuid = jsonUtils.getJsonValueForKey(allottedResource, "parentServiceModelUuid") + modelJson.put("parentServiceModelUuid", parentServiceModelUuid) + break + } + + + modelInfos.put(modelJson) + } + + String modelInfosString = modelInfos.toString() + msoLogger.debug("Returning allottedResources JSON: " + modelInfosString) + + } catch (Exception e) { + utils.log("ERROR", "Exception in parsing Catalog DB Response: " + e.message) + } + + return modelInfos + } + + 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) { + utils.log("ERROR", "Exception in parsing Catalog DB Response: " + 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) { + utils.log("ERROR", "Exception in parsing Catalog DB Response: " + 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")){ + String modelInstanceName = jsonUtils.getJsonValueForKey(modelFromDb, "modelInstanceName") + modelInfo.put("modelInstanceName", modelInstanceName) + } + if (!"vfModule".equals(modelType) && !"vnf".equals(modelType)) { + 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) { + utils.log("ERROR", "Exception while parsing model information: " + e.message) + } + return modelInfo + } + + private String getResponseFromCatalogDb (String endPoint) { + try { + RESTConfig config = new RESTConfig(endPoint); + 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'); + 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) + return null + } + + } +} diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/CompleteMsoProcess.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/CompleteMsoProcess.groovy index e7277b602b..2f9c8d299b 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/CompleteMsoProcess.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/CompleteMsoProcess.groovy @@ -1,361 +1,361 @@ -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - MSO - * ================================================================================ - * 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.openecomp.mso.bpmn.common.scripts - -import org.apache.commons.lang3.* -import org.camunda.bpm.engine.delegate.BpmnError -import org.camunda.bpm.engine.runtime.Execution - - -public class CompleteMsoProcess extends AbstractServiceTaskProcessor { - - String Prefix="CMSO_" - ExceptionUtil exceptionUtil = new ExceptionUtil() - - // Complete MSO Request processing - public initializeProcessVariables(Execution execution){ - - def method = getClass().getSimpleName() + '.initializeProcessVariables(' +'execution=' + execution.getId() +')' - def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') - logDebug('Entered ' + method, isDebugLogEnabled) - 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) { - logError('Caught exception in ' + method, e) - exceptionUtil.buildAndThrowWorkflowException(execution, 2000, "Internal Error - Occured in" + method) - } - - } - - public void preProcessRequest (Execution execution) { - - initializeProcessVariables(execution) - def method = getClass().getSimpleName() + '.preProcessRequest(' +'execution=' + execution.getId() +')' - def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') -// utils.log("DEBUG", "*** Started CompleteMsoProcess preProcessRequest Method ***", isDebugLogEnabled); - logDebug('Entered ' + method, isDebugLogEnabled) - try { - def xml = execution.getVariable("CompleteMsoProcessRequest") - - utils.logAudit("CompleteMsoProcess Request: " + xml) - utils.log("DEBUG", "Incoming Request is: "+ xml, isDebugLogEnabled) - - //mso-bpel-name from the incoming request - def msoBpelName = utils.getNodeText1(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 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")) - } - - utils.log("DEBUG", "CMSO_notification-url-Ok --> " + execution.getVariable("CMSO_notification-url-Ok"), isDebugLogEnabled) - utils.log("DEBUG", "CMSO_request_id-Ok --> " + execution.getVariable("CMSO_request_id-Ok"), isDebugLogEnabled) - - // set the DHV/Service Instantiation values if specified in the request - execution.setVariable("CMSO_is_srv_inst_req", String.valueOf("true".equals(utils.getNodeText1(xml, "is-srv-inst-req")))) - utils.log("DEBUG", "CMSO_is_srv_inst_req --> " + execution.getVariable("CMSO_is_srv_inst_req"), isDebugLogEnabled) - execution.setVariable("CMSO_is_json_content", String.valueOf("JSON".equals(utils.getNodeText1(xml, "resp-content-type")))) - utils.log("DEBUG", "CMSO_is_json_content --> " + execution.getVariable("CMSO_is_json_content"), isDebugLogEnabled) - execution.setVariable("CMSO_service_inst_id", utils.getNodeText1(xml, "service-instance-id")) - utils.log("DEBUG", "CMSO_service_inst_id --> " + execution.getVariable("CMSO_service_inst_id"), isDebugLogEnabled) - execution.setVariable("CMSO_start_time", utils.getNodeText1(xml, "start-time")) - utils.log("DEBUG", "CMSO_start_time --> " + execution.getVariable("CMSO_start_time"), isDebugLogEnabled) - // 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") - } - - logDebug('Exited ' + method, isDebugLogEnabled) - } catch (BpmnError e) { - throw e; - } catch (Exception e) { - utils.log("DEBUG", "Exception Occured During PreProcessRequest: " + e, isDebugLogEnabled); - exceptionUtil.buildAndThrowWorkflowException(execution, 2000, "Internal Error - Occured in " + method) - } - -// utils.log("DEBUG", "*** Completed CompleteMsoProcess preProcessRequest Method ***", isDebugLogEnabled); - } - - public void postProcessResponse (Execution execution) { - - def method = getClass().getSimpleName() + '.postProcessResponse(' +'execution=' + execution.getId() +')' - def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') - logDebug('Entered ' + method, isDebugLogEnabled) -// utils.log("DEBUG", "*** Started CompleteMsoProcess PostProcessRequest Method ***", isDebugLogEnabled); - try { - - def msoCompletionResponse = """ - - BPEL ${execution.getVariable("CMSO_mso-bpel-name")} completed - - """.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) - utils.logAudit("CompleteMsoProcess Response: " + buildMsoCompletionResponseAsString) - execution.setVariable("CompleteMsoProcessResponse", buildMsoCompletionResponseAsString) - execution.setVariable("CMSO_ResponseCode", "200") - - setSuccessIndicator(execution, true) - - utils.log("DEBUG", "@@ CompleteMsoProcess Response @@ " + "\n" + execution.getVariable("CompleteMsoProcessResponse"), isDebugLogEnabled) - - logDebug('Exited ' + method, isDebugLogEnabled) - } catch (BpmnError e) { - throw e; - } catch (Exception e) { - logError('Caught exception in ' + method, e) - exceptionUtil.buildAndThrowWorkflowException(execution, 2000, "Internal Error - Occured in" + method) - } -// utils.log("DEBUG", "*** Completed CompleteMsoProcess PostProcessRequest Method ***", isDebugLogEnabled); - - } - - public void updateDBStatusToSuccessPayload (Execution execution){ - def method = getClass().getSimpleName() + '.updateDBStatusToSuccessPayload(' +'execution=' + execution.getId() +')' - def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') - logDebug('Entered ' + method, isDebugLogEnabled) - - try { - // Catalog DB headers Authorization - String basicAuthValueDB = execution.getVariable("URN_mso_adapters_db_auth") - utils.log("DEBUG", " Obtained BasicAuth userid password for Catalog DB adapter: " + basicAuthValueDB, isDebugLogEnabled) - - def encodedString = utils.getBasicAuth(basicAuthValueDB, execution.getVariable("URN_mso_msoKey")) - execution.setVariable("BasicAuthHeaderValueDB",encodedString) - } catch (IOException ex) { - String dataErrorMessage = " Unable to encode Catalog DB user/password string - " + ex.getMessage() - utils.log("DEBUG", dataErrorMessage, isDebugLogEnabled) - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) - } - - try { - - String payload = """ - - - - - ${execution.getVariable("CMSO_request_id")} - BPEL - COMPLETED - - - - """ - execution.setVariable("CMSO_updateDBStatusToSuccessPayload", payload) - utils.logAudit("updateDBStatusToSuccessPayload: " + payload) - logDebug('Exited ' + method, isDebugLogEnabled) - //println("CMSO_updateDBStatusToSuccessPayload --> " + execution.getVariable("CMSO_updateDBStatusToSuccessPayload")) - - } catch (BpmnError e) { - throw e; - } catch (Exception e) { - logError('Caught exception in ' + method, e) - exceptionUtil.buildAndThrowWorkflowException(execution, 2000, "Internal Error - Occured in" + method) - } - } - - public void setUpdateDBstatustoSuccessPayload (Execution execution){ - - def method = getClass().getSimpleName() + '.setUpdateDBstatustoSuccessPayload(' +'execution=' + execution.getId() +')' - def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') - logDebug('Entered ' + method, isDebugLogEnabled) - - try { - String basicAuthValueDB = execution.getVariable("URN_mso_adapters_db_auth") - utils.log("DEBUG", " Obtained BasicAuth userid password for Catalog DB adapter: " + basicAuthValueDB, isDebugLogEnabled) - - def encodedString = utils.getBasicAuth(basicAuthValueDB, execution.getVariable("URN_mso_msoKey")) - execution.setVariable("BasicAuthHeaderValueDB",encodedString) - } catch (IOException ex) { - String dataErrorMessage = " Unable to encode Catalog DB user/password string - " + ex.getMessage() - utils.log("DEBUG", dataErrorMessage, isDebugLogEnabled) - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) - } - - try { - - def xml = execution.getVariable("CompleteMsoProcessRequest") - - //Get statusMessage if exists - def statusMessage - if(utils.nodeExists(xml, "status-message")){ - statusMessage = utils.getNodeText1(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, "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) - utils.log("DEBUG", "Incoming Instance Id Xml: " + idXml, isDebugLogEnabled) - - String payload = """ - - - - - ${execution.getVariable("CMSO_request_id")} - ${execution.getVariable("CMSO_mso-bpel-name")} - ${statusMessage} - COMPLETE - 100 - ${idXml} - - - """ - - execution.setVariable("CMSO_setUpdateDBstatustoSuccessPayload", payload) - utils.log("DEBUG", "Outgoing Update Mso Request Payload is: " + payload, isDebugLogEnabled) - utils.logAudit("setUpdateDBstatustoSuccessPayload: " + payload) - - } catch (BpmnError e) { - throw e; - } catch (Exception e) { - logError('Caught exception in ' + method, e) - exceptionUtil.buildAndThrowWorkflowException(execution, 2000, "Internal Error - Occured in" + method) - } - logDebug('Exited ' + method, isDebugLogEnabled) - } - - public void buildDataError (Execution execution, String message) { - - def method = getClass().getSimpleName() + '.buildDataError(' +'execution=' + execution.getId() +')' - def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') - logDebug('Entered ' + method, isDebugLogEnabled) - try { - - def msoCompletionResponse = """ - - BPEL ${execution.getVariable("CMSO_mso-bpel-name")} FAILED - - """.trim() - - // Format Response - def xmlMsoCompletionResponse = utils.formatXml(msoCompletionResponse) - String buildMsoCompletionResponseAsString = xmlMsoCompletionResponse.drop(38).trim() - utils.logAudit("CompleteMsoProcess Response: " + buildMsoCompletionResponseAsString) - execution.setVariable("CompleteMsoProcessResponse", buildMsoCompletionResponseAsString) - utils.log("DEBUG", "@@ CompleteMsoProcess Response @@ " + "\n" + execution.getVariable("CompletionHandlerResponse"), isDebugLogEnabled) - - exceptionUtil.buildAndThrowWorkflowException(execution, 500, message) - - } catch (BpmnError e) { - utils.log("DEBUG", "Rethrowing MSOWorkflowException", isDebugLogEnabled) - throw e; - } catch (Exception e) { - logError('Caught exception in ' + method, e) - exceptionUtil.buildAndThrowWorkflowException(execution, 2000, "Internal Error - Occured in" + method) - } - - } - -} +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.bpmn.common.scripts + +import org.apache.commons.lang3.* +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.runtime.Execution + + +public class CompleteMsoProcess extends AbstractServiceTaskProcessor { + + String Prefix="CMSO_" + ExceptionUtil exceptionUtil = new ExceptionUtil() + + // Complete MSO Request processing + public initializeProcessVariables(Execution execution){ + + def method = getClass().getSimpleName() + '.initializeProcessVariables(' +'execution=' + execution.getId() +')' + def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') + logDebug('Entered ' + method, isDebugLogEnabled) + 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) { + logError('Caught exception in ' + method, e) + exceptionUtil.buildAndThrowWorkflowException(execution, 2000, "Internal Error - Occured in" + method) + } + + } + + public void preProcessRequest (Execution execution) { + + initializeProcessVariables(execution) + def method = getClass().getSimpleName() + '.preProcessRequest(' +'execution=' + execution.getId() +')' + def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') +// utils.log("DEBUG", "*** Started CompleteMsoProcess preProcessRequest Method ***", isDebugLogEnabled); + logDebug('Entered ' + method, isDebugLogEnabled) + try { + def xml = execution.getVariable("CompleteMsoProcessRequest") + + utils.logAudit("CompleteMsoProcess Request: " + xml) + utils.log("DEBUG", "Incoming Request is: "+ xml, isDebugLogEnabled) + + //mso-bpel-name from the incoming request + def msoBpelName = utils.getNodeText1(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 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")) + } + + utils.log("DEBUG", "CMSO_notification-url-Ok --> " + execution.getVariable("CMSO_notification-url-Ok"), isDebugLogEnabled) + utils.log("DEBUG", "CMSO_request_id-Ok --> " + execution.getVariable("CMSO_request_id-Ok"), isDebugLogEnabled) + + // set the DHV/Service Instantiation values if specified in the request + execution.setVariable("CMSO_is_srv_inst_req", String.valueOf("true".equals(utils.getNodeText1(xml, "is-srv-inst-req")))) + utils.log("DEBUG", "CMSO_is_srv_inst_req --> " + execution.getVariable("CMSO_is_srv_inst_req"), isDebugLogEnabled) + execution.setVariable("CMSO_is_json_content", String.valueOf("JSON".equals(utils.getNodeText1(xml, "resp-content-type")))) + utils.log("DEBUG", "CMSO_is_json_content --> " + execution.getVariable("CMSO_is_json_content"), isDebugLogEnabled) + execution.setVariable("CMSO_service_inst_id", utils.getNodeText1(xml, "service-instance-id")) + utils.log("DEBUG", "CMSO_service_inst_id --> " + execution.getVariable("CMSO_service_inst_id"), isDebugLogEnabled) + execution.setVariable("CMSO_start_time", utils.getNodeText1(xml, "start-time")) + utils.log("DEBUG", "CMSO_start_time --> " + execution.getVariable("CMSO_start_time"), isDebugLogEnabled) + // 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") + } + + logDebug('Exited ' + method, isDebugLogEnabled) + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + utils.log("DEBUG", "Exception Occured During PreProcessRequest: " + e, isDebugLogEnabled); + exceptionUtil.buildAndThrowWorkflowException(execution, 2000, "Internal Error - Occured in " + method) + } + +// utils.log("DEBUG", "*** Completed CompleteMsoProcess preProcessRequest Method ***", isDebugLogEnabled); + } + + public void postProcessResponse (Execution execution) { + + def method = getClass().getSimpleName() + '.postProcessResponse(' +'execution=' + execution.getId() +')' + def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') + logDebug('Entered ' + method, isDebugLogEnabled) +// utils.log("DEBUG", "*** Started CompleteMsoProcess PostProcessRequest Method ***", isDebugLogEnabled); + try { + + def msoCompletionResponse = """ + + BPEL ${execution.getVariable("CMSO_mso-bpel-name")} completed + + """.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) + utils.logAudit("CompleteMsoProcess Response: " + buildMsoCompletionResponseAsString) + execution.setVariable("CompleteMsoProcessResponse", buildMsoCompletionResponseAsString) + execution.setVariable("CMSO_ResponseCode", "200") + + setSuccessIndicator(execution, true) + + utils.log("DEBUG", "@@ CompleteMsoProcess Response @@ " + "\n" + execution.getVariable("CompleteMsoProcessResponse"), isDebugLogEnabled) + + logDebug('Exited ' + method, isDebugLogEnabled) + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + logError('Caught exception in ' + method, e) + exceptionUtil.buildAndThrowWorkflowException(execution, 2000, "Internal Error - Occured in" + method) + } +// utils.log("DEBUG", "*** Completed CompleteMsoProcess PostProcessRequest Method ***", isDebugLogEnabled); + + } + + public void updateDBStatusToSuccessPayload (Execution execution){ + def method = getClass().getSimpleName() + '.updateDBStatusToSuccessPayload(' +'execution=' + execution.getId() +')' + def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') + logDebug('Entered ' + method, isDebugLogEnabled) + + try { + // Catalog DB headers Authorization + String basicAuthValueDB = execution.getVariable("URN_mso_adapters_db_auth") + utils.log("DEBUG", " Obtained BasicAuth userid password for Catalog DB adapter: " + basicAuthValueDB, isDebugLogEnabled) + + def encodedString = utils.getBasicAuth(basicAuthValueDB, execution.getVariable("URN_mso_msoKey")) + execution.setVariable("BasicAuthHeaderValueDB",encodedString) + } catch (IOException ex) { + String dataErrorMessage = " Unable to encode Catalog DB user/password string - " + ex.getMessage() + utils.log("DEBUG", dataErrorMessage, isDebugLogEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) + } + + try { + + String payload = """ + + + + + ${execution.getVariable("CMSO_request_id")} + BPEL + COMPLETED + + + + """ + execution.setVariable("CMSO_updateDBStatusToSuccessPayload", payload) + utils.logAudit("updateDBStatusToSuccessPayload: " + payload) + logDebug('Exited ' + method, isDebugLogEnabled) + //println("CMSO_updateDBStatusToSuccessPayload --> " + execution.getVariable("CMSO_updateDBStatusToSuccessPayload")) + + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + logError('Caught exception in ' + method, e) + exceptionUtil.buildAndThrowWorkflowException(execution, 2000, "Internal Error - Occured in" + method) + } + } + + public void setUpdateDBstatustoSuccessPayload (Execution execution){ + + def method = getClass().getSimpleName() + '.setUpdateDBstatustoSuccessPayload(' +'execution=' + execution.getId() +')' + def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') + logDebug('Entered ' + method, isDebugLogEnabled) + + try { + String basicAuthValueDB = execution.getVariable("URN_mso_adapters_db_auth") + utils.log("DEBUG", " Obtained BasicAuth userid password for Catalog DB adapter: " + basicAuthValueDB, isDebugLogEnabled) + + def encodedString = utils.getBasicAuth(basicAuthValueDB, execution.getVariable("URN_mso_msoKey")) + execution.setVariable("BasicAuthHeaderValueDB",encodedString) + } catch (IOException ex) { + String dataErrorMessage = " Unable to encode Catalog DB user/password string - " + ex.getMessage() + utils.log("DEBUG", dataErrorMessage, isDebugLogEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) + } + + try { + + def xml = execution.getVariable("CompleteMsoProcessRequest") + + //Get statusMessage if exists + def statusMessage + if(utils.nodeExists(xml, "status-message")){ + statusMessage = utils.getNodeText1(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, "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) + utils.log("DEBUG", "Incoming Instance Id Xml: " + idXml, isDebugLogEnabled) + + String payload = """ + + + + + ${execution.getVariable("CMSO_request_id")} + ${execution.getVariable("CMSO_mso-bpel-name")} + ${statusMessage} + COMPLETE + 100 + ${idXml} + + + """ + + execution.setVariable("CMSO_setUpdateDBstatustoSuccessPayload", payload) + utils.log("DEBUG", "Outgoing Update Mso Request Payload is: " + payload, isDebugLogEnabled) + utils.logAudit("setUpdateDBstatustoSuccessPayload: " + payload) + + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + logError('Caught exception in ' + method, e) + exceptionUtil.buildAndThrowWorkflowException(execution, 2000, "Internal Error - Occured in" + method) + } + logDebug('Exited ' + method, isDebugLogEnabled) + } + + public void buildDataError (Execution execution, String message) { + + def method = getClass().getSimpleName() + '.buildDataError(' +'execution=' + execution.getId() +')' + def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') + logDebug('Entered ' + method, isDebugLogEnabled) + try { + + def msoCompletionResponse = """ + + BPEL ${execution.getVariable("CMSO_mso-bpel-name")} FAILED + + """.trim() + + // Format Response + def xmlMsoCompletionResponse = utils.formatXml(msoCompletionResponse) + String buildMsoCompletionResponseAsString = xmlMsoCompletionResponse.drop(38).trim() + utils.logAudit("CompleteMsoProcess Response: " + buildMsoCompletionResponseAsString) + execution.setVariable("CompleteMsoProcessResponse", buildMsoCompletionResponseAsString) + utils.log("DEBUG", "@@ CompleteMsoProcess Response @@ " + "\n" + execution.getVariable("CompletionHandlerResponse"), isDebugLogEnabled) + + exceptionUtil.buildAndThrowWorkflowException(execution, 500, message) + + } catch (BpmnError e) { + utils.log("DEBUG", "Rethrowing MSOWorkflowException", isDebugLogEnabled) + throw e; + } catch (Exception e) { + logError('Caught exception in ' + method, e) + exceptionUtil.buildAndThrowWorkflowException(execution, 2000, "Internal Error - Occured in" + method) + } + + } + +} diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/ConfirmVolumeGroupName.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/ConfirmVolumeGroupName.groovy index 0a6f251653..ae4a758141 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/ConfirmVolumeGroupName.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/ConfirmVolumeGroupName.groovy @@ -1,157 +1,159 @@ -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - MSO - * ================================================================================ - * 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.openecomp.mso.bpmn.common.scripts -import org.camunda.bpm.engine.runtime.Execution -import org.openecomp.mso.rest.APIResponse - - -public class ConfirmVolumeGroupName extends AbstractServiceTaskProcessor{ - - def Prefix="CVGN_" - - public void initProcessVariables(Execution 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 Execution - public void preProcessRequest(Execution execution) { - def isDebugLogEnabled=execution.getVariable("isDebugLogEnabled") - 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) - logDebug('AAI URI is: ' + aai_uri, isDebugLogEnabled) - utils.logAudit("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(Execution execution) { - def isDebugLogEnabled=execution.getVariable("isDebugLogEnabled") - def endPoint = execution.getVariable("URN_aai_endpoint") + execution.getVariable("CVGN_volumeGroupGetEndpoint") - - try { - logDebug("invoking GET call to AAI endpoint :"+System.lineSeparator()+endPoint,isDebugLogEnabled) - utils.log("DEBUG","queryAAIForVolumeGroupId() endpoint-" + endPoint, isDebugLogEnabled) - utils.logAudit("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) - - utils.logAudit("Response code:" + responseStatusCode) - utils.logAudit("Response:" + responseData) - logDebug("Response code:" + responseStatusCode, isDebugLogEnabled) - logDebug("Response:" + System.lineSeparator()+responseData,isDebugLogEnabled) - } catch (Exception ex) { - ex.printStackTrace() - logDebug("Exception occurred while executing AAI GET:" + ex.getMessage(),isDebugLogEnabled) - execution.setVariable("CVGN_queryVolumeGroupResponseCode", 500) - execution.setVariable("CVGN_queryVolumeGroupResponse", "AAI GET Failed:" + ex.getMessage()) - } - } - - // process the result from queryAAIVolumeGroupId() - - public void checkAAIQueryResult(Execution execution) { - def isDebugLogEnabled=execution.getVariable("isDebugLogEnabled") - def result = execution.getVariable("CVGN_queryVolumeGroupResponse") - - if (execution.getVariable("CVGN_queryVolumeGroupResponseCode") == 404) { - logDebug('volumeGroupId does not exist in AAI', isDebugLogEnabled) - } - else if (execution.getVariable("CVGN_queryVolumeGroupResponseCode") == 200) { - logDebug("volumeGroupId exists in AAI", isDebugLogEnabled) - } - 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)) { - logDebug('Volume Group Name Matches AAI records', isDebugLogEnabled) - execution.setVariable("CVGN_volumeGroupNameMatches", true) - } - } - - - // generates a WorkflowException if the A&AI query returns a response code other than 200/404 - public void handleAAIQueryFailure(Execution execution) { - def isDebugLogEnabled=execution.getVariable("isDebugLogEnabled") - - logError("Error occurred attempting to query AAI, Response Code " + - execution.getVariable("CVGN_queryVolumeGroupResponseCode") + ", Error Response " + - 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(Execution execution) { - def isDebugLogEnabled=execution.getVariable("isDebugLogEnabled") - - def errorNotAssociated = "Error occurred - volume group id " + execution.getVariable("CVGN_volumeGroupId") + - " is not associated with " + execution.getVariable("CVGN_volumeGroupName") - logError(errorNotAssociated) - createWorkflowException(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(Execution execution) { - def isDebugLogEnabled=execution.getVariable("isDebugLogEnabled") - logDebug("Sending 200 back to the caller", isDebugLogEnabled) - def responseXML = "" - execution.setVariable("WorkflowResponse", responseXML) - } -} +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.bpmn.common.scripts +import org.camunda.bpm.engine.runtime.Execution +import org.openecomp.mso.rest.APIResponse + + +public class ConfirmVolumeGroupName extends AbstractServiceTaskProcessor{ + + def Prefix="CVGN_" + ExceptionUtil exceptionUtil = new ExceptionUtil() + + public void initProcessVariables(Execution 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 Execution + public void preProcessRequest(Execution execution) { + def isDebugLogEnabled=execution.getVariable("isDebugLogEnabled") + 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) + logDebug('AAI URI is: ' + aai_uri, isDebugLogEnabled) + utils.logAudit("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(Execution execution) { + def isDebugLogEnabled=execution.getVariable("isDebugLogEnabled") + def endPoint = execution.getVariable("URN_aai_endpoint") + execution.getVariable("CVGN_volumeGroupGetEndpoint") + + try { + logDebug("invoking GET call to AAI endpoint :"+System.lineSeparator()+endPoint,isDebugLogEnabled) + utils.log("DEBUG","queryAAIForVolumeGroupId() endpoint-" + endPoint, isDebugLogEnabled) + utils.logAudit("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) + + utils.logAudit("Response code:" + responseStatusCode) + utils.logAudit("Response:" + responseData) + logDebug("Response code:" + responseStatusCode, isDebugLogEnabled) + logDebug("Response:" + System.lineSeparator()+responseData,isDebugLogEnabled) + } catch (Exception ex) { + // ex.printStackTrace() + logDebug("Exception occurred while executing AAI GET:" + ex.getMessage(),isDebugLogEnabled) + 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(Execution execution) { + def isDebugLogEnabled=execution.getVariable("isDebugLogEnabled") + def result = execution.getVariable("CVGN_queryVolumeGroupResponse") + + if (execution.getVariable("CVGN_queryVolumeGroupResponseCode") == 404) { + logDebug('volumeGroupId does not exist in AAI', isDebugLogEnabled) + } + else if (execution.getVariable("CVGN_queryVolumeGroupResponseCode") == 200) { + logDebug("volumeGroupId exists in AAI", isDebugLogEnabled) + } + 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)) { + logDebug('Volume Group Name Matches AAI records', isDebugLogEnabled) + execution.setVariable("CVGN_volumeGroupNameMatches", true) + } + } + + + // generates a WorkflowException if the A&AI query returns a response code other than 200/404 + public void handleAAIQueryFailure(Execution execution) { + def isDebugLogEnabled=execution.getVariable("isDebugLogEnabled") + + logError("Error occurred attempting to query AAI, Response Code " + + execution.getVariable("CVGN_queryVolumeGroupResponseCode") + ", Error Response " + + 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(Execution execution) { + def isDebugLogEnabled=execution.getVariable("isDebugLogEnabled") + + def errorNotAssociated = "Error occurred - volume group id " + execution.getVariable("CVGN_volumeGroupId") + + " is not associated with " + execution.getVariable("CVGN_volumeGroupName") + logError(errorNotAssociated) + 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(Execution execution) { + def isDebugLogEnabled=execution.getVariable("isDebugLogEnabled") + logDebug("Sending 200 back to the caller", isDebugLogEnabled) + def responseXML = "" + execution.setVariable("WorkflowResponse", responseXML) + } +} \ No newline at end of file diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/ConfirmVolumeGroupTenant.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/ConfirmVolumeGroupTenant.groovy index bca2475a2f..cc26d9fa35 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/ConfirmVolumeGroupTenant.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/ConfirmVolumeGroupTenant.groovy @@ -1,195 +1,193 @@ -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - MSO - * ================================================================================ - * 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.openecomp.mso.bpmn.common.scripts - -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.runtime.Execution -import org.openecomp.mso.bpmn.core.WorkflowException -import org.openecomp.mso.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 - - -/** - * Vnf Module Subflow for confirming the volume group belongs - * to the tenant - * - * @param tenantId - * @param volumeGroupId - * - */ -class ConfirmVolumeGroupTenant extends AbstractServiceTaskProcessor{ - - String Prefix="CVGT_" - - public void preProcessRequest(Execution execution){ - def isDebugEnabled = execution.getVariable("isDebugLogEnabled") - execution.setVariable("prefix", Prefix) - utils.log("DEBUG", " ======== STARTED Confirm Volume Group Tenant Subflow ======== ", isDebugEnabled) - String processKey = getProcessKey(execution); - try{ - utils.log("DEBUG", " === Started QueryAAIForVolumeGroup Process === ", isDebugEnabled) - - String volumeGroupId = execution.getVariable("volumeGroupId") - String incomingGroupName = execution.getVariable("volumeGroupName") - String incomingTenantId = execution.getVariable("tenantId") - def aicCloudRegion = execution.getVariable("aicCloudRegion") - String aai = execution.getVariable("URN_aai_endpoint") - - AaiUtil aaiUriUtil = new AaiUtil(this) - def aai_uri = aaiUriUtil.getCloudInfrastructureCloudRegionUri(execution) - logDebug('AAI URI is: ' + aai_uri, isDebugEnabled) - - 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() - response = StringEscapeUtils.unescapeXml(response) - - utils.logAudit("ConfirmVolumeGroup Response: " + response) - utils.logAudit("ConfirmVolumeGroup Response Code: " + responseCode) - - if(responseCode == 200 && response != null){ - execution.setVariable("queryAAIVolumeGroupResponse", response) - utils.log("DEBUG", "QueryAAIForVolumeGroup Received a Good REST Response is: \n" + response, isDebugEnabled) - - 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)){ - utils.log("DEBUG", "Tenant Ids Match", isDebugEnabled) - execution.setVariable("tenantIdsMatch", true) - }else{ - utils.log("DEBUG", "Tenant Ids DO NOT Match", isDebugEnabled) - execution.setVariable("tenantIdsMatch", false) - } - - //Determine if Volume Group Names match - String volumeGroupName = utils.getNodeText1(response, "volume-group-name") - if(incomingGroupName == null || incomingGroupName.length() < 1){ - utils.log("DEBUG", "Incoming Volume Group Name is NOT Provided.", isDebugEnabled) - execution.setVariable("groupNamesMatch", true) - }else{ - utils.log("DEBUG", "Incoming Volume Group Name is: " + incomingGroupName, isDebugEnabled) - if(volumeGroupName.equals(incomingGroupName)){ - utils.log("DEBUG", "Volume Group Names Match.", isDebugEnabled) - execution.setVariable("groupNamesMatch", true) - }else{ - utils.log("DEBUG", "Volume Group Names DO NOT Match.", isDebugEnabled) - execution.setVariable("groupNamesMatch", false) - } - } - }else{ - utils.log("DEBUG", "QueryAAIForVolumeGroup Bad REST Response!", isDebugEnabled) - WorkflowException exception = new WorkflowException(processKey, 1, "Error Searching AAI for Volume Group. Received a Bad Response.") - execution.setVariable("WorkflowException", exception) - throw new BpmnError("MSOWorkflowException") - } - - }catch(Exception e){ - utils.log("ERROR", "Exception Occured Processing queryAAIForVolumeGroup. Exception is:\n" + e, isDebugEnabled) - throw new BpmnError("MSOWorkflowException") - } - utils.log("DEBUG", "=== COMPLETED queryAAIForVolumeGroup Process === ", isDebugEnabled) - } - - public void assignVolumeHeatId(Execution execution){ - def isDebugEnabled = execution.getVariable("isDebugLogEnabled") - execution.setVariable("prefix", Prefix) - try{ - utils.log("DEBUG", " === Started assignVolumeHeatId Process === ", isDebugEnabled) - - String response = execution.getVariable("queryAAIVolumeGroupResponse") - String heatStackId = utils.getNodeText1(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) - utils.log("DEBUG", "Volume Heat Stack Id is: " + heatStackId, isDebugEnabled) - - }catch(Exception e){ - utils.log("ERROR", "Exception Occured Processing assignVolumeHeatId. Exception is:\n" + e, isDebugEnabled) - throw new BpmnError("MSOWorkflowException") - } - utils.log("DEBUG", "=== COMPLETED assignVolumeHeatId Process === ", isDebugEnabled) - utils.log("DEBUG", "======== COMPLETED Confirm Volume Group Tenant Subflow ======== ", isDebugEnabled) -} - - public void assignWorkflowException(Execution execution, String message){ - def isDebugEnabled = execution.getVariable("isDebugLogEnabled") - execution.setVariable("prefix", Prefix) - String processKey = getProcessKey(execution); - utils.log("DEBUG", " === STARTED Assign Workflow Exception === ", isDebugEnabled) - try{ - String volumeGroupId = execution.getVariable("volumeGroupId") - int errorCode = 1 - String errorMessage = "Volume Group " + volumeGroupId + " " + message - - WorkflowException exception = new WorkflowException(processKey, errorCode, errorMessage) - execution.setVariable("WorkflowException", exception) - execution.setVariable("CVGT_ErrorResponse", "") // Setting for Unit Testing Purposes - - }catch(Exception e){ - utils.log("ERROR", "Exception Occured Processing assignWorkflowException. Exception is:\n" + e, isDebugEnabled) - } - utils.log("DEBUG", "=== COMPLETED Assign Workflow Exception ==== ", isDebugEnabled) - } - - - -} - +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.bpmn.common.scripts + +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.runtime.Execution +import org.openecomp.mso.bpmn.core.WorkflowException +import org.openecomp.mso.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 + + +/** + * Vnf Module Subflow for confirming the volume group belongs + * to the tenant + * + * @param tenantId + * @param volumeGroupId + * + */ +class ConfirmVolumeGroupTenant extends AbstractServiceTaskProcessor{ + + String Prefix="CVGT_" + ExceptionUtil exceptionUtil = new ExceptionUtil() + + public void preProcessRequest(Execution execution){ + def isDebugEnabled = execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix", Prefix) + utils.log("DEBUG", " ======== STARTED Confirm Volume Group Tenant Subflow ======== ", isDebugEnabled) + String processKey = getProcessKey(execution); + try{ + utils.log("DEBUG", " === Started QueryAAIForVolumeGroup Process === ", isDebugEnabled) + + String volumeGroupId = execution.getVariable("volumeGroupId") + String incomingGroupName = execution.getVariable("volumeGroupName") + String incomingTenantId = execution.getVariable("tenantId") + def aicCloudRegion = execution.getVariable("aicCloudRegion") + String aai = execution.getVariable("URN_aai_endpoint") + + AaiUtil aaiUriUtil = new AaiUtil(this) + def aai_uri = aaiUriUtil.getCloudInfrastructureCloudRegionUri(execution) + logDebug('AAI URI is: ' + aai_uri, isDebugEnabled) + + 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() + response = StringEscapeUtils.unescapeXml(response) + + utils.logAudit("ConfirmVolumeGroup Response: " + response) + utils.logAudit("ConfirmVolumeGroup Response Code: " + responseCode) + + if(responseCode == 200 && response != null){ + execution.setVariable("queryAAIVolumeGroupResponse", response) + utils.log("DEBUG", "QueryAAIForVolumeGroup Received a Good REST Response is: \n" + response, isDebugEnabled) + + 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)){ + utils.log("DEBUG", "Tenant Ids Match", isDebugEnabled) + execution.setVariable("tenantIdsMatch", true) + }else{ + utils.log("DEBUG", "Tenant Ids DO NOT Match", isDebugEnabled) + execution.setVariable("tenantIdsMatch", false) + } + + //Determine if Volume Group Names match + String volumeGroupName = utils.getNodeText1(response, "volume-group-name") + if(incomingGroupName == null || incomingGroupName.length() < 1){ + utils.log("DEBUG", "Incoming Volume Group Name is NOT Provided.", isDebugEnabled) + execution.setVariable("groupNamesMatch", true) + }else{ + utils.log("DEBUG", "Incoming Volume Group Name is: " + incomingGroupName, isDebugEnabled) + if(volumeGroupName.equals(incomingGroupName)){ + utils.log("DEBUG", "Volume Group Names Match.", isDebugEnabled) + execution.setVariable("groupNamesMatch", true) + }else{ + utils.log("DEBUG", "Volume Group Names DO NOT Match.", isDebugEnabled) + execution.setVariable("groupNamesMatch", false) + } + } + }else{ + utils.log("DEBUG", "QueryAAIForVolumeGroup Bad REST Response!", isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 1, "Error Searching AAI for Volume Group. Received a Bad Response.") + } + + }catch(BpmnError b){ + throw b + }catch(Exception e){ + utils.log("ERROR", "Exception Occured Processing queryAAIForVolumeGroup. Exception is:\n" + e, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 5000, "Internal Error - Occured in preProcessRequest.") + } + utils.log("DEBUG", "=== COMPLETED queryAAIForVolumeGroup Process === ", isDebugEnabled) + } + + public void assignVolumeHeatId(Execution execution){ + def isDebugEnabled = execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix", Prefix) + try{ + utils.log("DEBUG", " === Started assignVolumeHeatId Process === ", isDebugEnabled) + + String response = execution.getVariable("queryAAIVolumeGroupResponse") + String heatStackId = utils.getNodeText1(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) + utils.log("DEBUG", "Volume Heat Stack Id is: " + heatStackId, isDebugEnabled) + + }catch(Exception e){ + utils.log("ERROR", "Exception Occured Processing assignVolumeHeatId. Exception is:\n" + e, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 5000, "Internal Error - Occured in assignVolumeHeatId.") + } + utils.log("DEBUG", "=== COMPLETED assignVolumeHeatId Process === ", isDebugEnabled) + utils.log("DEBUG", "======== COMPLETED Confirm Volume Group Tenant Subflow ======== ", isDebugEnabled) +} + + public void assignWorkflowException(Execution execution, String message){ + def isDebugEnabled = execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix", Prefix) + String processKey = getProcessKey(execution); + utils.log("DEBUG", " === STARTED Assign Workflow Exception === ", isDebugEnabled) + try{ + String volumeGroupId = execution.getVariable("volumeGroupId") + int errorCode = 1 + String errorMessage = "Volume Group " + volumeGroupId + " " + message + + exceptionUtil.buildWorkflowException(execution, errorCode, errorMessage) + }catch(Exception e){ + utils.log("ERROR", "Exception Occured Processing assignWorkflowException. Exception is:\n" + e, isDebugEnabled) + } + utils.log("DEBUG", "=== COMPLETED Assign Workflow Exception ==== ", isDebugEnabled) + } + + + +} + diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/CreateAAIVfModule.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/CreateAAIVfModule.groovy index 39383609c8..986111ccda 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/CreateAAIVfModule.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/CreateAAIVfModule.groovy @@ -1,619 +1,624 @@ -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - MSO - * ================================================================================ - * 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.openecomp.mso.bpmn.common.scripts -import org.camunda.bpm.engine.runtime.Execution -import org.openecomp.mso.bpmn.core.RollbackData -import org.openecomp.mso.bpmn.core.WorkflowException -import org.openecomp.mso.rest.APIResponse -import org.springframework.web.util.UriUtils - - -public class CreateAAIVfModule extends AbstractServiceTaskProcessor{ - - def Prefix="CAAIVfMod_" - - public void initProcessVariables(Execution 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 Execution - public void preProcessRequest(Execution execution) { - def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - 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)) { - logDebug("VID Request received", isDebugEnabled) - } - - 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) - logDebug('AAI URI is: ' + aai_uri, isDebugEnabled) - String aaiNamespace = aaiUriUtil.getNamespaceFromUri(aai_uri) - logDebug('AAI namespace is: ' + aaiNamespace, isDebugEnabled) - - 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") - } - - utils.logAudit("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(Execution execution) { - def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - def endPoint = execution.getVariable("URN_aai_endpoint") + execution.getVariable("CAAIVfMod_genericVnfGetEndpoint") - - try { - utils.log("DEBUG","queryAAIForGenericVnf() endpoint-" + endPoint, isDebugEnabled) - utils.log("DEBUG", "invoking GET call to AAI endpoint :"+System.lineSeparator()+endPoint,isDebugEnabled) - utils.logAudit("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) - - utils.logAudit("CreateAAIVfModule Response Code: " + statusCode) - utils.logAudit("CreateAAIVfModule Response data: " + responseData) - utils.log("DEBUG", "Response code:" + statusCode, isDebugEnabled) - utils.log("DEBUG", "Response:" + System.lineSeparator()+responseData,isDebugEnabled) - } catch (Exception ex) { - ex.printStackTrace() - utils.log("DEBUG", "Exception occurred while executing AAI GET:" + ex.getMessage(),isDebugEnabled) - execution.setVariable("CAAIVfMod_queryGenericVnfResponseCode", 500) - execution.setVariable("CAAIVfMod_queryGenericVnfResponse", "AAI GET Failed:" + ex.getMessage()) - } - } - - // 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(Execution execution) { - def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - def result = execution.getVariable("CAAIVfMod_queryGenericVnfResponse") - - if (execution.getVariable("CAAIVfMod_queryGenericVnfResponseCode") == 404 && - execution.getVariable("CAAIVfMod_vnfId").isEmpty()) { - utils.log("DEBUG", "New Generic VNF requested and it does not already exist", isDebugEnabled) - } else if (execution.getVariable("CAAIVfMod_queryGenericVnfResponseCode") == 200 && - !execution.getVariable("CAAIVfMod_vnfId").isEmpty()) { - utils.log("DEBUG", "Adding module to existing Generic VNF", isDebugEnabled) - } else if (execution.getVariable("CAAIVfMod_queryGenericVnfResponseCode") == 200 && - execution.getVariable("CAAIVfMod_vnfId").isEmpty()) { - utils.log("DEBUG", "Invalid request for new Generic VNF which already exists", isDebugEnabled) - 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()) - utils.log("DEBUG", "Invalid request for Add-on Module requested for non-existant Generic VNF", isDebugEnabled) - 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(Execution execution) { - def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - // TBD - is this how we want to generate the Id for the new Generic VNF? - def newVnfId = UUID.randomUUID().toString() - def endPoint = execution.getVariable("URN_aai_endpoint") + - 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) - // logDebug('AAI URI is: ' + aai_uri, isDebugEnabled) - // String namespace = aaiUriUtil.getNamespaceFromUri(aai_uri) - // logDebug('AAI namespace is: ' + namespace, isDebugEnabled) - - - String payload = """ - ${newVnfId} - ${execution.getVariable("CAAIVfMod_vnfName")} - ${execution.getVariable("CAAIVfMod_vnfType")} - ${execution.getVariable("CAAIVfMod_serviceId")} - active - ${execution.getVariable("CAAIVfMod_vnfPersonaId")} - ${execution.getVariable("CAAIVfMod_vnfPersonaVer")} - """ as String - execution.setVariable("CAAIVfMod_createGenericVnfPayload", payload) - - try { - utils.log("DEBUG","createGenericVnf() endpoint-" + endPoint, isDebugEnabled) - utils.log("DEBUG", "invoking PUT call to AAI with payload:"+System.lineSeparator()+payload,isDebugEnabled) - utils.logAudit("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) - - utils.logAudit("Response Code: " + responseStatusCode) - utils.logAudit("Response Data: " + responseData) - utils.log("DEBUG", "Response code:" + responseStatusCode, isDebugEnabled) - utils.log("DEBUG", "Response:" + System.lineSeparator()+responseData,isDebugEnabled) - } catch (Exception ex) { - ex.printStackTrace() - utils.log("DEBUG", "Exception occurred while executing AAI PUT:" + ex.getMessage(),isDebugEnabled) - execution.setVariable("CAAIVfMod_createGenericVnfResponseCode", 500) - execution.setVariable("CAAIVfMod_createGenericVnfResponse", "AAI PUT Failed:" + ex.getMessage()) - } - } - - // construct and send a PUT request to A&AI to create a Base or Add-on VF Module - public void createVfModule(Execution execution, Boolean isBaseModule) { - def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - // 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 = execution.getVariable("URN_aai_endpoint") + 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; - - // 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) - utils.log("DEBUG", "RollbackData:" + rollbackData, isDebugEnabled) - String payload = """ - ${newModuleId} - ${execution.getVariable("CAAIVfMod_moduleName")} - ${execution.getVariable("CAAIVfMod_personaId")} - ${execution.getVariable("CAAIVfMod_personaVer")} - ${execution.getVariable("CAAIVfMod_modelCustomizationId")} - ${isBaseModule} - pending-create - """ as String - execution.setVariable("CAAIVfMod_createVfModulePayload", payload) - - try { - utils.log("DEBUG","createVfModule() endpoint-" + endPoint, isDebugEnabled) - utils.log("DEBUG", "invoking PUT call to AAI with payload:"+System.lineSeparator()+payload,isDebugEnabled) - utils.logAudit("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) - - utils.log("DEBUG", "Response code:" + statusCode, isDebugEnabled) - utils.log("DEBUG", "Response:" + System.lineSeparator()+responseData,isDebugEnabled) - utils.logAudit("Response Code: " + statusCode) - utils.logAudit("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) - utils.log("DEBUG", "RollbackData:" + rollbackData, isDebugEnabled) - - String responseOut = "" - - String isVidRequest = execution.getVariable("isVidRequest") - - if (isBaseModule && (isVidRequest == null || "false".equals(isVidRequest))) { - - responseOut = """ - ${execution.getVariable("CAAIVfMod_vnfId")} - ${newModuleId} - """ as String - } - else { - responseOut = """ - ${execution.getVariable("CAAIVfMod_vnfNameFromAAI")} - ${execution.getVariable("CAAIVfMod_vnfId")} - ${newModuleId} - """ as String - } - - execution.setVariable("CreateAAIVfModuleResponse", responseOut) - utils.log("DEBUG", "CreateAAIVfModuleResponse:" + System.lineSeparator()+responseOut,isDebugEnabled) - utils.logAudit("CreateAAIVfModule Response /n " + responseOut) - } - } catch (Exception ex) { - ex.printStackTrace() - utils.log("DEBUG", "Exception occurred while executing AAI PUT:" + ex.getMessage(),isDebugEnabled) - execution.setVariable("CAAIVfMod_createVfModuleResponseCode", 500) - execution.setVariable("CAAIVfMod_createVfModuleResponse", "AAI PUT Failed:" + ex.getMessage()) - } - } - - // 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(Execution execution) { - def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - def xml = execution.getVariable("CAAIVfMod_queryGenericVnfResponse") - def vnfNameFromAAI = utils.getNodeText1(xml, "vnf-name") - execution.setVariable("CAAIVfMod_vnfNameFromAAI", vnfNameFromAAI) - utils.log("DEBUG", "Obtained vnf-name from AAI for existing VNF: " + vnfNameFromAAI) - def newModuleName = execution.getVariable("CAAIVfMod_moduleName") - utils.log("DEBUG", "VF Module to be added: " + newModuleName, isDebugEnabled) - def qryModuleNameList = utils.getMultNodes(xml, "vf-module-name") - execution.setVariable("CAAIVfMod_moduleExists", false) - if (qryModuleNameList != null) { - utils.log("DEBUG", "Existing VF Module List: " + qryModuleNameList, isDebugEnabled) - for (String qryModuleName : qryModuleNameList) { - if (newModuleName.equals(qryModuleName)) { - // a module with the requested name already exists - failure - utils.log("DEBUG", "VF Module " + qryModuleName + " already exists for Generic VNF " + - execution.getVariable("CAAIVfMod_vnfNameFromAAI"), isDebugEnabled) - 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) { - utils.log("DEBUG", "VF Module " + execution.getVariable("CAAIVfMod_moduleName") + - " does not exist for Generic VNF " + execution.getVariable("CAAIVfMod_vnfNameFromAAI"), isDebugEnabled) - 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(Execution execution) { - def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - def xml = execution.getVariable("CAAIVfMod_queryGenericVnfResponse") - def vnfNameFromAAI = utils.getNodeText1(xml, "vnf-name") - execution.setVariable("CAAIVfMod_vnfNameFromAAI", vnfNameFromAAI) - utils.log("DEBUG", "Obtained vnf-name from AAI for existing VNF: " + vnfNameFromAAI) - def newModuleName = execution.getVariable("CAAIVfMod_moduleName") - utils.log("DEBUG", "VF Module to be added: " + newModuleName, isDebugEnabled) - def qryModuleNameList = utils.getMultNodes(xml, "vf-module-name") - execution.setVariable("CAAIVfMod_moduleExists", false) - if (qryModuleNameList != null) { - utils.log("DEBUG", "Existing VF Module List: " + qryModuleNameList, isDebugEnabled) - for (String qryModuleName : qryModuleNameList) { - if (newModuleName.equals(qryModuleName)) { - // a module with the requested name already exists - failure - utils.log("DEBUG", "VF Module " + qryModuleName + " already exists for Generic VNF " + - execution.getVariable("CAAIVfMod_vnfNameFromAAI"), isDebugEnabled) - 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 - utils.log("DEBUG", "Base VF Module already exists for Generic VNF " + - execution.getVariable("CAAIVfMod_vnfNameFromAAI"), isDebugEnabled) - 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) { - utils.log("DEBUG", "VF Module " + execution.getVariable("CAAIVfMod_moduleName") + - " does not exist for Generic VNF " + execution.getVariable("CAAIVfMod_vnfNameFromAAI"), isDebugEnabled) - 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(Execution execution) { - def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - - utils.log("ERROR", "Error occurred attempting to query AAI, Response Code " + - execution.getVariable("CAAIVfMod_queryGenericVnfResponseCode") + ", Error Response " + - execution.getVariable("CAAIVfMod_queryGenericVnfResponse"), isDebugEnabled) - String processKey = getProcessKey(execution); - WorkflowException exception = new WorkflowException(processKey, 5000, - execution.getVariable("CAAIVfMod_queryGenericVnfResponse")) - execution.setVariable("WorkflowException", exception) - } - - // 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(Execution execution) { - def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - - def errorCode - def errorResponse - if (execution.getVariable("CAAIVfMod_createGenericVnfResponseCode") != null && - !isOneOf(execution.getVariable("CAAIVfMod_createGenericVnfResponseCode"), 200, 201)) { - utils.log("DEBUG", "Failure creating Generic VNF: " + - execution.getVariable("CAAIVfMod_createGenericVnfResponse"), isDebugEnabled) - 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 - utils.log("DEBUG", execution.getVariable("CAAIVfMod_queryGenericVnfResponse"), isDebugEnabled) - 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 - utils.log("DEBUG", execution.getVariable("CAAIVfMod_queryGenericVnfResponse"), isDebugEnabled) - errorResponse = execution.getVariable("CAAIVfMod_queryGenericVnfResponse") - errorCode = 1002 - } else if (execution.getVariable("CAAIVfMod_createVfModuleResponseCode") != null) { - utils.log("DEBUG", "Failed to add VF Module: " + - execution.getVariable("CAAIVfMod_createVfModuleResponse"), isDebugEnabled) - errorResponse = execution.getVariable("CAAIVfMod_createVfModuleResponse") - errorCode = 5000 - } else if (execution.getVariable("CAAIVfMod_moduleExists") == true) { - utils.log("DEBUG", "Attempting to add VF Module that already exists: " + - execution.getVariable("CAAIVfMod_parseModuleResponse"), isDebugEnabled) - errorResponse = execution.getVariable("CAAIVfMod_parseModuleResponse") - errorCode = 1002 - } else if (execution.getVariable("CAAIVfMod_baseModuleConflict") == true) { - utils.log("DEBUG", "Attempting to add Base VF Module to VNF that already has a Base VF Module: " + - execution.getVariable("CAAIVfMod_parseModuleResponse"), isDebugEnabled) - 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 - } - - utils.log("ERROR", "Error occurred during CreateAAIVfModule flow: " + errorResponse, isDebugEnabled) - String processKey = getProcessKey(execution); - WorkflowException exception = new WorkflowException(processKey, errorCode, errorResponse) - execution.setVariable("WorkflowException", exception) - utils.logAudit("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(Execution execution) { - def method = getClass().getSimpleName() + ".rollback(" + - "execution=" + execution.getId() + - ")" - def isDebugLogEnabled = execution.getVariable("isDebugLogEnabled") - logDebug("Entered " + method, isDebugLogEnabled) - - try { - RollbackData rollbackData = (RollbackData) execution.getVariable("RollbackData") - logDebug("RollbackData:" + rollbackData, isDebugLogEnabled) - - AaiUtil aaiUriUtil = new AaiUtil(this) - def aai_uri = aaiUriUtil.getNetworkGenericVnfUri(execution) - logDebug('AAI URI is: ' + aai_uri, isDebugLogEnabled) - utils.logAudit("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)) { - logDebug("Received " + responseCode + " to VF Module rollback request", isDebugLogEnabled) -// execution.setVariable("RollbackResult", "SUCCESS") - } else { - logError("Received " + responseCode + " to VF Module rollback request: " + 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)) { - logDebug("Received " + responseCode + " to Generic VNF rollback request", isDebugLogEnabled) - execution.setVariable("RollbackResult", "SUCCESS") - } else { - logError("Received " + responseCode + " to Generic VNF rollback request: " + rollbackData + - System.lineSeparator() + "Response: " + response) - } - } else { - execution.setVariable("RollbackResult", "SUCCESS") - } - } - } - - logDebug("Exited " + method, isDebugLogEnabled) - } catch (Exception e) { - logError("Caught exception in " + method, e) - } - } -} +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.bpmn.common.scripts +import org.camunda.bpm.engine.runtime.Execution +import org.openecomp.mso.bpmn.core.RollbackData +import org.openecomp.mso.bpmn.core.WorkflowException +import org.openecomp.mso.rest.APIResponse +import org.springframework.web.util.UriUtils + + +public class CreateAAIVfModule extends AbstractServiceTaskProcessor{ + + def Prefix="CAAIVfMod_" + ExceptionUtil exceptionUtil = new ExceptionUtil() + public void initProcessVariables(Execution 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 Execution + public void preProcessRequest(Execution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + 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)) { + logDebug("VID Request received", isDebugEnabled) + } + + 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) + logDebug('AAI URI is: ' + aai_uri, isDebugEnabled) + String aaiNamespace = aaiUriUtil.getNamespaceFromUri(aai_uri) + logDebug('AAI namespace is: ' + aaiNamespace, isDebugEnabled) + + 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") + } + + utils.logAudit("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(Execution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + def endPoint = execution.getVariable("URN_aai_endpoint") + execution.getVariable("CAAIVfMod_genericVnfGetEndpoint") + + try { + utils.log("DEBUG","queryAAIForGenericVnf() endpoint-" + endPoint, isDebugEnabled) + utils.log("DEBUG", "invoking GET call to AAI endpoint :"+System.lineSeparator()+endPoint,isDebugEnabled) + utils.logAudit("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) + + utils.logAudit("CreateAAIVfModule Response Code: " + statusCode) + utils.logAudit("CreateAAIVfModule Response data: " + responseData) + utils.log("DEBUG", "Response code:" + statusCode, isDebugEnabled) + utils.log("DEBUG", "Response:" + System.lineSeparator()+responseData,isDebugEnabled) + } catch (Exception ex) { + utils.log("DEBUG", "Exception occurred while executing AAI GET:" + ex.getMessage(),isDebugEnabled) + 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(Execution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + def result = execution.getVariable("CAAIVfMod_queryGenericVnfResponse") + + if (execution.getVariable("CAAIVfMod_queryGenericVnfResponseCode") == 404 && + execution.getVariable("CAAIVfMod_vnfId").isEmpty()) { + utils.log("DEBUG", "New Generic VNF requested and it does not already exist", isDebugEnabled) + } else if (execution.getVariable("CAAIVfMod_queryGenericVnfResponseCode") == 200 && + !execution.getVariable("CAAIVfMod_vnfId").isEmpty()) { + utils.log("DEBUG", "Adding module to existing Generic VNF", isDebugEnabled) + } else if (execution.getVariable("CAAIVfMod_queryGenericVnfResponseCode") == 200 && + execution.getVariable("CAAIVfMod_vnfId").isEmpty()) { + utils.log("DEBUG", "Invalid request for new Generic VNF which already exists", isDebugEnabled) + 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()) + utils.log("DEBUG", "Invalid request for Add-on Module requested for non-existant Generic VNF", isDebugEnabled) + 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(Execution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + // TBD - is this how we want to generate the Id for the new Generic VNF? + def newVnfId = UUID.randomUUID().toString() + def endPoint = execution.getVariable("URN_aai_endpoint") + + 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) + // logDebug('AAI URI is: ' + aai_uri, isDebugEnabled) + // String namespace = aaiUriUtil.getNamespaceFromUri(aai_uri) + // logDebug('AAI namespace is: ' + namespace, isDebugEnabled) + + + String payload = """ + ${newVnfId} + ${execution.getVariable("CAAIVfMod_vnfName")} + ${execution.getVariable("CAAIVfMod_vnfType")} + ${execution.getVariable("CAAIVfMod_serviceId")} + active + ${execution.getVariable("CAAIVfMod_vnfPersonaId")} + ${execution.getVariable("CAAIVfMod_vnfPersonaVer")} + """ as String + execution.setVariable("CAAIVfMod_createGenericVnfPayload", payload) + + try { + utils.log("DEBUG","createGenericVnf() endpoint-" + endPoint, isDebugEnabled) + utils.log("DEBUG", "invoking PUT call to AAI with payload:"+System.lineSeparator()+payload,isDebugEnabled) + utils.logAudit("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) + + utils.logAudit("Response Code: " + responseStatusCode) + utils.logAudit("Response Data: " + responseData) + utils.log("DEBUG", "Response code:" + responseStatusCode, isDebugEnabled) + utils.log("DEBUG", "Response:" + System.lineSeparator()+responseData,isDebugEnabled) + } catch (Exception ex) { + ex.printStackTrace() + utils.log("DEBUG", "Exception occurred while executing AAI PUT:" + ex.getMessage(),isDebugEnabled) + 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(Execution execution, Boolean isBaseModule) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + // 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 = execution.getVariable("URN_aai_endpoint") + 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") + moduleIndex = aaiUtil.getLowestUnusedVfModuleIndexFromAAIVnfResponse(execution, aaiVnfResponse, + "persona-model-id", 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) + utils.log("DEBUG", "RollbackData:" + rollbackData, isDebugEnabled) + String payload = """ + ${newModuleId} + ${execution.getVariable("CAAIVfMod_moduleName")} + ${execution.getVariable("CAAIVfMod_personaId")} + ${execution.getVariable("CAAIVfMod_personaVer")} + ${execution.getVariable("CAAIVfMod_modelCustomizationId")} + ${isBaseModule} + pending-create + ${moduleIndex} + """ as String + execution.setVariable("CAAIVfMod_createVfModulePayload", payload) + + try { + utils.log("DEBUG","createVfModule() endpoint-" + endPoint, isDebugEnabled) + utils.log("DEBUG", "invoking PUT call to AAI with payload:"+System.lineSeparator()+payload,isDebugEnabled) + utils.logAudit("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) + + utils.log("DEBUG", "Response code:" + statusCode, isDebugEnabled) + utils.log("DEBUG", "Response:" + System.lineSeparator()+responseData,isDebugEnabled) + utils.logAudit("Response Code: " + statusCode) + utils.logAudit("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) + utils.log("DEBUG", "RollbackData:" + rollbackData, isDebugEnabled) + + String responseOut = "" + + String isVidRequest = execution.getVariable("isVidRequest") + + if (isBaseModule && (isVidRequest == null || "false".equals(isVidRequest))) { + + responseOut = """ + ${execution.getVariable("CAAIVfMod_vnfId")} + ${newModuleId} + ${moduleIndexString} + """ as String + } + else { + responseOut = """ + ${execution.getVariable("CAAIVfMod_vnfNameFromAAI")} + ${execution.getVariable("CAAIVfMod_vnfId")} + ${newModuleId} + ${moduleIndexString} + """ as String + } + + execution.setVariable("CreateAAIVfModuleResponse", responseOut) + utils.log("DEBUG", "CreateAAIVfModuleResponse:" + System.lineSeparator()+responseOut,isDebugEnabled) + utils.logAudit("CreateAAIVfModule Response /n " + responseOut) + } + } catch (Exception ex) { + utils.log("DEBUG", "Exception occurred while executing AAI PUT:" + ex.getMessage(),isDebugEnabled) + 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(Execution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + def xml = execution.getVariable("CAAIVfMod_queryGenericVnfResponse") + def vnfNameFromAAI = utils.getNodeText1(xml, "vnf-name") + execution.setVariable("CAAIVfMod_vnfNameFromAAI", vnfNameFromAAI) + utils.log("DEBUG", "Obtained vnf-name from AAI for existing VNF: " + vnfNameFromAAI) + def newModuleName = execution.getVariable("CAAIVfMod_moduleName") + utils.log("DEBUG", "VF Module to be added: " + newModuleName, isDebugEnabled) + def qryModuleNameList = utils.getMultNodes(xml, "vf-module-name") + execution.setVariable("CAAIVfMod_moduleExists", false) + if (qryModuleNameList != null) { + utils.log("DEBUG", "Existing VF Module List: " + qryModuleNameList, isDebugEnabled) + for (String qryModuleName : qryModuleNameList) { + if (newModuleName.equals(qryModuleName)) { + // a module with the requested name already exists - failure + utils.log("DEBUG", "VF Module " + qryModuleName + " already exists for Generic VNF " + + execution.getVariable("CAAIVfMod_vnfNameFromAAI"), isDebugEnabled) + 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) { + utils.log("DEBUG", "VF Module " + execution.getVariable("CAAIVfMod_moduleName") + + " does not exist for Generic VNF " + execution.getVariable("CAAIVfMod_vnfNameFromAAI"), isDebugEnabled) + 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(Execution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + def xml = execution.getVariable("CAAIVfMod_queryGenericVnfResponse") + def vnfNameFromAAI = utils.getNodeText1(xml, "vnf-name") + execution.setVariable("CAAIVfMod_vnfNameFromAAI", vnfNameFromAAI) + utils.log("DEBUG", "Obtained vnf-name from AAI for existing VNF: " + vnfNameFromAAI) + def newModuleName = execution.getVariable("CAAIVfMod_moduleName") + utils.log("DEBUG", "VF Module to be added: " + newModuleName, isDebugEnabled) + def qryModuleNameList = utils.getMultNodes(xml, "vf-module-name") + execution.setVariable("CAAIVfMod_moduleExists", false) + if (qryModuleNameList != null) { + utils.log("DEBUG", "Existing VF Module List: " + qryModuleNameList, isDebugEnabled) + for (String qryModuleName : qryModuleNameList) { + if (newModuleName.equals(qryModuleName)) { + // a module with the requested name already exists - failure + utils.log("DEBUG", "VF Module " + qryModuleName + " already exists for Generic VNF " + + execution.getVariable("CAAIVfMod_vnfNameFromAAI"), isDebugEnabled) + 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 + utils.log("DEBUG", "Base VF Module already exists for Generic VNF " + + execution.getVariable("CAAIVfMod_vnfNameFromAAI"), isDebugEnabled) + 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) { + utils.log("DEBUG", "VF Module " + execution.getVariable("CAAIVfMod_moduleName") + + " does not exist for Generic VNF " + execution.getVariable("CAAIVfMod_vnfNameFromAAI"), isDebugEnabled) + 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(Execution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + + utils.log("ERROR", "Error occurred attempting to query AAI, Response Code " + + execution.getVariable("CAAIVfMod_queryGenericVnfResponseCode") + ", Error Response " + + execution.getVariable("CAAIVfMod_queryGenericVnfResponse"), isDebugEnabled) + 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(Execution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + + def errorCode + def errorResponse + if (execution.getVariable("CAAIVfMod_createGenericVnfResponseCode") != null && + !isOneOf(execution.getVariable("CAAIVfMod_createGenericVnfResponseCode"), 200, 201)) { + utils.log("DEBUG", "Failure creating Generic VNF: " + + execution.getVariable("CAAIVfMod_createGenericVnfResponse"), isDebugEnabled) + 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 + utils.log("DEBUG", execution.getVariable("CAAIVfMod_queryGenericVnfResponse"), isDebugEnabled) + 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 + utils.log("DEBUG", execution.getVariable("CAAIVfMod_queryGenericVnfResponse"), isDebugEnabled) + errorResponse = execution.getVariable("CAAIVfMod_queryGenericVnfResponse") + errorCode = 1002 + } else if (execution.getVariable("CAAIVfMod_createVfModuleResponseCode") != null) { + utils.log("DEBUG", "Failed to add VF Module: " + + execution.getVariable("CAAIVfMod_createVfModuleResponse"), isDebugEnabled) + errorResponse = execution.getVariable("CAAIVfMod_createVfModuleResponse") + errorCode = 5000 + } else if (execution.getVariable("CAAIVfMod_moduleExists") == true) { + utils.log("DEBUG", "Attempting to add VF Module that already exists: " + + execution.getVariable("CAAIVfMod_parseModuleResponse"), isDebugEnabled) + errorResponse = execution.getVariable("CAAIVfMod_parseModuleResponse") + errorCode = 1002 + } else if (execution.getVariable("CAAIVfMod_baseModuleConflict") == true) { + utils.log("DEBUG", "Attempting to add Base VF Module to VNF that already has a Base VF Module: " + + execution.getVariable("CAAIVfMod_parseModuleResponse"), isDebugEnabled) + 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 + } + + utils.log("ERROR", "Error occurred during CreateAAIVfModule flow: " + errorResponse, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, errorCode, errorResponse) + utils.logAudit("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(Execution execution) { + def method = getClass().getSimpleName() + ".rollback(" + + "execution=" + execution.getId() + + ")" + def isDebugLogEnabled = execution.getVariable("isDebugLogEnabled") + logDebug("Entered " + method, isDebugLogEnabled) + + try { + RollbackData rollbackData = (RollbackData) execution.getVariable("RollbackData") + logDebug("RollbackData:" + rollbackData, isDebugLogEnabled) + + AaiUtil aaiUriUtil = new AaiUtil(this) + def aai_uri = aaiUriUtil.getNetworkGenericVnfUri(execution) + logDebug('AAI URI is: ' + aai_uri, isDebugLogEnabled) + utils.logAudit("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)) { + logDebug("Received " + responseCode + " to VF Module rollback request", isDebugLogEnabled) +// execution.setVariable("RollbackResult", "SUCCESS") + } else { + logError("Received " + responseCode + " to VF Module rollback request: " + 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)) { + logDebug("Received " + responseCode + " to Generic VNF rollback request", isDebugLogEnabled) + execution.setVariable("RollbackResult", "SUCCESS") + } else { + logError("Received " + responseCode + " to Generic VNF rollback request: " + rollbackData + + System.lineSeparator() + "Response: " + response) + } + } else { + execution.setVariable("RollbackResult", "SUCCESS") + } + } + } + + logDebug("Exited " + method, isDebugLogEnabled) + } catch (Exception e) { + logError("Caught exception in " + method, e) + } + } +} diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/CreateAAIVfModuleVolumeGroup.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/CreateAAIVfModuleVolumeGroup.groovy index 03a8596f20..07b98e6231 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/CreateAAIVfModuleVolumeGroup.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/CreateAAIVfModuleVolumeGroup.groovy @@ -1,332 +1,334 @@ -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - MSO - * ================================================================================ - * 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.openecomp.mso.bpmn.common.scripts - -import org.camunda.bpm.engine.delegate.BpmnError -import org.camunda.bpm.engine.runtime.Execution -import org.openecomp.mso.rest.APIResponse - - -public class CreateAAIVfModuleVolumeGroup extends AbstractServiceTaskProcessor { - - private XmlParser xmlParser = new XmlParser() - - /** - * Initialize the flow's variables. - * - * @param execution The flow's execution instance. - */ - public void initProcessVariables(Execution 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(Execution execution) { - def method = getClass().getSimpleName() + '.preProcessRequest(' + - 'execution=' + execution.getId() + - ')' - def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') - logDebug('Entered ' + method, isDebugLogEnabled) - - try { - def xml = execution.getVariable('CreateAAIVfModuleVolumeGroupRequest') - logDebug('Received request xml:\n' + xml, isDebugLogEnabled) - utils.logAudit("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) - - logDebug('Exited ' + method, isDebugLogEnabled) - } catch (BpmnError e) { - throw e; - } catch (Exception e) { - logError('Caught exception in ' + method, e) - createWorkflowException(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(Execution execution) { - def method = getClass().getSimpleName() + '.getVfModule(' + - 'execution=' + execution.getId() + - ')' - def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') - logDebug('Entered ' + method, isDebugLogEnabled) - - 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) - logDebug('AAI URI is: ' + aai_uri, isDebugLogEnabled) - String endPoint = execution.getVariable('URN_aai_endpoint') + aai_uri + '/' + URLEncoder.encode(vnfId, "UTF-8") + '/vf-modules/vf-module/' + URLEncoder.encode(vfModuleId, "UTF-8") - - try { - logDebug('sending GET to AAI endpoint \'' + endPoint + '\'', isDebugLogEnabled) - utils.logAudit("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) - - utils.logAudit("CreateAAIVfModule Response Code: " + response.getStatusCode()) - utils.logAudit("CreateAAIVfModule Response: " + response) - logDebug('Response code:' + response.getStatusCode(), isDebugLogEnabled) - logDebug('Response:' + System.lineSeparator() + responseData, isDebugLogEnabled) - } catch (Exception ex) { - ex.printStackTrace() - logDebug('Exception occurred while executing AAI GET:' + ex.getMessage(),isDebugLogEnabled) - execution.setVariable('CAAIVfModVG_getVfModuleResponseCode', 500) - execution.setVariable('CAAIVfModVG_getVfModuleResponse', 'AAI GET Failed:' + ex.getMessage()) - } - logDebug('Exited ' + method, isDebugLogEnabled) - } catch (BpmnError e) { - throw e; - } catch (Exception e) { - logError('Caught exception in ' + method, e) - createWorkflowException(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(Execution execution) { - def method = getClass().getSimpleName() + '.updateVfModule(' + - 'execution=' + execution.getId() + - ')' - def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') - logDebug('Entered ' + method, isDebugLogEnabled) - - 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' - logError(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) - logDebug('AAI URI is: ' + aai_uri, isDebugLogEnabled) - String endPoint = execution.getVariable('URN_aai_endpoint') + aai_uri + '/' + URLEncoder.encode(vnfId, "UTF-8") + '/vf-modules/vf-module/' + URLEncoder.encode(vfModuleId, "UTF-8") - - try { - utils.logAudit("CreateAAIVfModuleVolume Sendind PUT to AAI Endpoint \n " + endPoint + " with payload \n " + payload) - logDebug('sending PUT to AAI endpoint \'' + endPoint + '\'' + 'with payload \n' + payload, isDebugLogEnabled) - APIResponse response = aaiUtil.executeAAIPutCall(execution, endPoint, payload) - def responseData = response.getResponseBodyAsString() - execution.setVariable('CAAIVfModVG_updateVfModuleResponseCode', response.getStatusCode()) - execution.setVariable('CAAIVfModVG_updateVfModuleResponse', responseData) - - utils.logAudit("CreateAAIVfModule Response code: " + response.getStatusCode()) - utils.logAudit("CreateAAIVfModule Response: " + responseData) - logDebug('Response code:' + response.getStatusCode(), isDebugLogEnabled) - logDebug('Response:' + System.lineSeparator() + responseData, isDebugLogEnabled) - } catch (Exception ex) { - ex.printStackTrace() - logDebug('Exception occurred while executing AAI PUT:' + ex.getMessage(),isDebugLogEnabled) - execution.setVariable('CAAIVfModVG_updateVfModuleResponseCode', 500) - execution.setVariable('CAAIVfModVG_updateVfModuleResponse', 'AAI PUT Failed:' + ex.getMessage()) - } - logDebug('Exited ' + method, isDebugLogEnabled) - } catch (BpmnError e) { - throw e; - } catch (Exception e) { - logError('Caught exception in ' + method, e) - createWorkflowException(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(Execution execution) { - def method = getClass().getSimpleName() + '.handleAAIQueryFailure(' + - 'execution=' + execution.getId() + - ')' - def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') - logDebug('Entered ' + method, isDebugLogEnabled) - - logError('Error occurred attempting to query AAI, Response Code ' + - execution.getVariable('CAAIVfModVG_getVfModuleResponseCode') + ', Error Response ' + - execution.getVariable('CAAIVfModVG_getVfModuleResponse')) - ExceptionUtil exceptionUtil = new ExceptionUtil() - exceptionUtil.buildWorkflowException(execution, 5000, execution.getVariable('CAAIVfModVG_getVfModuleResponse')) - - logDebug('Exited ' + method, isDebugLogEnabled) - } - - /** - * 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(Execution execution) { - def method = getClass().getSimpleName() + '.handleUpdateVfModuleFailure(' + - 'execution=' + execution.getId() + - ')' - def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') - logDebug('Entered ' + method, isDebugLogEnabled) - - logError('Error occurred attempting to update VF Module in AAI, Response Code ' + - execution.getVariable('CAAIVfModVG_updateVfModuleResponseCode') + ', Error Response ' + - execution.getVariable('CAAIVfModVG_updateVfModuleResponse')) - ExceptionUtil exceptionUtil = new ExceptionUtil() - exceptionUtil.buildWorkflowException(execution, 5000, execution.getVariable('CAAIVfModVG_updateVfModuleResponse')) - - logDebug('Exited ' + method, isDebugLogEnabled) - } -} +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.bpmn.common.scripts + +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.runtime.Execution +import org.openecomp.mso.rest.APIResponse + + +public class CreateAAIVfModuleVolumeGroup extends AbstractServiceTaskProcessor { + + private XmlParser xmlParser = new XmlParser() + ExceptionUtil exceptionUtil = new ExceptionUtil() + + /** + * Initialize the flow's variables. + * + * @param execution The flow's execution instance. + */ + public void initProcessVariables(Execution 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(Execution execution) { + def method = getClass().getSimpleName() + '.preProcessRequest(' + + 'execution=' + execution.getId() + + ')' + def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') + logDebug('Entered ' + method, isDebugLogEnabled) + + try { + def xml = execution.getVariable('CreateAAIVfModuleVolumeGroupRequest') + logDebug('Received request xml:\n' + xml, isDebugLogEnabled) + utils.logAudit("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) + + logDebug('Exited ' + method, isDebugLogEnabled) + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + logError('Caught exception in ' + method, 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(Execution execution) { + def method = getClass().getSimpleName() + '.getVfModule(' + + 'execution=' + execution.getId() + + ')' + def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') + logDebug('Entered ' + method, isDebugLogEnabled) + + 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) + logDebug('AAI URI is: ' + aai_uri, isDebugLogEnabled) + String endPoint = execution.getVariable('URN_aai_endpoint') + aai_uri + '/' + URLEncoder.encode(vnfId, "UTF-8") + '/vf-modules/vf-module/' + URLEncoder.encode(vfModuleId, "UTF-8") + + try { + logDebug('sending GET to AAI endpoint \'' + endPoint + '\'', isDebugLogEnabled) + utils.logAudit("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) + + utils.logAudit("CreateAAIVfModule Response Code: " + response.getStatusCode()) + utils.logAudit("CreateAAIVfModule Response: " + response) + logDebug('Response code:' + response.getStatusCode(), isDebugLogEnabled) + logDebug('Response:' + System.lineSeparator() + responseData, isDebugLogEnabled) + } catch (Exception ex) { + ex.printStackTrace() + logDebug('Exception occurred while executing AAI GET:' + ex.getMessage(),isDebugLogEnabled) + execution.setVariable('CAAIVfModVG_getVfModuleResponseCode', 500) + execution.setVariable('CAAIVfModVG_getVfModuleResponse', 'AAI GET Failed:' + ex.getMessage()) + } + logDebug('Exited ' + method, isDebugLogEnabled) + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + logError('Caught exception in ' + method, 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(Execution execution) { + def method = getClass().getSimpleName() + '.updateVfModule(' + + 'execution=' + execution.getId() + + ')' + def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') + logDebug('Entered ' + method, isDebugLogEnabled) + + 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' + logError(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) + logDebug('AAI URI is: ' + aai_uri, isDebugLogEnabled) + String endPoint = execution.getVariable('URN_aai_endpoint') + aai_uri + '/' + URLEncoder.encode(vnfId, "UTF-8") + '/vf-modules/vf-module/' + URLEncoder.encode(vfModuleId, "UTF-8") + + try { + utils.logAudit("CreateAAIVfModuleVolume Sendind PUT to AAI Endpoint \n " + endPoint + " with payload \n " + payload) + logDebug('sending PUT to AAI endpoint \'' + endPoint + '\'' + 'with payload \n' + payload, isDebugLogEnabled) + APIResponse response = aaiUtil.executeAAIPutCall(execution, endPoint, payload) + def responseData = response.getResponseBodyAsString() + execution.setVariable('CAAIVfModVG_updateVfModuleResponseCode', response.getStatusCode()) + execution.setVariable('CAAIVfModVG_updateVfModuleResponse', responseData) + + utils.logAudit("CreateAAIVfModule Response code: " + response.getStatusCode()) + utils.logAudit("CreateAAIVfModule Response: " + responseData) + logDebug('Response code:' + response.getStatusCode(), isDebugLogEnabled) + logDebug('Response:' + System.lineSeparator() + responseData, isDebugLogEnabled) + } catch (Exception ex) { + ex.printStackTrace() + logDebug('Exception occurred while executing AAI PUT:' + ex.getMessage(),isDebugLogEnabled) + execution.setVariable('CAAIVfModVG_updateVfModuleResponseCode', 500) + execution.setVariable('CAAIVfModVG_updateVfModuleResponse', 'AAI PUT Failed:' + ex.getMessage()) + } + logDebug('Exited ' + method, isDebugLogEnabled) + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + logError('Caught exception in ' + method, 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(Execution execution) { + def method = getClass().getSimpleName() + '.handleAAIQueryFailure(' + + 'execution=' + execution.getId() + + ')' + def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') + logDebug('Entered ' + method, isDebugLogEnabled) + + logError('Error occurred attempting to query AAI, Response Code ' + + execution.getVariable('CAAIVfModVG_getVfModuleResponseCode') + ', Error Response ' + + execution.getVariable('CAAIVfModVG_getVfModuleResponse')) + ExceptionUtil exceptionUtil = new ExceptionUtil() + exceptionUtil.buildWorkflowException(execution, 5000, execution.getVariable('CAAIVfModVG_getVfModuleResponse')) + + logDebug('Exited ' + method, isDebugLogEnabled) + } + + /** + * 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(Execution execution) { + def method = getClass().getSimpleName() + '.handleUpdateVfModuleFailure(' + + 'execution=' + execution.getId() + + ')' + def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') + logDebug('Entered ' + method, isDebugLogEnabled) + + logError('Error occurred attempting to update VF Module in AAI, Response Code ' + + execution.getVariable('CAAIVfModVG_updateVfModuleResponseCode') + ', Error Response ' + + execution.getVariable('CAAIVfModVG_updateVfModuleResponse')) + ExceptionUtil exceptionUtil = new ExceptionUtil() + exceptionUtil.buildWorkflowException(execution, 5000, execution.getVariable('CAAIVfModVG_updateVfModuleResponse')) + + logDebug('Exited ' + method, isDebugLogEnabled) + } +} diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/CreateGenericVNFUtils.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/CreateGenericVNFUtils.groovy index ffc706d263..887eb7456d 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/CreateGenericVNFUtils.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/CreateGenericVNFUtils.groovy @@ -77,7 +77,7 @@ class CreateGenericVNFUtils{ String uuid = execution.getVariable('testReqId') // for junits if(uuid==null){ - uuid = execution.getVariable("att-mso-request-id") + "-" + System.currentTimeMillis() + uuid = execution.getVariable("mso-request-id") + "-" + System.currentTimeMillis() } def callbackURL = execution.getVariable("CRTGVNF_sdncCallbackUrl") def requestId = execution.getVariable("CRTGVNF_requestId") @@ -96,9 +96,9 @@ class CreateGenericVNFUtils{ } String sdncRequest = - """ + """ ${uuid} ${svcInstId} @@ -155,122 +155,6 @@ ${sdncVNFParamsXml} } return params } - - /** - * Builds a "CompletionHandler" request and stores it in the specified - * execution variable. - * @param execution the execution - */ - public void buildCompletionHandlerRequest(Execution execution, String flowName) { - def method = getClass().getSimpleName() + '.completionHandlerPrep(' + - 'execution=' + execution.getId() + - ')' - def prefix = execution.getVariable('prefix') - def resultVar = prefix + "CompletionHandlerRequest" - def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') - taskProcessor.logDebug('Entered ' + method, isDebugLogEnabled) - - try { - def request = taskProcessor.getVariable(execution, prefix+'Request') - def requestInformation = taskProcessor.utils.getNodeXml(request, 'request-information', false) - if (requestInformation == null || requestInformation == ""){ - requestInformation = taskProcessor.utils.getNodeXml(request, 'request-info', false) - } - - String content = """ - - ${requestInformation} - ${flowName} - - """ - - content = taskProcessor.utils.removeXmlPreamble(taskProcessor.utils.formatXML(content)) - taskProcessor.logDebug(resultVar + ' = ' + System.lineSeparator() + content, isDebugLogEnabled) - execution.setVariable(resultVar, content) - - taskProcessor.logDebug('Exited ' + method, isDebugLogEnabled) - } catch (BpmnError e) { - throw e; - } catch (Exception e) { - taskProcessor.logError('Caught exception in ' + method, e) - exceptionUtil.buildAndThrowWorkflowException(execution, 2000, "Internal Error Occured during completion handler request") - } - } - - /** - * Builds a "FalloutHandler" request and stores it in the specified - * execution variable. - * @param execution the execution - */ - public void buildfalloutHandlerRequest(Execution execution) { - def method = getClass().getSimpleName() + '.falloutHandlerPrep(' + - 'execution=' + execution.getId() + - ')' - def prefix = execution.getVariable('prefix') - def resultVar = prefix + "FalloutHandlerRequest" - def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') - taskProcessor.logDebug('Entered ' + method, isDebugLogEnabled) - try { - def request = taskProcessor.getVariable(execution, prefix+'Request') - - def requestInformation = "" - if (request != null){ - requestInformation = taskProcessor.utils.getNodeXml(request, 'request-information', false) - if (requestInformation == null || requestInformation == ""){ - requestInformation = taskProcessor.utils.getNodeXml(request, 'request-info', false) - } - } - def errorInformation = "" - def encErrorResponseMsg = "" - def errorResponseCode = "" - String content = "" - - def WorkflowException workflowException - def exception = execution.getVariable("WorkflowException") - - if (exception instanceof WorkflowException) - { - workflowException = execution.getVariable("WorkflowException") - } - - if (workflowException != null){ - errorResponseCode = workflowException.getErrorCode() - def errorResponseMsg = workflowException.getErrorMessage() - - if (errorResponseMsg != null) { - encErrorResponseMsg = errorResponseMsg.replace("&", "&").replace("<", "<").replace(">", ">") - } - - errorInformation = """ - ${encErrorResponseMsg} - ${errorResponseCode} - """ - } - else { - errorInformation = execution.getVariable(prefix+'ErrorResponse') - - if (errorInformation == null) errorInformation = "" - } - - content = """ - - ${requestInformation} - ${errorInformation} - - """ - - content = taskProcessor.utils.removeXmlPreamble(taskProcessor.utils.formatXML(content)) - - taskProcessor.logDebug(resultVar + ' = ' + System.lineSeparator() + content, isDebugLogEnabled) - execution.setVariable(resultVar, content) - taskProcessor.logDebug('Exited ' + method, isDebugLogEnabled) - } catch (Exception e) { - taskProcessor.logError('Caught exception in ' + method, e) - exceptionUtil.buildAndThrowWorkflowException(execution, 2000, "Internal Error in buildfalloutHandlerRequest") - } - } } diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/DeleteAAIVfModule.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/DeleteAAIVfModule.groovy index ca9a2e0849..72ad1402e1 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/DeleteAAIVfModule.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/DeleteAAIVfModule.groovy @@ -1,334 +1,349 @@ -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - MSO - * ================================================================================ - * 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.openecomp.mso.bpmn.common.scripts -import org.camunda.bpm.engine.runtime.Execution -import org.openecomp.mso.bpmn.core.WorkflowException -import org.openecomp.mso.rest.APIResponse - - -public class DeleteAAIVfModule extends AbstractServiceTaskProcessor{ - - def Prefix="DAAIVfMod_" - - public void initProcessVariables(Execution 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 Execution - public void preProcessRequest(Execution execution) { - def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - def xml = execution.getVariable("DeleteAAIVfModuleRequest") - utils.logAudit("DeleteAAIVfModule Request: " + xml) - utils.log("DEBUG", "input request xml:" + xml, isDebugEnabled) - 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) - logDebug('AAI URI is: ' + aai_uri, isDebugEnabled) - - 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(Execution execution) { - def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - def delModuleId = execution.getVariable("DAAIVfMod_vfModuleId") - def endPoint = execution.getVariable("URN_aai_endpoint") + execution.getVariable("DAAIVfMod_genericVnfEndpoint") + "?depth=1" - utils.logAudit("DeleteAAIVfModule endPoint: " + endPoint) - def aaiRequestId = UUID.randomUUID().toString() - - utils.log("DEBUG","queryAAIForGenericVnf() endpoint-" + endPoint, isDebugEnabled) - def responseData = "" - try { - utils.log("DEBUG", "invoking GET call to AAI endpoint :"+System.lineSeparator()+endPoint,isDebugEnabled) - utils.logAudit("DeleteAAIVfModule - invoking httpGet to AAI") - - AaiUtil aaiUtil = new AaiUtil(this) - APIResponse response = aaiUtil.executeAAIGetCall(execution, endPoint) - - responseData = response.getResponseBodyAsString() - execution.setVariable("DAAIVfMod_queryGenericVnfResponseCode", response.getStatusCode()) - execution.setVariable("DAAIVfMod_queryGenericVnfResponse", responseData) - utils.logAudit("AAI Response: " + responseData) - utils.log("DEBUG", "Response code:" + response.getStatusCode(), isDebugEnabled) - utils.log("DEBUG", "Response:" + System.lineSeparator()+responseData,isDebugEnabled) - } catch (Exception ex) { - ex.printStackTrace() - utils.log("DEBUG", "Exception occurred while executing AAI GET:" + ex.getMessage(),isDebugEnabled) - execution.setVariable("DAAIVfMod_queryGenericVnfResponseCode", 500) - execution.setVariable("DAAIVfMod_queryGenericVnfResponse", "AAI GET Failed:" + ex.getMessage()) - } - } - - // 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(Execution execution) { - def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - def aaiRequestId = UUID.randomUUID().toString() - def endPoint = execution.getVariable("URN_aai_endpoint") + execution.getVariable("DAAIVfMod_genericVnfEndpoint") + - "/?resource-version=" + execution.getVariable("DAAIVfMod_genVnfRsrcVer") - utils.logAudit("AAI endPoint: " + endPoint) - utils.log("DEBUG","deleteGenericVnf() endpoint-" + endPoint, isDebugEnabled) - def responseData = "" - try { - AaiUtil aaiUtil = new AaiUtil(this) - APIResponse response = aaiUtil.executeAAIDeleteCall(execution, endPoint) - - responseData = response.getResponseBodyAsString() - execution.setVariable("DAAIVfMod_deleteGenericVnfResponseCode", response.getStatusCode()) - execution.setVariable("DAAIVfMod_deleteGenericVnfResponse", responseData) - utils.log("DEBUG", "Response code:" + response.getStatusCode(), isDebugEnabled) - utils.log("DEBUG", "Response:" + System.lineSeparator()+responseData,isDebugEnabled) - } catch (Exception ex) { - ex.printStackTrace() - utils.log("DEBUG", "Exception occurred while executing AAI DELETE:" + ex.getMessage(),isDebugEnabled) - execution.setVariable("DAAIVfMod_deleteGenericVnfResponseCode", 500) - execution.setVariable("DAAIVfMod_deleteGenericVnfResponse", "AAI DELETE Failed:" + ex.getMessage()) - } - } - - // construct and send a DELETE request to A&AI to delete the Base or Add-on Vf Module - public void deleteVfModule(Execution execution) { - def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - def endPoint = execution.getVariable("URN_aai_endpoint") + execution.getVariable("DAAIVfMod_vfModuleEndpoint") + - "/?resource-version=" + execution.getVariable("DAAIVfMod_vfModRsrcVer") - def aaiRequestId = UUID.randomUUID().toString() - - utils.log("DEBUG","deleteVfModule() endpoint-" + endPoint, isDebugEnabled) - def responseData = "" - try { - AaiUtil aaiUtil = new AaiUtil(this) - APIResponse response = aaiUtil.executeAAIDeleteCall(execution, endPoint) - - utils.logAudit("DeleteAAIVfModule - invoking httpDelete to AAI") - - responseData = response.getResponseBodyAsString() - execution.setVariable("DAAIVfMod_deleteVfModuleResponseCode", response.getStatusCode()) - execution.setVariable("DAAIVfMod_deleteVfModuleResponse", responseData) - utils.logAudit("DeleteAAIVfModule - AAI Response" + responseData) - utils.log("DEBUG", "Response code:" + response.getStatusCode(), isDebugEnabled) - utils.log("DEBUG", "Response:" + System.lineSeparator()+responseData,isDebugEnabled) - - } catch (Exception ex) { - ex.printStackTrace() - utils.log("DEBUG", "Exception occurred while executing AAI PUT:" + ex.getMessage(),isDebugEnabled) - execution.setVariable("DAAIVfMod_deleteVfModuleResponseCode", 500) - execution.setVariable("DAAIVfMod_deleteVfModuleResponse", "AAI PUT Failed:" + ex.getMessage()) - } - } - - // 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(Execution execution) { - def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - def xml = execution.getVariable("DAAIVfMod_queryGenericVnfResponse") - utils.logAudit("DeleteAAIVfModule - queryGenericVnfResponse" + xml) - - def delModuleId = execution.getVariable("DAAIVfMod_vfModuleId") - utils.log("DEBUG", "Vf Module to be deleted: " + delModuleId, isDebugEnabled) - List qryModuleIdList = utils.getMultNodes(xml, "vf-module-id") - List qryBaseModuleList = utils.getMultNodes(xml, "is-base-vf-module") - List 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) { - utils.log("DEBUG", "Existing Vf Module Id List: " + qryModuleIdList, isDebugEnabled) - utils.log("DEBUG", "Existing Vf Module Resource Version List: " + qryResourceVerList, isDebugEnabled) - 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]) - utils.log("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"), isDebugEnabled) - 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") - } - } - } - utils.log("DEBUG", execution.getVariable("DAAIVfMod_parseModuleResponse"), isDebugEnabled) - } else { // (execution.getVariable("DAAIVfMod_moduleExists") == false) - utils.log("DEBUG", "Vf Module Id " + delModuleId + " does not exist for Generic Vnf Id " + - execution.getVariable("DAAIVfMod_vnfId"), isDebugEnabled) - 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(Execution execution) { - def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - def xml = execution.getVariable("DAAIVfMod_queryGenericVnfResponse") - utils.logAudit("DeleteAAIVfModule - queryGenericVnfResponse" + xml) - String resourceVer = utils.getNodeText1(xml, "resource-version") - execution.setVariable("DAAIVfMod_genVnfRsrcVer", resourceVer) - utils.log("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(Execution execution) { - def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - - utils.log("ERROR", "Error occurred attempting to query AAI, Response Code " + - execution.getVariable("DAAIVfMod_queryGenericVnfResponseCode") + ", Error Response " + - execution.getVariable("DAAIVfMod_queryGenericVnfResponse"), isDebugEnabled) - 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 - } - String processKey = getProcessKey(execution); - WorkflowException exception = new WorkflowException(processKey, errorCode, - execution.getVariable("DAAIVfMod_queryGenericVnfResponse")) - execution.setVariable("WorkflowException", exception) - } - - // 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(Execution execution) { - def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - - def errorCode = 2000 - def errorResponse = "" - if (execution.getVariable("DAAIVfMod_deleteVfModuleResponseCode") != null && - execution.getVariable("DAAIVfMod_deleteVfModuleResponseCode") != 200) { - utils.log("DEBUG", "AAI failure deleting a Vf Module: " + - execution.getVariable("DAAIVfMod_deleteVfModuleResponse"), isDebugEnabled) - errorResponse = execution.getVariable("DAAIVfMod_deleteVfModuleResponse") - utils.logAudit("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 - utils.log("DEBUG", execution.getVariable("DAAIVfMod_parseModuleResponse"), isDebugEnabled) - errorResponse = execution.getVariable("DAAIVfMod_parseModuleResponse") - utils.logAudit("DeleteAAIVfModule - parseModuleResponse" + errorResponse) - errorCode = 1002 - } else { - // attempt to delete a non-existant Vf Module - if (execution.getVariable("DAAIVfMod_moduleExists") == false) { - utils.log("DEBUG", execution.getVariable("DAAIVfMod_parseModuleResponse"), isDebugEnabled) - errorResponse = execution.getVariable("DAAIVfMod_parseModuleResponse") - utils.logAudit("DeleteAAIVfModule - parseModuleResponse" + errorResponse) - errorCode = 1002 - } else { - // if the responses get populated corerctly, we should never get here - errorResponse = "Unknown error occurred during DeleteAAIVfModule flow" - } - } - } - - utils.log("ERROR", "Error occurred during DeleteAAIVfModule flow: " + errorResponse, isDebugEnabled) - String processKey = getProcessKey(execution); - WorkflowException exception = new WorkflowException(processKey, errorCode, errorResponse) - execution.setVariable("WorkflowException", exception) - } - - // generates a WorkflowException if - // - the A&AI Generic Vnf DELETE returns a response code other than 200 - public void handleDeleteGenericVnfFailure(Execution execution) { - def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - utils.log("ERROR", "AAI error occurred deleting the Generic Vnf: " - + execution.getVariable("DAAIVfMod_deleteGenericVnfResponse"), isDebugEnabled) - String processKey = getProcessKey(execution); - WorkflowException exception = new WorkflowException(processKey, 5000, - execution.getVariable("DAAIVfMod_deleteGenericVnfResponse")) - execution.setVariable("WorkflowException", exception) - } +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.bpmn.common.scripts +import org.camunda.bpm.engine.runtime.Execution +import org.openecomp.mso.bpmn.core.WorkflowException +import org.openecomp.mso.rest.APIResponse +import org.openecomp.mso.rest.RESTClient; +import org.openecomp.mso.rest.RESTConfig; + + +public class DeleteAAIVfModule extends AbstractServiceTaskProcessor{ + + def Prefix="DAAIVfMod_" + ExceptionUtil exceptionUtil = new ExceptionUtil() + public void initProcessVariables(Execution 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 Execution + public void preProcessRequest(Execution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + def xml = execution.getVariable("DeleteAAIVfModuleRequest") + utils.logAudit("DeleteAAIVfModule Request: " + xml) + utils.log("DEBUG", "input request xml:" + xml, isDebugEnabled) + 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) + logDebug('AAI URI is: ' + aai_uri, isDebugEnabled) + + 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(Execution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + def delModuleId = execution.getVariable("DAAIVfMod_vfModuleId") + def endPoint = execution.getVariable("URN_aai_endpoint") + execution.getVariable("DAAIVfMod_genericVnfEndpoint") + "?depth=1" + utils.logAudit("DeleteAAIVfModule endPoint: " + endPoint) + def aaiRequestId = UUID.randomUUID().toString() + + RESTConfig config = new RESTConfig(endPoint); + utils.log("DEBUG","queryAAIForGenericVnf() endpoint-" + endPoint, isDebugEnabled) + def responseData = "" + try { + RESTClient client = new RESTClient(config).addHeader("X-TransactionId", aaiRequestId).addHeader("X-FromAppId", "MSO"). + addHeader("Accept","application/xml"); + String basicAuthCred = utils.getBasicAuth(execution.getVariable("URN_aai_auth"),execution.getVariable("URN_mso_msoKey")) + + if (basicAuthCred != null && !"".equals(basicAuthCred)) { + client.addAuthorizationHeader(basicAuthCred) + } + utils.log("DEBUG", "invoking GET call to AAI endpoint :"+System.lineSeparator()+endPoint,isDebugEnabled) + APIResponse response = client.httpGet() + utils.logAudit("DeleteAAIVfModule - invoking httpGet to AAI") + + responseData = response.getResponseBodyAsString() + execution.setVariable("DAAIVfMod_queryGenericVnfResponseCode", response.getStatusCode()) + execution.setVariable("DAAIVfMod_queryGenericVnfResponse", responseData) + utils.logAudit("AAI Response: " + responseData) + utils.log("DEBUG", "Response code:" + response.getStatusCode(), isDebugEnabled) + utils.log("DEBUG", "Response:" + System.lineSeparator()+responseData,isDebugEnabled) + } catch (Exception ex) { + utils.log("DEBUG", "Exception occurred while executing AAI GET:" + ex.getMessage(),isDebugEnabled) + 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(Execution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + def aaiRequestId = UUID.randomUUID().toString() + def endPoint = execution.getVariable("URN_aai_endpoint") + execution.getVariable("DAAIVfMod_genericVnfEndpoint") + + "/?resource-version=" + execution.getVariable("DAAIVfMod_genVnfRsrcVer") + utils.logAudit("AAI endPoint: " + endPoint) + RESTConfig config = new RESTConfig(endPoint); + utils.log("DEBUG","deleteGenericVnf() endpoint-" + endPoint, isDebugEnabled) + def responseData = "" + try { + RESTClient client = new RESTClient(config).addHeader("X-TransactionId", aaiRequestId).addHeader("X-FromAppId", "MSO"). + addHeader("Accept","application/xml"); + + String basicAuthCred = utils.getBasicAuth(execution.getVariable("URN_aai_auth"),execution.getVariable("URN_mso_msoKey")) + + 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) + utils.log("DEBUG", "Response code:" + response.getStatusCode(), isDebugEnabled) + utils.log("DEBUG", "Response:" + System.lineSeparator()+responseData,isDebugEnabled) + } catch (Exception ex) { + ex.printStackTrace() + utils.log("DEBUG", "Exception occurred while executing AAI DELETE:" + ex.getMessage(),isDebugEnabled) + 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(Execution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + def endPoint = execution.getVariable("URN_aai_endpoint") + execution.getVariable("DAAIVfMod_vfModuleEndpoint") + + "/?resource-version=" + execution.getVariable("DAAIVfMod_vfModRsrcVer") + def aaiRequestId = UUID.randomUUID().toString() + + RESTConfig config = new RESTConfig(endPoint); + utils.log("DEBUG","deleteVfModule() endpoint-" + endPoint, isDebugEnabled) + def responseData = "" + try { + RESTClient client = new RESTClient(config).addHeader("X-TransactionId", aaiRequestId).addHeader("X-FromAppId", "MSO"). + addHeader("Accept","application/xml"); + + String basicAuthCred = utils.getBasicAuth(execution.getVariable("URN_aai_auth"),execution.getVariable("URN_mso_msoKey")) + + if (basicAuthCred != null && !"".equals(basicAuthCred)) { + client.addAuthorizationHeader(basicAuthCred) + } + APIResponse response = client.httpDelete() + + utils.logAudit("DeleteAAIVfModule - invoking httpDelete to AAI") + + responseData = response.getResponseBodyAsString() + execution.setVariable("DAAIVfMod_deleteVfModuleResponseCode", response.getStatusCode()) + execution.setVariable("DAAIVfMod_deleteVfModuleResponse", responseData) + utils.logAudit("DeleteAAIVfModule - AAI Response" + responseData) + utils.log("DEBUG", "Response code:" + response.getStatusCode(), isDebugEnabled) + utils.log("DEBUG", "Response:" + System.lineSeparator()+responseData,isDebugEnabled) + + } catch (Exception ex) { + ex.printStackTrace() + utils.log("DEBUG", "Exception occurred while executing AAI PUT:" + ex.getMessage(),isDebugEnabled) + 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(Execution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + def xml = execution.getVariable("DAAIVfMod_queryGenericVnfResponse") + utils.logAudit("DeleteAAIVfModule - queryGenericVnfResponse" + xml) + + def delModuleId = execution.getVariable("DAAIVfMod_vfModuleId") + utils.log("DEBUG", "Vf Module to be deleted: " + delModuleId, isDebugEnabled) + List qryModuleIdList = utils.getMultNodes(xml, "vf-module-id") + List qryBaseModuleList = utils.getMultNodes(xml, "is-base-vf-module") + List 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) { + utils.log("DEBUG", "Existing Vf Module Id List: " + qryModuleIdList, isDebugEnabled) + utils.log("DEBUG", "Existing Vf Module Resource Version List: " + qryResourceVerList, isDebugEnabled) + 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]) + utils.log("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"), isDebugEnabled) + 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") + } + } + } + utils.log("DEBUG", execution.getVariable("DAAIVfMod_parseModuleResponse"), isDebugEnabled) + } else { // (execution.getVariable("DAAIVfMod_moduleExists") == false) + utils.log("DEBUG", "Vf Module Id " + delModuleId + " does not exist for Generic Vnf Id " + + execution.getVariable("DAAIVfMod_vnfId"), isDebugEnabled) + 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(Execution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + def xml = execution.getVariable("DAAIVfMod_queryGenericVnfResponse") + utils.logAudit("DeleteAAIVfModule - queryGenericVnfResponse" + xml) + String resourceVer = utils.getNodeText1(xml, "resource-version") + execution.setVariable("DAAIVfMod_genVnfRsrcVer", resourceVer) + utils.log("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(Execution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + + utils.log("ERROR", "Error occurred attempting to query AAI, Response Code " + + execution.getVariable("DAAIVfMod_queryGenericVnfResponseCode") + ", Error Response " + + execution.getVariable("DAAIVfMod_queryGenericVnfResponse"), isDebugEnabled) + 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(Execution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + + def errorCode = 2000 + def errorResponse = "" + if (execution.getVariable("DAAIVfMod_deleteVfModuleResponseCode") != null && + execution.getVariable("DAAIVfMod_deleteVfModuleResponseCode") != 200) { + utils.log("DEBUG", "AAI failure deleting a Vf Module: " + + execution.getVariable("DAAIVfMod_deleteVfModuleResponse"), isDebugEnabled) + errorResponse = execution.getVariable("DAAIVfMod_deleteVfModuleResponse") + utils.logAudit("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 + utils.log("DEBUG", execution.getVariable("DAAIVfMod_parseModuleResponse"), isDebugEnabled) + errorResponse = execution.getVariable("DAAIVfMod_parseModuleResponse") + utils.logAudit("DeleteAAIVfModule - parseModuleResponse" + errorResponse) + errorCode = 1002 + } else { + // attempt to delete a non-existant Vf Module + if (execution.getVariable("DAAIVfMod_moduleExists") == false) { + utils.log("DEBUG", execution.getVariable("DAAIVfMod_parseModuleResponse"), isDebugEnabled) + errorResponse = execution.getVariable("DAAIVfMod_parseModuleResponse") + utils.logAudit("DeleteAAIVfModule - parseModuleResponse" + errorResponse) + errorCode = 1002 + } else { + // if the responses get populated corerctly, we should never get here + errorResponse = "Unknown error occurred during DeleteAAIVfModule flow" + } + } + } + + utils.log("ERROR", "Error occurred during DeleteAAIVfModule flow: " + errorResponse, isDebugEnabled) + 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(Execution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + utils.log("ERROR", "AAI error occurred deleting the Generic Vnf: " + + execution.getVariable("DAAIVfMod_deleteGenericVnfResponse"), isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 5000, execution.getVariable("DAAIVfMod_deleteGenericVnfResponse")) + } } \ No newline at end of file diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/ExceptionUtil.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/ExceptionUtil.groovy index fb68f4efe9..4cc4da49b3 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/ExceptionUtil.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/ExceptionUtil.groovy @@ -1,599 +1,398 @@ -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - MSO - * ================================================================================ - * 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.openecomp.mso.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.runtime.Execution -import org.openecomp.mso.bpmn.core.WorkflowException - -/** - * @version 1.0 - */ -class ExceptionUtil extends AbstractServiceTaskProcessor { - - /** - * - * @Deprecated - * - * Instead use MapAAIExceptionToWorkflowException - * - * To Be Removed Once Refactoring Main Flow Error Handling Is Complete - * - * - */ - @Deprecated - String MapAAIExceptionToWorkflowExceptionOld(String response, Execution execution) - { - def utils=new MsoUtils() - def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - def prefix=execution.getVariable("prefix") - def errorMsg = execution.getVariable(prefix+"ErrorResponse") - utils.log("DEBUG","=========== Begin MapAAIExceptionToWorkflowException ===========",isDebugEnabled) - String text = null - def variables - String errorCode = '5000' - utils.log("DEBUG","response: " + response, isDebugEnabled) - try { - //String msg = utils.getNodeXml(response, "Fault") - variables = utils.getMultNodes(response, "variable") - text = utils.getNodeText1(response, "text") - } catch (Exception ex) { - //Ignore the exception - cases include non xml payload - utils.log("DEBUG","error mapping error, ignoring: " + ex,isDebugEnabled) - } - - 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&AI (' + text +')' - utils.log("DEBUG", "ModifiedErrorMessage " + modifiedErrorMessage, isDebugEnabled) - // let $ModifiedErrorMessage := concat( 'Received error from A',$exceptionaai:ampersand,'AI (' ,functx:replace-multi($ErrorMessage,$from,$Variables ),')') - String message = """ - $modifiedErrorMessage - $errorCode - """ - execution.setVariable(prefix+"ErrorResponse",message) - utils.log("ERROR","Fault:"+ execution.getVariable(prefix+"ErrorResponse")) - return message - } else { - try { - errorCode = MapErrorCode(errorMsg) - String mappedErrorMessage = MapErrorMessage(errorMsg, errorCode) - - String message = """ - $mappedErrorMessage - $errorCode - """ - utils.log("DEBUG", "mappedErrorMessage " + mappedErrorMessage, isDebugEnabled) - execution.setVariable(prefix+"ErrorResponse",message) - utils.log("ERROR","Fault:"+ execution.getVariable(prefix+"ErrorResponse")) - return message - } catch(Exception ex) { - utils.log("DEBUG","error mapping error, return null: " + ex,isDebugEnabled) - return null - - } - } - } - - /** - * 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, Execution execution) - { - def utils=new MsoUtils() - def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - def prefix=execution.getVariable("prefix") - def errorMsg = execution.getVariable(prefix+"ErrorResponse") - utils.log("DEBUG","=========== Begin MapAAIExceptionToWorkflowException ===========",isDebugEnabled) - String text = null - def variables - String errorCode = '5000' - WorkflowException wfex - utils.log("DEBUG","response: " + response, isDebugEnabled) - try { - //String msg = utils.getNodeXml(response, "Fault") - variables = utils.getMultNodes(response, "variable") - text = utils.getNodeText1(response, "text") - } catch (Exception ex) { - //Ignore the exception - cases include non xml payload - utils.log("DEBUG","error mapping error, ignoring: " + ex,isDebugEnabled) - } - - 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&AI (' + text +')' - utils.log("DEBUG", "ModifiedErrorMessage " + modifiedErrorMessage, isDebugEnabled) - // let $ModifiedErrorMessage := concat( 'Received error from A',$exceptionaai:ampersand,'AI (' ,functx:replace-multi($ErrorMessage,$from,$Variables ),')') - buildWorkflowException(execution, 5000, modifiedErrorMessage) - - wfex = execution.getVariable("WorkflowException") - utils.log("ERROR","Fault:"+ wfex) - return wfex - } else { - try { - errorCode = MapErrorCode(errorMsg) - String mappedErrorMessage = MapErrorMessage(errorMsg, errorCode) - - int errorCodeInt = Integer.parseInt(errorCode) - buildWorkflowException(execution, errorCodeInt, mappedErrorMessage) - - utils.log("DEBUG", "mappedErrorMessage " + mappedErrorMessage, isDebugEnabled) - wfex = execution.getVariable("WorkflowException") - utils.log("ERROR","Fault:"+ wfex, isDebugEnabled) - return wfex - } catch(Exception ex) { - utils.log("DEBUG","error mapping error, return null: " + ex, isDebugEnabled) - return null - - } - } - } - - /** - * 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 tags from AAI Response - * and puts it into the WorkflowException's errorMessage. - * - * @param execution the execution - * @param response the aai exception - */ - WorkflowException MapAAIExceptionToWorkflowExceptionGeneric(Execution execution, String response, int resCode){ - def utils=new MsoUtils() - def isDebugLogEnabled = execution.getVariable("isDebugLogEnabled") - utils.log("DEBUG", "Start MapAAIExceptionToWorkflowExceptionGeneric Process", isDebugLogEnabled) - - WorkflowException wfex - try { - if(utils.nodeExists(response, "Fault")){ - String fault = utils.getNodeXml(response, "Fault") - fault = utils.removeXmlPreamble(fault) - fault = fault.replace("", "").replace("", "") - 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) { - utils.log("DEBUG", "Exception Occured during MapAAIExceptionToWorkflowExceptionGeneric: " + ex, isDebugLogEnabled) - buildWorkflowException(execution, resCode, "Internal Error - Occured in MapAAIExceptionToWorkflowExceptionGeneric") - - } - utils.log("DEBUG", "Outgoing WorkflowException is: " + execution.getVariable("WorkflowException"), isDebugLogEnabled) - utils.log("DEBUG", "Completed MapAAIExceptionToWorkflowExceptionGeneric Process", isDebugLogEnabled) - } - - /** - * - *This method build a WorkflowException using the adapters response. - * - *@param String response - *@param String adapter - * - *@return WorkflowException wfex - */ - WorkflowException MapAdapterExecptionToWorkflowException(String response, Execution execution, String adapter){ - def utils=new MsoUtils() - def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - def prefix=execution.getVariable("prefix") - utils.log("DEBUG","=========== Start MapAdapterExecptionToWorkflowException Process ===========",isDebugEnabled) - - String errorCode - def errorMessage - WorkflowException wfex - try { - errorCode = MapCategoryToErrorCode(utils.getNodeText(response, "category")) - errorMessage = MapAdapterErrorMessage(utils.getNodeText(response, "message"), errorCode, adapter) - - int errorCodeInt = Integer.parseInt(errorCode) - buildWorkflowException(execution, errorCodeInt, errorMessage) - }catch (Exception ex) { - utils.log("DEBUG", "Exception Occured during MapAdapterExecptionToWorkflowException: " + ex, isDebugEnabled) - buildWorkflowException(execution, 2500, "Internal Error - Occured in MapAdapterExecptionToWorkflowException") - } - wfex = execution.getVariable("WorkflowException") - return wfex - utils.log("DEBUG","=========== Completed MapAdapterExecptionToWorkflowException Process ===========",isDebugEnabled) - } - - - /** - * - * @Deprecated - * - * Instead use buildWorkflowException(Execution execution, int errorCode, String errorMessage) method below - * - * To Be Removed Once Refactoring Of Main Flow Error Handling Is Complete - * - */ - @Deprecated - String buildWorkflowExceptionXml(String errorCode, String errorMessage) { - return """ - ${errorMessage} - ${errorCode} - """ - } - - /** - * This method takes a WorkflowException Object and builds - * WorkflowException Xml. This method should only be used - * for the purpose of sending an error response. - * - *@param - WorkflowException Object - * - *@return - String WorkflowException Xml - * - * - */ - String buildErrorResponseXml(WorkflowException wfex) { - String xml - if(wfex != null){ - String mes = wfex.getErrorMessage() - int code = wfex.getErrorCode() - xml = - """ - ${mes} - ${code} - """ - - }else{ - xml = - """ - Internal Error - 2500 - """ - } - 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. - */ - 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' - } - - 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 { - errorMessage = errorMessage.replace("&", "&").replace("<", "<").replace(">", ">") - return 'Received error from A&AI (' +errorMessage +')' - } - } - - String MapCategoryToErrorCode(String errorCategory) - { - if(errorCategory.equals('OPENSTACK')) - return '5100' - else if (errorCategory.equals('IO')) - return '5110' - else if (errorCategory.equals('INTERNAL')) - return '7020' - else if (errorCategory.equals('USERDATA')) - return '7020' - else - return '7020' - } - - - String MapAdapterErrorMessage(String errorMessage, String errorCode, String adapter) - { - if(errorCode.equals('5100')) - return 'Received error from Platform Orchestrator: ' + errorMessage - else if(errorCode.equals('5110')) - return 'Could not communicate with Platform Orchestrator' - else - return 'Received error from ' + adapter + ': ' + errorMessage - } - - 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(Execution execution, int errorCode, String errorMessage) { - MsoUtils utils = new MsoUtils() - def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') - String processKey = getProcessKey(execution); - utils.log("DEBUG", "Building a WorkflowException for " + processKey, isDebugLogEnabled) - - WorkflowException exception = new WorkflowException(processKey, errorCode, errorMessage); - execution.setVariable("WorkflowException", exception); - utils.log("DEBUG", "Outgoing WorkflowException is " + exception, isDebugLogEnabled) - } - - /** - * 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(Execution execution, int errorCode, String errorMessage) { - def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') - String processKey = getProcessKey(execution); - utils.log("Building a WorkflowException for Subflow " + processKey, isDebugLogEnabled) - - WorkflowException exception = new WorkflowException(processKey, errorCode, errorMessage); - execution.setVariable("WorkflowException", exception); - utils.log("DEBUG", "Outgoing WorkflowException is " + exception, isDebugLogEnabled) - utils.log("DEBUG", "Throwing MSOWorkflowException", isDebugLogEnabled) - 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(Execution execution){ - def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - String processKey = getProcessKey(execution) - try{ - utils.log("DEBUG", "Started ProcessSubflowsBPMNException Method", isDebugEnabled) - if(execution.getVariable("WorkflowException") == null){ - buildWorkflowException(execution, 2500, "Internal Error - Occured During " + processKey) - } - - utils.log("DEBUG", processKey + " Outgoing WorkflowException is: " + execution.getVariable("WorkflowException"), isDebugEnabled) - }catch(Exception e){ - utils.log("DEBUG", "Caught Exception during ProcessSubflowsBPMNException Method: " + e, isDebugEnabled) - } - utils.log("DEBUG", "Completed ProcessSubflowsBPMNException Method", isDebugEnabled) - } - - /** - * 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(Execution execution, String requestInfo){ - def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - String processKey = getProcessKey(execution) - try{ - utils.log("DEBUG", "Started ProcessMainflowBPMNException Method", isDebugEnabled) - 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 = wfex.getErrorMessage() - int errorCode = wfex.getErrorCode() - - String falloutHandlerRequest = - """ - ${requestInfo} - - ${errorMessage} - ${errorCode} - - """ - - utils.log("DEBUG", processKey + " Outgoing WorkflowException is: " + execution.getVariable("WorkflowException"), isDebugEnabled) - utils.log("DEBUG", processKey + " Outgoing FalloutHandler Request is: " + falloutHandlerRequest, isDebugEnabled) - - return falloutHandlerRequest - - }catch(Exception e){ - utils.log("DEBUG", "Caught Exception during ProcessMainflowBPMNException Method: " + e, isDebugEnabled) - return null - } - utils.log("DEBUG", "Completed ProcessMainflowBPMNException Method", isDebugEnabled) - } - - /** - * - * This method should only be used by DHV Flows. 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 processMainflowsBPMNExceptionDHV(Execution execution, String requestId, def source, def action, def notificationUrl, def serviceInstanceId, def startTime){ - def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - String processKey = getProcessKey(execution) - try{ - utils.log("DEBUG", "Started ProcessMainflowBPMNExceptionDHV Method", isDebugEnabled) - - def WorkflowException workflowException = execution.getVariable("WorkflowException") - int errorResponseCode = 0 - def errorResponseMsg = "" - if(workflowException != null){ - errorResponseCode = workflowException.getErrorCode() - def errorMsg = workflowException.getErrorMessage() - if (errorMsg != null) { - errorResponseMsg = errorMsg.replace("&", "&").replace("<", "<").replace(">", ">") - } - }else{ - errorResponseCode = 2500 - errorResponseMsg = "Internal Error occured during " + action + ", unable to retrieve error information." - } - - - String request = - """ - - ${requestId} - ${action} - ${source} - ${notificationUrl} - - BPMN - true - JSON - ${serviceInstanceId} - ${startTime} - - ${errorResponseMsg} - ${errorResponseCode} - - """ - - - request = utils.formatXml(request) - utils.log("DEBUG", processKey + " Outgoing WorkflowException is: " + execution.getVariable("WorkflowException"), isDebugEnabled) - utils.log("DEBUG", processKey + " Outgoing FalloutHandler Request is: " + request, isDebugEnabled) - - return request - - }catch(Exception e){ - utils.log("DEBUG", "Caught Exception during ProcessMainflowBPMNException Method: " + e, isDebugEnabled) - return null - } - utils.log("DEBUG", "Completed ProcessMainflowBPMNExceptionDHV Method", isDebugEnabled) - } - - /** - * This method is executed after an Java Exception is caught. - * It sets the WorkflowException variable and throws an MSOWorkflowException. - * - * @param - execution - * - */ - @Deprecated - public void processSubflowsJavaException(Execution execution){ - def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - String processKey = getProcessKey(execution) - try{ - utils.log("DEBUG", "Caught a Java Exception in " + processKey, isDebugEnabled) - utils.log("DEBUG", "Started processJavaException Method", isDebugEnabled) - buildAndThrowWorkflowException(execution, 2500, "Catch a Java Lang Exception in " + processKey) - - }catch(BpmnError b){ - throw b - }catch(Exception e){ - utils.log("DEBUG", "Caught Exception during processJavaException Method: " + e, isDebugEnabled) - buildAndThrowWorkflowException(execution, 2500, "Internal Error - During Process Java Exception") - } - utils.log("DEBUG", "Completed processJavaException Method", isDebugEnabled) - } - - /** - * - * 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(Execution execution){ - def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - String processKey = getProcessKey(execution) - try{ - utils.log("DEBUG", "Caught a Java Exception in " + processKey, isDebugEnabled) - utils.log("DEBUG", "Started processJavaException Method", isDebugEnabled) - buildWorkflowException(execution, 2500, "Catch a Java Lang Exception in " + processKey) - - }catch(BpmnError b){ - throw b - }catch(Exception e){ - utils.log("DEBUG", "Caught Exception during processJavaException Method: " + e, isDebugEnabled) - buildWorkflowException(execution, 2500, "Internal Error - During Process Java Exception") - } - utils.log("DEBUG", "Completed processJavaException Method", isDebugEnabled) - } - - - public void preProcessRequest(Execution execution) { - // TODO Auto-generated method stub - - } -} +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.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.runtime.Execution +import org.openecomp.mso.bpmn.core.WorkflowException + +/** + * @version 1.0 + */ +class ExceptionUtil extends AbstractServiceTaskProcessor { + + + /** + * 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, Execution execution) + { + def utils=new MsoUtils() + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + def prefix=execution.getVariable("prefix") + def errorMsg = execution.getVariable(prefix+"ErrorResponse") + utils.log("DEBUG","=========== Begin MapAAIExceptionToWorkflowException ===========",isDebugEnabled) + String text = null + def variables + String errorCode = '5000' + WorkflowException wfex + utils.log("DEBUG","response: " + response, isDebugEnabled) + try{ + try { + //String msg = utils.getNodeXml(response, "Fault") + variables = utils.getMultNodes(response, "variable") + text = utils.getNodeText1(response, "text") + } catch (Exception ex) { + //Ignore the exception - cases include non xml payload + utils.log("DEBUG","error mapping error, ignoring: " + ex,isDebugEnabled) + } + + 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&AI (' + text +')' + utils.log("DEBUG", "ModifiedErrorMessage " + modifiedErrorMessage, isDebugEnabled) + // let $ModifiedErrorMessage := concat( 'Received error from A',$exceptionaai:ampersand,'AI (' ,functx:replace-multi($ErrorMessage,$from,$Variables ),')') + buildWorkflowException(execution, 5000, modifiedErrorMessage) + + wfex = execution.getVariable("WorkflowException") + utils.log("ERROR","Fault:"+ wfex) + return wfex + } else { + try { + errorCode = MapErrorCode(errorMsg) + String mappedErrorMessage = MapErrorMessage(errorMsg, errorCode) + + int errorCodeInt = Integer.parseInt(errorCode) + buildWorkflowException(execution, errorCodeInt, mappedErrorMessage) + + utils.log("DEBUG", "mappedErrorMessage " + mappedErrorMessage, isDebugEnabled) + wfex = execution.getVariable("WorkflowException") + utils.log("ERROR","Fault:"+ wfex, isDebugEnabled) + return wfex + } catch(Exception ex) { + utils.log("DEBUG","error mapping error, return null: " + ex, isDebugEnabled) + return null + + } + } + }catch(Exception e){ + utils.log("DEBUG", "Exception occured during MapAAIExceptionToWorkflowException: " + e, isDebugEnabled) + 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 tags from AAI Response + * and puts it into the WorkflowException's errorMessage. + * + * @param execution the execution + * @param response the aai exception + */ + WorkflowException MapAAIExceptionToWorkflowExceptionGeneric(Execution execution, String response, int resCode){ + def utils=new MsoUtils() + def isDebugLogEnabled = execution.getVariable("isDebugLogEnabled") + utils.log("DEBUG", "Start MapAAIExceptionToWorkflowExceptionGeneric Process", isDebugLogEnabled) + + WorkflowException wfex + try { + if(utils.nodeExists(response, "Fault")){ + String fault = utils.getNodeXml(response, "Fault") + fault = utils.removeXmlPreamble(fault) + fault = fault.replace("", "").replace("", "") + 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) { + utils.log("DEBUG", "Exception Occured during MapAAIExceptionToWorkflowExceptionGeneric: " + ex, isDebugLogEnabled) + buildWorkflowException(execution, resCode, "Internal Error - Occured in MapAAIExceptionToWorkflowExceptionGeneric") + + } + utils.log("DEBUG", "Outgoing WorkflowException is: " + execution.getVariable("WorkflowException"), isDebugLogEnabled) + utils.log("DEBUG", "Completed MapAAIExceptionToWorkflowExceptionGeneric Process", isDebugLogEnabled) + } + + /** + * 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 = wfex.getErrorMessage() + int code = wfex.getErrorCode() + xml = + """ + ${mes} + ${code} + """ + + }else{ + xml = + """ + Internal Error + 2500 + """ + } + 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{ + errorMessage = errorMessage.replace("&", "&").replace("<", "<").replace(">", ">") + 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(Execution execution, int errorCode, String errorMessage) { + MsoUtils utils = new MsoUtils() + def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') + String processKey = getProcessKey(execution); + utils.log("DEBUG", "Building a WorkflowException for " + processKey, isDebugLogEnabled) + + WorkflowException exception = new WorkflowException(processKey, errorCode, errorMessage); + execution.setVariable("WorkflowException", exception); + utils.log("DEBUG", "Outgoing WorkflowException is " + exception, isDebugLogEnabled) + } + + /** + * 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(Execution execution, int errorCode, String errorMessage) { + def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') + String processKey = getProcessKey(execution); + utils.log("Building a WorkflowException for Subflow " + processKey, isDebugLogEnabled) + + WorkflowException exception = new WorkflowException(processKey, errorCode, errorMessage); + execution.setVariable("WorkflowException", exception); + utils.log("DEBUG", "Outgoing WorkflowException is " + exception, isDebugLogEnabled) + utils.log("DEBUG", "Throwing MSOWorkflowException", isDebugLogEnabled) + 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(Execution execution){ + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + String processKey = getProcessKey(execution) + try{ + utils.log("DEBUG", "Started ProcessSubflowsBPMNException Method", isDebugEnabled) + if(execution.getVariable("WorkflowException") == null){ + buildWorkflowException(execution, 2500, "Internal Error - Occured During " + processKey) + } + + utils.log("DEBUG", processKey + " Outgoing WorkflowException is: " + execution.getVariable("WorkflowException"), isDebugEnabled) + }catch(Exception e){ + utils.log("DEBUG", "Caught Exception during ProcessSubflowsBPMNException Method: " + e, isDebugEnabled) + } + utils.log("DEBUG", "Completed ProcessSubflowsBPMNException Method", isDebugEnabled) + } + + /** + * 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(Execution execution, String requestInfo){ + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + String processKey = getProcessKey(execution) + try{ + utils.log("DEBUG", "Started ProcessMainflowBPMNException Method", isDebugEnabled) + 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 = wfex.getErrorMessage() + int errorCode = wfex.getErrorCode() + + String falloutHandlerRequest = + """ + ${requestInfo} + + ${errorMessage} + ${errorCode} + + """ + + utils.log("DEBUG", processKey + " Outgoing WorkflowException is: " + execution.getVariable("WorkflowException"), isDebugEnabled) + utils.log("DEBUG", processKey + " Outgoing FalloutHandler Request is: " + falloutHandlerRequest, isDebugEnabled) + + return falloutHandlerRequest + + }catch(Exception e){ + utils.log("DEBUG", "Caught Exception during ProcessMainflowBPMNException Method: " + e, isDebugEnabled) + return null + } + utils.log("DEBUG", "Completed ProcessMainflowBPMNException Method", isDebugEnabled) + } + + /** + * + * 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(Execution execution){ + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + String processKey = getProcessKey(execution) + try{ + utils.log("DEBUG", "Caught a Java Exception in " + processKey, isDebugEnabled) + utils.log("DEBUG", "Started processJavaException Method", isDebugEnabled) + buildWorkflowException(execution, 2500, "Catch a Java Lang Exception in " + processKey) + + }catch(BpmnError b){ + throw b + }catch(Exception e){ + utils.log("DEBUG", "Caught Exception during processJavaException Method: " + e, isDebugEnabled) + buildWorkflowException(execution, 2500, "Internal Error - During Process Java Exception") + } + utils.log("DEBUG", "Completed processJavaException Method", isDebugEnabled) + } + + + public void preProcessRequest(Execution execution) { + // TODO Auto-generated method stub + + } +} diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/FalloutHandler.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/FalloutHandler.groovy index 62bf7be5ec..282cbb3c69 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/FalloutHandler.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/FalloutHandler.groovy @@ -1,390 +1,390 @@ -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - MSO - * ================================================================================ - * 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.openecomp.mso.bpmn.common.scripts - -import java.text.SimpleDateFormat - -import org.apache.commons.lang3.* -import org.camunda.bpm.engine.runtime.Execution - -public class FalloutHandler extends AbstractServiceTaskProcessor { - String Prefix="FH_" - ExceptionUtil exceptionUtil = new ExceptionUtil() - - public initializeProcessVariables(Execution execution){ - def method = getClass().getSimpleName() + '.initializeProcessVariables(' +'execution=' + execution.getId() +')' - def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') - logDebug('Entered ' + method, isDebugLogEnabled) - - 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) { - logError('Caught exception in ' + method, e) - // exceptionUtil.buildWorkflowException(execution, 2000, "Internal Error - Occured in " + method) - } - } - - public void preProcessRequest (Execution execution) { - def method = getClass().getSimpleName() + '.preProcessRequest(' +'execution=' + execution.getId() +')' - def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') - logDebug('Entered ' + method, isDebugLogEnabled) - - // Initialize flow variables - initializeProcessVariables(execution) - setSuccessIndicator(execution, false) - - try { - String basicAuthValueDB = execution.getVariable("URN_mso_adapters_db_auth") - utils.log("DEBUG", " Obtained BasicAuth userid password for Catalog DB adapter: " + basicAuthValueDB, isDebugLogEnabled) - - def encodedString = utils.getBasicAuth(basicAuthValueDB, execution.getVariable("URN_mso_msoKey")) - execution.setVariable("BasicAuthHeaderValueDB",encodedString) - } catch (IOException ex) { - String dataErrorMessage = " Unable to encode Catalog DB user/password string - " + ex.getMessage() - utils.log("DEBUG", dataErrorMessage, isDebugLogEnabled) - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) - } - - try { - def xml = execution.getVariable("FalloutHandlerRequest") - utils.log("DEBUG", " XML --> " + xml, isDebugLogEnabled) - utils.logAudit("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()) { - utils.log("DEBUG", "********** Incoming notification Url is: " + notificationurl,isDebugLogEnabled); - 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")) - } - utils.logAudit("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) - } - } - utils.logAudit("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.replace("&", "&").replace("<", "<").replace(">", ">") - 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) - } - - utils.log("DEBUG","FH_notification-url-Ok --> " + execution.getVariable("FH_notification-url-Ok"),isDebugLogEnabled) - utils.log("DEBUG","FH_request_id-OK --> " + execution.getVariable("FH_request_id-Ok"),isDebugLogEnabled) - - // set the DHV/Service Instantiation values if specified in the request - execution.setVariable("FH_is_srv_inst_req", String.valueOf("true".equals(utils.getNodeText1(xml, "is-srv-inst-req")))) - utils.log("DEBUG", "FH_is_srv_inst_req --> " + execution.getVariable("FH_is_srv_inst_req"), isDebugLogEnabled) - execution.setVariable("FH_is_json_content", String.valueOf("JSON".equals(utils.getNodeText1(xml, "resp-content-type")))) - utils.log("DEBUG", "FH_is_json_content --> " + execution.getVariable("FH_is_json_content"), isDebugLogEnabled) - execution.setVariable("FH_service_inst_id", utils.getNodeText1(xml, "service-instance-id")) - utils.log("DEBUG", "FH_service_inst_id --> " + execution.getVariable("FH_service_inst_id"), isDebugLogEnabled) - execution.setVariable("FH_start_time", utils.getNodeText1(xml, "start-time")) - utils.log("DEBUG", "FH_start_time --> " + execution.getVariable("FH_start_time"), isDebugLogEnabled) - // 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) { - logError('Caught exception in ' + method, e) - // exceptionUtil.buildWorkflowException(execution, 2000, "Internal Error - Occured in" + method) - } - - utils.log("DEBUG","OUTOF --> Initialize Variables Fallout Handler #########",isDebugLogEnabled); - } - - public String updateRequestPayload (Execution execution){ - def method = getClass().getSimpleName() + '.updateRequestPayload(' +'execution=' + execution.getId() +')' - def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') - logDebug('Entered ' + method, isDebugLogEnabled) - - try { - String payload = """ - - - - - ${execution.getVariable("FH_request_id")} - BPEL - ${execution.getVariable("FH_ErrorMessage")} - ${execution.getVariable("FH_ErrorCode")} - FAILED - ${execution.getVariable("FH_NOTIFY_STATUS")} - - - - """ - - utils.logAudit("updateRequestPayload: " + payload) - execution.setVariable("FH_updateRequestPayload", payload) - return execution.getVariable("FH_updateRequestPayload") - } catch (Exception e) { - logError('Caught exception in ' + method, e) - // exceptionUtil.buildWorkflowException(execution, 2000, "Internal Error - Occured in " + method) - } - } - - public String updateRequestInfraPayload (Execution execution){ - def method = getClass().getSimpleName() + '.updateRequestInfraPayload(' +'execution=' + execution.getId() +')' - def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') - logDebug('Entered ' + method, isDebugLogEnabled) - - try { - String payload = """ - - - - - ${execution.getVariable("FH_request_id")} - BPEL - ${execution.getVariable("FH_ErrorMessage")} - FAILED - 100 - - - - """ - - execution.setVariable("FH_updateRequestInfraPayload", payload) - utils.logAudit("updateRequestInfraPayload: " + payload) - return execution.getVariable("FH_updateRequestInfraPayload") - } catch (Exception e) { - logError('Caught exception in ' + method, e) - // exceptionUtil.buildWorkflowException(execution, 2000, "Internal Error - Occured in " + method) - } - } - - public String updateRequestGammaPayload (Execution execution){ - def method = getClass().getSimpleName() + '.updateRequestGammaPayload(' +'execution=' + execution.getId() +')' - def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') - logDebug('Entered ' + method, isDebugLogEnabled) - - try { - String payload = """ - - - - - ${execution.getVariable("FH_request_id")} - BPEL - ${execution.getVariable("FH_ErrorMessage")} - ${execution.getVariable("FH_ErrorCode")} - FAILED - - - - """ - - execution.setVariable("FH_updateRequestGammaPayload", payload) - utils.logAudit("updateRequestGammaPayload: " + payload) - return execution.getVariable("FH_updateRequestGammaPayload") - } catch (Exception e) { - logError('Caught exception in ' + method, e) - // exceptionUtil.buildWorkflowException(execution, 2000, "Internal Error - Occured in " + method) - } - } - - public String updateResponseStatusPayload (Execution execution){ - def method = getClass().getSimpleName() + '.updateResponseStatusPayload(' +'execution=' + execution.getId() +')' - def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') - logDebug('Entered ' + method, isDebugLogEnabled) - - try { - String payload = """ - - - - - ${execution.getVariable("FH_request_id")} - BPEL - SENDING_FINAL_NOTIFY - - - - """ - - execution.setVariable("FH_updateResponseStatusPayload", payload) - utils.logAudit("updateResponseStatusPayload: " + payload) - return execution.getVariable("FH_updateResponseStatusPayload") - } catch (Exception e) { - logError('Caught exception in ' + method, e) - // exceptionUtil.buildWorkflowException(execution, 2000, "Internal Error - Occured in " + method) - } - } - - public void buildDBWorkflowException(Execution execution, String responseCodeVariable) { - def method = getClass().getSimpleName() + '.buildDBWorkflowException(' + - 'execution=' + execution.getId() + - ', responseCodeVariable=' + responseCodeVariable + ')' - def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') - logDebug('Entered ' + method, isDebugLogEnabled) - - 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) { - logError('Caught exception in ' + method, e) - // exceptionUtil.buildWorkflowException(execution, 2000, "Internal Error - Occured in " + method) - } - } - - /** - * Used to create a workflow response in success and failure cases. - */ - public void postProcessResponse (Execution execution) { - def method = getClass().getSimpleName() + '.postProcessResponse(' +'execution=' + execution.getId() +')' - def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') - logDebug('Entered ' + method, isDebugLogEnabled) - - try { - Boolean success = (Boolean) execution.getVariable("FH_success") - String out = success ? "Fallout Handler Succeeded" : "Fallout Handler Failed"; - - def falloutHandlerResponse = """ - - ${out} - - """ - - falloutHandlerResponse = utils.formatXml(falloutHandlerResponse) - utils.logAudit("FalloutHandler Response: " + falloutHandlerResponse); - - execution.setVariable("FalloutHandlerResponse", falloutHandlerResponse) - execution.setVariable("WorkflowResponse", falloutHandlerResponse) - execution.setVariable("FH_ResponseCode", success ? "200" : "500") - setSuccessIndicator(execution, success) - - logDebug("FalloutHandlerResponse =\n" + falloutHandlerResponse, isDebugLogEnabled) - } catch (Exception e) { - // Do NOT throw WorkflowException! - logError('Caught exception in ' + method, e) - } - } +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.bpmn.common.scripts + +import java.text.SimpleDateFormat + +import org.apache.commons.lang3.* +import org.camunda.bpm.engine.runtime.Execution + +public class FalloutHandler extends AbstractServiceTaskProcessor { + String Prefix="FH_" + ExceptionUtil exceptionUtil = new ExceptionUtil() + + public initializeProcessVariables(Execution execution){ + def method = getClass().getSimpleName() + '.initializeProcessVariables(' +'execution=' + execution.getId() +')' + def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') + logDebug('Entered ' + method, isDebugLogEnabled) + + 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) { + logError('Caught exception in ' + method, e) + // exceptionUtil.buildWorkflowException(execution, 2000, "Internal Error - Occured in " + method) + } + } + + public void preProcessRequest (Execution execution) { + def method = getClass().getSimpleName() + '.preProcessRequest(' +'execution=' + execution.getId() +')' + def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') + logDebug('Entered ' + method, isDebugLogEnabled) + + // Initialize flow variables + initializeProcessVariables(execution) + setSuccessIndicator(execution, false) + + try { + String basicAuthValueDB = execution.getVariable("URN_mso_adapters_db_auth") + utils.log("DEBUG", " Obtained BasicAuth userid password for Catalog DB adapter: " + basicAuthValueDB, isDebugLogEnabled) + + def encodedString = utils.getBasicAuth(basicAuthValueDB, execution.getVariable("URN_mso_msoKey")) + execution.setVariable("BasicAuthHeaderValueDB",encodedString) + } catch (IOException ex) { + String dataErrorMessage = " Unable to encode Catalog DB user/password string - " + ex.getMessage() + utils.log("DEBUG", dataErrorMessage, isDebugLogEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) + } + + try { + def xml = execution.getVariable("FalloutHandlerRequest") + utils.log("DEBUG", " XML --> " + xml, isDebugLogEnabled) + utils.logAudit("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()) { + utils.log("DEBUG", "********** Incoming notification Url is: " + notificationurl,isDebugLogEnabled); + 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")) + } + utils.logAudit("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) + } + } + utils.logAudit("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.replace("&", "&").replace("<", "<").replace(">", ">") + 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) + } + + utils.log("DEBUG","FH_notification-url-Ok --> " + execution.getVariable("FH_notification-url-Ok"),isDebugLogEnabled) + utils.log("DEBUG","FH_request_id-OK --> " + execution.getVariable("FH_request_id-Ok"),isDebugLogEnabled) + + // set the DHV/Service Instantiation values if specified in the request + execution.setVariable("FH_is_srv_inst_req", String.valueOf("true".equals(utils.getNodeText1(xml, "is-srv-inst-req")))) + utils.log("DEBUG", "FH_is_srv_inst_req --> " + execution.getVariable("FH_is_srv_inst_req"), isDebugLogEnabled) + execution.setVariable("FH_is_json_content", String.valueOf("JSON".equals(utils.getNodeText1(xml, "resp-content-type")))) + utils.log("DEBUG", "FH_is_json_content --> " + execution.getVariable("FH_is_json_content"), isDebugLogEnabled) + execution.setVariable("FH_service_inst_id", utils.getNodeText1(xml, "service-instance-id")) + utils.log("DEBUG", "FH_service_inst_id --> " + execution.getVariable("FH_service_inst_id"), isDebugLogEnabled) + execution.setVariable("FH_start_time", utils.getNodeText1(xml, "start-time")) + utils.log("DEBUG", "FH_start_time --> " + execution.getVariable("FH_start_time"), isDebugLogEnabled) + // 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) { + logError('Caught exception in ' + method, e) + // exceptionUtil.buildWorkflowException(execution, 2000, "Internal Error - Occured in" + method) + } + + utils.log("DEBUG","OUTOF --> Initialize Variables Fallout Handler #########",isDebugLogEnabled); + } + + public String updateRequestPayload (Execution execution){ + def method = getClass().getSimpleName() + '.updateRequestPayload(' +'execution=' + execution.getId() +')' + def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') + logDebug('Entered ' + method, isDebugLogEnabled) + + try { + String payload = """ + + + + + ${execution.getVariable("FH_request_id")} + BPEL + ${execution.getVariable("FH_ErrorMessage")} + ${execution.getVariable("FH_ErrorCode")} + FAILED + ${execution.getVariable("FH_NOTIFY_STATUS")} + + + + """ + + utils.logAudit("updateRequestPayload: " + payload) + execution.setVariable("FH_updateRequestPayload", payload) + return execution.getVariable("FH_updateRequestPayload") + } catch (Exception e) { + logError('Caught exception in ' + method, e) + // exceptionUtil.buildWorkflowException(execution, 2000, "Internal Error - Occured in " + method) + } + } + + public String updateRequestInfraPayload (Execution execution){ + def method = getClass().getSimpleName() + '.updateRequestInfraPayload(' +'execution=' + execution.getId() +')' + def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') + logDebug('Entered ' + method, isDebugLogEnabled) + + try { + String payload = """ + + + + + ${execution.getVariable("FH_request_id")} + BPEL + ${execution.getVariable("FH_ErrorMessage")} + FAILED + 100 + + + + """ + + execution.setVariable("FH_updateRequestInfraPayload", payload) + utils.logAudit("updateRequestInfraPayload: " + payload) + return execution.getVariable("FH_updateRequestInfraPayload") + } catch (Exception e) { + logError('Caught exception in ' + method, e) + // exceptionUtil.buildWorkflowException(execution, 2000, "Internal Error - Occured in " + method) + } + } + + public String updateRequestGammaPayload (Execution execution){ + def method = getClass().getSimpleName() + '.updateRequestGammaPayload(' +'execution=' + execution.getId() +')' + def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') + logDebug('Entered ' + method, isDebugLogEnabled) + + try { + String payload = """ + + + + + ${execution.getVariable("FH_request_id")} + BPEL + ${execution.getVariable("FH_ErrorMessage")} + ${execution.getVariable("FH_ErrorCode")} + FAILED + + + + """ + + execution.setVariable("FH_updateRequestGammaPayload", payload) + utils.logAudit("updateRequestGammaPayload: " + payload) + return execution.getVariable("FH_updateRequestGammaPayload") + } catch (Exception e) { + logError('Caught exception in ' + method, e) + // exceptionUtil.buildWorkflowException(execution, 2000, "Internal Error - Occured in " + method) + } + } + + public String updateResponseStatusPayload (Execution execution){ + def method = getClass().getSimpleName() + '.updateResponseStatusPayload(' +'execution=' + execution.getId() +')' + def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') + logDebug('Entered ' + method, isDebugLogEnabled) + + try { + String payload = """ + + + + + ${execution.getVariable("FH_request_id")} + BPEL + SENDING_FINAL_NOTIFY + + + + """ + + execution.setVariable("FH_updateResponseStatusPayload", payload) + utils.logAudit("updateResponseStatusPayload: " + payload) + return execution.getVariable("FH_updateResponseStatusPayload") + } catch (Exception e) { + logError('Caught exception in ' + method, e) + // exceptionUtil.buildWorkflowException(execution, 2000, "Internal Error - Occured in " + method) + } + } + + public void buildDBWorkflowException(Execution execution, String responseCodeVariable) { + def method = getClass().getSimpleName() + '.buildDBWorkflowException(' + + 'execution=' + execution.getId() + + ', responseCodeVariable=' + responseCodeVariable + ')' + def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') + logDebug('Entered ' + method, isDebugLogEnabled) + + 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) { + logError('Caught exception in ' + method, e) + // exceptionUtil.buildWorkflowException(execution, 2000, "Internal Error - Occured in " + method) + } + } + + /** + * Used to create a workflow response in success and failure cases. + */ + public void postProcessResponse (Execution execution) { + def method = getClass().getSimpleName() + '.postProcessResponse(' +'execution=' + execution.getId() +')' + def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') + logDebug('Entered ' + method, isDebugLogEnabled) + + try { + Boolean success = (Boolean) execution.getVariable("FH_success") + String out = success ? "Fallout Handler Succeeded" : "Fallout Handler Failed"; + + def falloutHandlerResponse = """ + + ${out} + + """ + + falloutHandlerResponse = utils.formatXml(falloutHandlerResponse) + utils.logAudit("FalloutHandler Response: " + falloutHandlerResponse); + + execution.setVariable("FalloutHandlerResponse", falloutHandlerResponse) + execution.setVariable("WorkflowResponse", falloutHandlerResponse) + execution.setVariable("FH_ResponseCode", success ? "200" : "500") + setSuccessIndicator(execution, success) + + logDebug("FalloutHandlerResponse =\n" + falloutHandlerResponse, isDebugLogEnabled) + } catch (Exception e) { + // Do NOT throw WorkflowException! + logError('Caught exception in ' + method, e) + } + } } \ No newline at end of file diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/GenerateVfModuleName.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/GenerateVfModuleName.groovy index 8001931525..fba5cbe1b0 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/GenerateVfModuleName.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/GenerateVfModuleName.groovy @@ -1,166 +1,166 @@ -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - MSO - * ================================================================================ - * 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.openecomp.mso.bpmn.common.scripts -import java.io.Serializable; - -import org.camunda.bpm.engine.delegate.BpmnError -import org.camunda.bpm.engine.runtime.Execution -import org.springframework.web.util.UriUtils - -import org.openecomp.mso.bpmn.core.json.JsonUtils -import org.openecomp.mso.bpmn.core.WorkflowException -import org.openecomp.mso.rest.APIResponse; -import org.openecomp.mso.rest.RESTClient -import org.openecomp.mso.rest.RESTConfig - -public class GenerateVfModuleName extends AbstractServiceTaskProcessor{ - - def Prefix="GVFMN_" - ExceptionUtil exceptionUtil = new ExceptionUtil() - - - - public void preProcessRequest(Execution execution) { - def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - - try { - def vnfId = execution.getVariable("vnfId") - utils.log("DEBUG", "vnfId is " + vnfId, isDebugEnabled) - def vnfName = execution.getVariable("vnfName") - utils.log("DEBUG", "vnfName is " + vnfName, isDebugEnabled) - def vfModuleLabel = execution.getVariable("vfModuleLabel") - utils.log("DEBUG", "vfModuleLabel is " + vfModuleLabel, isDebugEnabled) - def personaModelId = execution.getVariable("personaModelId") - utils.log("DEBUG", "personaModelId is " + personaModelId, isDebugEnabled) - 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(Execution execution) { - def isDebugLogEnabled=execution.getVariable("isDebugLogEnabled") - def method = getClass().getSimpleName() + '.queryAAI(' + - 'execution=' + execution.getId() + - ')' - logDebug('Entered ' + method, isDebugLogEnabled) - - try { - def vnfId = execution.getVariable('vnfId') - def personaModelId = execution.getVariable('personaModelId') - - AaiUtil aaiUriUtil = new AaiUtil(this) - String aai_uri = aaiUriUtil.getNetworkGenericVnfUri(execution) - logDebug('AAI URI is: ' + aai_uri, isDebugLogEnabled) - - String endPoint = execution.getVariable("URN_aai_endpoint") + "${aai_uri}/" + UriUtils.encode(vnfId, "UTF-8") + "?depth=1" - utils.logAudit("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'); - logDebug('sending GET to AAI endpoint \'' + endPoint + '\'', isDebugLogEnabled) - APIResponse response = client.httpGet() - utils.logAudit("GenerateVfModuleName - invoking httpGet() to AAI") - - responseData = response.getResponseBodyAsString() - if (responseData != null) { - logDebug("Received generic VNF data: " + responseData, isDebugLogEnabled) - - } - - utils.logAudit("GenerateVfModuleName - queryAAIVfModule Response: " + responseData) - utils.logAudit("GenerateVfModuleName - queryAAIVfModule ResponseCode: " + response.getStatusCode()) - - execution.setVariable('GVFMN_queryAAIVfModuleResponseCode', response.getStatusCode()) - execution.setVariable('GVFMN_queryAAIVfModuleResponse', responseData) - logDebug('Response code:' + response.getStatusCode(), isDebugLogEnabled) - logDebug('Response:' + System.lineSeparator() + responseData, isDebugLogEnabled) - if (response.getStatusCode() == 200) { - // Set the VfModuleXML - if (responseData != null) { - String vfModulesText = utils.getNodeXml(responseData, "vf-modules") - if (vfModulesText == null || vfModulesText.isEmpty()) { - logDebug("There are no VF modules in this VNF yet", isDebugLogEnabled) - 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 = "" - for (i in 0..vfModulesSize-1) { - def vfModuleXml = groovy.xml.XmlUtil.serialize(vfModules[i]) - def personaModelIdFromAAI = utils.getNodeText(vfModuleXml, "persona-model-id") - if (personaModelIdFromAAI != null && personaModelIdFromAAI.equals(personaModelId)) { - matchingVfModules = matchingVfModules + utils.removeXmlPreamble(vfModuleXml) - } - } - matchingVfModules = matchingVfModules + "" - logDebug("Matching VF Modules: " + matchingVfModules, isDebugLogEnabled) - execution.setVariable("GVFMN_vfModuleXml", matchingVfModules) - } - } - } - } catch (Exception ex) { - ex.printStackTrace() - logDebug('Exception occurred while executing AAI GET:' + ex.getMessage(),isDebugLogEnabled) - exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'AAI GET Failed:' + ex.getMessage()) - } - logDebug('Exited ' + method, isDebugLogEnabled) - } catch (BpmnError e) { - throw e; - } catch (Exception e) { - logError('Caught exception in ' + method, e) - exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in queryAAI(): ' + e.getMessage()) - } - - } - - public void generateName (Execution execution) { - def isDebugLogEnabled=execution.getVariable("isDebugLogEnabled") - def method = getClass().getSimpleName() + '.generateName() ' + - 'execution=' + execution.getId() + - ')' - logDebug('Entered ' + method, isDebugLogEnabled) - - String vfModuleXml = execution.getVariable("GVFMN_vfModuleXml") - - String moduleIndex = utils.getLowestUnusedIndex(vfModuleXml) - logDebug("moduleIndex is: " + moduleIndex, isDebugLogEnabled) - def vnfName = execution.getVariable("vnfName") - def vfModuleLabel = execution.getVariable("vfModuleLabel") - def vfModuleName = vnfName + "_" + vfModuleLabel + "_" + moduleIndex - logDebug("vfModuleName is: " + vfModuleName, isDebugLogEnabled) - execution.setVariable("vfModuleName", vfModuleName) - } -} +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.bpmn.common.scripts +import java.io.Serializable; + +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.runtime.Execution +import org.springframework.web.util.UriUtils + +import org.openecomp.mso.bpmn.core.json.JsonUtils +import org.openecomp.mso.bpmn.core.WorkflowException +import org.openecomp.mso.rest.APIResponse; +import org.openecomp.mso.rest.RESTClient +import org.openecomp.mso.rest.RESTConfig + +public class GenerateVfModuleName extends AbstractServiceTaskProcessor{ + + def Prefix="GVFMN_" + ExceptionUtil exceptionUtil = new ExceptionUtil() + + + + public void preProcessRequest(Execution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + + try { + def vnfId = execution.getVariable("vnfId") + utils.log("DEBUG", "vnfId is " + vnfId, isDebugEnabled) + def vnfName = execution.getVariable("vnfName") + utils.log("DEBUG", "vnfName is " + vnfName, isDebugEnabled) + def vfModuleLabel = execution.getVariable("vfModuleLabel") + utils.log("DEBUG", "vfModuleLabel is " + vfModuleLabel, isDebugEnabled) + def personaModelId = execution.getVariable("personaModelId") + utils.log("DEBUG", "personaModelId is " + personaModelId, isDebugEnabled) + 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(Execution execution) { + def isDebugLogEnabled=execution.getVariable("isDebugLogEnabled") + def method = getClass().getSimpleName() + '.queryAAI(' + + 'execution=' + execution.getId() + + ')' + logDebug('Entered ' + method, isDebugLogEnabled) + + try { + def vnfId = execution.getVariable('vnfId') + def personaModelId = execution.getVariable('personaModelId') + + AaiUtil aaiUriUtil = new AaiUtil(this) + String aai_uri = aaiUriUtil.getNetworkGenericVnfUri(execution) + logDebug('AAI URI is: ' + aai_uri, isDebugLogEnabled) + + String endPoint = execution.getVariable("URN_aai_endpoint") + "${aai_uri}/" + UriUtils.encode(vnfId, "UTF-8") + "?depth=1" + utils.logAudit("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'); + logDebug('sending GET to AAI endpoint \'' + endPoint + '\'', isDebugLogEnabled) + APIResponse response = client.httpGet() + utils.logAudit("GenerateVfModuleName - invoking httpGet() to AAI") + + responseData = response.getResponseBodyAsString() + if (responseData != null) { + logDebug("Received generic VNF data: " + responseData, isDebugLogEnabled) + + } + + utils.logAudit("GenerateVfModuleName - queryAAIVfModule Response: " + responseData) + utils.logAudit("GenerateVfModuleName - queryAAIVfModule ResponseCode: " + response.getStatusCode()) + + execution.setVariable('GVFMN_queryAAIVfModuleResponseCode', response.getStatusCode()) + execution.setVariable('GVFMN_queryAAIVfModuleResponse', responseData) + logDebug('Response code:' + response.getStatusCode(), isDebugLogEnabled) + logDebug('Response:' + System.lineSeparator() + responseData, isDebugLogEnabled) + if (response.getStatusCode() == 200) { + // Set the VfModuleXML + if (responseData != null) { + String vfModulesText = utils.getNodeXml(responseData, "vf-modules") + if (vfModulesText == null || vfModulesText.isEmpty()) { + logDebug("There are no VF modules in this VNF yet", isDebugLogEnabled) + 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 = "" + for (i in 0..vfModulesSize-1) { + def vfModuleXml = groovy.xml.XmlUtil.serialize(vfModules[i]) + def personaModelIdFromAAI = utils.getNodeText(vfModuleXml, "persona-model-id") + if (personaModelIdFromAAI != null && personaModelIdFromAAI.equals(personaModelId)) { + matchingVfModules = matchingVfModules + utils.removeXmlPreamble(vfModuleXml) + } + } + matchingVfModules = matchingVfModules + "" + logDebug("Matching VF Modules: " + matchingVfModules, isDebugLogEnabled) + execution.setVariable("GVFMN_vfModuleXml", matchingVfModules) + } + } + } + } catch (Exception ex) { + ex.printStackTrace() + logDebug('Exception occurred while executing AAI GET:' + ex.getMessage(),isDebugLogEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'AAI GET Failed:' + ex.getMessage()) + } + logDebug('Exited ' + method, isDebugLogEnabled) + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + logError('Caught exception in ' + method, e) + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in queryAAI(): ' + e.getMessage()) + } + + } + + public void generateName (Execution execution) { + def isDebugLogEnabled=execution.getVariable("isDebugLogEnabled") + def method = getClass().getSimpleName() + '.generateName() ' + + 'execution=' + execution.getId() + + ')' + logDebug('Entered ' + method, isDebugLogEnabled) + + String vfModuleXml = execution.getVariable("GVFMN_vfModuleXml") + + String moduleIndex = utils.getLowestUnusedIndex(vfModuleXml) + logDebug("moduleIndex is: " + moduleIndex, isDebugLogEnabled) + def vnfName = execution.getVariable("vnfName") + def vfModuleLabel = execution.getVariable("vfModuleLabel") + def vfModuleName = vnfName + "_" + vfModuleLabel + "_" + moduleIndex + logDebug("vfModuleName is: " + vfModuleName, isDebugLogEnabled) + execution.setVariable("vfModuleName", vfModuleName) + } +} diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/GenericDeleteService.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/GenericDeleteService.groovy index 2db3d97853..3784ae2249 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/GenericDeleteService.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/GenericDeleteService.groovy @@ -1,303 +1,308 @@ -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - MSO - * ================================================================================ - * 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.openecomp.mso.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.runtime.Execution -import org.openecomp.mso.rest.APIResponse -import org.springframework.web.util.UriUtils - - -/** - * This class supports the GenericDeleteService Sub Flow. - * This Generic sub flow can be used by any flow for the - * goal of deleting a Service-Instance or Service-Subscription. - * The calling flow must set the GENDS_type variable as "service-instance" - * or "service-subscription". - * - * If the resource-version is not provided by the calling flow - * then this sub flow will query the service-instance or - * service-subscription, prior to deleting it, in order to - * obtain this resource version. Upon successful completion of - * this sub flow the GENDS_SuccessIndicator will be true. A - * MSOWorkflowException will be thrown if an error occurs within this 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 - * response. - * - * Incoming Variables (Service-Instance): - * @param - GENDS_serviceInstanceId - * @param - GENDS_serviceType - * @param - GENDS_globalCustomerId - * @param - GENDS_type - * @param (Optional) - GENDS_resourceVersion - * - * Incoming Variables (Service-Subscription): - * @param - GENDS_serviceType - * @param - GENDS_globalCustomerId - * @param - GENDS_type - * @param (Optional) - GENDS_resourceVersion - * - * - * Outgoing Variables: - * @param - GENDS_SuccessIndicator - * @param - GENDS_FoundIndicator - * @param - WorkflowException - */ -class GenericDeleteService extends AbstractServiceTaskProcessor{ - - String Prefix = "GENDS_" - ExceptionUtil exceptionUtil = new ExceptionUtil() - - /** - * This method validates the incoming variables and - * determines if the resource version was provided - * - * @param - execution - */ - public void preProcessRequest(Execution execution) { - def isDebugEnabled = execution.getVariable("isDebugLogEnabled") - execution.setVariable("prefix",Prefix) - utils.log("DEBUG", " *** STARTED GenericDeleteService PreProcessRequest Process*** ", isDebugEnabled) - - execution.setVariable("GENDS_resourceVersionProvidedFlag", true) - execution.setVariable("GENDS_SuccessIndicator", false) - execution.setVariable("GENDS_FoundIndicator", false) - - try{ - // Get Variables - String globalCustomerId = execution.getVariable("GENDS_globalCustomerId") - String serviceInstanceId = execution.getVariable("GENDS_serviceInstanceId") - String serviceType = execution.getVariable("GENDS_serviceType") - String type = execution.getVariable("GENDS_type") - - if(type != null){ - utils.log("DEBUG", "Incoming GENDS_type is: " + type, isDebugEnabled) - if(isBlank(globalCustomerId) || isBlank(serviceType)){ - utils.log("DEBUG", "Incoming Required Variable is null!", isDebugEnabled) - exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Incoming Required Variable is Missing or Null!") - }else{ - utils.log("DEBUG", "Incoming Global Customer Id is: " + globalCustomerId, isDebugEnabled) - utils.log("DEBUG", "Incoming Service Type is: " + serviceType, isDebugEnabled) - if(type.equalsIgnoreCase("service-instance")){ - if(isBlank(serviceInstanceId)){ - utils.log("DEBUG", "Incoming Required Variable is null!", isDebugEnabled) - exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Incoming Required Variable is Missing or Null!") - }else{ - utils.log("DEBUG", "Incoming Service Instance Id is: " + serviceInstanceId, isDebugEnabled) - utils.log("DEBUG", "Preparing Delete Service-Instance Process", isDebugEnabled) - } - }else if(type.equalsIgnoreCase("service-subscription")){ - utils.log("DEBUG", "Preparing Delete Service-Subscription Process", isDebugEnabled) - }else{ - exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Incoming Type is Invalid. Please Specify Type as service-instance or service-subscription") - } - } - - String resourceVersion = execution.getVariable('GENDS_resourceVersion') - if(isBlank(resourceVersion)){ - utils.log("DEBUG", "Service Instance Resource Version is NOT Provided", isDebugEnabled) - execution.setVariable("GENDS_resourceVersionProvidedFlag", false) - }else{ - utils.log("DEBUG", "Incoming SI Resource Version is: " + resourceVersion, isDebugEnabled) - } - - }else{ - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Incoming GENDS_type is null. Variable is Required.") - } - }catch(BpmnError b){ - utils.log("DEBUG", "Rethrowing MSOWorkflowException", isDebugEnabled) - throw b - }catch(Exception e){ - utils.log("ERROR", " Error encountered within GenericDeleteService PreProcessRequest method!" + e, isDebugEnabled) - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured in GenericDeleteService PreProcessRequest") - - } - utils.log("DEBUG", "*** COMPLETED GenericDeleteService PreProcessRequest Process ***", isDebugEnabled) - } - - /** - * This method executes a GET call to AAI for the service instance - * or service-subscription so that the objects's resource-version - * can be obtained. - * - * @param - execution - */ - public void getServiceResourceVersion(Execution execution){ - def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - execution.setVariable("prefix",Prefix) - utils.log("DEBUG", " *** STARTED GenericDeleteService GetServiceResourceVersion Process*** ", isDebugEnabled) - try { - String serviceType = execution.getVariable("GENDS_serviceType") - utils.log("DEBUG", " Incoming GENDS_serviceType is: " + serviceType, isDebugEnabled) - String globalCustomerId = execution.getVariable("GENDS_globalCustomerId") - utils.log("DEBUG", "Incoming Global Customer Id is: " + globalCustomerId, isDebugEnabled) - String type = execution.getVariable("GENDS_type") - String serviceEndpoint = "" - - if(type.equalsIgnoreCase("service-instance")){ - String serviceInstanceId = execution.getVariable("GENDS_serviceInstanceId") - utils.log("DEBUG", " Incoming GENDS_serviceInstanceId is: " + serviceInstanceId, isDebugEnabled) - serviceEndpoint = UriUtils.encode(globalCustomerId,"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")){ - serviceEndpoint = UriUtils.encode(globalCustomerId,"UTF-8") + "/service-subscriptions/service-subscription/" + UriUtils.encode(serviceType,"UTF-8") - } - - String aai_endpoint = execution.getVariable("URN_aai_endpoint") - AaiUtil aaiUriUtil = new AaiUtil(this) - String aai_uri = aaiUriUtil.getBusinessCustomerUri(execution) - logDebug('AAI URI is: ' + aai_uri, isDebugEnabled) - - String serviceAaiPath = "${aai_endpoint}${aai_uri}/" + serviceEndpoint - - execution.setVariable("GENDS_serviceAaiPath", serviceAaiPath) - utils.log("DEBUG", "GET Service Instance AAI Path is: " + "\n" + serviceAaiPath, isDebugEnabled) - utils.logAudit("GenericDeleteService GET AAI Path: " + serviceAaiPath) - - APIResponse response = aaiUriUtil.executeAAIGetCall(execution, serviceAaiPath) - int responseCode = response.getStatusCode() - execution.setVariable("GENDS_getServiceResponseCode", responseCode) - utils.log("DEBUG", " GET Service Instance response code is: " + responseCode, isDebugEnabled) - utils.logAudit("GET Service Instance response code: " + responseCode) - - String aaiResponse = response.getResponseBodyAsString() - aaiResponse = StringEscapeUtils.unescapeXml(aaiResponse) - execution.setVariable("GENDS_getServiceResponse", aaiResponse) - - utils.logAudit("GET Service Instance response : " + aaiResponse) - //Process Response - if(responseCode == 200 || responseCode == 202){ - utils.log("DEBUG", "GET Service Received a Good Response: \n" + aaiResponse, isDebugEnabled) - execution.setVariable("GENDS_SuccessIndicator", true) - execution.setVariable("GENDS_FoundIndicator", true) - String resourceVersion = utils.getNodeText1(aaiResponse, "resource-version") - execution.setVariable("GENDS_resourceVersion", resourceVersion) - utils.log("DEBUG", type + " Resource Version is: " + resourceVersion, isDebugEnabled) - - }else if(responseCode == 404){ - utils.log("DEBUG", "GET Service Received a Not Found (404) Response", isDebugEnabled) - execution.setVariable("GENDS_SuccessIndicator", true) - execution.setVariable("WorkflowResponse", " ") // for junits - } - else{ - utils.log("DEBUG", " GET Service Received a Bad Response: \n" + aaiResponse, isDebugEnabled) - exceptionUtil.MapAAIExceptionToWorkflowExceptionGeneric(execution, aaiResponse, responseCode) - throw new BpmnError("MSOWorkflowException") - } - }catch(BpmnError b){ - utils.log("DEBUG", "Rethrowing MSOWorkflowException", isDebugEnabled) - throw b - }catch(Exception e){ - utils.log("DEBUG", " Error encountered within GenericDeleteService GetServiceResourceVersion method!" + e, isDebugEnabled) - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured During GetServiceResourceVersion") - } - utils.log("DEBUG", " *** COMPLETED GenericDeleteService GetServiceResourceVersion Process*** ", isDebugEnabled) - } - - /** - * This method executes a DELETE call to AAI for the provided - * service-instance or service-subscription. - * - * @param - execution - */ - public void deleteServiceObject(Execution execution){ - def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - execution.setVariable("prefix",Prefix) - utils.log("DEBUG", " *** STARTED GenericDeleteService DeleteServiceObject Process*** ", isDebugEnabled) - try { - AaiUtil aaiUriUtil = new AaiUtil(this) - String type = execution.getVariable("GENDS_type") - String serviceAaiPath = execution.getVariable("GENDS_serviceAaiPath") - String serviceEndpoint = "" - - if(isEmpty(serviceAaiPath)){ - String serviceType = execution.getVariable("GENDS_serviceType") - utils.log("DEBUG", " Incoming GENDS_serviceType is: " + serviceType, isDebugEnabled) - String globalCustomerId = execution.getVariable("GENDS_globalCustomerId") - utils.log("DEBUG", "Incoming Global Customer Id is: " + globalCustomerId, isDebugEnabled) - if(type.equalsIgnoreCase("service-instance")){ - String serviceInstanceId = execution.getVariable("GENDS_serviceInstanceId") - utils.log("DEBUG", " Incoming GENDS_serviceInstanceId is: " + serviceInstanceId, isDebugEnabled) - serviceEndpoint = UriUtils.encode(globalCustomerId,"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")){ - serviceEndpoint = UriUtils.encode(globalCustomerId,"UTF-8") + "/service-subscriptions/service-subscription/" + UriUtils.encode(serviceType,"UTF-8") - } - - String aai_endpoint = execution.getVariable("URN_aai_endpoint") - String aai_uri = aaiUriUtil.getBusinessCustomerUri(execution) - logDebug('AAI URI is: ' + aai_uri, isDebugEnabled) - - serviceAaiPath = "${aai_endpoint}${aai_uri}/" + serviceEndpoint - } - - String resourceVersion = execution.getVariable("GENDS_resourceVersion") - utils.log("DEBUG", "Incoming Resource Version is: " + resourceVersion, isDebugEnabled) - if(resourceVersion !=null){ - serviceAaiPath = serviceAaiPath +'?resource-version=' + UriUtils.encode(resourceVersion,"UTF-8") - } - - execution.setVariable("GENDS_deleteServiceAaiPath", serviceAaiPath) - utils.log("DEBUG", "DELETE Service AAI Path is: " + "\n" + serviceAaiPath, isDebugEnabled) - utils.logAudit("DELETE Service AAI Path: " + serviceAaiPath) - - APIResponse response = aaiUriUtil.executeAAIDeleteCall(execution, serviceAaiPath) - int responseCode = response.getStatusCode() - execution.setVariable("GENDS_deleteServiceResponseCode", responseCode) - utils.log("DEBUG", " DELETE Service response code is: " + responseCode, isDebugEnabled) - utils.logAudit("DELETE Service Response Code: " + responseCode) - - String aaiResponse = response.getResponseBodyAsString() - aaiResponse = StringEscapeUtils.unescapeXml(aaiResponse) - execution.setVariable("GENDS_deleteServiceResponse", aaiResponse) - utils.logAudit("DELETE Service Response: " + aaiResponse) - - //Process Response - if(responseCode == 200 || responseCode == 204){ - utils.log("DEBUG", " DELETE Service Received a Good Response", isDebugEnabled) - execution.setVariable("GENDS_FoundIndicator", true) - }else if(responseCode == 404){ - utils.log("DEBUG", " DELETE Service Received a Not Found (404) Response", isDebugEnabled) - execution.setVariable("GENDS_FoundIndicator", false) - }else{ - utils.log("DEBUG", "DELETE Service Received a BAD REST Response: \n" + aaiResponse, isDebugEnabled) - exceptionUtil.MapAAIExceptionToWorkflowExceptionGeneric(execution, aaiResponse, responseCode) - throw new BpmnError("MSOWorkflowException") - } - }catch(BpmnError b){ - utils.log("DEBUG", "Rethrowing MSOWorkflowException", isDebugEnabled) - throw b - }catch(Exception e){ - utils.log("DEBUG", " Error encountered within GenericDeleteService DeleteServiceObject method!" + e, isDebugEnabled) - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured During Delete Service Object") - } - utils.log("DEBUG", " *** COMPLETED GenericDeleteService DeleteServiceObject Process*** ", isDebugEnabled) - } - -} +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.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.runtime.Execution +import org.openecomp.mso.rest.APIResponse +import org.springframework.web.util.UriUtils + + +/** + * This class supports the GenericDeleteService Sub Flow. + * This Generic sub flow can be used by any flow for the + * goal of deleting a Service-Instance or Service-Subscription. + * The calling flow must set the GENDS_type variable as "service-instance" + * or "service-subscription". + * + * If the resource-version is not provided by the calling flow + * then this sub flow will query the service-instance or + * service-subscription, prior to deleting it, in order to + * obtain this resource version. Upon successful completion of + * this sub flow the GENDS_SuccessIndicator will be true. A + * MSOWorkflowException will be thrown if an error occurs within this 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 + * response. + * + * + * Variable Mapping Below + * + * In Mapping Variables: + * For Service-Instance: + * @param - GENDS_serviceInstanceId + * @param - GENDS_serviceType + * @param - GENDS_globalCustomerId + * @param - GENDS_type + * @param (Optional) - GENDS_resourceVersion + * + * For Service-Subscription: + * @param - GENDS_serviceType + * @param - GENDS_globalCustomerId + * @param - GENDS_type + * @param (Optional) - GENDS_resourceVersion + * + * + * Out Mapping Variables: + * @param - GENDS_FoundIndicator + * @param - WorkflowException + * + * + */ +class GenericDeleteService extends AbstractServiceTaskProcessor{ + + String Prefix = "GENDS_" + ExceptionUtil exceptionUtil = new ExceptionUtil() + + /** + * This method validates the incoming variables and + * determines if the resource version was provided + * + * @param - execution + */ + public void preProcessRequest(Execution execution) { + def isDebugEnabled = execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix",Prefix) + utils.log("DEBUG", " *** STARTED GenericDeleteService PreProcessRequest Process*** ", isDebugEnabled) + + execution.setVariable("GENDS_resourceVersionProvidedFlag", true) + execution.setVariable("GENDS_SuccessIndicator", false) + execution.setVariable("GENDS_FoundIndicator", false) + + try{ + // Get Variables + String globalCustomerId = execution.getVariable("GENDS_globalCustomerId") + String serviceInstanceId = execution.getVariable("GENDS_serviceInstanceId") + String serviceType = execution.getVariable("GENDS_serviceType") + String type = execution.getVariable("GENDS_type") + + if(type != null){ + utils.log("DEBUG", "Incoming GENDS_type is: " + type, isDebugEnabled) + if(isBlank(globalCustomerId) || isBlank(serviceType)){ + utils.log("DEBUG", "Incoming Required Variable is null!", isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Incoming Required Variable is Missing or Null!") + }else{ + utils.log("DEBUG", "Incoming Global Customer Id is: " + globalCustomerId, isDebugEnabled) + utils.log("DEBUG", "Incoming Service Type is: " + serviceType, isDebugEnabled) + if(type.equalsIgnoreCase("service-instance")){ + if(isBlank(serviceInstanceId)){ + utils.log("DEBUG", "Incoming Required Variable is null!", isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Incoming Required Variable is Missing or Null!") + }else{ + utils.log("DEBUG", "Incoming Service Instance Id is: " + serviceInstanceId, isDebugEnabled) + utils.log("DEBUG", "Preparing Delete Service-Instance Process", isDebugEnabled) + } + }else if(type.equalsIgnoreCase("service-subscription")){ + utils.log("DEBUG", "Preparing Delete Service-Subscription Process", isDebugEnabled) + }else{ + exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Incoming Type is Invalid. Please Specify Type as service-instance or service-subscription") + } + } + + String resourceVersion = execution.getVariable('GENDS_resourceVersion') + if(isBlank(resourceVersion)){ + utils.log("DEBUG", "Service Instance Resource Version is NOT Provided", isDebugEnabled) + execution.setVariable("GENDS_resourceVersionProvidedFlag", false) + }else{ + utils.log("DEBUG", "Incoming SI Resource Version is: " + resourceVersion, isDebugEnabled) + } + + }else{ + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Incoming GENDS_type is null. Variable is Required.") + } + }catch(BpmnError b){ + utils.log("DEBUG", "Rethrowing MSOWorkflowException", isDebugEnabled) + throw b + }catch(Exception e){ + utils.log("ERROR", " Error encountered within GenericDeleteService PreProcessRequest method!" + e, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured in GenericDeleteService PreProcessRequest") + + } + utils.log("DEBUG", "*** COMPLETED GenericDeleteService PreProcessRequest Process ***", isDebugEnabled) + } + + /** + * This method executes a GET call to AAI for the service instance + * or service-subscription so that the objects's resource-version + * can be obtained. + * + * @param - execution + */ + public void getServiceResourceVersion(Execution execution){ + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix",Prefix) + utils.log("DEBUG", " *** STARTED GenericDeleteService GetServiceResourceVersion Process*** ", isDebugEnabled) + try { + String serviceType = execution.getVariable("GENDS_serviceType") + utils.log("DEBUG", " Incoming GENDS_serviceType is: " + serviceType, isDebugEnabled) + String globalCustomerId = execution.getVariable("GENDS_globalCustomerId") + utils.log("DEBUG", "Incoming Global Customer Id is: " + globalCustomerId, isDebugEnabled) + String type = execution.getVariable("GENDS_type") + String serviceEndpoint = "" + + if(type.equalsIgnoreCase("service-instance")){ + String serviceInstanceId = execution.getVariable("GENDS_serviceInstanceId") + utils.log("DEBUG", " Incoming GENDS_serviceInstanceId is: " + serviceInstanceId, isDebugEnabled) + serviceEndpoint = UriUtils.encode(globalCustomerId,"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")){ + serviceEndpoint = UriUtils.encode(globalCustomerId,"UTF-8") + "/service-subscriptions/service-subscription/" + UriUtils.encode(serviceType,"UTF-8") + } + + String aai_endpoint = execution.getVariable("URN_aai_endpoint") + AaiUtil aaiUriUtil = new AaiUtil(this) + String aai_uri = aaiUriUtil.getBusinessCustomerUri(execution) + logDebug('AAI URI is: ' + aai_uri, isDebugEnabled) + + String serviceAaiPath = "${aai_endpoint}${aai_uri}/" + serviceEndpoint + + execution.setVariable("GENDS_serviceAaiPath", serviceAaiPath) + utils.log("DEBUG", "GET Service Instance AAI Path is: " + "\n" + serviceAaiPath, isDebugEnabled) + utils.logAudit("GenericDeleteService GET AAI Path: " + serviceAaiPath) + + APIResponse response = aaiUriUtil.executeAAIGetCall(execution, serviceAaiPath) + int responseCode = response.getStatusCode() + execution.setVariable("GENDS_getServiceResponseCode", responseCode) + utils.log("DEBUG", " GET Service Instance response code is: " + responseCode, isDebugEnabled) + utils.logAudit("GET Service Instance response code: " + responseCode) + + String aaiResponse = response.getResponseBodyAsString() + aaiResponse = StringEscapeUtils.unescapeXml(aaiResponse) + execution.setVariable("GENDS_getServiceResponse", aaiResponse) + + utils.logAudit("GET Service Instance response : " + aaiResponse) + //Process Response + if(responseCode == 200 || responseCode == 202){ + utils.log("DEBUG", "GET Service Received a Good Response: \n" + aaiResponse, isDebugEnabled) + execution.setVariable("GENDS_SuccessIndicator", true) + execution.setVariable("GENDS_FoundIndicator", true) + String resourceVersion = utils.getNodeText1(aaiResponse, "resource-version") + execution.setVariable("GENDS_resourceVersion", resourceVersion) + utils.log("DEBUG", type + " Resource Version is: " + resourceVersion, isDebugEnabled) + + }else if(responseCode == 404){ + utils.log("DEBUG", "GET Service Received a Not Found (404) Response", isDebugEnabled) + execution.setVariable("GENDS_SuccessIndicator", true) + execution.setVariable("WorkflowResponse", " ") // for junits + } + else{ + utils.log("DEBUG", " GET Service Received a Bad Response: \n" + aaiResponse, isDebugEnabled) + exceptionUtil.MapAAIExceptionToWorkflowExceptionGeneric(execution, aaiResponse, responseCode) + throw new BpmnError("MSOWorkflowException") + } + }catch(BpmnError b){ + utils.log("DEBUG", "Rethrowing MSOWorkflowException", isDebugEnabled) + throw b + }catch(Exception e){ + utils.log("DEBUG", " Error encountered within GenericDeleteService GetServiceResourceVersion method!" + e, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured During GetServiceResourceVersion") + } + utils.log("DEBUG", " *** COMPLETED GenericDeleteService GetServiceResourceVersion Process*** ", isDebugEnabled) + } + + /** + * This method executes a DELETE call to AAI for the provided + * service-instance or service-subscription. + * + * @param - execution + */ + public void deleteServiceObject(Execution execution){ + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix",Prefix) + utils.log("DEBUG", " *** STARTED GenericDeleteService DeleteServiceObject Process*** ", isDebugEnabled) + try { + AaiUtil aaiUriUtil = new AaiUtil(this) + String type = execution.getVariable("GENDS_type") + String serviceAaiPath = execution.getVariable("GENDS_serviceAaiPath") + String serviceEndpoint = "" + + if(isEmpty(serviceAaiPath)){ + String serviceType = execution.getVariable("GENDS_serviceType") + utils.log("DEBUG", " Incoming GENDS_serviceType is: " + serviceType, isDebugEnabled) + String globalCustomerId = execution.getVariable("GENDS_globalCustomerId") + utils.log("DEBUG", "Incoming Global Customer Id is: " + globalCustomerId, isDebugEnabled) + if(type.equalsIgnoreCase("service-instance")){ + String serviceInstanceId = execution.getVariable("GENDS_serviceInstanceId") + utils.log("DEBUG", " Incoming GENDS_serviceInstanceId is: " + serviceInstanceId, isDebugEnabled) + serviceEndpoint = UriUtils.encode(globalCustomerId,"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")){ + serviceEndpoint = UriUtils.encode(globalCustomerId,"UTF-8") + "/service-subscriptions/service-subscription/" + UriUtils.encode(serviceType,"UTF-8") + } + + String aai_endpoint = execution.getVariable("URN_aai_endpoint") + String aai_uri = aaiUriUtil.getBusinessCustomerUri(execution) + logDebug('AAI URI is: ' + aai_uri, isDebugEnabled) + + serviceAaiPath = "${aai_endpoint}${aai_uri}/" + serviceEndpoint + } + + String resourceVersion = execution.getVariable("GENDS_resourceVersion") + utils.log("DEBUG", "Incoming Resource Version is: " + resourceVersion, isDebugEnabled) + if(resourceVersion !=null){ + serviceAaiPath = serviceAaiPath +'?resource-version=' + UriUtils.encode(resourceVersion,"UTF-8") + } + + execution.setVariable("GENDS_deleteServiceAaiPath", serviceAaiPath) + utils.log("DEBUG", "DELETE Service AAI Path is: " + "\n" + serviceAaiPath, isDebugEnabled) + utils.logAudit("DELETE Service AAI Path: " + serviceAaiPath) + + APIResponse response = aaiUriUtil.executeAAIDeleteCall(execution, serviceAaiPath) + int responseCode = response.getStatusCode() + execution.setVariable("GENDS_deleteServiceResponseCode", responseCode) + utils.log("DEBUG", " DELETE Service response code is: " + responseCode, isDebugEnabled) + utils.logAudit("DELETE Service Response Code: " + responseCode) + + String aaiResponse = response.getResponseBodyAsString() + aaiResponse = StringEscapeUtils.unescapeXml(aaiResponse) + execution.setVariable("GENDS_deleteServiceResponse", aaiResponse) + utils.logAudit("DELETE Service Response: " + aaiResponse) + + //Process Response + if(responseCode == 200 || responseCode == 204){ + utils.log("DEBUG", " DELETE Service Received a Good Response", isDebugEnabled) + execution.setVariable("GENDS_FoundIndicator", true) + }else if(responseCode == 404){ + utils.log("DEBUG", " DELETE Service Received a Not Found (404) Response", isDebugEnabled) + execution.setVariable("GENDS_FoundIndicator", false) + }else{ + utils.log("DEBUG", "DELETE Service Received a BAD REST Response: \n" + aaiResponse, isDebugEnabled) + exceptionUtil.MapAAIExceptionToWorkflowExceptionGeneric(execution, aaiResponse, responseCode) + throw new BpmnError("MSOWorkflowException") + } + }catch(BpmnError b){ + utils.log("DEBUG", "Rethrowing MSOWorkflowException", isDebugEnabled) + throw b + }catch(Exception e){ + utils.log("DEBUG", " Error encountered within GenericDeleteService DeleteServiceObject method!" + e, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured During Delete Service Object") + } + utils.log("DEBUG", " *** COMPLETED GenericDeleteService DeleteServiceObject Process*** ", isDebugEnabled) + } + +} diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/GenericDeleteVnf.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/GenericDeleteVnf.groovy index 979083377e..1bd4383b74 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/GenericDeleteVnf.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/GenericDeleteVnf.groovy @@ -1,274 +1,278 @@ -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - MSO - * ================================================================================ - * 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.openecomp.mso.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.runtime.Execution -import org.openecomp.mso.rest.APIResponse -import org.springframework.web.util.UriUtils - - -/** - * 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 GENDV_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 - * GENDV_SuccessIndicator will be true and the query response payload - * will be set to GENDV_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 GENDV_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". - * - * - * Incoming Variables: - * @param - GENDV_vnfId - * @param - GENDV_type - * @param (Optional) - GENDV_resourceVersion - * - * - * Outgoing Variables: - * @param - GENDV_vnf - * @param - GENDV_SuccessIndicator - * @param - GENDV_FoundIndicator - * @param - WorkflowException - */ -class GenericDeleteVnf extends AbstractServiceTaskProcessor{ - - String Prefix = "GENDV_" - ExceptionUtil exceptionUtil = new ExceptionUtil() - - /** - * This method validates the incoming variables and - * determines if the resource version was provided - * - * @param - execution - */ - public void preProcessRequest(Execution execution) { - def isDebugEnabled = execution.getVariable("isDebugLogEnabled") - execution.setVariable("prefix",Prefix) - utils.log("DEBUG", " *** STARTED GenericDeleteVnf PreProcessRequest Process*** ", isDebugEnabled) - - execution.setVariable("GENDV_resourceVersionProvided", true) - execution.setVariable("GENDV_SuccessIndicator", false) - execution.setVariable("GENDV_FoundIndicator", false) - - try{ - // Get Variables - String vnfId = execution.getVariable("GENDV_vnfId") - String type = execution.getVariable("GENDV_type") - - if(isBlank(type) || isBlank(vnfId)){ - utils.log("ERROR", "Incoming Required Variable is null!", isDebugEnabled) - exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Incoming Required Variable is Missing or Null!") - }else{ - utils.log("DEBUG", "Incoming Vnf Id is: " + vnfId, isDebugEnabled) - - String resourceVersion = execution.getVariable("GENDV_resourceVersion") - if(isBlank(resourceVersion)){ - utils.log("DEBUG", "Vnf Resource Version is NOT Provided", isDebugEnabled) - execution.setVariable("GENDV_resourceVersionProvided", false) - }else{ - utils.log("DEBUG", "Incoming Vnf Resource Version is: " + resourceVersion, isDebugEnabled) - } - } - }catch(BpmnError b){ - utils.log("DEBUG", "Rethrowing MSOWorkflowException", isDebugEnabled) - throw b - }catch(Exception e){ - utils.log("ERROR", " Error encountered within GenericDeleteVnf PreProcessRequest method!" + e, isDebugEnabled) - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured in GenericDeleteVnf PreProcessRequest") - - } - utils.log("DEBUG", "*** COMPLETED GenericDeleteVnf PreProcessRequest Process ***", isDebugEnabled) - } - - /** - * This method executes a GET call to AAI for the Vnf - * so that the Vnf's resource-version can be - * obtained. - * - * @param - execution - */ - public void getVnfResourceVersion(Execution execution){ - def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - execution.setVariable("prefix",Prefix) - utils.log("DEBUG", " *** STARTED GenericDeleteVnf GetVnfResourceVersion Process*** ", isDebugEnabled) - try { - String vnfId = execution.getVariable("GENDV_vnfId") - String type = execution.getVariable("GENDV_type") - utils.log("DEBUG", "Type of Vnf Getting is: " + type, isDebugEnabled) - - String aai_endpoint = execution.getVariable("URN_aai_endpoint") - 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{ - utils.log("DEBUG", "Invalid Incoming GENDV_type", isDebugEnabled) - exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Invalid Incoming GENDV_type") - } - - String getVnfPath = "${aai_endpoint}${aai_uri}/" + UriUtils.encode(vnfId, "UTF-8") - - execution.setVariable("GENDV_getVnfPath", getVnfPath) - utils.logAudit("Get Vnf Resource Version Url is: " + getVnfPath) - - APIResponse response = aaiUriUtil.executeAAIGetCall(execution, getVnfPath) - int responseCode = response.getStatusCode() - execution.setVariable("GENDV_getVnfResponseCode", responseCode) - utils.log("DEBUG", " GET Vnf response code is: " + responseCode, isDebugEnabled) - - utils.logAudit("GenericDeleteVnf Get VNF Response Code: " + responseCode) - String aaiResponse = response.getResponseBodyAsString() - aaiResponse = StringEscapeUtils.unescapeXml(aaiResponse) - execution.setVariable("GENDV_getVnfResponse", aaiResponse) - - utils.logAudit("GenericDeleteVnf Get VNF Response: " + aaiResponse) - //Process Response - if(responseCode == 200 || responseCode == 202){ - utils.log("DEBUG", "GET Vnf Received a Good Response: \n" + aaiResponse, isDebugEnabled) - execution.setVariable("GENDV_FoundIndicator", true) - if(utils.nodeExists(aaiResponse, "resource-version")){ - String resourceVersion = utils.getNodeText1(aaiResponse, "resource-version") - execution.setVariable("GENDV_resourceVersion", resourceVersion) - utils.log("DEBUG", "SI Resource Version is: " + resourceVersion, isDebugEnabled) - }else{ - utils.log("DEBUG", "GET Vnf for Resource Version Response Does NOT Contain a resource-version", isDebugEnabled) - exceptionUtil.buildAndThrowWorkflowException(execution, 400, "Unable to obtain Vnf resource-version. GET Vnf Response Does NOT Contain a resource-version") - } - - }else if(responseCode == 404){ - utils.log("DEBUG", "GET Vnf Received a Not Found (404) Response", isDebugEnabled) - execution.setVariable("GENDV_SuccessIndicator", true) - execution.setVariable("WorkflowResponse", " ") // for junits - } - else{ - utils.log("DEBUG", " GET Vnf Received a Bad Response: \n" + aaiResponse, isDebugEnabled) - exceptionUtil.MapAAIExceptionToWorkflowExceptionGeneric(execution, aaiResponse, responseCode) - throw new BpmnError("MSOWorkflowException") - } - }catch(BpmnError b){ - utils.log("DEBUG", "Rethrowing MSOWorkflowException", isDebugEnabled) - throw b - }catch(Exception e){ - utils.log("DEBUG", " Error encountered within GenericDeleteVnf GetVnfResourceVersion method!" + e, isDebugEnabled) - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured During GetVnfResourceVersion") - } - utils.log("DEBUG", " *** COMPLETED GenericDeleteVnf GetVnfResourceVersion Process*** ", isDebugEnabled) - } - - /** - * This method executes a DELETE call to AAI for the provided - * Vnf. - * - * @param - execution - */ - public void deleteVnf(Execution execution){ - def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - execution.setVariable("prefix",Prefix) - utils.log("DEBUG", " *** STARTED GenericDeleteVnf DeleteVnf Process*** ", isDebugEnabled) - try { - String vnfId = execution.getVariable("GENDV_vnfId") - String type = execution.getVariable("GENDV_type") - utils.log("DEBUG", "Type of Vnf Getting is: " + type, isDebugEnabled) - String resourceVersion = execution.getVariable("GENDV_resourceVersion") - utils.log("DEBUG", "Incoming Vnf Resource Version is: " + resourceVersion, isDebugEnabled) - - String aai_endpoint = execution.getVariable("URN_aai_endpoint") - 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{ - utils.log("DEBUG", "Invalid Incoming GENDV_type", isDebugEnabled) - exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Invalid Incoming GENDV_type") - } - - String deleteVnfPath = "${aai_endpoint}${aai_uri}/" + UriUtils.encode(vnfId, "UTF-8") +'?resource-version=' + UriUtils.encode(resourceVersion,"UTF-8") - - execution.setVariable("GENDV_deleteVnfPath", deleteVnfPath) - utils.logAudit("Delete Vnf Url is: " + deleteVnfPath) - - APIResponse response = aaiUriUtil.executeAAIDeleteCall(execution, deleteVnfPath) - int responseCode = response.getStatusCode() - execution.setVariable("GENDV_deleteVnfResponseCode", responseCode) - utils.log("DEBUG", " DELETE Vnf response code is: " + responseCode, isDebugEnabled) - - utils.logAudit("GenericDeleteVnf Delete VNF Response Code: " + responseCode) - String aaiResponse = response.getResponseBodyAsString() - aaiResponse = StringEscapeUtils.unescapeXml(aaiResponse) - execution.setVariable("GENDV_deleteVnfResponse", aaiResponse) - - utils.logAudit("GenericDeleteVnf Delete VNF Response: " + aaiResponse) - //Process Response - if(responseCode == 204){ - utils.log("DEBUG", " DELETE Vnf Received a Good Response", isDebugEnabled) - execution.setVariable("GENDV_FoundIndicator", true) - }else if(responseCode == 404){ - utils.log("DEBUG", " DELETE Vnf Received a Not Found (404) Response", isDebugEnabled) - }else if(responseCode == 412){ - utils.log("DEBUG", "DELETE Vnf Received a Resource Version Mismatch Error: \n" + aaiResponse, isDebugEnabled) - exceptionUtil.buildAndThrowWorkflowException(execution, 412, "Delete Vnf Received a resource-version Mismatch Error Response from AAI") - }else{ - utils.log("DEBUG", "DELETE Vnf Received a BAD REST Response: \n" + aaiResponse, isDebugEnabled) - exceptionUtil.MapAAIExceptionToWorkflowExceptionGeneric(execution, aaiResponse, responseCode) - throw new BpmnError("MSOWorkflowException") - } - }catch(BpmnError b){ - utils.log("DEBUG", "Rethrowing MSOWorkflowException", isDebugEnabled) - throw b - }catch(Exception e){ - utils.log("DEBUG", " Error encountered within GenericDeleteVnf DeleteVnf method!" + e, isDebugEnabled) - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured During Delete Vnf") - } - utils.log("DEBUG", " *** COMPLETED GenericDeleteVnf DeleteVnf Process*** ", isDebugEnabled) - } - - -} +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.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.runtime.Execution +import org.openecomp.mso.rest.APIResponse +import org.springframework.web.util.UriUtils + + +/** + * 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 GENDV_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 + * GENDV_SuccessIndicator will be true and the query response payload + * will be set to GENDV_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 GENDV_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 - GENDV_vnfId + * @param - GENDV_type + * @param (Optional) - GENDV_resourceVersion + * + * + * Out Mapping Variables: + * @param - GENDV_vnf + * @param - GENDV_SuccessIndicator + * @param - GENDV_FoundIndicator + * @param - WorkflowException + * + * + */ +class GenericDeleteVnf extends AbstractServiceTaskProcessor{ + + String Prefix = "GENDV_" + ExceptionUtil exceptionUtil = new ExceptionUtil() + + /** + * This method validates the incoming variables and + * determines if the resource version was provided + * + * @param - execution + */ + public void preProcessRequest(Execution execution) { + def isDebugEnabled = execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix",Prefix) + utils.log("DEBUG", " *** STARTED GenericDeleteVnf PreProcessRequest Process*** ", isDebugEnabled) + + execution.setVariable("GENDV_resourceVersionProvided", true) + execution.setVariable("GENDV_SuccessIndicator", false) + execution.setVariable("GENDV_FoundIndicator", false) + + try{ + // Get Variables + String vnfId = execution.getVariable("GENDV_vnfId") + String type = execution.getVariable("GENDV_type") + + if(isBlank(type) || isBlank(vnfId)){ + utils.log("ERROR", "Incoming Required Variable is null!", isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Incoming Required Variable is Missing or Null!") + }else{ + utils.log("DEBUG", "Incoming Vnf Id is: " + vnfId, isDebugEnabled) + + String resourceVersion = execution.getVariable("GENDV_resourceVersion") + if(isBlank(resourceVersion)){ + utils.log("DEBUG", "Vnf Resource Version is NOT Provided", isDebugEnabled) + execution.setVariable("GENDV_resourceVersionProvided", false) + }else{ + utils.log("DEBUG", "Incoming Vnf Resource Version is: " + resourceVersion, isDebugEnabled) + } + } + }catch(BpmnError b){ + utils.log("DEBUG", "Rethrowing MSOWorkflowException", isDebugEnabled) + throw b + }catch(Exception e){ + utils.log("ERROR", " Error encountered within GenericDeleteVnf PreProcessRequest method!" + e, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured in GenericDeleteVnf PreProcessRequest") + + } + utils.log("DEBUG", "*** COMPLETED GenericDeleteVnf PreProcessRequest Process ***", isDebugEnabled) + } + + /** + * This method executes a GET call to AAI for the Vnf + * so that the Vnf's resource-version can be + * obtained. + * + * @param - execution + */ + public void getVnfResourceVersion(Execution execution){ + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix",Prefix) + utils.log("DEBUG", " *** STARTED GenericDeleteVnf GetVnfResourceVersion Process*** ", isDebugEnabled) + try { + String vnfId = execution.getVariable("GENDV_vnfId") + String type = execution.getVariable("GENDV_type") + utils.log("DEBUG", "Type of Vnf Getting is: " + type, isDebugEnabled) + + String aai_endpoint = execution.getVariable("URN_aai_endpoint") + 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{ + utils.log("DEBUG", "Invalid Incoming GENDV_type", isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Invalid Incoming GENDV_type") + } + + String getVnfPath = "${aai_endpoint}${aai_uri}/" + UriUtils.encode(vnfId, "UTF-8") + + execution.setVariable("GENDV_getVnfPath", getVnfPath) + utils.logAudit("Get Vnf Resource Version Url is: " + getVnfPath) + + APIResponse response = aaiUriUtil.executeAAIGetCall(execution, getVnfPath) + int responseCode = response.getStatusCode() + execution.setVariable("GENDV_getVnfResponseCode", responseCode) + utils.log("DEBUG", " GET Vnf response code is: " + responseCode, isDebugEnabled) + + utils.logAudit("GenericDeleteVnf Get VNF Response Code: " + responseCode) + String aaiResponse = response.getResponseBodyAsString() + aaiResponse = StringEscapeUtils.unescapeXml(aaiResponse) + execution.setVariable("GENDV_getVnfResponse", aaiResponse) + + utils.logAudit("GenericDeleteVnf Get VNF Response: " + aaiResponse) + //Process Response + if(responseCode == 200 || responseCode == 202){ + utils.log("DEBUG", "GET Vnf Received a Good Response: \n" + aaiResponse, isDebugEnabled) + execution.setVariable("GENDV_FoundIndicator", true) + if(utils.nodeExists(aaiResponse, "resource-version")){ + String resourceVersion = utils.getNodeText1(aaiResponse, "resource-version") + execution.setVariable("GENDV_resourceVersion", resourceVersion) + utils.log("DEBUG", "SI Resource Version is: " + resourceVersion, isDebugEnabled) + }else{ + utils.log("DEBUG", "GET Vnf for Resource Version Response Does NOT Contain a resource-version", isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 400, "Unable to obtain Vnf resource-version. GET Vnf Response Does NOT Contain a resource-version") + } + + }else if(responseCode == 404){ + utils.log("DEBUG", "GET Vnf Received a Not Found (404) Response", isDebugEnabled) + execution.setVariable("GENDV_SuccessIndicator", true) + execution.setVariable("WorkflowResponse", " ") // for junits + } + else{ + utils.log("DEBUG", " GET Vnf Received a Bad Response: \n" + aaiResponse, isDebugEnabled) + exceptionUtil.MapAAIExceptionToWorkflowExceptionGeneric(execution, aaiResponse, responseCode) + throw new BpmnError("MSOWorkflowException") + } + }catch(BpmnError b){ + utils.log("DEBUG", "Rethrowing MSOWorkflowException", isDebugEnabled) + throw b + }catch(Exception e){ + utils.log("DEBUG", " Error encountered within GenericDeleteVnf GetVnfResourceVersion method!" + e, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured During GetVnfResourceVersion") + } + utils.log("DEBUG", " *** COMPLETED GenericDeleteVnf GetVnfResourceVersion Process*** ", isDebugEnabled) + } + + /** + * This method executes a DELETE call to AAI for the provided + * Vnf. + * + * @param - execution + */ + public void deleteVnf(Execution execution){ + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix",Prefix) + utils.log("DEBUG", " *** STARTED GenericDeleteVnf DeleteVnf Process*** ", isDebugEnabled) + try { + String vnfId = execution.getVariable("GENDV_vnfId") + String type = execution.getVariable("GENDV_type") + utils.log("DEBUG", "Type of Vnf Getting is: " + type, isDebugEnabled) + String resourceVersion = execution.getVariable("GENDV_resourceVersion") + utils.log("DEBUG", "Incoming Vnf Resource Version is: " + resourceVersion, isDebugEnabled) + + String aai_endpoint = execution.getVariable("URN_aai_endpoint") + 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{ + utils.log("DEBUG", "Invalid Incoming GENDV_type", isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Invalid Incoming GENDV_type") + } + + String deleteVnfPath = "${aai_endpoint}${aai_uri}/" + UriUtils.encode(vnfId, "UTF-8") +'?resource-version=' + UriUtils.encode(resourceVersion,"UTF-8") + + execution.setVariable("GENDV_deleteVnfPath", deleteVnfPath) + utils.logAudit("Delete Vnf Url is: " + deleteVnfPath) + + APIResponse response = aaiUriUtil.executeAAIDeleteCall(execution, deleteVnfPath) + int responseCode = response.getStatusCode() + execution.setVariable("GENDV_deleteVnfResponseCode", responseCode) + utils.log("DEBUG", " DELETE Vnf response code is: " + responseCode, isDebugEnabled) + + utils.logAudit("GenericDeleteVnf Delete VNF Response Code: " + responseCode) + String aaiResponse = response.getResponseBodyAsString() + aaiResponse = StringEscapeUtils.unescapeXml(aaiResponse) + execution.setVariable("GENDV_deleteVnfResponse", aaiResponse) + + utils.logAudit("GenericDeleteVnf Delete VNF Response: " + aaiResponse) + //Process Response + if(responseCode == 204){ + utils.log("DEBUG", " DELETE Vnf Received a Good Response", isDebugEnabled) + execution.setVariable("GENDV_FoundIndicator", true) + }else if(responseCode == 404){ + utils.log("DEBUG", " DELETE Vnf Received a Not Found (404) Response", isDebugEnabled) + }else if(responseCode == 412){ + utils.log("DEBUG", "DELETE Vnf Received a Resource Version Mismatch Error: \n" + aaiResponse, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 412, "Delete Vnf Received a resource-version Mismatch Error Response from AAI") + }else{ + utils.log("DEBUG", "DELETE Vnf Received a BAD REST Response: \n" + aaiResponse, isDebugEnabled) + exceptionUtil.MapAAIExceptionToWorkflowExceptionGeneric(execution, aaiResponse, responseCode) + throw new BpmnError("MSOWorkflowException") + } + }catch(BpmnError b){ + utils.log("DEBUG", "Rethrowing MSOWorkflowException", isDebugEnabled) + throw b + }catch(Exception e){ + utils.log("DEBUG", " Error encountered within GenericDeleteVnf DeleteVnf method!" + e, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured During Delete Vnf") + } + utils.log("DEBUG", " *** COMPLETED GenericDeleteVnf DeleteVnf Process*** ", isDebugEnabled) + } + + +} diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/GenericGetService.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/GenericGetService.groovy index 304f33edcc..70ce1ba5cf 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/GenericGetService.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/GenericGetService.groovy @@ -1,381 +1,385 @@ -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - MSO - * ================================================================================ - * 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.openecomp.mso.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.runtime.Execution -import org.openecomp.mso.rest.APIResponse -import org.springframework.web.util.UriUtils - - -/** - * 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". - * - * - * Incoming Variables (Service-Instance): - * @param - GENGS_serviceInstanceId or @param - GENGS_serviceInstanceName - * @param - GENGS_type - * @param (Optional) - GENGS_serviceType - * @param (Optional) - GENGS_globalCustomerId - * - * Incoming Variables (Service-Subscription): - * @param - GENGS_type - * @param - GENGS_serviceType - * @param - GENGS_globalCustomerId - * - * - * Outgoing Variables: - * @param - GENGS_service - * @param - GENGS_SuccessIndicator - * @param - GENGS_FoundIndicator - * @param - WorkflowException - */ -class GenericGetService extends AbstractServiceTaskProcessor{ - - 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(Execution execution) { - def isDebugEnabled = execution.getVariable("isDebugLogEnabled") - execution.setVariable("prefix",Prefix) - utils.log("DEBUG", " *** STARTED GenericGetService PreProcessRequest Process*** ", isDebugEnabled) - - execution.setVariable("GENGS_obtainServiceInstanceUrl", false) - execution.setVariable("GENGS_obtainServiceInstanceUrlByName", false) - execution.setVariable("GENGS_SuccessIndicator", false) - execution.setVariable("GENGS_FoundIndicator", false) - execution.setVariable("GENGS_siResourceLink", null) - - try{ - // Get Variables - 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){ - utils.log("DEBUG", "Incoming GENGS_type is: " + type, isDebugEnabled) - if(type.equalsIgnoreCase("service-instance")){ - if(isBlank(serviceInstanceId) && isBlank(serviceInstanceName)){ - utils.log("DEBUG", "Incoming serviceInstanceId and serviceInstanceName are null. ServiceInstanceId or ServiceInstanceName is required to Get a service-instance.", isDebugEnabled) - exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Incoming serviceInstanceId and serviceInstanceName are null. ServiceInstanceId or ServiceInstanceName is required to Get a service-instance.") - }else{ - utils.log("DEBUG", "Incoming Service Instance Id is: " + serviceInstanceId, isDebugEnabled) - utils.log("DEBUG", "Incoming Service Instance Name is: " + serviceInstanceName, isDebugEnabled) - if(isBlank(globalCustomerId) || isBlank(serviceType)){ - execution.setVariable("GENGS_obtainServiceInstanceUrl", true) - if(isBlank(serviceInstanceId)){ - execution.setVariable("GENGS_obtainServiceInstanceUrlByName", true) - } - }else{ - utils.log("DEBUG", "Incoming Global Customer Id is: " + globalCustomerId, isDebugEnabled) - utils.log("DEBUG", "Incoming Service Type is: " + serviceType, isDebugEnabled) - } - } - }else if(type.equalsIgnoreCase("service-subscription")){ - if(isBlank(serviceType) || isBlank(globalCustomerId)){ - utils.log("DEBUG", "Incoming ServiceType or GlobalCustomerId is null. These variables are required to Get a service-subscription.", isDebugEnabled) - exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Incoming ServiceType or GlobalCustomerId is null. These variables are required to Get a service-subscription.") - }else{ - utils.log("DEBUG", "Incoming Service Type is: " + serviceType, isDebugEnabled) - utils.log("DEBUG", "Incoming Global Customer Id is: " + globalCustomerId, isDebugEnabled) - } - }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){ - utils.log("DEBUG", "Rethrowing MSOWorkflowException", isDebugEnabled) - throw b - }catch(Exception e){ - utils.log("DEBUG", "Internal Error encountered within GenericGetService PreProcessRequest method!" + e, isDebugEnabled) - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured in GenericGetService PreProcessRequest") - - } - utils.log("DEBUG", "*** COMPLETED GenericGetService PreProcessRequest Process ***", isDebugEnabled) - } - - /** - * This method obtains the Url to the provided service instance - * using the Service Instance Id. - * - * @param - execution - */ - public void obtainServiceInstanceUrlById(Execution execution){ - def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - execution.setVariable("prefix",Prefix) - utils.log("DEBUG", " *** STARTED GenericGetService ObtainServiceInstanceUrlById Process*** ", isDebugEnabled) - try { - String serviceInstanceId = execution.getVariable("GENGS_serviceInstanceId") - utils.log("DEBUG", " Querying Node for Service-Instance URL by using Service-Instance Id: " + serviceInstanceId, isDebugEnabled) - - AaiUtil aaiUriUtil = new AaiUtil(this) - String aai_uri = aaiUriUtil.getSearchNodesQueryEndpoint(execution) - String aai_endpoint = execution.getVariable("URN_aai_endpoint") - - utils.logAudit("GenericGetService AAI Endpoint: " + aai_endpoint) - String path = "${aai_uri}?search-node-type=service-instance&filter=service-instance-id:EQUALS:${serviceInstanceId}" - - //String url = "${aai_endpoint}${path}" host name needs to be removed from property - String url = "${path}" - execution.setVariable("GENGS_obtainSIUrlPath", url) - - APIResponse response = aaiUriUtil.executeAAIGetCall(execution, url) - int responseCode = response.getStatusCode() - execution.setVariable("GENGS_obtainSIUrlResponseCode", responseCode) - utils.log("DEBUG", " GET Service Instance response code is: " + responseCode, isDebugEnabled) - utils.logAudit("GenericGetService AAI GET Response Code: " + responseCode) - - String aaiResponse = response.getResponseBodyAsString() - aaiResponse = StringEscapeUtils.unescapeXml(aaiResponse) - execution.setVariable("GENGS_obtainSIUrlResponse", aaiResponse) - utils.logAudit("GenericGetService AAI Response: " + aaiResponse) - //Process Response - if(responseCode == 200){ - utils.log("DEBUG", " Query for Service Instance Url Received a Good Response Code", isDebugEnabled) - execution.setVariable("GENGS_SuccessIndicator", true) - if(utils.nodeExists(aaiResponse, "result-data")){ - utils.log("DEBUG", "Query for Service Instance Url Response Does Contain Data" , isDebugEnabled) - execution.setVariable("GENGS_FoundIndicator", true) - String resourceLink = utils.getNodeText1(aaiResponse, "resource-link") - execution.setVariable("GENGS_siResourceLink", resourceLink) - }else{ - utils.log("DEBUG", "Query for Service Instance Url Response Does NOT Contains Data" , isDebugEnabled) - execution.setVariable("WorkflowResponse", " ") //for junits - } - }else if(responseCode == 404){ - utils.log("DEBUG", " Query for Service Instance Received a Not Found (404) Response", isDebugEnabled) - execution.setVariable("GENGS_SuccessIndicator", true) - execution.setVariable("WorkflowResponse", " ") //for junits - }else{ - utils.log("DEBUG", "Query for Service Instance Received a BAD REST Response: \n" + aaiResponse, isDebugEnabled) - exceptionUtil.MapAAIExceptionToWorkflowExceptionGeneric(execution, aaiResponse, responseCode) - throw new BpmnError("MSOWorkflowException") - } - }catch(BpmnError b){ - utils.log("DEBUG", "Rethrowing MSOWorkflowException", isDebugEnabled) - throw b - }catch(Exception e){ - utils.log("ERROR", " Error encountered within GenericGetService ObtainServiceInstanceUrlById method!" + e, isDebugEnabled) - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured During ObtainServiceInstanceUrlById") - } - utils.log("DEBUG", " *** COMPLETED GenericGetService ObtainServiceInstanceUrlById Process*** ", isDebugEnabled) - } - - /** - * This method obtains the Url to the provided service instance - * using the Service Instance Name. - * - * @param - execution - */ - public void obtainServiceInstanceUrlByName(Execution execution){ - def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - execution.setVariable("prefix",Prefix) - utils.log("DEBUG", " *** STARTED GenericGetService ObtainServiceInstanceUrlByName Process*** ", isDebugEnabled) - try { - String serviceInstanceName = execution.getVariable("GENGS_serviceInstanceName") - utils.log("DEBUG", " Querying Node for Service-Instance URL by using Service-Instance Name " + serviceInstanceName, isDebugEnabled) - - AaiUtil aaiUriUtil = new AaiUtil(this) - String aai_uri = aaiUriUtil.getSearchNodesQueryEndpoint(execution) - String aai_endpoint = execution.getVariable("URN_aai_endpoint") - 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) - - utils.logAudit("GenericGetService AAI Endpoint: " + aai_endpoint) - APIResponse response = aaiUriUtil.executeAAIGetCall(execution, url) - int responseCode = response.getStatusCode() - execution.setVariable("GENGS_obtainSIUrlResponseCode", responseCode) - utils.log("DEBUG", " GET Service Instance response code is: " + responseCode, isDebugEnabled) - utils.logAudit("GenericGetService AAI Response Code: " + responseCode) - - String aaiResponse = response.getResponseBodyAsString() - aaiResponse = StringEscapeUtils.unescapeXml(aaiResponse) - execution.setVariable("GENGS_obtainSIUrlResponse", aaiResponse) - utils.logAudit("GenericGetService AAI Response: " + aaiResponse) - //Process Response - if(responseCode == 200){ - utils.log("DEBUG", " Query for Service Instance Url Received a Good Response Code", isDebugEnabled) - execution.setVariable("GENGS_SuccessIndicator", true) - if(utils.nodeExists(aaiResponse, "result-data")){ - utils.log("DEBUG", "Query for Service Instance Url Response Does Contain Data" , isDebugEnabled) - execution.setVariable("GENGS_FoundIndicator", true) - String resourceLink = utils.getNodeText1(aaiResponse, "resource-link") - execution.setVariable("GENGS_siResourceLink", resourceLink) - }else{ - utils.log("DEBUG", "Query for Service Instance Url Response Does NOT Contains Data" , isDebugEnabled) - execution.setVariable("WorkflowResponse", " ") //for junits - } - }else if(responseCode == 404){ - utils.log("DEBUG", " Query for Service Instance Received a Not Found (404) Response", isDebugEnabled) - execution.setVariable("GENGS_SuccessIndicator", true) - execution.setVariable("WorkflowResponse", " ") //for junits - }else{ - utils.log("DEBUG", "Query for Service Instance Received a BAD REST Response: \n" + aaiResponse, isDebugEnabled) - exceptionUtil.MapAAIExceptionToWorkflowExceptionGeneric(execution, aaiResponse, responseCode) - throw new BpmnError("MSOWorkflowException") - } - }catch(BpmnError b){ - utils.log("DEBUG", "Rethrowing MSOWorkflowException", isDebugEnabled) - throw b - }catch(Exception e){ - utils.log("ERROR", " Error encountered within GenericGetService ObtainServiceInstanceUrlByName method!" + e, isDebugEnabled) - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured During ObtainServiceInstanceUrlByName") - } - utils.log("DEBUG", " *** COMPLETED GenericGetService ObtainServiceInstanceUrlByName Process*** ", isDebugEnabled) - } - - - /** - * This method executes a GET call to AAI to obtain the - * service-instance or service-subscription - * - * @param - execution - */ - public void getServiceObject(Execution execution){ - def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - execution.setVariable("prefix",Prefix) - utils.log("DEBUG", " *** STARTED GenericGetService GetServiceObject Process*** ", isDebugEnabled) - try { - String type = execution.getVariable("GENGS_type") - AaiUtil aaiUriUtil = new AaiUtil(this) - String aai_endpoint = execution.getVariable("URN_aai_endpoint") - String serviceEndpoint = "" - - utils.logAudit("GenericGetService getServiceObject AAI Endpoint: " + aai_endpoint) - if(type.equalsIgnoreCase("service-instance")){ - String siResourceLink = execution.getVariable("GENGS_siResourceLink") - if(isBlank(siResourceLink)){ - String serviceInstanceId = execution.getVariable("GENGS_serviceInstanceId") - utils.log("DEBUG", " Incoming GENGS_serviceInstanceId is: " + serviceInstanceId, isDebugEnabled) - String serviceType = execution.getVariable("GENGS_serviceType") - utils.log("DEBUG", " Incoming GENGS_serviceType is: " + serviceType, isDebugEnabled) - String globalCustomerId = execution.getVariable("GENGS_globalCustomerId") - utils.log("DEBUG", "Incoming Global Customer Id is: " + globalCustomerId, isDebugEnabled) - - String aai_uri = aaiUriUtil.getBusinessCustomerUri(execution) - logDebug('AAI URI is: ' + aai_uri, isDebugEnabled) - 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{ - utils.log("DEBUG", "Incoming Service Instance Resource Link is: " + siResourceLink, isDebugEnabled) - 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) - utils.log("DEBUG", "GET Service AAI Path is: \n" + serviceUrl, isDebugEnabled) - - APIResponse response = aaiUriUtil.executeAAIGetCall(execution, serviceUrl) - int responseCode = response.getStatusCode() - execution.setVariable("GENGS_getServiceResponseCode", responseCode) - utils.log("DEBUG", " GET Service response code is: " + responseCode, isDebugEnabled) - utils.logAudit("GenericGetService AAI Response Code: " + responseCode) - - String aaiResponse = response.getResponseBodyAsString() - aaiResponse = StringEscapeUtils.unescapeXml(aaiResponse) - execution.setVariable("GENGS_getServiceResponse", aaiResponse) - utils.logAudit("GenericGetService AAI Response: " + aaiResponse) - - //Process Response - if(responseCode == 200 || responseCode == 202){ - utils.log("DEBUG", "GET Service Received a Good Response Code", isDebugEnabled) - if(utils.nodeExists(aaiResponse, "service-instance") || utils.nodeExists(aaiResponse, "service-subscription")){ - utils.log("DEBUG", "GET Service Response Contains a service-instance" , isDebugEnabled) - execution.setVariable("GENGS_FoundIndicator", true) - execution.setVariable("GENGS_service", aaiResponse) - execution.setVariable("WorkflowResponse", aaiResponse) - - }else{ - utils.log("DEBUG", "GET Service Response Does NOT Contain Data" , isDebugEnabled) - } - }else if(responseCode == 404){ - utils.log("DEBUG", "GET Service Received a Not Found (404) Response", isDebugEnabled) - execution.setVariable("WorkflowResponse", " ") //for junits - } - else{ - utils.log("DEBUG", " GET Service Received a Bad Response: \n" + aaiResponse, isDebugEnabled) - exceptionUtil.MapAAIExceptionToWorkflowExceptionGeneric(execution, aaiResponse, responseCode) - throw new BpmnError("MSOWorkflowException") - } - }catch(BpmnError b){ - utils.log("DEBUG", "Rethrowing MSOWorkflowException", isDebugEnabled) - throw b - }catch(Exception e){ - utils.log("DEBUG", " Error encountered within GenericGetService GetServiceObject method!" + e, isDebugEnabled) - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured During GenericGetService") - } - utils.log("DEBUG", " *** COMPLETED GenericGetService GetServiceObject Process*** ", isDebugEnabled) - } - -} +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.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.runtime.Execution +import org.openecomp.mso.rest.APIResponse +import org.springframework.web.util.UriUtils + + +/** + * 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 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{ + + 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(Execution execution) { + def isDebugEnabled = execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix",Prefix) + utils.log("DEBUG", " *** STARTED GenericGetService PreProcessRequest Process*** ", isDebugEnabled) + + execution.setVariable("GENGS_obtainServiceInstanceUrl", false) + execution.setVariable("GENGS_obtainServiceInstanceUrlByName", false) + execution.setVariable("GENGS_SuccessIndicator", false) + execution.setVariable("GENGS_FoundIndicator", false) + execution.setVariable("GENGS_siResourceLink", null) + + try{ + // Get Variables + 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){ + utils.log("DEBUG", "Incoming GENGS_type is: " + type, isDebugEnabled) + if(type.equalsIgnoreCase("service-instance")){ + if(isBlank(serviceInstanceId) && isBlank(serviceInstanceName)){ + utils.log("DEBUG", "Incoming serviceInstanceId and serviceInstanceName are null. ServiceInstanceId or ServiceInstanceName is required to Get a service-instance.", isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Incoming serviceInstanceId and serviceInstanceName are null. ServiceInstanceId or ServiceInstanceName is required to Get a service-instance.") + }else{ + utils.log("DEBUG", "Incoming Service Instance Id is: " + serviceInstanceId, isDebugEnabled) + utils.log("DEBUG", "Incoming Service Instance Name is: " + serviceInstanceName, isDebugEnabled) + if(isBlank(globalCustomerId) || isBlank(serviceType)){ + execution.setVariable("GENGS_obtainServiceInstanceUrl", true) + if(isBlank(serviceInstanceId)){ + execution.setVariable("GENGS_obtainServiceInstanceUrlByName", true) + } + }else{ + utils.log("DEBUG", "Incoming Global Customer Id is: " + globalCustomerId, isDebugEnabled) + utils.log("DEBUG", "Incoming Service Type is: " + serviceType, isDebugEnabled) + } + } + }else if(type.equalsIgnoreCase("service-subscription")){ + if(isBlank(serviceType) || isBlank(globalCustomerId)){ + utils.log("DEBUG", "Incoming ServiceType or GlobalCustomerId is null. These variables are required to Get a service-subscription.", isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Incoming ServiceType or GlobalCustomerId is null. These variables are required to Get a service-subscription.") + }else{ + utils.log("DEBUG", "Incoming Service Type is: " + serviceType, isDebugEnabled) + utils.log("DEBUG", "Incoming Global Customer Id is: " + globalCustomerId, isDebugEnabled) + } + }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){ + utils.log("DEBUG", "Rethrowing MSOWorkflowException", isDebugEnabled) + throw b + }catch(Exception e){ + utils.log("DEBUG", "Internal Error encountered within GenericGetService PreProcessRequest method!" + e, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured in GenericGetService PreProcessRequest") + + } + utils.log("DEBUG", "*** COMPLETED GenericGetService PreProcessRequest Process ***", isDebugEnabled) + } + + /** + * This method obtains the Url to the provided service instance + * using the Service Instance Id. + * + * @param - execution + */ + public void obtainServiceInstanceUrlById(Execution execution){ + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix",Prefix) + utils.log("DEBUG", " *** STARTED GenericGetService ObtainServiceInstanceUrlById Process*** ", isDebugEnabled) + try { + String serviceInstanceId = execution.getVariable("GENGS_serviceInstanceId") + utils.log("DEBUG", " Querying Node for Service-Instance URL by using Service-Instance Id: " + serviceInstanceId, isDebugEnabled) + + AaiUtil aaiUriUtil = new AaiUtil(this) + String aai_uri = aaiUriUtil.getSearchNodesQueryEndpoint(execution) + String aai_endpoint = execution.getVariable("URN_aai_endpoint") + + utils.logAudit("GenericGetService AAI Endpoint: " + aai_endpoint) + String path = "${aai_uri}?search-node-type=service-instance&filter=service-instance-id:EQUALS:${serviceInstanceId}" + + //String url = "${aai_endpoint}${path}" host name needs to be removed from property + String url = "${path}" + execution.setVariable("GENGS_obtainSIUrlPath", url) + + APIResponse response = aaiUriUtil.executeAAIGetCall(execution, url) + int responseCode = response.getStatusCode() + execution.setVariable("GENGS_obtainSIUrlResponseCode", responseCode) + utils.log("DEBUG", " GET Service Instance response code is: " + responseCode, isDebugEnabled) + utils.logAudit("GenericGetService AAI GET Response Code: " + responseCode) + + String aaiResponse = response.getResponseBodyAsString() + aaiResponse = StringEscapeUtils.unescapeXml(aaiResponse) + execution.setVariable("GENGS_obtainSIUrlResponse", aaiResponse) + utils.logAudit("GenericGetService AAI Response: " + aaiResponse) + //Process Response + if(responseCode == 200){ + utils.log("DEBUG", " Query for Service Instance Url Received a Good Response Code", isDebugEnabled) + execution.setVariable("GENGS_SuccessIndicator", true) + if(utils.nodeExists(aaiResponse, "result-data")){ + utils.log("DEBUG", "Query for Service Instance Url Response Does Contain Data" , isDebugEnabled) + execution.setVariable("GENGS_FoundIndicator", true) + String resourceLink = utils.getNodeText1(aaiResponse, "resource-link") + execution.setVariable("GENGS_siResourceLink", resourceLink) + }else{ + utils.log("DEBUG", "Query for Service Instance Url Response Does NOT Contains Data" , isDebugEnabled) + execution.setVariable("WorkflowResponse", " ") //for junits + } + }else if(responseCode == 404){ + utils.log("DEBUG", " Query for Service Instance Received a Not Found (404) Response", isDebugEnabled) + execution.setVariable("GENGS_SuccessIndicator", true) + execution.setVariable("WorkflowResponse", " ") //for junits + }else{ + utils.log("DEBUG", "Query for Service Instance Received a BAD REST Response: \n" + aaiResponse, isDebugEnabled) + exceptionUtil.MapAAIExceptionToWorkflowExceptionGeneric(execution, aaiResponse, responseCode) + throw new BpmnError("MSOWorkflowException") + } + }catch(BpmnError b){ + utils.log("DEBUG", "Rethrowing MSOWorkflowException", isDebugEnabled) + throw b + }catch(Exception e){ + utils.log("ERROR", " Error encountered within GenericGetService ObtainServiceInstanceUrlById method!" + e, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured During ObtainServiceInstanceUrlById") + } + utils.log("DEBUG", " *** COMPLETED GenericGetService ObtainServiceInstanceUrlById Process*** ", isDebugEnabled) + } + + /** + * This method obtains the Url to the provided service instance + * using the Service Instance Name. + * + * @param - execution + */ + public void obtainServiceInstanceUrlByName(Execution execution){ + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix",Prefix) + utils.log("DEBUG", " *** STARTED GenericGetService ObtainServiceInstanceUrlByName Process*** ", isDebugEnabled) + try { + String serviceInstanceName = execution.getVariable("GENGS_serviceInstanceName") + utils.log("DEBUG", " Querying Node for Service-Instance URL by using Service-Instance Name " + serviceInstanceName, isDebugEnabled) + + AaiUtil aaiUriUtil = new AaiUtil(this) + String aai_uri = aaiUriUtil.getSearchNodesQueryEndpoint(execution) + String aai_endpoint = execution.getVariable("URN_aai_endpoint") + 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) + + utils.logAudit("GenericGetService AAI Endpoint: " + aai_endpoint) + APIResponse response = aaiUriUtil.executeAAIGetCall(execution, url) + int responseCode = response.getStatusCode() + execution.setVariable("GENGS_obtainSIUrlResponseCode", responseCode) + utils.log("DEBUG", " GET Service Instance response code is: " + responseCode, isDebugEnabled) + utils.logAudit("GenericGetService AAI Response Code: " + responseCode) + + String aaiResponse = response.getResponseBodyAsString() + aaiResponse = StringEscapeUtils.unescapeXml(aaiResponse) + execution.setVariable("GENGS_obtainSIUrlResponse", aaiResponse) + utils.logAudit("GenericGetService AAI Response: " + aaiResponse) + //Process Response + if(responseCode == 200){ + utils.log("DEBUG", " Query for Service Instance Url Received a Good Response Code", isDebugEnabled) + execution.setVariable("GENGS_SuccessIndicator", true) + if(utils.nodeExists(aaiResponse, "result-data")){ + utils.log("DEBUG", "Query for Service Instance Url Response Does Contain Data" , isDebugEnabled) + execution.setVariable("GENGS_FoundIndicator", true) + String resourceLink = utils.getNodeText1(aaiResponse, "resource-link") + execution.setVariable("GENGS_siResourceLink", resourceLink) + }else{ + utils.log("DEBUG", "Query for Service Instance Url Response Does NOT Contains Data" , isDebugEnabled) + execution.setVariable("WorkflowResponse", " ") //for junits + } + }else if(responseCode == 404){ + utils.log("DEBUG", " Query for Service Instance Received a Not Found (404) Response", isDebugEnabled) + execution.setVariable("GENGS_SuccessIndicator", true) + execution.setVariable("WorkflowResponse", " ") //for junits + }else{ + utils.log("DEBUG", "Query for Service Instance Received a BAD REST Response: \n" + aaiResponse, isDebugEnabled) + exceptionUtil.MapAAIExceptionToWorkflowExceptionGeneric(execution, aaiResponse, responseCode) + throw new BpmnError("MSOWorkflowException") + } + }catch(BpmnError b){ + utils.log("DEBUG", "Rethrowing MSOWorkflowException", isDebugEnabled) + throw b + }catch(Exception e){ + utils.log("ERROR", " Error encountered within GenericGetService ObtainServiceInstanceUrlByName method!" + e, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured During ObtainServiceInstanceUrlByName") + } + utils.log("DEBUG", " *** COMPLETED GenericGetService ObtainServiceInstanceUrlByName Process*** ", isDebugEnabled) + } + + + /** + * This method executes a GET call to AAI to obtain the + * service-instance or service-subscription + * + * @param - execution + */ + public void getServiceObject(Execution execution){ + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix",Prefix) + utils.log("DEBUG", " *** STARTED GenericGetService GetServiceObject Process*** ", isDebugEnabled) + try { + String type = execution.getVariable("GENGS_type") + AaiUtil aaiUriUtil = new AaiUtil(this) + String aai_endpoint = execution.getVariable("URN_aai_endpoint") + String serviceEndpoint = "" + + utils.logAudit("GenericGetService getServiceObject AAI Endpoint: " + aai_endpoint) + if(type.equalsIgnoreCase("service-instance")){ + String siResourceLink = execution.getVariable("GENGS_siResourceLink") + if(isBlank(siResourceLink)){ + String serviceInstanceId = execution.getVariable("GENGS_serviceInstanceId") + utils.log("DEBUG", " Incoming GENGS_serviceInstanceId is: " + serviceInstanceId, isDebugEnabled) + String serviceType = execution.getVariable("GENGS_serviceType") + utils.log("DEBUG", " Incoming GENGS_serviceType is: " + serviceType, isDebugEnabled) + String globalCustomerId = execution.getVariable("GENGS_globalCustomerId") + utils.log("DEBUG", "Incoming Global Customer Id is: " + globalCustomerId, isDebugEnabled) + + String aai_uri = aaiUriUtil.getBusinessCustomerUri(execution) + logDebug('AAI URI is: ' + aai_uri, isDebugEnabled) + 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{ + utils.log("DEBUG", "Incoming Service Instance Resource Link is: " + siResourceLink, isDebugEnabled) + 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) + utils.log("DEBUG", "GET Service AAI Path is: \n" + serviceUrl, isDebugEnabled) + + APIResponse response = aaiUriUtil.executeAAIGetCall(execution, serviceUrl) + int responseCode = response.getStatusCode() + execution.setVariable("GENGS_getServiceResponseCode", responseCode) + utils.log("DEBUG", " GET Service response code is: " + responseCode, isDebugEnabled) + utils.logAudit("GenericGetService AAI Response Code: " + responseCode) + + String aaiResponse = response.getResponseBodyAsString() + aaiResponse = StringEscapeUtils.unescapeXml(aaiResponse) + execution.setVariable("GENGS_getServiceResponse", aaiResponse) + utils.logAudit("GenericGetService AAI Response: " + aaiResponse) + + //Process Response + if(responseCode == 200 || responseCode == 202){ + utils.log("DEBUG", "GET Service Received a Good Response Code", isDebugEnabled) + if(utils.nodeExists(aaiResponse, "service-instance") || utils.nodeExists(aaiResponse, "service-subscription")){ + utils.log("DEBUG", "GET Service Response Contains a service-instance" , isDebugEnabled) + execution.setVariable("GENGS_FoundIndicator", true) + execution.setVariable("GENGS_service", aaiResponse) + execution.setVariable("WorkflowResponse", aaiResponse) + + }else{ + utils.log("DEBUG", "GET Service Response Does NOT Contain Data" , isDebugEnabled) + } + }else if(responseCode == 404){ + utils.log("DEBUG", "GET Service Received a Not Found (404) Response", isDebugEnabled) + execution.setVariable("WorkflowResponse", " ") //for junits + } + else{ + utils.log("DEBUG", " GET Service Received a Bad Response: \n" + aaiResponse, isDebugEnabled) + exceptionUtil.MapAAIExceptionToWorkflowExceptionGeneric(execution, aaiResponse, responseCode) + throw new BpmnError("MSOWorkflowException") + } + }catch(BpmnError b){ + utils.log("DEBUG", "Rethrowing MSOWorkflowException", isDebugEnabled) + throw b + }catch(Exception e){ + utils.log("DEBUG", " Error encountered within GenericGetService GetServiceObject method!" + e, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured During GenericGetService") + } + utils.log("DEBUG", " *** COMPLETED GenericGetService GetServiceObject Process*** ", isDebugEnabled) + } + +} diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/GenericGetVnf.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/GenericGetVnf.groovy index 5f03786180..df9a97c78c 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/GenericGetVnf.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/GenericGetVnf.groovy @@ -1,270 +1,273 @@ -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - MSO - * ================================================================================ - * 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.openecomp.mso.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.runtime.Execution -import org.openecomp.mso.rest.APIResponse -import org.springframework.web.util.UriUtils - - -/** - * 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". - * - * - * Incoming Required Variables: - * @param - GENGV_vnfId or @param - GENGV_vnfName - * @param - GENGV_type - * - * - * Outgoing Variables: - * @param - GENGV_vnf - * @param - GENGV_SuccessIndicator - * @param - GENGV_FoundIndicator - * @param - WorkflowException - */ -class GenericGetVnf extends AbstractServiceTaskProcessor{ - - 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(Execution execution) { - def isDebugEnabled = execution.getVariable("isDebugLogEnabled") - execution.setVariable("prefix",Prefix) - utils.log("DEBUG", " *** STARTED GenericGetVnf PreProcessRequest Process*** ", isDebugEnabled) - - execution.setVariable("GENGV_getVnfByName", false) - execution.setVariable("GENGV_SuccessIndicator", false) - execution.setVariable("GENGV_FoundIndicator", false) - - try{ - // Get Variables - String vnfId = execution.getVariable("GENGV_vnfId") - utils.log("DEBUG", "Incoming Vnf Id is: " + vnfId, isDebugEnabled) - String vnfName = execution.getVariable("GENGV_vnfName") - utils.log("DEBUG", "Incoming Vnf Name is: " + vnfName, isDebugEnabled) - - if(isBlank(vnfId) && isBlank(vnfName)){ - utils.log("DEBUG", "Incoming Vnf Name and Vnf Id are null. At least one is required!", isDebugEnabled) - 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){ - utils.log("DEBUG", "Rethrowing MSOWorkflowException", isDebugEnabled) - throw b - }catch(Exception e){ - utils.log("DEBUG", " Error encountered within GenericGetVnf PreProcessRequest method!" + e, isDebugEnabled) - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured in GenericGetVnf PreProcessRequest") - - } - utils.log("DEBUG", "*** COMPLETED GenericGetVnf PreProcessRequest Process ***", isDebugEnabled) - } - - /** - * This method executes a GET call to AAI to obtain the - * Vnf using the Vnf Name - * - * @param - execution - */ - public void getVnfByName(Execution execution){ - def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - execution.setVariable("prefix",Prefix) - utils.log("DEBUG", " *** STARTED GenericGetVnf GetVnfByName Process*** ", isDebugEnabled) - try { - String vnfName = execution.getVariable("GENGV_vnfName") - utils.log("DEBUG", "Getting Vnf by Vnf Name: " + vnfName, isDebugEnabled) - String type = execution.getVariable("GENGV_type") - utils.log("DEBUG", "Type of Vnf Getting is: " + type, isDebugEnabled) - - String aai_endpoint = execution.getVariable("URN_aai_endpoint") - 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{ - utils.log("DEBUG", "Invalid Incoming GENGV_type", isDebugEnabled) - 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) - utils.logAudit("Get Vnf Url is: " + getVnfPath) - - APIResponse response = aaiUriUtil.executeAAIGetCall(execution, getVnfPath) - int responseCode = response.getStatusCode() - execution.setVariable("GENGV_getVnfResponseCode", responseCode) - utils.log("DEBUG", " GET Vnf response code is: " + responseCode, isDebugEnabled) - - String aaiResponse = response.getResponseBodyAsString() - aaiResponse = StringEscapeUtils.unescapeXml(aaiResponse) - execution.setVariable("GENGV_getVnfResponse", aaiResponse) - - //Process Response - if(responseCode == 200){ - utils.log("DEBUG", "GET Vnf Received a Good Response", isDebugEnabled) - if(utils.nodeExists(aaiResponse, type)){ - utils.log("DEBUG", "GET Vnf Response Contains a Vnf", isDebugEnabled) - execution.setVariable("GENGV_FoundIndicator", true) - execution.setVariable("GENGV_vnf", aaiResponse) - execution.setVariable("WorkflowResponse", aaiResponse) - }else{ - utils.log("DEBUG", "GET Vnf Response Does NOT Contain a Vnf", isDebugEnabled) - } - - }else if(responseCode == 404){ - utils.log("DEBUG", "GET Vnf Received a Not Found (404) Response", isDebugEnabled) - }else{ - utils.log("DEBUG", "GET Vnf Received a Bad Response: \n" + aaiResponse, isDebugEnabled) - exceptionUtil.MapAAIExceptionToWorkflowExceptionGeneric(execution, aaiResponse, responseCode) - throw new BpmnError("MSOWorkflowException") - } - }catch(BpmnError b){ - utils.log("DEBUG", "Rethrowing MSOWorkflowException", isDebugEnabled) - throw b - }catch(Exception e){ - utils.log("ERROR", " Error encountered within GenericGetVnf GetVnfByName method!" + e, isDebugEnabled) - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured During GetVnfByName") - } - utils.log("DEBUG", " *** COMPLETED GenericGetVnf GetVnfByName Process*** ", isDebugEnabled) - } - - /** - * This method executes a GET call to AAI to obtain the - * Vnf using the Vnf Id - * - * @param - execution - */ - public void getVnfById(Execution execution){ - def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - execution.setVariable("prefix",Prefix) - utils.log("DEBUG", " *** STARTED GenericGetVnf GetVnfById Process*** ", isDebugEnabled) - try { - String vnfId = execution.getVariable("GENGV_vnfId") - utils.log("DEBUG", "Getting Vnf by Vnf Id: " + vnfId, isDebugEnabled) - String type = execution.getVariable("GENGV_type") - utils.log("DEBUG", "Type of Vnf Getting is: " + type, isDebugEnabled) - - String aai_endpoint = execution.getVariable("URN_aai_endpoint") - 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{ - utils.log("DEBUG", "Invalid Incoming GENGV_type", isDebugEnabled) - exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Invalid Incoming GENGV_type") - } - utils.log("DEBUG", "Using AAI Uri: " + aai_uri, isDebugEnabled) - - String getVnfPath = "${aai_endpoint}${aai_uri}/" + UriUtils.encode(vnfId, "UTF-8") + "?depth=1" - utils.log("DEBUG", "GET Vnf Endpoint is: " + getVnfPath, isDebugEnabled) - - execution.setVariable("GENGV_getVnfPath", getVnfPath) - utils.logAudit("Get Vnf Url is: " + getVnfPath) - - APIResponse response = aaiUriUtil.executeAAIGetCall(execution, getVnfPath) - int responseCode = response.getStatusCode() - execution.setVariable("GENGV_getVnfResponseCode", responseCode) - utils.log("DEBUG", " GET Vnf response code is: " + responseCode, isDebugEnabled) - - String aaiResponse = response.getResponseBodyAsString() - aaiResponse = StringEscapeUtils.unescapeXml(aaiResponse) - execution.setVariable("GENGV_getVnfResponse", aaiResponse) - - //Process Response - if(responseCode == 200){ - utils.log("DEBUG", "GET Vnf Received a Good Response", isDebugEnabled) - if(utils.nodeExists(aaiResponse, type)){ - utils.log("DEBUG", "GET Vnf Response Contains a Vnf", isDebugEnabled) - execution.setVariable("GENGV_FoundIndicator", true) - execution.setVariable("GENGV_vnf", aaiResponse) - execution.setVariable("WorkflowResponse", aaiResponse) - }else{ - utils.log("DEBUG", "GET Vnf Response Does NOT Contain a Vnf", isDebugEnabled) - } - - }else if(responseCode == 404){ - utils.log("DEBUG", "GET Vnf Received a Not Found (404) Response", isDebugEnabled) - }else{ - utils.log("DEBUG", "GET Vnf Received a BAD REST Response: \n" + aaiResponse, isDebugEnabled) - exceptionUtil.MapAAIExceptionToWorkflowExceptionGeneric(execution, aaiResponse, responseCode) - throw new BpmnError("MSOWorkflowException") - } - }catch(BpmnError b){ - utils.log("DEBUG", "Rethrowing MSOWorkflowException", isDebugEnabled) - throw b - }catch(Exception e){ - utils.log("ERROR", " Error encountered within GenericGetVnf GetVnfById method!" + e, isDebugEnabled) - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured During GetVnfById") - } - utils.log("DEBUG", " *** COMPLETED GenericGetVnf GetVnfById Process*** ", isDebugEnabled) - } - -} +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.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.runtime.Execution +import org.openecomp.mso.rest.APIResponse +import org.springframework.web.util.UriUtils + + +/** + * 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{ + + 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(Execution execution) { + def isDebugEnabled = execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix",Prefix) + utils.log("DEBUG", " *** STARTED GenericGetVnf PreProcessRequest Process*** ", isDebugEnabled) + + execution.setVariable("GENGV_getVnfByName", false) + execution.setVariable("GENGV_SuccessIndicator", false) + execution.setVariable("GENGV_FoundIndicator", false) + + try{ + // Get Variables + String vnfId = execution.getVariable("GENGV_vnfId") + utils.log("DEBUG", "Incoming Vnf Id is: " + vnfId, isDebugEnabled) + String vnfName = execution.getVariable("GENGV_vnfName") + utils.log("DEBUG", "Incoming Vnf Name is: " + vnfName, isDebugEnabled) + + if(isBlank(vnfId) && isBlank(vnfName)){ + utils.log("DEBUG", "Incoming Vnf Name and Vnf Id are null. At least one is required!", isDebugEnabled) + 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){ + utils.log("DEBUG", "Rethrowing MSOWorkflowException", isDebugEnabled) + throw b + }catch(Exception e){ + utils.log("DEBUG", " Error encountered within GenericGetVnf PreProcessRequest method!" + e, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured in GenericGetVnf PreProcessRequest") + + } + utils.log("DEBUG", "*** COMPLETED GenericGetVnf PreProcessRequest Process ***", isDebugEnabled) + } + + /** + * This method executes a GET call to AAI to obtain the + * Vnf using the Vnf Name + * + * @param - execution + */ + public void getVnfByName(Execution execution){ + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix",Prefix) + utils.log("DEBUG", " *** STARTED GenericGetVnf GetVnfByName Process*** ", isDebugEnabled) + try { + String vnfName = execution.getVariable("GENGV_vnfName") + utils.log("DEBUG", "Getting Vnf by Vnf Name: " + vnfName, isDebugEnabled) + String type = execution.getVariable("GENGV_type") + utils.log("DEBUG", "Type of Vnf Getting is: " + type, isDebugEnabled) + + String aai_endpoint = execution.getVariable("URN_aai_endpoint") + 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{ + utils.log("DEBUG", "Invalid Incoming GENGV_type", isDebugEnabled) + 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) + utils.logAudit("Get Vnf Url is: " + getVnfPath) + + APIResponse response = aaiUriUtil.executeAAIGetCall(execution, getVnfPath) + int responseCode = response.getStatusCode() + execution.setVariable("GENGV_getVnfResponseCode", responseCode) + utils.log("DEBUG", " GET Vnf response code is: " + responseCode, isDebugEnabled) + + String aaiResponse = response.getResponseBodyAsString() + aaiResponse = StringEscapeUtils.unescapeXml(aaiResponse) + execution.setVariable("GENGV_getVnfResponse", aaiResponse) + + //Process Response + if(responseCode == 200){ + utils.log("DEBUG", "GET Vnf Received a Good Response", isDebugEnabled) + if(utils.nodeExists(aaiResponse, type)){ + utils.log("DEBUG", "GET Vnf Response Contains a Vnf", isDebugEnabled) + execution.setVariable("GENGV_FoundIndicator", true) + execution.setVariable("GENGV_vnf", aaiResponse) + execution.setVariable("WorkflowResponse", aaiResponse) + }else{ + utils.log("DEBUG", "GET Vnf Response Does NOT Contain a Vnf", isDebugEnabled) + } + + }else if(responseCode == 404){ + utils.log("DEBUG", "GET Vnf Received a Not Found (404) Response", isDebugEnabled) + }else{ + utils.log("DEBUG", "GET Vnf Received a Bad Response: \n" + aaiResponse, isDebugEnabled) + exceptionUtil.MapAAIExceptionToWorkflowExceptionGeneric(execution, aaiResponse, responseCode) + throw new BpmnError("MSOWorkflowException") + } + }catch(BpmnError b){ + utils.log("DEBUG", "Rethrowing MSOWorkflowException", isDebugEnabled) + throw b + }catch(Exception e){ + utils.log("ERROR", " Error encountered within GenericGetVnf GetVnfByName method!" + e, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured During GetVnfByName") + } + utils.log("DEBUG", " *** COMPLETED GenericGetVnf GetVnfByName Process*** ", isDebugEnabled) + } + + /** + * This method executes a GET call to AAI to obtain the + * Vnf using the Vnf Id + * + * @param - execution + */ + public void getVnfById(Execution execution){ + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix",Prefix) + utils.log("DEBUG", " *** STARTED GenericGetVnf GetVnfById Process*** ", isDebugEnabled) + try { + String vnfId = execution.getVariable("GENGV_vnfId") + utils.log("DEBUG", "Getting Vnf by Vnf Id: " + vnfId, isDebugEnabled) + String type = execution.getVariable("GENGV_type") + utils.log("DEBUG", "Type of Vnf Getting is: " + type, isDebugEnabled) + + String aai_endpoint = execution.getVariable("URN_aai_endpoint") + 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{ + utils.log("DEBUG", "Invalid Incoming GENGV_type", isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Invalid Incoming GENGV_type") + } + utils.log("DEBUG", "Using AAI Uri: " + aai_uri, isDebugEnabled) + + String getVnfPath = "${aai_endpoint}${aai_uri}/" + UriUtils.encode(vnfId, "UTF-8") + "?depth=1" + utils.log("DEBUG", "GET Vnf Endpoint is: " + getVnfPath, isDebugEnabled) + + execution.setVariable("GENGV_getVnfPath", getVnfPath) + utils.logAudit("Get Vnf Url is: " + getVnfPath) + + APIResponse response = aaiUriUtil.executeAAIGetCall(execution, getVnfPath) + int responseCode = response.getStatusCode() + execution.setVariable("GENGV_getVnfResponseCode", responseCode) + utils.log("DEBUG", " GET Vnf response code is: " + responseCode, isDebugEnabled) + + String aaiResponse = response.getResponseBodyAsString() + aaiResponse = StringEscapeUtils.unescapeXml(aaiResponse) + execution.setVariable("GENGV_getVnfResponse", aaiResponse) + + //Process Response + if(responseCode == 200){ + utils.log("DEBUG", "GET Vnf Received a Good Response", isDebugEnabled) + if(utils.nodeExists(aaiResponse, type)){ + utils.log("DEBUG", "GET Vnf Response Contains a Vnf", isDebugEnabled) + execution.setVariable("GENGV_FoundIndicator", true) + execution.setVariable("GENGV_vnf", aaiResponse) + execution.setVariable("WorkflowResponse", aaiResponse) + }else{ + utils.log("DEBUG", "GET Vnf Response Does NOT Contain a Vnf", isDebugEnabled) + } + + }else if(responseCode == 404){ + utils.log("DEBUG", "GET Vnf Received a Not Found (404) Response", isDebugEnabled) + }else{ + utils.log("DEBUG", "GET Vnf Received a BAD REST Response: \n" + aaiResponse, isDebugEnabled) + exceptionUtil.MapAAIExceptionToWorkflowExceptionGeneric(execution, aaiResponse, responseCode) + throw new BpmnError("MSOWorkflowException") + } + }catch(BpmnError b){ + utils.log("DEBUG", "Rethrowing MSOWorkflowException", isDebugEnabled) + throw b + }catch(Exception e){ + utils.log("ERROR", " Error encountered within GenericGetVnf GetVnfById method!" + e, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured During GetVnfById") + } + utils.log("DEBUG", " *** COMPLETED GenericGetVnf GetVnfById Process*** ", isDebugEnabled) + } + +} diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/GenericNotificationService.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/GenericNotificationService.groovy new file mode 100644 index 0000000000..62d476d294 --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/GenericNotificationService.groovy @@ -0,0 +1,21 @@ +package org.openecomp.mso.bpmn.common.scripts + +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.runtime.Execution +import org.openecomp.mso.bpmn.common.scripts.AbstractServiceTaskProcessor +import org.openecomp.mso.bpmn.common.scripts.ExceptionUtil +import org.openecomp.mso.bpmn.core.WorkflowException +import org.openecomp.mso.bpmn.core.json.JsonUtils +import java.text.SimpleDateFormat + +public class GenericNotificationService extends AbstractServiceTaskProcessor { + + + + ExceptionUtil exceptionUtil = new ExceptionUtil() + + public void preProcessRequest (Execution execution) { + + } + +} diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/GenericPutVnf.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/GenericPutVnf.groovy index 9a7aa5ab9f..207830aea0 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/GenericPutVnf.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/GenericPutVnf.groovy @@ -1,172 +1,172 @@ -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - MSO - * ================================================================================ - * 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.openecomp.mso.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.runtime.Execution -import org.openecomp.mso.rest.APIResponse -import org.springframework.web.util.UriUtils - -/** - * TODO: Support Putting vnf type = vpe and vce - * - * This class supports the GenericPutVnf Sub Flow. - * This Generic sub flow can be used by any flow for accomplishing - * the goal of Creating/Updating(PUT) a Vnf Object (in AAI). The flow - * supports the Creating/Updating of 3 types of Vnfs (generic-vnf, vce, and vpe). - * The "type" must be provided by the calling flow and this type should - * be mapped to the variable GENPV_type. The type should either be - * "generic-vnf", "vce", or "vpe". In addition, the Vnf Id and - * payload should be provided. - * - * Upon successful completion of this sub flow the - * GENPV_SuccessIndicator. An MSOWorkflowException will - * be thrown if an error occurs at any time during this - * sub flow. Please map input variables to the corresponding - * variable names below. - * - * - * Incoming Required Variables: - * @param - GENPV_vnfId - * @param - GENPV_vnfPayload - * @param - GENPV_type - * - * - * Outgoing Variables: - * @param - GENPV_SuccessIndicator - * @param - WorkflowException - */ -class GenericPutVnf extends AbstractServiceTaskProcessor{ - - String Prefix = "GENPV_" - ExceptionUtil exceptionUtil = new ExceptionUtil() - - /** - * This method validates the incoming variables and - * generates a Vnf Id if one is not provided. - * - * @param - execution - */ - public void preProcessRequest(Execution execution) { - def isDebugEnabled = execution.getVariable("isDebugLogEnabled") - execution.setVariable("prefix",Prefix) - utils.log("DEBUG", " *** STARTED GenericPutVnf PreProcessRequest Process*** ", isDebugEnabled) - - execution.setVariable("GENPV_SuccessIndicator", false) - execution.setVariable("GENPV_FoundIndicator", false) - - try{ - // Get Variables - String payload = execution.getVariable("GENPV_vnfPayload") - utils.log("DEBUG", "Incoming Vnf Payload is: " + payload, isDebugEnabled) - String type = execution.getVariable("GENPV_type") - utils.log("DEBUG", "Incoming Type of Vnf is: " + type, isDebugEnabled) - - if(isBlank(payload) || isBlank(type)){ - utils.log("ERROR", "Incoming Vnf Payload and/or Type is null. These Variables are required!", isDebugEnabled) - exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Incoming Vnf Payload and/or Type is null. These Variables are required!") - }else{ - String vnfId = execution.getVariable("GENPV_vnfId") - if(isBlank(vnfId)){ - vnfId = UUID.randomUUID().toString() - utils.log("DEBUG", "Generated Vnf Id is: " + vnfId, isDebugEnabled) - execution.setVariable("GENPV_vnfId", vnfId) - }else{ - utils.log("DEBUG", "Incoming Vnf Id is: " + vnfId, isDebugEnabled) - } - } - }catch(BpmnError b){ - utils.log("DEBUG", "Rethrowing MSOWorkflowException", isDebugEnabled) - throw b - }catch(Exception e){ - utils.log("ERROR", " Error encountered within GenericPutVnf PreProcessRequest method!" + e, isDebugEnabled) - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured in GenericPutVnf PreProcessRequest") - - } - utils.log("DEBUG", "*** COMPLETED GenericPutVnf PreProcessRequest Process ***", isDebugEnabled) - } - - /** - * This method executes a Put call to AAI to create - * or update a Vnf Object using the provided payload - * - * @param - execution - */ - public void putVnf(Execution execution){ - def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - execution.setVariable("prefix",Prefix) - utils.log("DEBUG", " *** STARTED GenericPutVnf PutVnf Process*** ", isDebugEnabled) - try { - String vnfId = execution.getVariable("GENPV_vnfId") - String payload = execution.getVariable("GENPV_vnfPayload") - String type = execution.getVariable("GENPV_type") - - AaiUtil aaiUtil = new AaiUtil(this) - def aai_uri = "" - if(type.equals("generic-vnf")){ - aai_uri = aaiUtil.getNetworkGenericVnfUri(execution) - }else if(type.equals("vce")){ - aai_uri = aaiUtil.getNetworkVceUri(execution) - }else if(type.equals("vpe")){ - exceptionUtil.buildAndThrowWorkflowException(execution, 500, "GenericPutVnf does not yet support getting type of vnf = vpe") - }else{ - utils.log("DEBUG", "Invalid Incoming GENGV_type", isDebugEnabled) - exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Invalid Incoming GENPV_type") - } - utils.log("DEBUG", "Using AAI Uri: " + aai_uri, isDebugEnabled) - - String path = "${aai_uri}/" + UriUtils.encode(vnfId, "UTF-8") - utils.log("DEBUG", "PUT Vnf Endpoint is: " + path, isDebugEnabled) - - String putVnfAAIPath = execution.getVariable("URN_aai_endpoint") + path - execution.setVariable("GENPV_putVnfAAIPath", putVnfAAIPath) - utils.logAudit("PUT Vnf Url is: " + putVnfAAIPath) - - APIResponse apiResponse = aaiUtil.executeAAIPutCall(execution, putVnfAAIPath, payload) - int responseCode = apiResponse.getStatusCode() - execution.setVariable("GENPV_putVnfResponseCode", responseCode) - utils.logAudit("AAI Response Code: " + responseCode) - String aaiResponse = apiResponse.getResponseBodyAsString() - aaiResponse = StringEscapeUtils.unescapeXml(aaiResponse) - execution.setVariable("GENPV_putVnfResponse", aaiResponse) - utils.logAudit("AAI Response: " + aaiResponse) - - if(responseCode == 200 || responseCode == 201){ - utils.log("DEBUG", "PUT Vnf Received a Good Response Code.", isDebugEnabled) - }else{ - utils.log("DEBUG", "PUT Vnf Received a Bad Response Code. Response Code is: " + responseCode, isDebugEnabled) - exceptionUtil.MapAAIExceptionToWorkflowExceptionGeneric(execution, aaiResponse, responseCode) - throw new BpmnError("MSOWorkflowException") - } - }catch(BpmnError b){ - utils.log("DEBUG", "Rethrowing MSOWorkflowException", isDebugEnabled) - throw b - }catch(Exception e){ - utils.log("ERROR", " Error encountered within GenericPutVnf PutVnf method!" + e, isDebugEnabled) - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured During PutVnf") - } - utils.log("DEBUG", " *** COMPLETED GenericPutVnf PutVnf Process*** ", isDebugEnabled) - } - -} +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.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.runtime.Execution +import org.openecomp.mso.rest.APIResponse +import org.springframework.web.util.UriUtils + +/** + * TODO: Support Putting vnf type = vpe and vce + * + * This class supports the GenericPutVnf Sub Flow. + * This Generic sub flow can be used by any flow for accomplishing + * the goal of Creating/Updating(PUT) a Vnf Object (in AAI). The flow + * supports the Creating/Updating of 3 types of Vnfs (generic-vnf, vce, and vpe). + * The "type" must be provided by the calling flow and this type should + * be mapped to the variable GENPV_type. The type should either be + * "generic-vnf", "vce", or "vpe". In addition, the Vnf Id and + * payload should be provided. + * + * Upon successful completion of this sub flow the + * GENPV_SuccessIndicator. An MSOWorkflowException will + * be thrown if an error occurs at any time during this + * sub flow. Please map input variables to the corresponding + * variable names below. + * + * + * Incoming Required Variables: + * @param - GENPV_vnfId + * @param - GENPV_vnfPayload + * @param - GENPV_type + * + * + * Outgoing Variables: + * @param - GENPV_SuccessIndicator + * @param - WorkflowException + */ +class GenericPutVnf extends AbstractServiceTaskProcessor{ + + String Prefix = "GENPV_" + ExceptionUtil exceptionUtil = new ExceptionUtil() + + /** + * This method validates the incoming variables and + * generates a Vnf Id if one is not provided. + * + * @param - execution + */ + public void preProcessRequest(Execution execution) { + def isDebugEnabled = execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix",Prefix) + utils.log("DEBUG", " *** STARTED GenericPutVnf PreProcessRequest Process*** ", isDebugEnabled) + + execution.setVariable("GENPV_SuccessIndicator", false) + execution.setVariable("GENPV_FoundIndicator", false) + + try{ + // Get Variables + String payload = execution.getVariable("GENPV_vnfPayload") + utils.log("DEBUG", "Incoming Vnf Payload is: " + payload, isDebugEnabled) + String type = execution.getVariable("GENPV_type") + utils.log("DEBUG", "Incoming Type of Vnf is: " + type, isDebugEnabled) + + if(isBlank(payload) || isBlank(type)){ + utils.log("ERROR", "Incoming Vnf Payload and/or Type is null. These Variables are required!", isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Incoming Vnf Payload and/or Type is null. These Variables are required!") + }else{ + String vnfId = execution.getVariable("GENPV_vnfId") + if(isBlank(vnfId)){ + vnfId = UUID.randomUUID().toString() + utils.log("DEBUG", "Generated Vnf Id is: " + vnfId, isDebugEnabled) + execution.setVariable("GENPV_vnfId", vnfId) + }else{ + utils.log("DEBUG", "Incoming Vnf Id is: " + vnfId, isDebugEnabled) + } + } + }catch(BpmnError b){ + utils.log("DEBUG", "Rethrowing MSOWorkflowException", isDebugEnabled) + throw b + }catch(Exception e){ + utils.log("ERROR", " Error encountered within GenericPutVnf PreProcessRequest method!" + e, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured in GenericPutVnf PreProcessRequest") + + } + utils.log("DEBUG", "*** COMPLETED GenericPutVnf PreProcessRequest Process ***", isDebugEnabled) + } + + /** + * This method executes a Put call to AAI to create + * or update a Vnf Object using the provided payload + * + * @param - execution + */ + public void putVnf(Execution execution){ + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix",Prefix) + utils.log("DEBUG", " *** STARTED GenericPutVnf PutVnf Process*** ", isDebugEnabled) + try { + String vnfId = execution.getVariable("GENPV_vnfId") + String payload = execution.getVariable("GENPV_vnfPayload") + String type = execution.getVariable("GENPV_type") + + AaiUtil aaiUtil = new AaiUtil(this) + def aai_uri = "" + if(type.equals("generic-vnf")){ + aai_uri = aaiUtil.getNetworkGenericVnfUri(execution) + }else if(type.equals("vce")){ + aai_uri = aaiUtil.getNetworkVceUri(execution) + }else if(type.equals("vpe")){ + exceptionUtil.buildAndThrowWorkflowException(execution, 500, "GenericPutVnf does not yet support getting type of vnf = vpe") + }else{ + utils.log("DEBUG", "Invalid Incoming GENGV_type", isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Invalid Incoming GENPV_type") + } + utils.log("DEBUG", "Using AAI Uri: " + aai_uri, isDebugEnabled) + + String path = "${aai_uri}/" + UriUtils.encode(vnfId, "UTF-8") + utils.log("DEBUG", "PUT Vnf Endpoint is: " + path, isDebugEnabled) + + String putVnfAAIPath = execution.getVariable("URN_aai_endpoint") + path + execution.setVariable("GENPV_putVnfAAIPath", putVnfAAIPath) + utils.logAudit("PUT Vnf Url is: " + putVnfAAIPath) + + APIResponse apiResponse = aaiUtil.executeAAIPutCall(execution, putVnfAAIPath, payload) + int responseCode = apiResponse.getStatusCode() + execution.setVariable("GENPV_putVnfResponseCode", responseCode) + utils.logAudit("AAI Response Code: " + responseCode) + String aaiResponse = apiResponse.getResponseBodyAsString() + aaiResponse = StringEscapeUtils.unescapeXml(aaiResponse) + execution.setVariable("GENPV_putVnfResponse", aaiResponse) + utils.logAudit("AAI Response: " + aaiResponse) + + if(responseCode == 200 || responseCode == 201){ + utils.log("DEBUG", "PUT Vnf Received a Good Response Code.", isDebugEnabled) + }else{ + utils.log("DEBUG", "PUT Vnf Received a Bad Response Code. Response Code is: " + responseCode, isDebugEnabled) + exceptionUtil.MapAAIExceptionToWorkflowExceptionGeneric(execution, aaiResponse, responseCode) + throw new BpmnError("MSOWorkflowException") + } + }catch(BpmnError b){ + utils.log("DEBUG", "Rethrowing MSOWorkflowException", isDebugEnabled) + throw b + }catch(Exception e){ + utils.log("ERROR", " Error encountered within GenericPutVnf PutVnf method!" + e, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured During PutVnf") + } + utils.log("DEBUG", " *** COMPLETED GenericPutVnf PutVnf Process*** ", isDebugEnabled) + } + +} diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/MsoUtils.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/MsoUtils.groovy index 6796fb1a95..a0256d33e9 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/MsoUtils.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/MsoUtils.groovy @@ -1,944 +1,951 @@ -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - MSO - * ================================================================================ - * 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.openecomp.mso.bpmn.common.scripts - -import groovy.xml.XmlUtil - -import java.text.SimpleDateFormat - -import org.apache.commons.codec.binary.Base64 -import org.openecomp.mso.bpmn.core.BPMNLogger -import org.openecomp.mso.bpmn.core.xml.XmlTool -import org.openecomp.mso.logger.MessageEnum -import org.openecomp.mso.logger.MsoLogger -import org.openecomp.mso.utils.CryptoUtils -import org.w3c.dom.Element - -class MsoUtils { - 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") - } - def getNodeText(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 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 - } - def getNodeText1(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 getNodeXml(xmlInput,element){ - return getNodeXml(xmlInput, element, true) - } - def getNodeXml(xmlInput,element,incPreamble){ - def fxml= new XmlSlurper().parseText(xmlInput) - def nodeToSerialize = fxml.'**'.find {it.name() == element} - if(nodeToSerialize==null){ - return "" - } - def nodeAsText = XmlUtil.serialize(nodeToSerialize) - if (!incPreamble) { - nodeAsText = removeXmlPreamble(nodeAsText) - } - return nodeAsText - } - 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){ - xmlInput = xmlInput.replaceAll("&", "&") - xmlInput = xmlInput.replaceAll("<", "<") - xmlInput = xmlInput.replaceAll(">", ">") - 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 String decodeXML(xml) { - def String decodedXml = xml.replaceAll("&", "&") - decodedXml = decodedXml.replaceAll("<", "<") - decodedXml = decodedXml.replaceAll(">", ">") - } - - 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"){ - MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL); - if ("INFO"==logmode) { - msoLogger.info(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, logtxt); - } else if ("WARN"==logmode) { - msoLogger.warn (MessageEnum.BPMN_GENERAL_WARNING, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, logtxt); - } else if ("ERROR"==logmode) { - msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, logtxt); - - } else { - BPMNLogger.debug(isDebugLogEnabled, logtxt); - } - } - - def logContext(requestId, serviceInstanceId){ - MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL); - msoLogger.setLogContext(requestId, serviceInstanceId); - } - - def logMetrics(elapsedTime, logtxt){ - MsoLogger metricsLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL); - - metricsLogger.recordMetricEvent (elapsedTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, - logtxt, "BPMN", MsoLogger.getServiceName(), null); - } - - def logAudit(logtxt){ - MsoLogger auditLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL); - long startTime = System.currentTimeMillis(); - - auditLogger.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. - * @param s the string to encode - * @return the encoded string - */ - public String xmlEncode(Object value) { - return XmlTool.encode(value) - } - - /** - * Encodes a value so it can be used inside an XML attribute. - * @param s the string to encode - * @return the encoded string - */ - public String xmlEncodeAttr(Object value) { - return XmlTool.encodeAttr(value) - } - - /** - * Decodes XML entities in a string value - * @param value a value with embedded XML entities - * @return the decoded string - */ - public String xmlDecode(Object value) { - return XmlTool.decode(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 += "" - } - if (xmlInput != null) { - for (element in elementList) { - def xml= new XmlSlurper().parseText(xmlInput) - var = xml.'**'.find {it.name() == element} - if (var != null) { - xmlBuild += ""+var.toString()+"" - } - } - } - if (parentName != "") { - xmlBuild += "" - } - 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 += "" - } - for (element in elementList) { - var = varParents[i].'*'.find {it.name() == element} - if (var != null) { - xmlBuildUnbounded += ""+var.toString()+"" - //println " i = " + i + ", element: " + element + " = " + var.toString() - } - } - if (parentName != "") { - xmlBuildUnbounded += "" - } - } - } - return xmlBuildUnbounded - } - - // Build l2-homing-information - def buildL2HomingInformation(xmlInput) { - def elementsL2HomingList = ["evc-name", "topology", "preferred-aic-clli"] - 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 = "" - // transport-service-information - rebuildUcpeVmsServiceInformation += "" - 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 += "" - // ucpe-information - def elementsUcpeInformationList = ["ucpe-host-name", "ucpe-activation-code", "out-of-band-management-modem" ] - rebuildUcpeVmsServiceInformation += buildElements(ucpeVmsServiceInformation, elementsUcpeInformationList, "ucpe-information") - // vnf-list - rebuildUcpeVmsServiceInformation += "" - 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 += "" - rebuildUcpeVmsServiceInformation += "" - } - 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 = "" - rebuildInternetServiceChangeDetails += buildElements(internetServiceChangeDetails, ["internet-evc-speed-value"], "") - rebuildInternetServiceChangeDetails += buildElements(internetServiceChangeDetails, ["internet-evc-speed-units"], "") - 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 += "" - } 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 = "" - def vrLan = getNodeXml(xmlInput, "vr-lan").drop(38).trim() - rebuildVrLan += buildElements(vrLan, ["routing-protocol"], "") - - // vr-lan-interface - def rebuildVrLanInterface = "" - 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 += "" - rebuildVrLan += "" - - } - 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 += "" - 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 += "" - rebuildingVrLanInterface += "" - 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 += "" - } - log("DEBUG", " rebuildingVrLanInterface - " + rebuildingVrLanInterface) - return rebuildingVrLanInterface - } - - // Build dhcp - def buildDhcp(xmlInput) { - def rebuildingDhcp = '' - if (xmlInput != null) { - def dhcpData = new XmlSlurper().parseText(xmlInput) - rebuildingDhcp = "" - 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 += "" - 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 += "" - } - } 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 += "" - 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 += "" - } - } catch (Exception e) { - log("ERROR", " Optional - Exception DHCP 'v6-dhcp-pools' ") - } - rebuildingDhcp += "" - } - log("DEBUG", " rebuildingDhcp - " + rebuildingDhcp) - return rebuildingDhcp - } - - // Build pat - def buildPat(xmlInput) { - def rebuildingPat = '' - if (xmlInput != null) { - rebuildingPat = "" - 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 += "" - } - log("DEBUG", " rebuildingPat - " + rebuildingPat) - return rebuildingPat - } - - // Build nat - def buildNat(xmlInput) { - def rebuildingNat = '' - if (xmlInput != null) { - rebuildingNat = "" - 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 += "" - } - log("DEBUG", " rebuildingNat - " + rebuildingNat) - return rebuildingNat - } - - // Build firewall-lite - def buildFirewallLite(xmlInput) { - def rebuildingFirewallLite = '' - - if (xmlInput != null) { - - def firewallLiteData = new XmlSlurper().parseText(xmlInput) - rebuildingFirewallLite = "" - 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 += "" - 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 += "" - } - } 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 += "" - 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 += "" - } - } catch (Exception e) { - log("ERROR", " Optional - Exception FIREWALL-LITE 'v6-firewall-packet-filters' ") - } - rebuildingFirewallLite+= "" - } - log("DEBUG", " rebuildingFirewallLite - " + rebuildingFirewallLite) - return rebuildingFirewallLite - } - - def buildStaticRoutes(xmlInput) { - def rebuildingStaticRoutes = '' - if (xmlInput != null) { - rebuildingStaticRoutes = "" - 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 += "" - } - 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){ - 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() - } - -} +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.bpmn.common.scripts + +import groovy.xml.XmlUtil + +import java.text.SimpleDateFormat + +import org.apache.commons.codec.binary.Base64 +import org.openecomp.mso.bpmn.core.BPMNLogger +import org.openecomp.mso.bpmn.core.xml.XmlTool +import org.openecomp.mso.logger.MessageEnum +import org.openecomp.mso.logger.MsoLogger +import org.openecomp.mso.utils.CryptoUtils +import org.w3c.dom.Element + +class MsoUtils { + 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") + } + + /** + * Use getNodeText1 Instead! + */ + @Deprecated + def getNodeText(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 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 + } + def getNodeText1(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 getNodeXml(xmlInput,element){ + return getNodeXml(xmlInput, element, true) + } + def getNodeXml(xmlInput,element,incPreamble){ + def fxml= new XmlSlurper().parseText(xmlInput) + def nodeToSerialize = fxml.'**'.find {it.name() == element} + if(nodeToSerialize==null){ + return "" + } + def nodeAsText = XmlUtil.serialize(nodeToSerialize) + if (!incPreamble) { + nodeAsText = removeXmlPreamble(nodeAsText) + } + return nodeAsText + } + 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){ + xmlInput = xmlInput.replaceAll("&", "&") + xmlInput = xmlInput.replaceAll("<", "<") + xmlInput = xmlInput.replaceAll(">", ">") + 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 String decodeXML(xml) { + def String decodedXml = xml.replaceAll("&", "&") + decodedXml = decodedXml.replaceAll("<", "<") + decodedXml = decodedXml.replaceAll(">", ">") + } + + 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"){ + MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL); + if ("INFO"==logmode) { + msoLogger.info(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, logtxt); + } 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 msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL); + msoLogger.setLogContext(requestId, serviceInstanceId); + } + + def logMetrics(elapsedTime, logtxt){ + MsoLogger metricsLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL); + + metricsLogger.recordMetricEvent (elapsedTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, + logtxt, "BPMN", MsoLogger.getServiceName(), null); + } + + def logAudit(logtxt){ + MsoLogger auditLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL); + long startTime = System.currentTimeMillis(); + + auditLogger.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. + * @param s the string to encode + * @return the encoded string + */ + public String xmlEncode(Object value) { + return XmlTool.encode(value) + } + + /** + * Encodes a value so it can be used inside an XML attribute. + * @param s the string to encode + * @return the encoded string + */ + public String xmlEncodeAttr(Object value) { + return XmlTool.encodeAttr(value) + } + + /** + * Decodes XML entities in a string value + * @param value a value with embedded XML entities + * @return the decoded string + */ + public String xmlDecode(Object value) { + return XmlTool.decode(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 += "" + } + if (xmlInput != null) { + for (element in elementList) { + def xml= new XmlSlurper().parseText(xmlInput) + var = xml.'**'.find {it.name() == element} + if (var != null) { + xmlBuild += ""+var.toString()+"" + } + } + } + if (parentName != "") { + xmlBuild += "" + } + 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 += "" + } + for (element in elementList) { + var = varParents[i].'*'.find {it.name() == element} + if (var != null) { + xmlBuildUnbounded += ""+var.toString()+"" + //println " i = " + i + ", element: " + element + " = " + var.toString() + } + } + if (parentName != "") { + xmlBuildUnbounded += "" + } + } + } + return xmlBuildUnbounded + } + + // Build l2-homing-information + def buildL2HomingInformation(xmlInput) { + def elementsL2HomingList = ["evc-name", "topology", "preferred-aic-clli"] + 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 = "" + // transport-service-information + rebuildUcpeVmsServiceInformation += "" + 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 += "" + // ucpe-information + def elementsUcpeInformationList = ["ucpe-host-name", "ucpe-activation-code", "out-of-band-management-modem" ] + rebuildUcpeVmsServiceInformation += buildElements(ucpeVmsServiceInformation, elementsUcpeInformationList, "ucpe-information") + // vnf-list + rebuildUcpeVmsServiceInformation += "" + 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 += "" + rebuildUcpeVmsServiceInformation += "" + } + 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 = "" + rebuildInternetServiceChangeDetails += buildElements(internetServiceChangeDetails, ["internet-evc-speed-value"], "") + rebuildInternetServiceChangeDetails += buildElements(internetServiceChangeDetails, ["internet-evc-speed-units"], "") + 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 += "" + } 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 = "" + def vrLan = getNodeXml(xmlInput, "vr-lan").drop(38).trim() + rebuildVrLan += buildElements(vrLan, ["routing-protocol"], "") + + // vr-lan-interface + def rebuildVrLanInterface = "" + 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 += "" + rebuildVrLan += "" + + } + 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 += "" + 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 += "" + rebuildingVrLanInterface += "" + 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 += "" + } + log("DEBUG", " rebuildingVrLanInterface - " + rebuildingVrLanInterface) + return rebuildingVrLanInterface + } + + // Build dhcp + def buildDhcp(xmlInput) { + def rebuildingDhcp = '' + if (xmlInput != null) { + def dhcpData = new XmlSlurper().parseText(xmlInput) + rebuildingDhcp = "" + 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 += "" + 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 += "" + } + } 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 += "" + 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 += "" + } + } catch (Exception e) { + log("ERROR", " Optional - Exception DHCP 'v6-dhcp-pools' ") + } + rebuildingDhcp += "" + } + log("DEBUG", " rebuildingDhcp - " + rebuildingDhcp) + return rebuildingDhcp + } + + // Build pat + def buildPat(xmlInput) { + def rebuildingPat = '' + if (xmlInput != null) { + rebuildingPat = "" + 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 += "" + } + log("DEBUG", " rebuildingPat - " + rebuildingPat) + return rebuildingPat + } + + // Build nat + def buildNat(xmlInput) { + def rebuildingNat = '' + if (xmlInput != null) { + rebuildingNat = "" + 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 += "" + } + log("DEBUG", " rebuildingNat - " + rebuildingNat) + return rebuildingNat + } + + // Build firewall-lite + def buildFirewallLite(xmlInput) { + def rebuildingFirewallLite = '' + + if (xmlInput != null) { + + def firewallLiteData = new XmlSlurper().parseText(xmlInput) + rebuildingFirewallLite = "" + 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 += "" + 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 += "" + } + } 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 += "" + 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 += "" + } + } catch (Exception e) { + log("ERROR", " Optional - Exception FIREWALL-LITE 'v6-firewall-packet-filters' ") + } + rebuildingFirewallLite+= "" + } + log("DEBUG", " rebuildingFirewallLite - " + rebuildingFirewallLite) + return rebuildingFirewallLite + } + + def buildStaticRoutes(xmlInput) { + def rebuildingStaticRoutes = '' + if (xmlInput != null) { + rebuildingStaticRoutes = "" + 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 += "" + } + 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){ + 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() + } + +} diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/NetworkUtils.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/NetworkUtils.groovy index c9e243dd54..3ff2863d54 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/NetworkUtils.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/NetworkUtils.groovy @@ -1,1445 +1,1491 @@ -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - MSO - * ================================================================================ - * 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.openecomp.mso.bpmn.common.scripts; - -import org.apache.commons.lang3.* - -import groovy.xml.XmlUtil - -import javax.xml.parsers.DocumentBuilder -import javax.xml.parsers.DocumentBuilderFactory -import javax.xml.transform.Transformer -import javax.xml.transform.TransformerFactory -import javax.xml.transform.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.runtime.Execution -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.camunda.bpm.engine.delegate.BpmnError -import org.camunda.bpm.engine.runtime.Execution -import org.openecomp.mso.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 { - - 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 'openecomp-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.getNodeText1(queryIdResponse, "is-shared-network") != null ? utils.getNodeText1(queryIdResponse, "is-shared-network") : "false" - externalValue = utils.getNodeText1(queryIdResponse, "is-external-network") != null ? utils.getNodeText1(queryIdResponse, "is-external-network") : "false" - serviceInstanceId = utils.getNodeText1(requestInput, "service-instance-id") - - } else { // source = 'PORTAL' - sharedValue = getParameterValue(requestInput, "shared") - externalValue = getParameterValue(requestInput, "external") - serviceInstanceId = utils.getNodeText1(requestInput, "service-instance-id") != null ? utils.getNodeText1(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.getNodeText1(requestInput, "tenant-id") - String networkType = "" - if (utils.nodeExists(requestInput, "networkModelInfo")) { - String networkModelInfo = utils.getNodeXml(requestInput, "networkModelInfo", false).replace("tag0:","").replace(":tag0","") - networkType = utils.getNodeText1(networkModelInfo, "modelName") - } else { - networkType = utils.getNodeText1(queryIdResponse, "network-type") - } - - // queryIdResponse - String networkName = utils.getNodeText1(queryIdResponse, "network-name") - String networkId = utils.getNodeText1(queryIdResponse, "network-id") - String networkTechnology = utils.getNodeText1(queryIdResponse, "network-technology") - - // contrailNetwork - networkTechnology = 'Contrail' vs. 'AIC_SR_IOV') - String contrailNetwork = "" - if (networkTechnology.contains('Contrail') || networkTechnology.contains('contrail') || networkTechnology.contains('CONTRAIL')) { - contrailNetwork = """ - ${sharedValue} - ${externalValue} - ${routeCollection} - ${policyFqdns} - ${tableCollection} - """ - 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.getNodeText1(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 = """ - - ${cloudRegion} - ${tenantId} - ${networkId} - ${networkName} - ${networkType} - ${networkTechnology} - - ${physicalNetworkName} - ${vlansCollection} - - ${contrailNetwork} - ${subnets} - true - ${backoutOnFailure} - ${failIfExists} - ${networkParams} - - ${requestId} - ${serviceInstanceId} - - ${messageId} - ${notificationUrl} - - """.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 'openecomp-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.getNodeText1(queryIdResponse, "is-shared-network") != null ? utils.getNodeText1(queryIdResponse, "is-shared-network") : "false" - externalValue = utils.getNodeText1(queryIdResponse, "is-external-network") != null ? utils.getNodeText1(queryIdResponse, "is-external-network") : "false" - serviceInstanceId = utils.getNodeText1(requestInput, "service-instance-id") - - } else { // source = 'PORTAL' - sharedValue = getParameterValue(requestInput, "shared") - externalValue = getParameterValue(requestInput, "external") - serviceInstanceId = utils.getNodeText1(requestInput, "service-instance-id") != null ? utils.getNodeText1(requestInput, "service-instance-id") : "" - } - - String failIfExists = "false" - // requestInput - String cloudRegion = cloudRegionId - String tenantId = utils.getNodeText1(requestInput, "tenant-id") - - // queryIdResponse - String networkName = utils.getNodeText1(queryIdResponse, "network-name") - String networkId = utils.getNodeText1(queryIdResponse, "network-id") - String networkType = utils.getNodeText1(queryIdResponse, "network-type") - - // 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.getNodeText1(queryIdResponse, "heat-stack-id") - if (networkStackId == 'null' || networkStackId == "" || networkStackId == null) { - networkStackId = "force_update" - } - - String physicalNetworkName = utils.getNodeText1(queryIdResponse, "physical-network-name") - String vlansCollection = buildVlans(queryIdResponse) - - updateNetworkRequest = - """ - ${cloudRegion} - ${tenantId} - ${networkId} - ${networkStackId} - ${networkName} - ${networkType} - - CONTRAIL - - ${physicalNetworkName} - ${vlansCollection} - - - ${sharedValue} - ${externalValue} - ${routeCollection} - ${policyFqdns} - ${tableCollection} - - ${subnets} - true - ${backoutOnFailure} - ${failIfExists} - ${networkParams} - - - ${requestId} - ${serviceInstanceId} - - ${messageId} - - """.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 = - """ - ${groupId} - ${volumeName} - - ${vnfType} - Pending - - - tenant - - tenant.tenant-id - ${tenantId} - - - - """ - - return requestPayload - } - - def String createCloudRegionVolumeRequest(groupId, volumeName, vnfType, tenantId, cloudRegion, namespace, modelCustomizationId) { - - String requestPayload = - """ - ${groupId} - ${volumeName} - - ${vnfType} - Pending - ${modelCustomizationId} - - - tenant - - tenant.tenant-id - ${tenantId} - - - cloud-region.cloud-owner - openecomp-aic - - - cloud-region.cloud-region-id - ${cloudRegion} - - - - """ - - return requestPayload - } - - def String createCloudRegionVolumeRequest(groupId, volumeName, vnfType, vnfId, tenantId, cloudRegion, namespace, modelCustomizationId) { - - String requestPayload = - """ - ${groupId} - ${volumeName} - - ${vnfType} - Pending - ${modelCustomizationId} - - - generic-vnf - - generic-vnf.vnf-id - ${vnfId} - - - - tenant - - tenant.tenant-id - ${tenantId} - - - cloud-region.cloud-owner - openecomp-aic - - - cloud-region.cloud-region-id - ${cloudRegion} - - - - """ - - 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 = - """ - ${groupId} - ${volumeName} - ${heatStackId} - ${vnfType} - Active - ${resourceVersion} - ${modelCustomizationId} - ${relationshipList} - """ - } - - 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 = - """ - ${groupId} - ${volumeName} - ${heatStackId} - ${vnfType} - Active - ${resourceVersion} - ${relationshipList} - """ - } - - 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"] - 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 = - """ - ${rebuildNetworkElements} - ${rebuildSubnetList} - ${rebuildSegmentationAssignments} - ${rebuildCtagAssignmentsList} - ${relationshipList} - ${contrailNetworkFQDN} - """.trim() - - } - return contrailNetworkCreatedUpdate - } - - - - /** - * This method returns the value for the name paramName. - * Ex: - * 1 - * 0 - * - * - * @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: - * 1 - * 0 - * - * - * @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: - * - * 1 - * 0 - * - * - * Sample result: - * - * 1 - * 0 - * - * - */ - - 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 += "" - 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}>${value}" - } - build += "" - } - - } 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 += ''+vlansList[i]+'' - } - } - } - return rtn - - - } - - /** - * This method returns the uri value for the vpn bindings. - * Return the a list of value of vpn binding in the string. - * Ex. - * - * - * vpn-binding - * https://aai-app-e2e.test.openecomp.com:8443/aai/v6/network/vpn-bindings/vpn-binding/85f015d0-2e32-4c30-96d2-87a1a27f8017/ - * - * vpn-binding.vpn-id - * 85f015d0-2e32-4c30-96d2-87a1a27f8017 - * - * - * - * vpn-binding - * https://aai-ext1.test.openecomp.com:8443/aai/v6/network/vpn-bindings/vpn-binding/24a4b507-853a-4a38-99aa-05fcc54be24d/ - * - * vpn-binding.vpn-id - * 24a4b507-853a-4a38-99aa-05fcc54be24d - * - * - * vpn-binding.vpn-name - * oam_protected_net_6_MTN5_msotest1 - * - * - * @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.getNodeText1(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.getNodeText1(relationshipXml, 'related-link') - if (relatedLink != null || relatedLink != "") { - 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.getNodeText1(relationshipXml, 'related-link') - if (relatedLink != null || relatedLink != "") { - 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.getNodeText1(relationshipXml, 'related-link') - if (relatedLink != null || relatedLink != "") { - lcpCloudRegion = relatedLink.substring(relatedLink.indexOf("/openecomp-aic/")+9, relatedLink.length()) - if (lcpCloudRegion.contains('/')) { - lcpCloudRegion = relatedLink.substring(relatedLink.indexOf("/openecomp-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.getNodeText1(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") { - xmlNetwork += "<"+element+">"+"active"+"" - } - if (element=="heat-stack-id") { - if (replaceNetworkId != "") { - xmlNetwork += "<"+element+">"+replaceNetworkId+"" - } - } - if (element=="neutron-network-id") { - if (replaceNeutronNetworkId != "") { - xmlNetwork += "<"+element+">"+replaceNeutronNetworkId+"" - } - } - if (element=="contrail-network-fqdn") { - if (replaceContrailNetworkFqdn != "") { - xmlNetwork += "<"+element+">"+replaceContrailNetworkFqdn+"" - } - } - - } else { - if (element=="orchestration-status") { - xmlNetwork += "<"+element+">"+"active"+"" - } else { - xmlNetwork += "<"+element+">"+var.toString()+"" - } - } - - } - } - 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 += "" - 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 subnetList = ["subnet-id", "neutron-subnet-id", "gateway-address", "network-start-address", "cidr-mask", "ip-version", "orchestration-status", "dhcp-enabled", "dhcp-start", "dhcp-end", "resource-version", "subnet-name"] - rebuildingSubnets += buildSubNetworkElements(subnetXml, createNetworkResponse, subnetList, "subnet") - } - if (utils.nodeExists(subnetsData, 'relationship')) { - rebuildingSubnets = rebuildRelationship(requeryIdAAIResponse) - } - - } catch (Exception ex) { - // error - } finally { - rebuildingSubnets += "" - } - } - return rebuildingSubnets - } - - def buildSubnets(queryIdResponse) { - def rebuildingSubnets = "" - def subnetsData = new XmlSlurper().parseText(queryIdResponse) - //rebuildingSubnets += "" - 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 subnetList = ["dhcp-start", "dhcp-end", "network-start-address", "cidr-mask", "dhcp-enabled", "gateway-address", "ip-version", "subnet-id", "subnet-name"] - rebuildingSubnets += buildSubNetworkElements(subnetXml, subnetList, "subnets") - //rebuildingSubnets += buildSubNetworkElements(subnetXml, subnetList, "") - } - } catch (Exception ex) { - // - } finally { - //rebuildingSubnets += "" - } - 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") { - xmlBuild += "<"+element+">"+"active"+"" - } else { // "subnet-id", "neutron-subnet-id" - if (element=="subnet-id") { - if (utils.nodeExists(createNetworkResponse, "subnetMap")) { - xmlBuild += "<"+element+">"+var.toString()+"" - String neutronSubnetId = extractNeutSubId(createNetworkResponse, var.toString()) - xmlBuild += ""+neutronSubnetId+"" - } - } else { - if (element=="neutron-subnet-id") { - // skip - } else { - xmlBuild += "<"+element+">"+var.toString()+"" - } - } - } - } - } - - } - if (parentName != "") { - xmlBuild += "" - } - 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 += "" - if (var.toString() == 'null') { - xmlBuild += ""+""+"" - } else { - xmlBuild += ""+var.toString()+"" - } - } - if (element == "dhcp-end") { - if (var.toString() == 'null') { - xmlBuild += ""+""+"" - } else { - xmlBuild += ""+var.toString()+"" - } - xmlBuild += "" - } - if (element == "network-start-address" || element == "cidr-mask") { - if (element == "network-start-address") { - networkStartAddress = var.toString() - } - if (element == "cidr-mask") { - xmlBuild += ""+networkStartAddress+"/"+var.toString()+"" - } - } - if (element == "dhcp-enabled") { - xmlBuild += ""+var.toString()+"" - } - if (element == "gateway-address") { - xmlBuild += ""+var.toString()+"" - } - if (element == "ip-version") { - xmlBuild += ""+var.toString()+"" - } - if (element == "subnet-id") { - xmlBuild += ""+var.toString()+"" - } - if ((element == "subnet-name") && (var != null)) { - xmlBuild += ""+var.toString()+"" - } - } - } - if (parentName != "") { - xmlBuild += "" - } - return xmlBuild - } - - // rebuild ctag-assignments - def rebuildCtagAssignments(xmlInput) { - def rebuildingCtagAssignments = "" - if (xmlInput!=null) { - def ctagAssignmentsData = new XmlSlurper().parseText(xmlInput) - rebuildingCtagAssignments += "" - 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 += "" - List elementList = ["vlan-id-inner", "resource-version"] - rebuildingCtagAssignments += buildXMLElements(ctagAssignmentXml, "" , "", elementList) - if (utils.nodeExists(ctagAssignmentXml, 'relationship')) { - rebuildingCtagAssignments += rebuildRelationship(ctagAssignmentXml) - } - rebuildingCtagAssignments += "" - } - rebuildingCtagAssignments += "" - } - return rebuildingCtagAssignments - } - - // rebuild 'relationship-list' - def rebuildRelationship(xmlInput) { - def rebuildingSubnets = "" - if (xmlInput!=null) { - def subnetsData = new XmlSlurper().parseText(xmlInput) - rebuildingSubnets += "" - 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 += "" - 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 += "" - } - rebuildingSubnets += "" - } - return rebuildingSubnets - } - - def buildVlans(queryIdResponse) { - def rebuildingSubnets = "" - 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.getNodeText1(subnetXml, "segmentation-id") - if (i>0){ - rebuildingSubnets += "," - } - rebuildingSubnets += vlan - } - } catch (Exception ex) { - // - } finally { - //rebuildingSubnets += "" - rebuildingSubnets += "" - } - 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: - * - * - * name - * Edward - * - * - * age - * 30 - * - * - * age - * 30 - * - * - * Usage: - * List elementList = ["key", "value"] - * String rebuild = buildXMLElements(xmlInput, "inputs", "entry", elementList) - * - * Ex 2: xmlInput // no parent tag - * - * fec8ec88-151a-45c9-ad60-8233e0fc8ff2 - * https://msojra.mtsnj.aic.cip.openecomp.com:8443/adapters/rest/SDNCNotify - * assign - * - * 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) - * myTestid - * myUser - * 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()+"" +'\n' - } - } - xmlBuildUnbounded += "" +'\n' - } - } else { - for (element in elementList) { - var = xml.'*'.find {it.name() == element} - if (var != null) { - xmlBuildUnbounded += "<"+element+">"+var.toString()+"" +'\n' - } - } - } - - } - if (parentName!="") {xmlBuildUnbounded += "" +'\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 = - """ - ${subnetId} - ${neutronSubnetId} - ${gatewayAddress} - ${netAddress} - ${mask} - ${ipVersion} - active - ${dhcpEnabledSubnet} - ${relationshipList} - """ - - }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} - """ - - 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 (Execution execution, String payloadXml) { - - def rollbackEnabled = false - def rollbackValueSet = false - if (utils.nodeExists(payloadXml, "backout-on-failure")) { - String backoutValue = utils.getNodeText1(payloadXml, "backout-on-failure") - if (backoutValue != null && !backoutValue.isEmpty()) { - if (backoutValue.equalsIgnoreCase("false")) { - rollbackEnabled = false - } - else { - rollbackEnabled = true - } - rollbackValueSet = true; - } - } - - if (!rollbackValueSet) { - if (execution.getVariable("URN_mso_rollback") != null) { - rollbackEnabled = execution.getVariable("URN_mso_rollback").toBoolean() - } - } - return rollbackEnabled - } -} +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.bpmn.common.scripts; + +import org.apache.commons.lang3.* + +import groovy.xml.XmlUtil + +import javax.xml.parsers.DocumentBuilder +import javax.xml.parsers.DocumentBuilderFactory +import javax.xml.transform.Transformer +import javax.xml.transform.TransformerFactory +import javax.xml.transform.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.runtime.Execution +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.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.runtime.Execution +import org.openecomp.mso.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 { + + 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.getNodeText1(queryIdResponse, "is-shared-network") != null ? utils.getNodeText1(queryIdResponse, "is-shared-network") : "false" + externalValue = utils.getNodeText1(queryIdResponse, "is-external-network") != null ? utils.getNodeText1(queryIdResponse, "is-external-network") : "false" + serviceInstanceId = utils.getNodeText1(requestInput, "service-instance-id") + + } else { // source = 'PORTAL' + sharedValue = getParameterValue(requestInput, "shared") + externalValue = getParameterValue(requestInput, "external") + serviceInstanceId = utils.getNodeText1(requestInput, "service-instance-id") != null ? utils.getNodeText1(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.getNodeText1(requestInput, "tenant-id") + String networkType = "" + if (utils.nodeExists(requestInput, "networkModelInfo")) { + String networkModelInfo = utils.getNodeXml(requestInput, "networkModelInfo", false).replace("tag0:","").replace(":tag0","") + networkType = utils.getNodeText1(networkModelInfo, "modelName") + } else { + networkType = utils.getNodeText1(queryIdResponse, "network-type") + } + + // queryIdResponse + String networkName = utils.getNodeText1(queryIdResponse, "network-name") + String networkId = utils.getNodeText1(queryIdResponse, "network-id") + String networkTechnology = utils.getNodeText1(queryIdResponse, "network-technology") + + // contrailNetwork - networkTechnology = 'Contrail' vs. 'AIC_SR_IOV') + String contrailNetwork = "" + if (networkTechnology.contains('Contrail') || networkTechnology.contains('contrail') || networkTechnology.contains('CONTRAIL')) { + contrailNetwork = """ + ${sharedValue} + ${externalValue} + ${routeCollection} + ${policyFqdns} + ${tableCollection} + """ + 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.getNodeText1(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 = """ + + ${cloudRegion} + ${tenantId} + ${networkId} + ${networkName} + ${networkType} + ${modelCustomizationUuid} + ${networkTechnology} + + ${physicalNetworkName} + ${vlansCollection} + + ${contrailNetwork} + ${subnets} + true + ${backoutOnFailure} + ${failIfExists} + ${networkParams} + + ${requestId} + ${serviceInstanceId} + + ${messageId} + ${notificationUrl} + + """.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.getNodeText1(queryIdResponse, "is-shared-network") != null ? utils.getNodeText1(queryIdResponse, "is-shared-network") : "false" + externalValue = utils.getNodeText1(queryIdResponse, "is-external-network") != null ? utils.getNodeText1(queryIdResponse, "is-external-network") : "false" + serviceInstanceId = utils.getNodeText1(requestInput, "service-instance-id") + + } else { // source = 'PORTAL' + sharedValue = getParameterValue(requestInput, "shared") + externalValue = getParameterValue(requestInput, "external") + serviceInstanceId = utils.getNodeText1(requestInput, "service-instance-id") != null ? utils.getNodeText1(requestInput, "service-instance-id") : "" + } + + String failIfExists = "false" + // requestInput + String cloudRegion = cloudRegionId + String tenantId = utils.getNodeText1(requestInput, "tenant-id") + + // queryIdResponse + String networkName = utils.getNodeText1(queryIdResponse, "network-name") + String networkId = utils.getNodeText1(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.getNodeText1(networkModelInfo, "modelName") + modelCustomizationUuid = utils.getNodeText1(networkModelInfo, "modelCustomizationUuid") + } else { + networkType = utils.getNodeText1(queryIdResponse, "network-type") + } + + + // 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.getNodeText1(queryIdResponse, "heat-stack-id") + if (networkStackId == 'null' || networkStackId == "" || networkStackId == null) { + networkStackId = "force_update" + } + + String physicalNetworkName = utils.getNodeText1(queryIdResponse, "physical-network-name") + String vlansCollection = buildVlans(queryIdResponse) + + updateNetworkRequest = + """ + ${cloudRegion} + ${tenantId} + ${networkId} + ${networkStackId} + ${networkName} + ${networkType} + ${modelCustomizationUuid} + + CONTRAIL + + ${physicalNetworkName} + ${vlansCollection} + + + ${sharedValue} + ${externalValue} + ${routeCollection} + ${policyFqdns} + ${tableCollection} + + ${subnets} + true + ${backoutOnFailure} + ${failIfExists} + ${networkParams} + + + ${requestId} + ${serviceInstanceId} + + ${messageId} + + """.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 = + """ + ${groupId} + ${volumeName} + + ${vnfType} + Pending + + + tenant + + tenant.tenant-id + ${tenantId} + + + + """ + + return requestPayload + } + + def String createCloudRegionVolumeRequest(groupId, volumeName, vnfType, tenantId, cloudRegion, namespace, modelCustomizationId) { + + String requestPayload = + """ + ${groupId} + ${volumeName} + + ${vnfType} + Pending + ${modelCustomizationId} + + + tenant + + tenant.tenant-id + ${tenantId} + + + cloud-region.cloud-owner + att-aic + + + cloud-region.cloud-region-id + ${cloudRegion} + + + + """ + + return requestPayload + } + + def String createCloudRegionVolumeRequest(groupId, volumeName, vnfType, vnfId, tenantId, cloudRegion, namespace, modelCustomizationId) { + + String requestPayload = + """ + ${groupId} + ${volumeName} + + ${vnfType} + Pending + ${modelCustomizationId} + + + generic-vnf + + generic-vnf.vnf-id + ${vnfId} + + + + tenant + + tenant.tenant-id + ${tenantId} + + + cloud-region.cloud-owner + att-aic + + + cloud-region.cloud-region-id + ${cloudRegion} + + + + """ + + 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 = + """ + ${groupId} + ${volumeName} + ${heatStackId} + ${vnfType} + Active + ${resourceVersion} + ${modelCustomizationId} + ${relationshipList} + """ + } + + 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 = + """ + ${groupId} + ${volumeName} + ${heatStackId} + ${vnfType} + Active + ${resourceVersion} + ${relationshipList} + """ + } + + 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"] + 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 = + """ + ${rebuildNetworkElements} + ${rebuildSubnetList} + ${rebuildSegmentationAssignments} + ${rebuildCtagAssignmentsList} + ${relationshipList} + ${contrailNetworkFQDN} + """.trim() + + } + return contrailNetworkCreatedUpdate + } + + + + /** + * This method returns the value for the name paramName. + * Ex: + * 1 + * 0 + * + * + * @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: + * 1 + * 0 + * + * + * @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: + * + * 1 + * 0 + * + * + * Sample result: + * + * 1 + * 0 + * + * + */ + + 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 += "" + 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}>${value}" + } + build += "" + } + + } 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 += ''+vlansList[i]+'' + } + } + } + return rtn + + + } + + /** + * This method returns the uri value for the vpn bindings. + * Return the a list of value of vpn binding in the string. + * Ex. + * + * + * vpn-binding + * https://aai-app-e2e.test.openecomp.com:8443/aai/v6/network/vpn-bindings/vpn-binding/85f015d0-2e32-4c30-96d2-87a1a27f8017/ + * + * vpn-binding.vpn-id + * 85f015d0-2e32-4c30-96d2-87a1a27f8017 + * + * + * + * vpn-binding + * https://aai-ext1.test.openecomp.com:8443/aai/v6/network/vpn-bindings/vpn-binding/24a4b507-853a-4a38-99aa-05fcc54be24d/ + * + * vpn-binding.vpn-id + * 24a4b507-853a-4a38-99aa-05fcc54be24d + * + * + * vpn-binding.vpn-name + * oam_protected_net_6_MTN5_msotest1 + * + * + * @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.getNodeText1(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.getNodeText1(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.getNodeText1(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.getNodeText1(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.getNodeText1(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"+"" + } else { //pending-update or PendingUpdate + xmlNetwork += "<"+element+">"+"Active"+"" + } + } + + if (element=="heat-stack-id") { + if (replaceNetworkId != "") { + xmlNetwork += "<"+element+">"+replaceNetworkId+"" + } + } + if (element=="neutron-network-id") { + if (replaceNeutronNetworkId != "") { + xmlNetwork += "<"+element+">"+replaceNeutronNetworkId+"" + } + } + if (element=="contrail-network-fqdn") { + if (replaceContrailNetworkFqdn != "") { + xmlNetwork += "<"+element+">"+replaceContrailNetworkFqdn+"" + } + } + + } else { + if (element=="orchestration-status") { + if (element=="orchestration-status") { + if (var.toString() == 'pending-create' || var.toString() == 'PendingCreate') { + xmlNetwork += "<"+element+">"+"Created"+"" + } else { //pending-update or PendingUpdate + xmlNetwork += "<"+element+">"+"Active"+"" + } + } + } else { + xmlNetwork += "<"+element+">"+var.toString()+"" + } + } + } + + } + 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 += "" + 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.getNodeText1(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", "resource-version", "subnet-name"] + rebuildingSubnets += buildSubNetworkElements(subnetXml, createNetworkResponse, subnetList, "subnet") + } + } + if (utils.nodeExists(subnetsData, 'relationship')) { + rebuildingSubnets = rebuildRelationship(requeryIdAAIResponse) + } + + } catch (Exception ex) { + // error + } finally { + rebuildingSubnets += "" + } + } + return rebuildingSubnets + } + + def buildSubnets(queryIdResponse) { + def rebuildingSubnets = "" + def subnetsData = new XmlSlurper().parseText(queryIdResponse) + //rebuildingSubnets += "" + 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.getNodeText1(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"] + rebuildingSubnets += buildSubNetworkElements(subnetXml, subnetList, "subnets") + //rebuildingSubnets += buildSubNetworkElements(subnetXml, subnetList, "") + } } + } catch (Exception ex) { + // + } finally { + //rebuildingSubnets += "" + } + 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"+"" + } else { // pending-update or PendingUpdate' + xmlBuild += "<"+element+">"+"Active"+"" + } + } else { // "subnet-id", "neutron-subnet-id" + if (element=="subnet-id") { + if (utils.nodeExists(createNetworkResponse, "subnetMap")) { + xmlBuild += "<"+element+">"+var.toString()+"" + String neutronSubnetId = extractNeutSubId(createNetworkResponse, var.toString()) + xmlBuild += ""+neutronSubnetId+"" + } + } else { + if (element=="neutron-subnet-id") { + // skip + } else { + xmlBuild += "<"+element+">"+var.toString()+"" + } + } + } + } + } + + } + if (parentName != "") { + xmlBuild += "" + } + 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 += "" + if (var.toString() == 'null') { + xmlBuild += ""+""+"" + } else { + xmlBuild += ""+var.toString()+"" + } + } + if (element == "dhcp-end") { + if (var.toString() == 'null') { + xmlBuild += ""+""+"" + } else { + xmlBuild += ""+var.toString()+"" + } + xmlBuild += "" + } + if (element == "network-start-address" || element == "cidr-mask") { + if (element == "network-start-address") { + networkStartAddress = var.toString() + } + if (element == "cidr-mask") { + xmlBuild += ""+networkStartAddress+"/"+var.toString()+"" + } + } + if (element == "dhcp-enabled") { + xmlBuild += ""+var.toString()+"" + } + if (element == "gateway-address") { + xmlBuild += ""+var.toString()+"" + } + if (element == "ip-version") { + xmlBuild += ""+var.toString()+"" + } + if (element == "subnet-id") { + xmlBuild += ""+var.toString()+"" + } + if ((element == "subnet-name") && (var != null)) { + xmlBuild += ""+var.toString()+"" + } + } + } + if (parentName != "") { + xmlBuild += "" + } + return xmlBuild + } + + // rebuild ctag-assignments + def rebuildCtagAssignments(xmlInput) { + def rebuildingCtagAssignments = "" + if (xmlInput!=null) { + def ctagAssignmentsData = new XmlSlurper().parseText(xmlInput) + rebuildingCtagAssignments += "" + 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 += "" + List elementList = ["vlan-id-inner", "resource-version"] + rebuildingCtagAssignments += buildXMLElements(ctagAssignmentXml, "" , "", elementList) + if (utils.nodeExists(ctagAssignmentXml, 'relationship')) { + rebuildingCtagAssignments += rebuildRelationship(ctagAssignmentXml) + } + rebuildingCtagAssignments += "" + } + rebuildingCtagAssignments += "" + } + return rebuildingCtagAssignments + } + + // rebuild 'relationship-list' + def rebuildRelationship(xmlInput) { + def rebuildingSubnets = "" + if (xmlInput!=null) { + def subnetsData = new XmlSlurper().parseText(xmlInput) + rebuildingSubnets += "" + 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 += "" + 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 += "" + } + rebuildingSubnets += "" + } + return rebuildingSubnets + } + + def buildVlans(queryIdResponse) { + def rebuildingSubnets = "" + 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.getNodeText1(subnetXml, "segmentation-id") + if (i>0){ + rebuildingSubnets += "," + } + rebuildingSubnets += vlan + } + } catch (Exception ex) { + // + } finally { + //rebuildingSubnets += "" + rebuildingSubnets += "" + } + 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: + * + * + * name + * Edward + * + * + * age + * 30 + * + * + * age + * 30 + * + * + * Usage: + * List elementList = ["key", "value"] + * String rebuild = buildXMLElements(xmlInput, "inputs", "entry", elementList) + * + * Ex 2: xmlInput // no parent tag + * + * fec8ec88-151a-45c9-ad60-8233e0fc8ff2 + * https://msojra.mtsnj.aic.cip.openecomp.com:8443/adapters/rest/SDNCNotify + * assign + * + * 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) + * myTestid + * myUser + * 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()+"" +'\n' + } + } + xmlBuildUnbounded += "" +'\n' + } + } else { + for (element in elementList) { + var = xml.'*'.find {it.name() == element} + if (var != null) { + xmlBuildUnbounded += "<"+element+">"+var.toString()+"" +'\n' + } + } + } + + } + if (parentName!="") {xmlBuildUnbounded += "" +'\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 = + """ + ${subnetId} + ${neutronSubnetId} + ${gatewayAddress} + ${netAddress} + ${mask} + ${ipVersion} + active + ${dhcpEnabledSubnet} + ${relationshipList} + """ + + }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} + """ + + 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 (Execution execution, String payloadXml) { + + def rollbackEnabled = false + def rollbackValueSet = false + if (utils.nodeExists(payloadXml, "backout-on-failure")) { + String backoutValue = utils.getNodeText1(payloadXml, "backout-on-failure") + if (backoutValue != null && !backoutValue.isEmpty()) { + if (backoutValue.equalsIgnoreCase("false")) { + rollbackEnabled = false + } + else { + rollbackEnabled = true + } + rollbackValueSet = true; + } + } + + if (!rollbackValueSet) { + if (execution.getVariable("URN_mso_rollback") != null) { + rollbackEnabled = execution.getVariable("URN_mso_rollback").toBoolean() + } + } + return rollbackEnabled + } +} diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/PrepareUpdateAAIVfModule.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/PrepareUpdateAAIVfModule.groovy index e64fda6356..f30692c409 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/PrepareUpdateAAIVfModule.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/PrepareUpdateAAIVfModule.groovy @@ -1,368 +1,374 @@ -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - MSO - * ================================================================================ - * 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.openecomp.mso.bpmn.common.scripts - -import org.camunda.bpm.engine.delegate.BpmnError -import org.camunda.bpm.engine.runtime.Execution -import org.openecomp.mso.bpmn.core.WorkflowException -import org.openecomp.mso.rest.APIResponse -import org.openecomp.mso.rest.RESTClient -import org.openecomp.mso.rest.RESTConfig -import org.springframework.web.util.UriUtils - -public class PrepareUpdateAAIVfModule extends VfModuleBase { - - /** - * Initialize the flow's variables. - * - * @param execution The flow's execution instance. - */ - public void initProcessVariables(Execution 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(Execution execution) { - def method = getClass().getSimpleName() + '.preProcessRequest(' + - 'execution=' + execution.getId() + - ')' - def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') - logDebug('Entered ' + method, isDebugLogEnabled) - - try { - def xml = execution.getVariable('PrepareUpdateAAIVfModuleRequest') - logDebug('Received request xml:\n' + xml, isDebugLogEnabled) - utils.logAudit("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) - - logDebug('Exited ' + method, isDebugLogEnabled) - } catch (BpmnError e) { - throw e; - } catch (Exception e) { - logError('Caught exception in ' + method, e) - createWorkflowException(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(Execution execution) { - def method = getClass().getSimpleName() + '.getGenericVnf(' + - 'execution=' + execution.getId() + - ')' - def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') - logDebug('Entered ' + method, isDebugLogEnabled) - - try { - def vnfId = execution.getVariable('PUAAIVfMod_vnfId') - - AaiUtil aaiUriUtil = new AaiUtil(this) - def aai_uri = aaiUriUtil.getNetworkGenericVnfUri(execution) - logDebug('AAI URI is: ' + aai_uri, isDebugLogEnabled) - - String endPoint = execution.getVariable("URN_aai_endpoint") + "${aai_uri}/" + UriUtils.encode(vnfId, "UTF-8") + "?depth=1" - - utils.logAudit("PrepareUpdateAAIVfModule: AAI endPoint : " + endPoint) - String basicAuthCred = utils.getBasicAuth(execution.getVariable("URN_aai_auth"),execution.getVariable("URN_mso_msoKey")) - 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'); - if (basicAuthCred != null && !"".equals(basicAuthCred)) { - client.addAuthorizationHeader(basicAuthCred) - } - logDebug('sending GET to AAI endpoint \'' + endPoint + '\'', isDebugLogEnabled) - APIResponse response = client.httpGet() - utils.logAudit("PrepareUpdateAAIVfModule: - invoking httpGet to AAI") - - responseData = response.getResponseBodyAsString() - execution.setVariable('PUAAIVfMod_getVnfResponseCode', response.getStatusCode()) - execution.setVariable('PUAAIVfMod_getVnfResponse', responseData) - - utils.logAudit("PrepareUpdateAAIVfModule: AAI Response : " + responseData) - utils.logAudit("PrepareUpdateAAIVfModule: AAI ResponseCode : " + response.getStatusCode()) - - logDebug('Response code:' + response.getStatusCode(), isDebugLogEnabled) - logDebug('Response:' + System.lineSeparator() + responseData, isDebugLogEnabled) - } catch (Exception ex) { - ex.printStackTrace() - logDebug('Exception occurred while executing AAI GET:' + ex.getMessage(), isDebugLogEnabled) - execution.setVariable('PUAAIVfMod_getVnfResponseCode', 500) - execution.setVariable('PUAAIVfMod_getVnfResponse', 'AAI GET Failed:' + ex.getMessage()) - } - logDebug('Exited ' + method, isDebugLogEnabled) - } catch (BpmnError e) { - throw e; - } catch (Exception e) { - logError('Caught exception in ' + method, e) - createWorkflowException(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(Execution execution) { - def method = getClass().getSimpleName() + '.validateVfModule(' + - 'execution=' + execution.getId() + - ')' - def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') - logDebug('Entered ' + method, isDebugLogEnabled) - - 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') - if (isDebugLogEnabled) { - logDebug('VF Module \'' + vfModuleId + '\': isBaseVfModule=' + vfModule.isBaseVfModule() + - ', isOnlyVfModule=' + vfModule.isOnlyVfModule() + ', new orchestration-status=' + orchestrationStatus, - isDebugLogEnabled) - } - 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) - } - } - - logDebug('Exited ' + method, isDebugLogEnabled) - } catch (BpmnError e) { - throw e; - } catch (Exception e) { - logError('Caught exception in ' + method, e) - createWorkflowException(execution, 1002, 'Error in validateVfModule(): ' + e.getMessage()) - } - } - - /** - * Construct and send a PUT request to AAI to update the VF Module. - * - * @param execution The flow's execution instance. - */ - public void updateVfModule(Execution execution) { - def method = getClass().getSimpleName() + '.updateVfModule(' + - 'execution=' + execution.getId() + - ')' - def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') - logDebug('Entered ' + method, isDebugLogEnabled) - - 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) - - utils.logAudit("VfModule payload : " + payload) - - // Construct endpoint - def vnfId = execution.getVariable('PUAAIVfMod_vnfId') - def vfModuleId = execution.getVariable('PUAAIVfMod_vfModuleId') - - - AaiUtil aaiUriUtil = new AaiUtil(this) - def aai_uri = aaiUriUtil.getNetworkGenericVnfUri(execution) - logDebug('AAI URI is: ' + aai_uri, isDebugLogEnabled) - - String endPoint = execution.getVariable("URN_aai_endpoint") + "${aai_uri}/" + UriUtils.encode(vnfId, "UTF-8") + "/vf-modules/vf-module/" + UriUtils.encode(vfModuleId, "UTF-8") - utils.logAudit("PrepareUpdateAAIVfModule: AAI endPoint : " + endPoint) - String basicAuthCred = utils.getBasicAuth(execution.getVariable("URN_aai_auth"),execution.getVariable("URN_mso_msoKey")) - 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'); - if (basicAuthCred != null && !"".equals(basicAuthCred)) { - client.addAuthorizationHeader(basicAuthCred) - } - logDebug('sending PUT to AAI endpoint \'' + endPoint + '\'' + 'with payload \n' + payload, isDebugLogEnabled) - APIResponse response = client.httpPut(payload) - utils.logAudit("PrepareUpdateAAIVfModule: - invoking httpPut to AAI") - - responseData = response.getResponseBodyAsString() - execution.setVariable('PUAAIVfMod_updateVfModuleResponseCode', response.getStatusCode()) - execution.setVariable('PUAAIVfMod_updateVfModuleResponse', responseData) - logDebug('Response code:' + response.getStatusCode(), isDebugLogEnabled) - logDebug('Response:' + System.lineSeparator() + responseData, isDebugLogEnabled) - utils.logAudit("PrepareUpdateAAIVfModule: AAI Response : " + responseData) - utils.logAudit("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') - logDebug('Output PUAAIVfMod_vnfName set to ' + vnfName, isDebugLogEnabled) - // TODO: Should deprecate use of processKey+Response variable for the response. Will use "WorkflowResponse" instead - execution.setVariable('WorkflowResponse', newVfModule) - logDebug('Output PUAAIVfMod_outVfModule set for VF Module Id \'' + newVfModule.getElementText('vf-module-id') + '\'', isDebugLogEnabled) - def heatStackId = newVfModule.getElementText('heat-stack-id') - execution.setVariable('PUAAIVfMod_heatStackId', heatStackId) - logDebug('Output PUAAIVfMod_heatStackId set to \'' + heatStackId + '\'', isDebugLogEnabled) - } catch (Exception ex) { - ex.printStackTrace() - logDebug('Exception occurred while executing AAI PUT:' + ex.getMessage(), isDebugLogEnabled) - execution.setVariable('PUAAIVfMod_updateVfModuleResponseCode', 500) - execution.setVariable('PUAAIVfMod_updateVfModuleResponse', 'AAI PUT Failed:' + ex.getMessage()) - } - logDebug('Exited ' + method, isDebugLogEnabled) - } catch (BpmnError e) { - throw e; - } catch (Exception e) { - logError('Caught exception in ' + method, e) - createWorkflowException(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(Execution execution) { - def method = getClass().getSimpleName() + '.handleVnfNotFound(' + - 'execution=' + execution.getId() + - ')' - def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') - logDebug('Entered ' + method, isDebugLogEnabled) - - logError('Error occurred attempting to query AAI, Response Code ' + - execution.getVariable('PUAAIVfMod_getVnfResponseCode') + ', Error Response ' + - execution.getVariable('PUAAIVfMod_getVnfResponse')) - String processKey = getProcessKey(execution); - WorkflowException exception = new WorkflowException(processKey, 5000, - execution.getVariable('PUAAIVfMod_getVnfResponse')) - execution.setVariable('WorkflowException', exception) - - logDebug('Exited ' + method, isDebugLogEnabled) - } - - /** - * Generates a WorkflowException if the VF Module does not pass validation. - * - * @param execution The flow's execution instance. - */ - public void handleVfModuleValidationError(Execution execution) { - def method = getClass().getSimpleName() + '.handleVfModuleValidationError(' + - 'execution=' + execution.getId() + - ')' - def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') - logDebug('Entered ' + method, isDebugLogEnabled) - - def String errorMsg = 'VF Module validation error: ' + execution.getVariable('PUAAIVfMod_vfModuleValidationError') - logError(errorMsg) - utils.logAudit("PrepareUpdateAAIVfModule: Error Message : " + errorMsg) - - String processKey = getProcessKey(execution); - WorkflowException exception = new WorkflowException(processKey, 5000, errorMsg) - execution.setVariable('WorkflowException', exception) - - logDebug('Exited ' + method, isDebugLogEnabled) - } - - /** - * 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(Execution execution) { - def method = getClass().getSimpleName() + '.handleUpdateVfModuleFailure(' + - 'execution=' + execution.getId() + - ')' - def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') - logDebug('Entered ' + method, isDebugLogEnabled) - - logError('Error occurred attempting to update VF Module in AAI, Response Code ' + - execution.getVariable('PUAAIVfMod_updateVfModuleResponseCode') + ', Error Response ' + - execution.getVariable('PUAAIVfMod_updateVfModuleResponse')) - String processKey = getProcessKey(execution); - WorkflowException exception = new WorkflowException(processKey, 5000, - execution.getVariable('PUAAIVfMod_updateVfModuleResponse')) - execution.setVariable('WorkflowException', exception) - - logDebug('Exited ' + method, isDebugLogEnabled) - } -} +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.bpmn.common.scripts + +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.runtime.Execution +import org.openecomp.mso.bpmn.core.WorkflowException +import org.openecomp.mso.rest.APIResponse +import org.openecomp.mso.rest.RESTClient +import org.openecomp.mso.rest.RESTConfig +import org.springframework.web.util.UriUtils + +public class PrepareUpdateAAIVfModule extends VfModuleBase { + + ExceptionUtil exceptionUtil = new ExceptionUtil() + /** + * Initialize the flow's variables. + * + * @param execution The flow's execution instance. + */ + public void initProcessVariables(Execution 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(Execution execution) { + def method = getClass().getSimpleName() + '.preProcessRequest(' + + 'execution=' + execution.getId() + + ')' + def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') + logDebug('Entered ' + method, isDebugLogEnabled) + + try { + def xml = execution.getVariable('PrepareUpdateAAIVfModuleRequest') + logDebug('Received request xml:\n' + xml, isDebugLogEnabled) + utils.logAudit("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) + + logDebug('Exited ' + method, isDebugLogEnabled) + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + logError('Caught exception in ' + method, 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(Execution execution) { + def method = getClass().getSimpleName() + '.getGenericVnf(' + + 'execution=' + execution.getId() + + ')' + def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') + logDebug('Entered ' + method, isDebugLogEnabled) + + try { + def vnfId = execution.getVariable('PUAAIVfMod_vnfId') + + AaiUtil aaiUriUtil = new AaiUtil(this) + def aai_uri = aaiUriUtil.getNetworkGenericVnfUri(execution) + logDebug('AAI URI is: ' + aai_uri, isDebugLogEnabled) + + String endPoint = execution.getVariable("URN_aai_endpoint") + "${aai_uri}/" + UriUtils.encode(vnfId, "UTF-8") + "?depth=1" + + utils.logAudit("PrepareUpdateAAIVfModule: AAI endPoint : " + endPoint) + String basicAuthCred = utils.getBasicAuth(execution.getVariable("URN_aai_auth"),execution.getVariable("URN_mso_msoKey")) + 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'); + if (basicAuthCred != null && !"".equals(basicAuthCred)) { + client.addAuthorizationHeader(basicAuthCred) + } + logDebug('sending GET to AAI endpoint \'' + endPoint + '\'', isDebugLogEnabled) + APIResponse response = client.httpGet() + utils.logAudit("PrepareUpdateAAIVfModule: - invoking httpGet to AAI") + + responseData = response.getResponseBodyAsString() + execution.setVariable('PUAAIVfMod_getVnfResponseCode', response.getStatusCode()) + execution.setVariable('PUAAIVfMod_getVnfResponse', responseData) + + utils.logAudit("PrepareUpdateAAIVfModule: AAI Response : " + responseData) + utils.logAudit("PrepareUpdateAAIVfModule: AAI ResponseCode : " + response.getStatusCode()) + + logDebug('Response code:' + response.getStatusCode(), isDebugLogEnabled) + logDebug('Response:' + System.lineSeparator() + responseData, isDebugLogEnabled) + } catch (Exception ex) { + ex.printStackTrace() + logDebug('Exception occurred while executing AAI GET:' + ex.getMessage(), isDebugLogEnabled) + execution.setVariable('PUAAIVfMod_getVnfResponseCode', 500) + execution.setVariable('PUAAIVfMod_getVnfResponse', 'AAI GET Failed:' + ex.getMessage()) + } + logDebug('Exited ' + method, isDebugLogEnabled) + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + logError('Caught exception in ' + method, 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(Execution execution) { + def method = getClass().getSimpleName() + '.validateVfModule(' + + 'execution=' + execution.getId() + + ')' + def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') + logDebug('Entered ' + method, isDebugLogEnabled) + + 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') + if (isDebugLogEnabled) { + logDebug('VF Module \'' + vfModuleId + '\': isBaseVfModule=' + vfModule.isBaseVfModule() + + ', isOnlyVfModule=' + vfModule.isOnlyVfModule() + ', new orchestration-status=' + orchestrationStatus, + isDebugLogEnabled) + } + 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) + } + } + + logDebug('Exited ' + method, isDebugLogEnabled) + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + logError('Caught exception in ' + method, 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(Execution execution) { + def method = getClass().getSimpleName() + '.updateVfModule(' + + 'execution=' + execution.getId() + + ')' + def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') + logDebug('Entered ' + method, isDebugLogEnabled) + + 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}" + }""" + + utils.logAudit("VfModule payload : " + payload) + + AaiUtil aaiUriUtil = new AaiUtil(this) + def aai_uri = aaiUriUtil.getNetworkGenericVnfUri(execution) + logDebug('AAI URI is: ' + aai_uri, isDebugLogEnabled) + + String endPoint = execution.getVariable("URN_aai_endpoint") + "${aai_uri}/" + UriUtils.encode(vnfId, "UTF-8") + "/vf-modules/vf-module/" + UriUtils.encode(vfModuleId, "UTF-8") + utils.logAudit("PrepareUpdateAAIVfModule: AAI endPoint : " + endPoint) + String basicAuthCred = utils.getBasicAuth(execution.getVariable("URN_aai_auth"),execution.getVariable("URN_mso_msoKey")) + 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/merge-patch+json'). + addHeader('Accept','application/json'); + if (basicAuthCred != null && !"".equals(basicAuthCred)) { + client.addAuthorizationHeader(basicAuthCred) + } + logDebug('sending PATCH to AAI endpoint \'' + endPoint + '\'' + 'with payload \n' + payload, isDebugLogEnabled) + APIResponse response = client.httpPatch(payload) + utils.logAudit("PrepareUpdateAAIVfModule: - invoking httpPatch to AAI") + utils.logAudit("PrepareUpdateAAIVfModule: - invoking httpPatch to AAI") + + responseData = response.getResponseBodyAsString() + execution.setVariable('PUAAIVfMod_updateVfModuleResponseCode', response.getStatusCode()) + execution.setVariable('PUAAIVfMod_updateVfModuleResponse', responseData) + logDebug('Response code:' + response.getStatusCode(), isDebugLogEnabled) + logDebug('Response:' + System.lineSeparator() + responseData, isDebugLogEnabled) + utils.logAudit("PrepareUpdateAAIVfModule: AAI Response : " + responseData) + utils.logAudit("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') + logDebug('Output PUAAIVfMod_vnfName set to ' + vnfName, isDebugLogEnabled) + // TODO: Should deprecate use of processKey+Response variable for the response. Will use "WorkflowResponse" instead + execution.setVariable('WorkflowResponse', newVfModule) + logDebug('Output PUAAIVfMod_outVfModule set for VF Module Id \'' + newVfModule.getElementText('vf-module-id') + '\'', isDebugLogEnabled) + def heatStackId = newVfModule.getElementText('heat-stack-id') + execution.setVariable('PUAAIVfMod_heatStackId', heatStackId) + logDebug('Output PUAAIVfMod_heatStackId set to \'' + heatStackId + '\'', isDebugLogEnabled) + } catch (Exception ex) { + ex.printStackTrace() + logDebug('Exception occurred while executing AAI PUT:' + ex.getMessage(), isDebugLogEnabled) + execution.setVariable('PUAAIVfMod_updateVfModuleResponseCode', 500) + execution.setVariable('PUAAIVfMod_updateVfModuleResponse', 'AAI PATCH Failed:' + ex.getMessage()) + } + logDebug('Exited ' + method, isDebugLogEnabled) + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + logError('Caught exception in ' + method, 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(Execution execution) { + def method = getClass().getSimpleName() + '.handleVnfNotFound(' + + 'execution=' + execution.getId() + + ')' + def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') + logDebug('Entered ' + method, isDebugLogEnabled) + + logError('Error occurred attempting to query AAI, Response Code ' + + execution.getVariable('PUAAIVfMod_getVnfResponseCode') + ', Error Response ' + + execution.getVariable('PUAAIVfMod_getVnfResponse')) + String processKey = getProcessKey(execution); + WorkflowException exception = new WorkflowException(processKey, 5000, + execution.getVariable('PUAAIVfMod_getVnfResponse')) + execution.setVariable('WorkflowException', exception) + + logDebug('Exited ' + method, isDebugLogEnabled) + } + + /** + * Generates a WorkflowException if the VF Module does not pass validation. + * + * @param execution The flow's execution instance. + */ + public void handleVfModuleValidationError(Execution execution) { + def method = getClass().getSimpleName() + '.handleVfModuleValidationError(' + + 'execution=' + execution.getId() + + ')' + def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') + logDebug('Entered ' + method, isDebugLogEnabled) + + def String errorMsg = 'VF Module validation error: ' + execution.getVariable('PUAAIVfMod_vfModuleValidationError') + logError(errorMsg) + utils.logAudit("PrepareUpdateAAIVfModule: Error Message : " + errorMsg) + + String processKey = getProcessKey(execution); + WorkflowException exception = new WorkflowException(processKey, 5000, errorMsg) + execution.setVariable('WorkflowException', exception) + + logDebug('Exited ' + method, isDebugLogEnabled) + } + + /** + * 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(Execution execution) { + def method = getClass().getSimpleName() + '.handleUpdateVfModuleFailure(' + + 'execution=' + execution.getId() + + ')' + def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') + logDebug('Entered ' + method, isDebugLogEnabled) + + logError('Error occurred attempting to update VF Module in AAI, Response Code ' + + execution.getVariable('PUAAIVfMod_updateVfModuleResponseCode') + ', Error Response ' + + execution.getVariable('PUAAIVfMod_updateVfModuleResponse')) + String processKey = getProcessKey(execution); + WorkflowException exception = new WorkflowException(processKey, 5000, + execution.getVariable('PUAAIVfMod_updateVfModuleResponse')) + execution.setVariable('WorkflowException', exception) + + logDebug('Exited ' + method, isDebugLogEnabled) + } +} diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/SDNCAdapter.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/SDNCAdapter.groovy index d83f46e85f..0f05a6b82c 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/SDNCAdapter.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/SDNCAdapter.groovy @@ -1,326 +1,334 @@ -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - MSO - * ================================================================================ - * 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.openecomp.mso.bpmn.common.scripts; - -import java.text.SimpleDateFormat - -import org.camunda.bpm.engine.runtime.Execution -import org.openecomp.mso.bpmn.core.WorkflowException - - -// SDNC Adapter Request/Response processing - -public class SDNCAdapter extends AbstractServiceTaskProcessor { - - def Prefix="SDNCA_" - ExceptionUtil exceptionUtil = new ExceptionUtil() - - // Script Task: Process SDNC Workflow Request - // Params: Workflow Execution - // Assume: Received SDNCAdapterWorkflowRequest is in variable 'sdncAdapterWorkflowRequest' - // Put created SDNCAdapterRequest in variable 'sdncAdapterRequest' - public void preProcessRequest (Execution execution) { - def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - try{ - - utils.log("DEBUG", "=========== Begin PreProcess SDNCAdapterRequestScript ===========", isDebugEnabled) - utils.log("DEBUG", "Incoming sdncAdapterWorkflowRequest:\n" + execution.getVariable("sdncAdapterWorkflowRequest"), isDebugEnabled) - - // 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) - - // Authorization Info - String basicAuthValue = execution.getVariable("URN_mso_adapters_po_auth") - utils.log("DEBUG", "Obtained BasicAuth userid password for sdnc adapter:" + basicAuthValue, isDebugEnabled) - try { - def encodedString = utils.getBasicAuth(basicAuthValue, execution.getVariable("URN_mso_msoKey")) - execution.setVariable("BasicAuthHeaderValue",encodedString) - } catch (IOException ex) { - utils.log("ERROR", "Unable to encode username password string") - } - - // 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("\n", "") - utils.log("DEBUG", "RequestHeader:\n" + requestHeader, isDebugEnabled) - - // Set Callback URL to use from URN Mapping or jBoss Property - def origCallbackUrl = utils.getNodeText(requestHeader, "CallbackUrl") - def callbackUrlToUse = execution.getVariable("URN_mso_workflow_sdncadapter_callback") - MsoUtils msoUtil = new MsoUtils() - def useQualifiedHostName = execution.getVariable("URN_mso_use_qualified_host") - if((useQualifiedHostName!=null) && (useQualifiedHostName.equals("true"))){ - callbackUrlToUse = msoUtil.getQualifiedHostNameForCallback(callbackUrlToUse) - } - utils.log("DEBUG", "Callback URL to use:\n" + callbackUrlToUse, isDebugEnabled) - requestHeader = requestHeader.replace(origCallbackUrl, callbackUrlToUse) - - // Get parameters from request header - def sdnca_svcInstanceId = utils.getNodeText1(requestHeader, "SvcInstanceId") // optional - utils.log("DEBUG", "SvcInstanceId: " + sdnca_svcInstanceId, isDebugEnabled) - def sdnca_msoAction = utils.getNodeText1(requestHeader, "MsoAction") // optional - utils.log("DEBUG", "MsoAction: " + sdnca_msoAction, isDebugEnabled) - def sdnca_svcAction = utils.getNodeText(requestHeader, "SvcAction") - utils.log("DEBUG", "SvcAction: " + sdnca_svcAction, isDebugEnabled) - def sdnca_svcOperation = utils.getNodeText(requestHeader, "SvcOperation") - utils.log("DEBUG", "SvcOperation: " + sdnca_svcOperation, isDebugEnabled) - def sdncRequestData = utils.getChildNodes(sdncwfreq, "SDNCRequestData") - sdncRequestData = sdncRequestData.replace("\n", "") - sdncRequestData = sdncRequestData.replaceAll('tag0:', '').replaceAll(':tag0', '') - utils.log("DEBUG", "SDNCRequestData:\n" + sdncRequestData, isDebugEnabled) - def sdnca_serviceType = "" - if (utils.nodeExists(sdncwfreq, "service-type")) { - sdnca_serviceType = utils.getNodeText(sdncwfreq, "service-type") - } - utils.log("DEBUG", "service-type: " + sdnca_serviceType, isDebugEnabled) - 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) - utils.log("DEBUG", "serviceConfigActivate: " + serviceConfigActivate, isDebugEnabled) - execution.setVariable("source", source) - utils.log("DEBUG", "source: " + source, isDebugEnabled) - - //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 = """ - - - - - ${requestId}""" - - if (sdnca_svcInstanceId != null) { - sdncAdapterRequest += """ - ${sdnca_svcInstanceId}""" - } - - sdncAdapterRequest += """ - ${sdnca_svcAction} - ${sdnca_svcOperation} - ${callbackUrlToUse}""" - - if (sdnca_msoAction != null) { - sdncAdapterRequest += """ - ${sdnca_msoAction}""" - } - - sdncAdapterRequest += """ - - ${sdncRequestData}""" - - utils.logAudit("Outgoing SDNCAdapterRequest:\n" + sdncAdapterRequest) - execution.setVariable("sdncAdapterRequest", sdncAdapterRequest) - +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.bpmn.common.scripts; + +import java.text.SimpleDateFormat + +import org.camunda.bpm.engine.runtime.Execution +import org.openecomp.mso.bpmn.core.WorkflowException + + +// SDNC Adapter Request/Response processing + +public class SDNCAdapter extends AbstractServiceTaskProcessor { + + def Prefix="SDNCA_" + ExceptionUtil exceptionUtil = new ExceptionUtil() + + // Script Task: Process SDNC Workflow Request + // Params: Workflow Execution + // Assume: Received SDNCAdapterWorkflowRequest is in variable 'sdncAdapterWorkflowRequest' + // Put created SDNCAdapterRequest in variable 'sdncAdapterRequest' + public void preProcessRequest (Execution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + try{ + + utils.log("DEBUG", "=========== Begin PreProcess SDNCAdapterRequestScript ===========", isDebugEnabled) + utils.log("DEBUG", "Incoming sdncAdapterWorkflowRequest:\n" + execution.getVariable("sdncAdapterWorkflowRequest"), isDebugEnabled) + + // 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) + + // Authorization Info + String basicAuthValue = execution.getVariable("URN_mso_adapters_po_auth") + utils.log("DEBUG", "Obtained BasicAuth userid password for sdnc adapter:" + basicAuthValue, isDebugEnabled) + try { + def encodedString = utils.getBasicAuth(basicAuthValue, execution.getVariable("URN_mso_msoKey")) + execution.setVariable("BasicAuthHeaderValue",encodedString) + } catch (IOException ex) { + utils.log("ERROR", "Unable to encode username password string") + } + + // 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("\n", "") + utils.log("DEBUG", "RequestHeader:\n" + requestHeader, isDebugEnabled) + + // Set Callback URL to use from URN Mapping or jBoss Property + def origCallbackUrl = utils.getNodeText(requestHeader, "CallbackUrl") + def callbackUrlToUse = execution.getVariable("URN_mso_workflow_sdncadapter_callback") + MsoUtils msoUtil = new MsoUtils() + def useQualifiedHostName = execution.getVariable("URN_mso_use_qualified_host") + if((useQualifiedHostName!=null) && (useQualifiedHostName.equals("true"))){ + callbackUrlToUse = msoUtil.getQualifiedHostNameForCallback(callbackUrlToUse) + } + utils.log("DEBUG", "Callback URL to use:\n" + callbackUrlToUse, isDebugEnabled) + requestHeader = requestHeader.replace(origCallbackUrl, callbackUrlToUse) + + // Get parameters from request header + def sdnca_svcInstanceId = utils.getNodeText1(requestHeader, "SvcInstanceId") // optional + utils.log("DEBUG", "SvcInstanceId: " + sdnca_svcInstanceId, isDebugEnabled) + def sdnca_msoAction = utils.getNodeText1(requestHeader, "MsoAction") // optional + utils.log("DEBUG", "MsoAction: " + sdnca_msoAction, isDebugEnabled) + def sdnca_svcAction = utils.getNodeText(requestHeader, "SvcAction") + utils.log("DEBUG", "SvcAction: " + sdnca_svcAction, isDebugEnabled) + def sdnca_svcOperation = utils.getNodeText(requestHeader, "SvcOperation") + utils.log("DEBUG", "SvcOperation: " + sdnca_svcOperation, isDebugEnabled) + def sdncRequestData = utils.getChildNodes(sdncwfreq, "SDNCRequestData") + sdncRequestData = sdncRequestData.replace("\n", "") + sdncRequestData = sdncRequestData.replaceAll('tag0:', '').replaceAll(':tag0', '') + utils.log("DEBUG", "SDNCRequestData:\n" + sdncRequestData, isDebugEnabled) + def sdnca_serviceType = "" + if (utils.nodeExists(sdncwfreq, "service-type")) { + sdnca_serviceType = utils.getNodeText(sdncwfreq, "service-type") + } + utils.log("DEBUG", "service-type: " + sdnca_serviceType, isDebugEnabled) + 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) + utils.log("DEBUG", "serviceConfigActivate: " + serviceConfigActivate, isDebugEnabled) + execution.setVariable("source", source) + utils.log("DEBUG", "source: " + source, isDebugEnabled) + + //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 = """ + + + + + ${requestId}""" + + if (sdnca_svcInstanceId != null) { + sdncAdapterRequest += """ + ${sdnca_svcInstanceId}""" + } + + sdncAdapterRequest += """ + ${sdnca_svcAction} + ${sdnca_svcOperation} + ${callbackUrlToUse}""" + + if (sdnca_msoAction != null) { + sdncAdapterRequest += """ + ${sdnca_msoAction}""" + } + + sdncAdapterRequest += """ + + ${sdncRequestData}""" + + utils.logAudit("Outgoing SDNCAdapterRequest:\n" + sdncAdapterRequest) + execution.setVariable("sdncAdapterRequest", sdncAdapterRequest) + utils.log("DEBUG", execution.getVariable("sdncAdapterRequest"), isDebugEnabled) utils.log("DEBUG", execution.getVariable("URN_mso_adapters_sdnc_endpoint"), isDebugEnabled) - }catch(Exception e){ - utils.log("DEBUG", 'Internal Error occured during PreProcess Method: ' + e, isDebugEnabled) - exceptionUtil.buildAndThrowWorkflowException(execution, 9999, 'Internal Error occured during PreProcess Method') // TODO: what message and error code? - } - utils.log("DEBUG","=========== End pre Process SDNCRequestScript ===========", isDebugEnabled) - } - - public void postProcessResponse (Execution execution) { - - def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - try{ - utils.log("DEBUG","=========== Begin POSTProcess SDNCAdapter ===========", isDebugEnabled) - utils.log("DEBUG","Incoming sdncAdapterCallbackRequest:\n" + execution.getVariable("sdncAdapterCallbackRequest"), isDebugEnabled) - - // Check the sdnccallback request and get the responsecode - def sdnccallbackreq = execution.getVariable("sdncAdapterCallbackRequest") - def callbackRequestData = "" - def callbackHeader = "" - utils.logAudit("SDNCAdapterCallback Request :" + sdnccallbackreq) - - if(sdnccallbackreq != null){ - callbackHeader = utils.getNodeXml(sdnccallbackreq, "CallbackHeader") - callbackRequestData = utils.getNodeXml(sdnccallbackreq, "RequestData") - - callbackHeader = callbackHeader.replace("\n", "") - utils.log("DEBUG","SDNCCallbackHeader is:\n" + callbackHeader, isDebugEnabled) - - callbackRequestData = callbackRequestData.replace("\n", "") - utils.log("DEBUG","DECODED SDNCCallback RequestData is:\n" + callbackRequestData, isDebugEnabled) - - String sdncAdapterWorkflowResponse =""" + }catch(Exception e){ + utils.log("DEBUG", 'Internal Error occured during PreProcess Method: ' + e, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 9999, 'Internal Error occured during PreProcess Method') // TODO: what message and error code? + } + utils.log("DEBUG","=========== End pre Process SDNCRequestScript ===========", isDebugEnabled) + } + + public void postProcessResponse (Execution execution) { + + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + try{ + utils.log("DEBUG","=========== Begin POSTProcess SDNCAdapter ===========", isDebugEnabled) + utils.log("DEBUG","Incoming sdncAdapterCallbackRequest:\n" + execution.getVariable("sdncAdapterCallbackRequest"), isDebugEnabled) + + // Check the sdnccallback request and get the responsecode + def sdnccallbackreq = execution.getVariable("sdncAdapterCallbackRequest") + def callbackRequestData = "" + def callbackHeader = "" + utils.logAudit("SDNCAdapterCallback Request :" + sdnccallbackreq) + + if(sdnccallbackreq != null){ + callbackHeader = utils.getNodeXml(sdnccallbackreq, "CallbackHeader") + callbackRequestData = utils.getNodeXml(sdnccallbackreq, "RequestData") + + callbackHeader = callbackHeader.replace("\n", "") + utils.log("DEBUG","SDNCCallbackHeader is:\n" + callbackHeader, isDebugEnabled) + + callbackRequestData = callbackRequestData.replace("\n", "") + utils.log("DEBUG","DECODED SDNCCallback RequestData is:\n" + callbackRequestData, isDebugEnabled) + + String sdncAdapterWorkflowResponse =""" - - ${callbackHeader} - ${callbackRequestData} - - """ - - - utils.log("DEBUG","Outgoing sdncAdapterWorkflowResponse:\n" + sdncAdapterWorkflowResponse, isDebugEnabled) - sdncAdapterWorkflowResponse = utils.formatXml(sdncAdapterWorkflowResponse) - utils.logAudit("sdncAdapterWorkflowResponse :" + 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 String enhancedCallbackRequestData = callbackRequestData.replaceAll("&", "&") - enhancedCallbackRequestData = enhancedCallbackRequestData.replaceAll("<", "<") - enhancedCallbackRequestData = enhancedCallbackRequestData.replaceAll(">", ">") - // replace the data with '&' (ex: subscriber-name= 'FOUR SEASONS HEATING & COOLING' - enhancedCallbackRequestData = enhancedCallbackRequestData.replace("&", "&") - utils.log("DEBUG","EnhancedCallbackRequestData:\n" + enhancedCallbackRequestData, isDebugEnabled) - execution.setVariable("enhancedCallbackRequestData", enhancedCallbackRequestData) - def continueListening = false - if (utils.nodeExists(enhancedCallbackRequestData, "ack-final-indicator")) { - if (utils.getNodeText(enhancedCallbackRequestData, "ack-final-indicator") == 'N') { - continueListening = true - } - } - execution.setVariable("continueListening", continueListening) - utils.log("DEBUG", "Continue Listening: " + continueListening, isDebugEnabled) - }else{ - // Timed out waiting for asynchronous message, build error response - exceptionUtil.buildWorkflowException(execution, 500, "SDNC Callback Timeout Error") - execution.setVariable("asynchronousResponseTimeout", true) - utils.log("DEBUG", "Timed out waiting for asynchronous message", isDebugEnabled) - } - }catch(Exception e){ - utils.log("DEBUG", 'Internal Error occured during PostProcess Method: ' + e, isDebugEnabled) - exceptionUtil.buildAndThrowWorkflowException(execution, 9999, 'Internal Error occured during PostProcess Method') // TODO: what message and error code? - } - utils.log("DEBUG","=========== End POSTProcess SDNCAdapter ===========", isDebugEnabled) - } - - public void callbackResponsecheck(Execution execution){ - - def sdnccallbackreq=execution.getVariable("sdncAdapterCallbackRequest") - utils.logAudit("sdncAdapterCallbackRequest :" + sdnccallbackreq) - if (sdnccallbackreq==null){ - execution.setVariable("callbackResponseReceived",false); - }else{ - execution.setVariable("callbackResponseReceived",true); - } - } - - public void resetCallbackRequest(Execution execution) { - - def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - - utils.log("DEBUG","=========== Begin Reset Callback Info SDNCAdapter ===========", isDebugEnabled) - - // Clear sdncAdapterCallbackRequest variable - execution.removeVariable("sdncAdapterCallbackRequest") - - // Determine and set SDNC Timeout Value - def enhancedCallbackRequestData = execution.getVariable("enhancedCallbackRequestData") - utils.logAudit("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 = execution.getVariable("URN_mso_sdnc_timeout") - 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) - utils.log("DEBUG", "Setting SDNC Timeout Value to " + timeoutValue, isDebugEnabled) - - utils.log("DEBUG","=========== End Reset Callback Info SDNCAdapter ===========", isDebugEnabled) - } - - - public void prepareDBMessage(Execution execution) { - - def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - - utils.log("DEBUG","=========== Begin Prepare DB Message SDNCAdapter ===========", isDebugEnabled) - - // Create DB Message - def dbRequestId = execution.getVariable("mso-request-id") - String dbUpdateInterimStageCompletion = """ - - - - ${dbRequestId} - 1 - BPEL - - - - """ - - execution.setVariable("dbUpdateInterimStageCompletion", dbUpdateInterimStageCompletion) - utils.logAudit("sdncAdapter - dbUpdateInterimStageCompletion :" + dbUpdateInterimStageCompletion) - utils.log("DEBUG","DB UpdateInterimStageCompletion:\n" + dbUpdateInterimStageCompletion, isDebugEnabled) - utils.log("DEBUG","=========== End Prepare DB Message SDNCAdapter ===========", isDebugEnabled) - } - - - - 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(Execution execution){ - def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - execution.setVariable("SDNCA_SuccessIndicator", true) - utils.log("DEBUG","Setting SDNCA Success Indicator to True", isDebugEnabled) - } - - public void assignError(Execution execution){ - def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - utils.log("DEBUG","=========== Started Assign Error ===========", isDebugEnabled) - 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) - } - - utils.log("DEBUG","Outgoing WorkflowException is: " + execution.getVariable("WorkflowException"), isDebugEnabled) - utils.log("DEBUG","=========== End Assign Error ===========", isDebugEnabled) - } - -} - + + ${callbackHeader} + ${callbackRequestData} + + """ + + + utils.log("DEBUG","Outgoing sdncAdapterWorkflowResponse:\n" + sdncAdapterWorkflowResponse, isDebugEnabled) + sdncAdapterWorkflowResponse = utils.formatXml(sdncAdapterWorkflowResponse) + utils.logAudit("sdncAdapterWorkflowResponse :" + 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 String enhancedCallbackRequestData = callbackRequestData.replaceAll("&", "&") + enhancedCallbackRequestData = enhancedCallbackRequestData.replaceAll("<", "<") + enhancedCallbackRequestData = enhancedCallbackRequestData.replaceAll(">", ">") + // replace the data with '&' (ex: subscriber-name= 'FOUR SEASONS HEATING & COOLING' + enhancedCallbackRequestData = enhancedCallbackRequestData.replace("&", "&") + utils.log("DEBUG","EnhancedCallbackRequestData:\n" + enhancedCallbackRequestData, isDebugEnabled) + execution.setVariable("enhancedCallbackRequestData", enhancedCallbackRequestData) + def continueListening = false + if (utils.nodeExists(enhancedCallbackRequestData, "ack-final-indicator")) { + if (utils.getNodeText(enhancedCallbackRequestData, "ack-final-indicator") == 'N') { + continueListening = true + } + } + execution.setVariable("continueListening", continueListening) + utils.log("DEBUG", "Continue Listening: " + continueListening, isDebugEnabled) + 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) + utils.log("DEBUG", "Timed out waiting for asynchronous message", isDebugEnabled) + } + }catch(Exception e){ + utils.log("DEBUG", 'Internal Error occured during PostProcess Method: ' + e, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 9999, 'Internal Error occured during PostProcess Method') // TODO: what message and error code? + } + utils.log("DEBUG","=========== End POSTProcess SDNCAdapter ===========", isDebugEnabled) + } + + public void callbackResponsecheck(Execution execution){ + + def sdnccallbackreq=execution.getVariable("sdncAdapterCallbackRequest") + utils.logAudit("sdncAdapterCallbackRequest :" + sdnccallbackreq) + if (sdnccallbackreq==null){ + execution.setVariable("callbackResponseReceived",false); + }else{ + execution.setVariable("callbackResponseReceived",true); + } + } + + public void resetCallbackRequest(Execution execution) { + + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + + utils.log("DEBUG","=========== Begin Reset Callback Info SDNCAdapter ===========", isDebugEnabled) + + // Clear sdncAdapterCallbackRequest variable + execution.removeVariable("sdncAdapterCallbackRequest") + + // Determine and set SDNC Timeout Value + def enhancedCallbackRequestData = execution.getVariable("enhancedCallbackRequestData") + utils.logAudit("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 = execution.getVariable("URN_mso_sdnc_timeout") + 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) + utils.log("DEBUG", "Setting SDNC Timeout Value to " + timeoutValue, isDebugEnabled) + + utils.log("DEBUG","=========== End Reset Callback Info SDNCAdapter ===========", isDebugEnabled) + } + + + public void prepareDBMessage(Execution execution) { + + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + + utils.log("DEBUG","=========== Begin Prepare DB Message SDNCAdapter ===========", isDebugEnabled) + + // Create DB Message + def dbRequestId = execution.getVariable("mso-request-id") + String dbUpdateInterimStageCompletion = """ + + + + ${dbRequestId} + 1 + BPEL + + + + """ + + execution.setVariable("dbUpdateInterimStageCompletion", dbUpdateInterimStageCompletion) + utils.logAudit("sdncAdapter - dbUpdateInterimStageCompletion :" + dbUpdateInterimStageCompletion) + utils.log("DEBUG","DB UpdateInterimStageCompletion:\n" + dbUpdateInterimStageCompletion, isDebugEnabled) + utils.log("DEBUG","=========== End Prepare DB Message SDNCAdapter ===========", isDebugEnabled) + } + + 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(Execution execution){ + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + execution.setVariable("SDNCA_SuccessIndicator", true) + utils.log("DEBUG","Setting SDNCA Success Indicator to True", isDebugEnabled) + } + + public void assignError(Execution execution){ + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + utils.log("DEBUG","=========== Started Assign Error ===========", isDebugEnabled) + 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) + } + + utils.log("DEBUG","Outgoing WorkflowException is: " + execution.getVariable("WorkflowException"), isDebugEnabled) + utils.log("DEBUG","=========== End Assign Error ===========", isDebugEnabled) + } + + public void setTimeout(Execution execution){ + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + utils.log("DEBUG","=========== Started SetTimeout ===========", isDebugEnabled) + utils.log("DEBUG", "Timer expired, telling correlation service to stop listening", isDebugEnabled) + execution.setVariable("asynchronousResponseTimeout", true) + + utils.log("DEBUG", "Timed out branch sleeping for one second to give success branch a chance to complete if running", isDebugEnabled) + Thread.sleep(1000) + utils.log("DEBUG","=========== End SetTimeout ===========", isDebugEnabled) + } +} diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/SDNCAdapterRestV1.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/SDNCAdapterRestV1.groovy new file mode 100644 index 0000000000..1859838f29 --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/SDNCAdapterRestV1.groovy @@ -0,0 +1,343 @@ +package org.openecomp.mso.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.runtime.Execution + +import groovy.json.* + +import org.json.JSONObject + +import org.openecomp.mso.bpmn.core.WorkflowException +import org.openecomp.mso.bpmn.core.json.JsonUtils +import org.openecomp.mso.rest.APIResponse +import org.openecomp.mso.rest.RESTClient +import org.openecomp.mso.rest.RESTConfig + + +class SDNCAdapterRestV1 extends AbstractServiceTaskProcessor { + + ExceptionUtil exceptionUtil = new ExceptionUtil() + JsonUtils jsonUtil = new JsonUtils() + + /** + * Processes the incoming request. + */ + public void preProcessRequest (Execution execution) { + def method = getClass().getSimpleName() + '.preProcessRequest(' + + 'execution=' + execution.getId() + + ')' + def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') + logDebug('Entered ' + method, isDebugLogEnabled) + + 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) + logDebug(getProcessKey(execution) + ': ' + prefix + 'requestType = ' + requestType, isDebugLogEnabled) + utils.logAudit('SDNCAdapterRestV1, request: ' + request) + + // Determine the SDNCAdapter endpoint + + String sdncAdapterEndpoint = execution.getVariable("URN_mso_adapters_sdnc_rest_endpoint") + + if (sdncAdapterEndpoint == null || sdncAdapterEndpoint.isEmpty()) { + String msg = getProcessKey(execution) + ': mso:adapters:sdnc:rest:endpoint URN mapping is not defined' + logDebug(msg, isDebugLogEnabled) + logError(msg) + 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 + logDebug(msg, isDebugLogEnabled) + logError(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg) + } + + execution.setVariable('SDNCAResponse_CORRELATOR', sdncRequestId) + logDebug(getProcessKey(execution) + ': SDNCAResponse_CORRELATOR = ' + sdncRequestId, isDebugLogEnabled) + + // 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 + logDebug(msg, isDebugLogEnabled) + logError(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg) + } + + sdncAdapterMethod = 'POST' + sdncAdapterUrl = sdncAdapterEndpoint + '/services' + + } else { + String msg = getProcessKey(execution) + ': Unsupported request type: ' + requestType + logDebug(msg, isDebugLogEnabled) + logError(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg) + } + + execution.setVariable(prefix + 'sdncAdapterMethod', sdncAdapterMethod) + logDebug(getProcessKey(execution) + ': ' + prefix + 'sdncAdapterMethod = ' + sdncAdapterMethod, isDebugLogEnabled) + execution.setVariable(prefix + 'sdncAdapterUrl', sdncAdapterUrl) + logDebug(getProcessKey(execution) + ': ' + prefix + 'sdncAdapterUrl = ' + sdncAdapterUrl, isDebugLogEnabled) + execution.setVariable(prefix + 'sdncAdapterRequest', sdncAdapterRequest) + logDebug(getProcessKey(execution) + ': ' + prefix + 'sdncAdapterRequest = \n' + sdncAdapterRequest, isDebugLogEnabled) + + // Get the Basic Auth credentials for the SDNCAdapter (yes... we ARE using the PO adapters credentials) + + String basicAuthValue = execution.getVariable("URN_mso_adapters_po_auth") + + if (basicAuthValue == null || basicAuthValue.isEmpty()) { + logDebug(getProcessKey(execution) + ": mso:adapters:po:auth URN mapping is not defined", isDebugLogEnabled) + logError(getProcessKey(execution) + ": mso:adapters:po:auth URN mapping is not defined") + } else { + logDebug(getProcessKey(execution) + ": Obtained BasicAuth credentials for SDNCAdapter:" + + basicAuthValue, isDebugLogEnabled) + try { + def encodedString = utils.getBasicAuth(basicAuthValue, execution.getVariable("URN_mso_msoKey")) + execution.setVariable(prefix + 'basicAuthHeaderValue', encodedString) + } catch (IOException ex) { + logDebug(getProcessKey(execution) + ": Unable to encode BasicAuth credentials for SDNCAdapter", isDebugLogEnabled) + logError(getProcessKey(execution) + ": Unable to encode BasicAuth credentials for SDNCAdapter") + } + } + + // 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") + + if (timeout == null || timeout.isEmpty()) { + timeout = execution.getVariable("URN_mso_sdnc_timeout") + } + + execution.setVariable(prefix + 'timeout', timeout) + logDebug(getProcessKey(execution) + ': ' + prefix + 'timeout = ' + timeout, isDebugLogEnabled) + } catch (BpmnError e) { + throw e + } catch (Exception e) { + String msg = 'Caught exception in ' + method + ": " + e + logDebug(msg, isDebugLogEnabled) + logError(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg) + } + } + + /** + * Sends the request to the SDNC adapter. + */ + public void sendRequestToSDNCAdapter(Execution execution) { + def method = getClass().getSimpleName() + '.sendRequestToSDNCAdapter(' + + 'execution=' + execution.getId() + + ')' + def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') + logDebug('Entered ' + method, isDebugLogEnabled) + + String prefix = execution.getVariable('prefix') + + try { + String sdncAdapterMethod = execution.getVariable(prefix + 'sdncAdapterMethod') + String sdncAdapterUrl = execution.getVariable(prefix + 'sdncAdapterUrl') + String sdncAdapterRequest = execution.getVariable(prefix + 'sdncAdapterRequest') + utils.logAudit("Outgoing SDNC Rest Request is: " + sdncAdapterRequest) + + RESTConfig config = new RESTConfig(sdncAdapterUrl) + RESTClient client = new RESTClient(config). + addHeader("Content-Type", "application/json"). + 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 + logDebug(msg, isDebugLogEnabled) + logError(msg) + 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 + logDebug(msg, isDebugLogEnabled) + logError(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg) + } + } + + /** + * Processes a callback. + */ + public void processCallback(Execution execution){ + def method = getClass().getSimpleName() + '.processCallback(' + + 'execution=' + execution.getId() + + ')' + def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') + logDebug('Entered ' + method, isDebugLogEnabled) + + String prefix = execution.getVariable('prefix') + String callback = execution.getVariable('SDNCAResponse_MESSAGE') + utils.logAudit("Incoming SDNC Rest Callback is: " + callback) + + try { + logDebug(getProcessKey(execution) + ": received callback:\n" + callback, isDebugLogEnabled) + + 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 + logDebug(getProcessKey(execution) + ': ' + msg, isDebugLogEnabled) + 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(Execution 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(Execution execution) { + def method = getClass().getSimpleName() + '.getLastCallback(' + + 'execution=' + execution.getId() + + ')' + def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') + logDebug('Entered ' + method, isDebugLogEnabled) + + 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 + logDebug(msg, isDebugLogEnabled) + logError(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg) + } + } + + /** + * Sets the timeout value to wait for the next notification. + */ + public void setTimeoutValue(Execution execution) { + def method = getClass().getSimpleName() + '.setTimeoutValue(' + + 'execution=' + execution.getId() + + ')' + def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') + logDebug('Entered ' + method, isDebugLogEnabled) + + String prefix = execution.getVariable('prefix') + + try { + def timeoutValue = execution.getVariable("URN_mso_sdnc_timeout") + + if (execution.getVariable(prefix + 'callback1') != null) { + // Waiting for subsequent notifications + } + } catch (Exception e) { + String msg = 'Caught exception in ' + method + ": " + e + logDebug(msg, isDebugLogEnabled) + logError(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg) + } + } +} diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/SDNCAdapterUtils.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/SDNCAdapterUtils.groovy index 5c01bb9c4d..f870e30d1d 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/SDNCAdapterUtils.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/SDNCAdapterUtils.groovy @@ -1,925 +1,966 @@ -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - MSO - * ================================================================================ - * 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.openecomp.mso.bpmn.common.scripts; - -import org.apache.commons.lang3.* -import org.camunda.bpm.engine.delegate.BpmnError -import org.camunda.bpm.engine.runtime.Execution -import org.openecomp.mso.bpmn.core.WorkflowException -import org.springframework.web.util.UriUtils - - -/** - * @version 1.0 - * - */ -class SDNCAdapterUtils { - - ExceptionUtil exceptionUtil = new ExceptionUtil() - - private AbstractServiceTaskProcessor taskProcessor - - public SDNCAdapterUtils(AbstractServiceTaskProcessor taskProcessor) { - this.taskProcessor = taskProcessor - } - - String SDNCAdapterFeatureRequest(Execution 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("openecomp-mso-request-id") + "-" + System.currentTimeMillis() - } - - def svcInstanceId = execution.getVariable("openecomp-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 = """ - - - ${requestId} - ${svcInstanceId} - ${action} - ${serviceOperation} - ${callbackURL} - - - ${nnsRequestInformation} - ${nnsServiceInformation} - ${nnsFeatureInformation} - ${nnsFeatureParameters} - - ${timeoutValueInMinutes} - - """ - sdncAdapterFeatureRequest = utils.removeXmlPreamble(utils.formatXML(sdncAdapterFeatureRequest)) - return sdncAdapterFeatureRequest - } - - String SDNCAdapterActivateVnfRequest(Execution 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("openecomp-mso-request-id") + "-" + System.currentTimeMillis() - } - - def svcInstanceId = execution.getVariable("openecomp-mso-service-instance-id") - - def nnsRequestInformation = utils.removeXmlNamespaces(requestInformation) - def nnsServiceInformation = utils.removeXmlNamespaces(serviceInformation) - def nnsVnfInformationList = utils.removeXmlNamespaces(vnfInformationList) - - String sdncAdapterActivateVnfRequest = """ - - - ${requestId} - ${svcInstanceId} - ${action} - ${serviceOperation} - ${callbackURL} - ${msoAction} - - - ${nnsRequestInformation} - ${nnsServiceInformation} - ${nnsVnfInformationList} - - ${timeoutValueInMinutes} - - """ - sdncAdapterActivateVnfRequest = utils.removeXmlPreamble(utils.formatXML(sdncAdapterActivateVnfRequest)) - return sdncAdapterActivateVnfRequest - } - - String SDNCAdapterL3ToHigherLayerRequest(Execution 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 = """ - ${execution.getVariable("openecomp-mso-request-id")} - torepl - ${execution.getVariable(prefix+"source")} - ${execution.getVariable(prefix+"notificationUrl")} - """ - - // 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("openecomp-mso-request-id") + "-" + System.currentTimeMillis() - } - - def svcInstanceId = execution.getVariable("openecomp-mso-service-instance-id") - - //Build Service Information - // Send serviceName from CANOPI to sdnc for service-type - def serviceInformation = """ - ${execution.getVariable(prefix+"serviceName")} - ${svcInstanceId} - ${execution.getVariable(prefix+"subscriberName")} - ${execution.getVariable(prefix+"subscriberGlobalId")} - """ - - //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 = """ - ${vpnId} - ${vpnRt} - ${vpnService} - ${vpnRegion} - """ - }else if("activate".equalsIgnoreCase(action) || "delete".equalsIgnoreCase(action)){ - def vniId = execution.getVariable(prefix+'vniId') - additionalInfo = "${vniId}" - } - - //Set Interface Status - def interfaceStatus = "DISABLE" - if("activate".equalsIgnoreCase(action)){ - interfaceStatus = "ENABLE" - } - - //Build SDNC Adapter Request - String sdncAdapterL3ToHLRequest = """ - - - ${requestId} - ${svcInstanceId} - ${action} - ${serviceOperation} - ${callbackURL} - - - ${nnsRequestInformation} - ${serviceInformation} - - ${service} - ${customerId} - ${interfaceStatus} - ${additionalInfo} - - - ${timeoutValueInMinutes} - - """ - sdncAdapterL3ToHLRequest = utils.removeXmlPreamble(utils.formatXML(sdncAdapterL3ToHLRequest)) - - return sdncAdapterL3ToHLRequest - } - - - - private void SDNCAdapterActivateRequest(Execution 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("openecomp-mso-request-id") + "-" + System.currentTimeMillis() - } - - def svcInstanceId = execution.getVariable("openecomp-mso-service-instance-id") - def msoAction = 'gammainternet' - - def timeoutInMinutes = execution.getVariable('URN_mso_sdnc_timeout_firewall_minutes') - - def callbackUrl = (String) execution.getVariable('URN_mso_workflow_sdncadapter_callback') - if (callbackUrl == null || callbackUrl.trim() == "") { - logError('mso:workflow:sdncadapter:callback URN is not set') - 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 = "" - } - - String content = """ - - - ${requestId} - ${svcInstanceId} - ${svcAction} - ${svcOperation} - ${callbackUrl} - ${msoAction} - - - ${additionalData} - ${nnsRequestInformation} - ${nnsServiceInformation} - ${nnsl2HomingInformation} - ${nnsInternetEvcAccessInformation} - ${nnsVrLan} - ${nnsUpceVmsServiceInformation} - - ${timeoutInMinutes} - - """ - - 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 resultVar the execution variable in which the result will be stored - */ - public void sdncReservePrep(Execution execution, String action, String resultVar) { - sdncPrep(execution, resultVar, action , 'service-configuration-operation', null, 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(Execution execution, String resultVar, String svcAction, - String svcOperation, String additionalData, AbstractServiceTaskProcessor taskProcessor) { - def method = getClass().getSimpleName() + '.sdncPrep(' + - 'execution=' + execution.getId() + - ', resultVar=' + resultVar + - ', svcAction=' + svcAction + - ', svcOperation=' + svcOperation + - ', additionalData=' + (additionalData == null ? "no" : "yes") + - ')' - - def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') - taskProcessor.logDebug('Entered ' + method, isDebugLogEnabled) - 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.getNodeText1(request, 'request-action') - - def timeoutInMinutes = execution.getVariable('URN_mso_sdnc_timeout_firewall_minutes') - - def requestId = execution.getVariable('testReqId') // for junits - if(requestId==null){ - requestId = execution.getVariable("openecomp-mso-request-id") + "-" + System.currentTimeMillis() - } - - def svcInstanceId = execution.getVariable("openecomp-mso-service-instance-id") - def msoAction = 'gammainternet' - - def callbackUrl = (String) execution.getVariable('URN_mso_workflow_sdncadapter_callback') - if (callbackUrl == null || callbackUrl.trim() == "") { - taskProcessor.logError('mso:workflow:sdncadapter:callback URN is not set') - taskProcessor.workflowException(execution, 'Internal Error', 9999) // TODO: what message and error code? - } - - 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 = """ - ${internetSvcChangeDetails} - """ - } - - if (additionalData == null) { - additionalData = "" - } - - String content = """ - - - ${requestId} - ${svcInstanceId} - ${svcAction} - ${svcOperation} - ${callbackUrl} - ${msoAction} - - - ${additionalData} - ${nnsRequestInformation} - ${nnsServiceInformation} - ${nnsl2HomingInformation} - ${nnsInternetEvcAccessInformation} - ${nnsVrLan} - ${nnsUpceVmsServiceInfo} - ${nnsVnfInformationList} - ${nnsinternetSvcChangeDetails} - - - """ - - content = utils.removeXmlPreamble(utils.formatXML(content)) - execution.setVariable(resultVar, content) - taskProcessor.logDebug(resultVar + ' = ' + System.lineSeparator() + content, isDebugLogEnabled) - - taskProcessor.logDebug('Exited ' + method, isDebugLogEnabled) - } catch (BpmnError e) { - throw e; - } catch (Exception e) { - taskProcessor.logError('Caught exception in ' + method, e) - taskProcessor.workflowException(execution, 'Internal Error', 9999) // TODO: what message and error code? - } - } - - /** - * 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 (Execution execution, String requestXML, String serviceInstanceId, String callbackUrl, String action, String requestAction, String cloudRegionId, networkId, String queryAAIResponse, String additionalData) { - def utils=new MsoUtils() - - String requestId = "" - try { - requestId = execution.getVariable("openecomp-mso-request-id") - } catch (Exception ex) { - requestId = utils.getNodeText1(requestXML, "request-id") - } - - String aicCloudRegion = cloudRegionId - String tenantId = "" - if (utils.nodeExists(requestXML, "tenant-id")) { - tenantId = utils.getNodeText1(requestXML, "tenant-id") - } - String networkType = "" - if (utils.nodeExists(requestXML, "network-type")) { - networkType = utils.getNodeText1(requestXML, "network-type") - } - - // Replace/Use the value of network-type from aai query (vs input) during Delete Network flows. - if (queryAAIResponse != null) { - networkType = utils.getNodeText1(queryAAIResponse, "network-type") - } - - String serviceId = "" - if (utils.nodeExists(requestXML, "service-id")) { - serviceId = utils.getNodeText1(requestXML, "service-id") - } - String networkName = "" - if (utils.nodeExists(requestXML, "network-name")) { - networkName = utils.getNodeText1(requestXML, "network-name") - } - String source = "" - if (utils.nodeExists(requestXML, "source")) { - source = utils.getNodeText1(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 = - """ - - ${requestId} - ${serviceInstanceId} - ${action} - network-topology-operation - sdncCallback - - - - ${requestId} - ${requestAction} - ${source} - - - - - - ${serviceId} - ${serviceType} - ${serviceInstanceId} - ${subscriberName} - - - ${networkId} - ${networkType} - ${networkName} - ${tenantId} - ${aicCloudRegion} - - - """.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 (Execution execution, String requestXML, String serviceInstanceId, String callbackUrl, String action, String requestAction, String cloudRegionId, networkId, String additionalData) { - def utils=new MsoUtils() - - // SNDC is expecting requestId as unique each call. - String requestId = "" - String testRequestId = execution.getVariable("testMessageId") // for test purposes. - if (testRequestId == null) { - requestId = UUID.randomUUID() // generate unique - } else { - requestId = testRequestId - } - - String aicCloudRegion = cloudRegionId - String tenantId = "" - if (utils.nodeExists(requestXML, "tenant-id")) { - tenantId = utils.getNodeText1(requestXML, "tenant-id") - } - String networkType = "" - if (utils.nodeExists(requestXML, "network-type")) { - networkType = utils.getNodeText1(requestXML, "network-type") - } - - String subscriptionServiceType = "" - if (utils.nodeExists(requestXML, "subscription-service-type")) { - subscriptionServiceType = utils.getNodeText1(requestXML, "subscription-service-type") - } - - String globalCustomerId = "" - if (utils.nodeExists(requestXML, "global-customer-id")) { - globalCustomerId = utils.getNodeText1(requestXML, "global-customer-id") - } - - String serviceId = "" - if (utils.nodeExists(requestXML, "service-id")) { - serviceId = utils.getNodeText1(requestXML, "service-id") - } - String networkName = "" - if (utils.nodeExists(requestXML, "network-name")) { - networkName = utils.getNodeText1(requestXML, "network-name") - } - String source = "" - if (utils.nodeExists(requestXML, "source")) { - source = utils.getNodeText1(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.getNodeText1(networkModelInfo, "modelInvariantUuid") !=null ? - utils.getNodeText1(networkModelInfo, "modelInvariantUuid") : "" - String modelCustomizationUuid = utils.getNodeText1(networkModelInfo, "modelCustomizationUuid") !=null ? - utils.getNodeText1(networkModelInfo, "modelCustomizationUuid") : "" - String modelUuid = utils.getNodeText1(networkModelInfo, "modelUuid") !=null ? - utils.getNodeText1(networkModelInfo, "modelUuid") : "" - String modelVersion = utils.getNodeText1(networkModelInfo, "modelVersion") !=null ? - utils.getNodeText1(networkModelInfo, "modelVersion") : "" - String modelName = utils.getNodeText1(networkModelInfo, "modelName") !=null ? - utils.getNodeText1(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.getNodeText1(serviceModelInfo, "modelInvariantUuid") !=null ? - utils.getNodeText1(serviceModelInfo, "modelInvariantUuid") : "" - String serviceModelUuid = utils.getNodeText1(serviceModelInfo, "modelUuid") !=null ? - utils.getNodeText1(serviceModelInfo, "modelUuid") : "" - String serviceModelVersion = utils.getNodeText1(serviceModelInfo, "modelVersion") !=null ? - utils.getNodeText1(serviceModelInfo, "modelVersion") : "" - String serviceModelName = utils.getNodeText1(serviceModelInfo, "modelName") !=null ? - utils.getNodeText1(serviceModelInfo, "modelName") : "" - - - String content = - """ - - ${requestId} - ${serviceInstanceId} - ${action} - network-topology-operation - sdncCallback - generic-resource - - - - ${requestId} - ${requestAction} - ${source} - - - - - - ${serviceId} - ${subscriptionServiceType} - - ${serviceModelInvariantUuid} - ${serviceModelUuid} - ${serviceModelVersion} - ${serviceModelName} - - ${serviceInstanceId} - ${globalCustomerId} - ${subscriberName} - - - ${networkId} - ${networkType} - - ${modelInvariantUuid} - ${modelCustomizationUuid} - ${modelUuid} - ${modelVersion} - ${modelName} - - - - ${networkName} - ${tenantId} - ${aicCloudRegion} - - - - - """.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(Execution execution, String response, WorkflowException workflowException, boolean successIndicator){ - def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') - taskProcessor.utils.log("DEBUG", "SDNC Response is: " + response, isDebugLogEnabled) - taskProcessor.utils.log("DEBUG", "SuccessIndicator is: " + successIndicator, isDebugLogEnabled) - - try { - def prefix = execution.getVariable('prefix') - execution.setVariable(prefix+'sdncResponseSuccess', false) - taskProcessor.utils.log("DEBUG", "Response" + ' = ' + (response == null ? "" : System.lineSeparator()) + response, isDebugLogEnabled) - - if (successIndicator == true){ - if (response == null || response.trim().equals("")) { - taskProcessor.utils.log("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 = decodeXML(sdncAdapterWorkflowResponse).replace('', "") - - // change '&' to "& (if present as data, ex: subscriber-name = 'FOUR SEASONS HEATING & COOLING_8310006378683' - decodedXml = decodedXml.replace("&", "&") - - taskProcessor.utils.log("DEBUG","decodedXml:\n" + decodedXml, isDebugLogEnabled) - - 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(decodedXml, "ResponseMessage")) { - requestDataResponseMessage = taskProcessor.utils.getNodeText(decodedXml, "ResponseMessage") - } - }catch(Exception e){ - taskProcessor.utils.log("DEBUG", 'Error caught while decoding resposne ' + e.getMessage(), isDebugLogEnabled) - } - - if(taskProcessor.utils.nodeExists(decodedXml, "response-code")) { - taskProcessor.utils.log("DEBUG","response-code node Exist ", isDebugLogEnabled) - String code = taskProcessor.utils.getNodeText1(decodedXml, "response-code") - if(code.isEmpty() || code.equals("")){ - // if response-code is blank then Success - taskProcessor.utils.log("DEBUG","response-code node is empty", isDebugLogEnabled) - requestDataResponseCode = 0 - }else{ - requestDataResponseCode = code.toInteger() - taskProcessor.utils.log("DEBUG","response-code is: " + requestDataResponseCode, isDebugLogEnabled) - } - }else if(taskProcessor.utils.nodeExists(decodedXml, "ResponseCode")){ - taskProcessor.utils.log("DEBUG","ResponseCode node Exist ", isDebugLogEnabled) - String code = taskProcessor.utils.getNodeText1(decodedXml, "ResponseCode") - if(code.isEmpty() || code.equals("")){ - // if ResponseCode blank then Success - taskProcessor.utils.log("DEBUG","ResponseCode node is empty", isDebugLogEnabled) - requestDataResponseCode = 0 - }else{ - requestDataResponseCode = code.toInteger() - taskProcessor.utils.log("DEBUG","ResponseCode is: " + requestDataResponseCode, isDebugLogEnabled) - } - }else{ - taskProcessor.utils.log("DEBUG","A Response Code DOES NOT Exist.", isDebugLogEnabled) - // if a response code does not exist then Success - requestDataResponseCode = 0 - } - try{ - - // if a response code is 0 or 200 then Success - if (requestDataResponseCode == 200 || requestDataResponseCode == 0) { - execution.setVariable(prefix+'sdncResponseSuccess', true) - taskProcessor.utils.log("DEBUG", "Setting sdncResponseSuccess to True ", isDebugLogEnabled) - taskProcessor.utils.log("DEBUG", "Exited ValidateSDNCResponse Method", isDebugLogEnabled) - }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 - } - - taskProcessor.utils.log("DEBUG", "SDNC callback response-code: " + requestDataResponseCode, isDebugLogEnabled) - taskProcessor.utils.log("DEBUG", "SDNC callback response-message: " + requestDataResponseMessage, isDebugLogEnabled) - } - - }else { - taskProcessor.utils.log("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) { - taskProcessor.utils.log("DEBUG", 'END of Validate SDNC Response', isDebugLogEnabled) - 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(Execution execution, String response, WorkflowException workflowException, boolean success) { - def method = getClass().getSimpleName() + '.validateL3BondingSDNCResp(' + - 'execution=' + execution.getId() + - ', response=' + response + - ')' - def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') - taskProcessor.logDebug('Entered ' + method, isDebugLogEnabled) - def prefix = execution.getVariable('prefix') - CommonExceptionUtil commonExceptionUtil = new CommonExceptionUtil() - - try { - execution.setVariable(prefix+'sdncResponseSuccess', false) - - taskProcessor.utils.log("sdncAdapter Success Indicator is: " + success, isDebugLogEnabled) - if (success == true) { - - // we need to look inside the request data for error - def String callbackRequestData = taskProcessor.utils.getNodeXml(response, 'RequestData', false) - def String decodedXml = decodeXML(callbackRequestData) - taskProcessor.utils.log("DEBUG","decodedXml:\n" + decodedXml, isDebugLogEnabled) - - 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.getNodeText1(decodedXml, "ResponseCode")).toInteger() - }else if(taskProcessor.utils.nodeExists(response, "ResponseCode")){ - requestDataResponseCode = ((String) taskProcessor.utils.getNodeText1(response, "ResponseCode")).toInteger() - requestDataResponseMessage = taskProcessor.utils.getNodeText(response, "ResponseMessage") - } - - taskProcessor.utils.log("DEBUG", "SDNC callback response-code: " + requestDataResponseCode, isDebugLogEnabled) - taskProcessor.utils.log("DEBUG", "SDNC callback response-message: " + requestDataResponseMessage, isDebugLogEnabled) - - // 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")) - taskProcessor.utils.log("DEBUG", "SDNC sent AAI STATUS code: " + aai_status, isDebugLogEnabled) - } - if (aai_status != null && !aai_status.equals("")) { - execution.setVariable(prefix+"AaiStatus",aai_status) - taskProcessor.utils.log("DEBUG", "Set variable " + prefix + "AaiStatus: " + execution.getVariable(prefix+"AaiStatus"), isDebugLogEnabled) - } - - // 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")) - taskProcessor.utils.log("DEBUG", "SDNC sent result: " + sdncResult, isDebugLogEnabled) - } - if (sdncResult != null && !sdncResult.equals("")) { - execution.setVariable(prefix+"SdncResult",sdncResult) - taskProcessor.utils.log("DEBUG", "Set variable " + prefix + "SdncResult: " + execution.getVariable(prefix+"SdncResult"), isDebugLogEnabled) - } - - try{ - intDataResponseCode = Integer.parseInt(String.valueOf(requestDataResponseCode)) - }catch(Exception e){ - intDataResponseCode = 400 - } - - taskProcessor.utils.log("DEBUG", "intDataResponseCode " + intDataResponseCode , isDebugLogEnabled) - - // if response-code is not Success (200, 201, etc) we need to throw an exception - if (intDataResponseCode != 200 && intDataResponseCode != 0) { - execution.setVariable(prefix+'ResponseCode', intDataResponseCode) - execution.setVariable("L3HLAB_rollback", true) - def msg = commonExceptionUtil.mapSDNCAdapterExceptionToErrorResponse(response, execution) - taskProcessor.commonWorkflowException(execution, intDataResponseCode, "Received error from SDN-C: " + msg) - - } - }else { - taskProcessor.logWarn('sdncAdapter did not complete successfully, sdncAdapter Success Indicator was false ') - execution.setVariable("L3HLAB_rollback", true) - def msg = commonExceptionUtil.mapSDNCAdapterExceptionToErrorResponse(response, execution) - taskProcessor.commonWorkflowException(execution, responseCode, msg) - } - - if (response == null || response.trim().equals("")) { - taskProcessor.logWarn('sdncAdapter workflow response is empty'); - execution.setVariable("L3HLAB_rollback", true) - def msg = commonExceptionUtil.buildException("Exception occurred while validating SDNC response " , execution) - taskProcessor.commonWorkflowException(execution, intResponseCode, msg) - } - - execution.setVariable(prefix+'sdncResponseSuccess', true) - taskProcessor.logDebug('Exited ' + method, isDebugLogEnabled) - } catch (BpmnError e) { - throw e; - } catch (Exception e) { - taskProcessor.logError('Caught exception in ' + method, e) - execution.setVariable(prefix+"ResponseCode",400) - execution.setVariable("L3HLAB_rollback", true) - def msg = commonExceptionUtil.buildException("Exception occurred while validating SDNC response: " + e.getMessage(), execution) - taskProcessor.commonWorkflowException(execution, 400, msg) - } - } - - /** - * Decode XML - replace & < and > with '&', '<' and '>' - * @param xml - the xml to be decoded - */ - private String decodeXML(String xml) { - def String decodedXml = xml.replaceAll("&", "&") - decodedXml = decodedXml.replaceAll("<", "<") - decodedXml = decodedXml.replaceAll(">", ">") - } - -} +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.bpmn.common.scripts; + +import org.apache.commons.lang3.* +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.runtime.Execution +import org.openecomp.mso.bpmn.core.WorkflowException +import org.openecomp.mso.bpmn.core.json.JsonUtils; +import org.springframework.web.util.UriUtils + + +/** + * @version 1.0 + * + */ +class SDNCAdapterUtils { + + ExceptionUtil exceptionUtil = new ExceptionUtil() + JsonUtils jsonUtil = new JsonUtils() + + private AbstractServiceTaskProcessor taskProcessor + + public SDNCAdapterUtils(AbstractServiceTaskProcessor taskProcessor) { + this.taskProcessor = taskProcessor + } + + String SDNCAdapterFeatureRequest(Execution 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 = """ + + + ${requestId} + ${svcInstanceId} + ${action} + ${serviceOperation} + ${callbackURL} + + + ${nnsRequestInformation} + ${nnsServiceInformation} + ${nnsFeatureInformation} + ${nnsFeatureParameters} + + ${timeoutValueInMinutes} + + """ + sdncAdapterFeatureRequest = utils.removeXmlPreamble(utils.formatXML(sdncAdapterFeatureRequest)) + return sdncAdapterFeatureRequest + } + + String SDNCAdapterActivateVnfRequest(Execution 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 = """ + + + ${requestId} + ${svcInstanceId} + ${action} + ${serviceOperation} + ${callbackURL} + ${msoAction} + + + ${nnsRequestInformation} + ${nnsServiceInformation} + ${nnsVnfInformationList} + + ${timeoutValueInMinutes} + + """ + sdncAdapterActivateVnfRequest = utils.removeXmlPreamble(utils.formatXML(sdncAdapterActivateVnfRequest)) + return sdncAdapterActivateVnfRequest + } + + String SDNCAdapterL3ToHigherLayerRequest(Execution 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 = """ + ${execution.getVariable("mso-request-id")} + torepl + ${execution.getVariable(prefix+"source")} + ${execution.getVariable(prefix+"notificationUrl")} + """ + + // 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 = """ + ${execution.getVariable(prefix+"serviceName")} + ${svcInstanceId} + ${execution.getVariable(prefix+"subscriberName")} + ${execution.getVariable(prefix+"subscriberGlobalId")} + """ + + //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 = """ + ${vpnId} + ${vpnRt} + ${vpnService} + ${vpnRegion} + """ + }else if("activate".equalsIgnoreCase(action) || "delete".equalsIgnoreCase(action)){ + def vniId = execution.getVariable(prefix+'vniId') + additionalInfo = "${vniId}" + } + + //Set Interface Status + def interfaceStatus = "DISABLE" + if("activate".equalsIgnoreCase(action)){ + interfaceStatus = "ENABLE" + } + + //Build SDNC Adapter Request + String sdncAdapterL3ToHLRequest = """ + + + ${requestId} + ${svcInstanceId} + ${action} + ${serviceOperation} + ${callbackURL} + + + ${nnsRequestInformation} + ${serviceInformation} + + ${service} + ${customerId} + ${interfaceStatus} + ${additionalInfo} + + + ${timeoutValueInMinutes} + + """ + sdncAdapterL3ToHLRequest = utils.removeXmlPreamble(utils.formatXML(sdncAdapterL3ToHLRequest)) + + return sdncAdapterL3ToHLRequest + } + + + + private void SDNCAdapterActivateRequest(Execution 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 = execution.getVariable('URN_mso_sdnc_timeout_firewall_minutes') + + def callbackUrl = (String) execution.getVariable('URN_mso_workflow_sdncadapter_callback') + if (callbackUrl == null || callbackUrl.trim() == "") { + logError('mso:workflow:sdncadapter:callback URN is not set') + 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 = "" + } + + String content = """ + + + ${requestId} + ${svcInstanceId} + ${svcAction} + ${svcOperation} + ${callbackUrl} + ${msoAction} + + + ${additionalData} + ${nnsRequestInformation} + ${nnsServiceInformation} + ${nnsl2HomingInformation} + ${nnsInternetEvcAccessInformation} + ${nnsVrLan} + ${nnsUpceVmsServiceInformation} + + ${timeoutInMinutes} + + """ + + 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 resultVar the execution variable in which the result will be stored + */ + public void sdncReservePrep(Execution execution, String action, String resultVar) { + sdncPrep(execution, resultVar, action , 'service-configuration-operation', null, 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(Execution execution, String resultVar, String svcAction, + String svcOperation, String additionalData, AbstractServiceTaskProcessor taskProcessor) { + def method = getClass().getSimpleName() + '.sdncPrep(' + + 'execution=' + execution.getId() + + ', resultVar=' + resultVar + + ', svcAction=' + svcAction + + ', svcOperation=' + svcOperation + + ', additionalData=' + (additionalData == null ? "no" : "yes") + + ')' + + def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') + taskProcessor.logDebug('Entered ' + method, isDebugLogEnabled) + 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.getNodeText1(request, 'request-action') + + def timeoutInMinutes = execution.getVariable('URN_mso_sdnc_timeout_firewall_minutes') + + 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) execution.getVariable('URN_mso_workflow_sdncadapter_callback') + if (callbackUrl == null || callbackUrl.trim() == "") { + taskProcessor.logError('mso:workflow:sdncadapter:callback URN is not set') + 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 = """ + ${internetSvcChangeDetails} + """ + } + + if (additionalData == null) { + additionalData = "" + } + + String content = """ + + + ${requestId} + ${svcInstanceId} + ${svcAction} + ${svcOperation} + ${callbackUrl} + ${msoAction} + + + ${additionalData} + ${nnsRequestInformation} + ${nnsServiceInformation} + ${nnsl2HomingInformation} + ${nnsInternetEvcAccessInformation} + ${nnsVrLan} + ${nnsUpceVmsServiceInfo} + ${nnsVnfInformationList} + ${nnsinternetSvcChangeDetails} + + + """ + + content = utils.removeXmlPreamble(utils.formatXML(content)) + execution.setVariable(resultVar, content) + taskProcessor.logDebug(resultVar + ' = ' + System.lineSeparator() + content, isDebugLogEnabled) + + taskProcessor.logDebug('Exited ' + method, isDebugLogEnabled) + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + taskProcessor.logError('Caught exception in ' + method, e) + exceptionUtil.buildAndThrowWorkflowException(execution, 5000, "Internal Error") + } + } + + /** + * 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 (Execution execution, String requestXML, String serviceInstanceId, String callbackUrl, String action, String requestAction, String cloudRegionId, networkId, String queryAAIResponse, String additionalData) { + def utils=new MsoUtils() + + String requestId = "" + try { + requestId = execution.getVariable("mso-request-id") + } catch (Exception ex) { + requestId = utils.getNodeText1(requestXML, "request-id") + } + + String aicCloudRegion = cloudRegionId + String tenantId = "" + if (utils.nodeExists(requestXML, "tenant-id")) { + tenantId = utils.getNodeText1(requestXML, "tenant-id") + } + String networkType = "" + if (utils.nodeExists(requestXML, "network-type")) { + networkType = utils.getNodeText1(requestXML, "network-type") + } + + // Replace/Use the value of network-type from aai query (vs input) during Delete Network flows. + if (queryAAIResponse != null) { + networkType = utils.getNodeText1(queryAAIResponse, "network-type") + } + + String serviceId = "" + if (utils.nodeExists(requestXML, "service-id")) { + serviceId = utils.getNodeText1(requestXML, "service-id") + } + String networkName = "" + if (utils.nodeExists(requestXML, "network-name")) { + networkName = utils.getNodeText1(requestXML, "network-name") + } + String source = "" + if (utils.nodeExists(requestXML, "source")) { + source = utils.getNodeText1(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 = + """ + + ${requestId} + ${serviceInstanceId} + ${action} + network-topology-operation + sdncCallback + + + + ${requestId} + ${requestAction} + ${source} + + + + + + ${serviceId} + ${serviceType} + ${serviceInstanceId} + ${subscriberName} + + + ${networkId} + ${networkType} + ${networkName} + ${tenantId} + ${aicCloudRegion} + + + """.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 (Execution 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) { + try { + requestId = execution.getVariable("mso-request-id") + } catch (Exception ex) { + requestId = utils.getNodeText1(requestXML, "request-id") + } + } else { + requestId = testRequestId + } + + String aicCloudRegion = cloudRegionId + String tenantId = "" + if (utils.nodeExists(requestXML, "tenant-id")) { + tenantId = utils.getNodeText1(requestXML, "tenant-id") + } + String networkType = "" + if (utils.nodeExists(requestXML, "network-type")) { + networkType = utils.getNodeText1(requestXML, "network-type") + } + + String subscriptionServiceType = "" + if (utils.nodeExists(requestXML, "subscription-service-type")) { + subscriptionServiceType = utils.getNodeText1(requestXML, "subscription-service-type") + } + + String globalCustomerId = "" + if (utils.nodeExists(requestXML, "global-customer-id")) { + globalCustomerId = utils.getNodeText1(requestXML, "global-customer-id") + } + + String serviceId = "" + if (utils.nodeExists(requestXML, "service-id")) { + serviceId = utils.getNodeText1(requestXML, "service-id") + } + String networkName = "" + if (utils.nodeExists(requestXML, "network-name")) { + networkName = utils.getNodeText1(requestXML, "network-name") + } + String source = "" + if (utils.nodeExists(requestXML, "source")) { + source = utils.getNodeText1(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.getNodeText1(networkModelInfo, "modelInvariantUuid") !=null ? + utils.getNodeText1(networkModelInfo, "modelInvariantUuid") : "" + String modelCustomizationUuid = utils.getNodeText1(networkModelInfo, "modelCustomizationUuid") !=null ? + utils.getNodeText1(networkModelInfo, "modelCustomizationUuid") : "" + String modelUuid = utils.getNodeText1(networkModelInfo, "modelUuid") !=null ? + utils.getNodeText1(networkModelInfo, "modelUuid") : "" + String modelVersion = utils.getNodeText1(networkModelInfo, "modelVersion") !=null ? + utils.getNodeText1(networkModelInfo, "modelVersion") : "" + String modelName = utils.getNodeText1(networkModelInfo, "modelName") !=null ? + utils.getNodeText1(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.getNodeText1(serviceModelInfo, "modelInvariantUuid") !=null ? + utils.getNodeText1(serviceModelInfo, "modelInvariantUuid") : "" + String serviceModelUuid = utils.getNodeText1(serviceModelInfo, "modelUuid") !=null ? + utils.getNodeText1(serviceModelInfo, "modelUuid") : "" + String serviceModelVersion = utils.getNodeText1(serviceModelInfo, "modelVersion") !=null ? + utils.getNodeText1(serviceModelInfo, "modelVersion") : "" + String serviceModelName = utils.getNodeText1(serviceModelInfo, "modelName") !=null ? + utils.getNodeText1(serviceModelInfo, "modelName") : "" + + + String content = + """ + + ${hdrRequestId} + ${serviceInstanceId} + ${action} + network-topology-operation + sdncCallback + generic-resource + + + + ${requestId} + ${requestAction} + ${source} + + + + + + ${serviceId} + ${subscriptionServiceType} + + ${serviceModelInvariantUuid} + ${serviceModelUuid} + ${serviceModelVersion} + ${serviceModelName} + + ${serviceInstanceId} + ${globalCustomerId} + ${subscriberName} + + + ${networkId} + ${networkType} + + ${modelInvariantUuid} + ${modelCustomizationUuid} + ${modelUuid} + ${modelVersion} + ${modelName} + + + + ${networkName} + ${tenantId} + ${aicCloudRegion} + + + + + """.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(Execution execution, String response, WorkflowException workflowException, boolean successIndicator){ + def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') + taskProcessor.utils.log("DEBUG", "SDNC Response is: " + response, isDebugLogEnabled) + taskProcessor.utils.log("DEBUG", "SuccessIndicator is: " + successIndicator, isDebugLogEnabled) + + try { + def prefix = execution.getVariable('prefix') + execution.setVariable(prefix+'sdncResponseSuccess', false) + taskProcessor.utils.log("DEBUG", "Response" + ' = ' + (response == null ? "" : System.lineSeparator()) + response, isDebugLogEnabled) + + if (successIndicator == true){ + if (response == null || response.trim().equals("")) { + taskProcessor.utils.log("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 = decodeXML(sdncAdapterWorkflowResponse).replace('', "") + + // change '&' to "& (if present as data, ex: subscriber-name = 'FOUR SEASONS HEATING & COOLING_8310006378683' + decodedXml = decodedXml.replace("&", "&") + + taskProcessor.utils.log("DEBUG","decodedXml:\n" + decodedXml, isDebugLogEnabled) + + 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(decodedXml, "ResponseMessage")) { + requestDataResponseMessage = taskProcessor.utils.getNodeText(decodedXml, "ResponseMessage") + } + }catch(Exception e){ + taskProcessor.utils.log("DEBUG", 'Error caught while decoding resposne ' + e.getMessage(), isDebugLogEnabled) + } + + if(taskProcessor.utils.nodeExists(decodedXml, "response-code")) { + taskProcessor.utils.log("DEBUG","response-code node Exist ", isDebugLogEnabled) + String code = taskProcessor.utils.getNodeText1(decodedXml, "response-code") + if(code.isEmpty() || code.equals("")){ + // if response-code is blank then Success + taskProcessor.utils.log("DEBUG","response-code node is empty", isDebugLogEnabled) + requestDataResponseCode = 0 + }else{ + requestDataResponseCode = code.toInteger() + taskProcessor.utils.log("DEBUG","response-code is: " + requestDataResponseCode, isDebugLogEnabled) + } + }else if(taskProcessor.utils.nodeExists(decodedXml, "ResponseCode")){ + taskProcessor.utils.log("DEBUG","ResponseCode node Exist ", isDebugLogEnabled) + String code = taskProcessor.utils.getNodeText1(decodedXml, "ResponseCode") + if(code.isEmpty() || code.equals("")){ + // if ResponseCode blank then Success + taskProcessor.utils.log("DEBUG","ResponseCode node is empty", isDebugLogEnabled) + requestDataResponseCode = 0 + }else{ + requestDataResponseCode = code.toInteger() + taskProcessor.utils.log("DEBUG","ResponseCode is: " + requestDataResponseCode, isDebugLogEnabled) + } + }else{ + taskProcessor.utils.log("DEBUG","A Response Code DOES NOT Exist.", isDebugLogEnabled) + // if a response code does not exist then Success + requestDataResponseCode = 0 + } + try{ + + // if a response code is 0 or 200 then Success + if (requestDataResponseCode == 200 || requestDataResponseCode == 0) { + execution.setVariable(prefix+'sdncResponseSuccess', true) + taskProcessor.utils.log("DEBUG", "Setting sdncResponseSuccess to True ", isDebugLogEnabled) + taskProcessor.utils.log("DEBUG", "Exited ValidateSDNCResponse Method", isDebugLogEnabled) + }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 + } + + taskProcessor.utils.log("DEBUG", "SDNC callback response-code: " + requestDataResponseCode, isDebugLogEnabled) + taskProcessor.utils.log("DEBUG", "SDNC callback response-message: " + requestDataResponseMessage, isDebugLogEnabled) + } + + }else { + taskProcessor.utils.log("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) { + taskProcessor.utils.log("DEBUG", 'END of Validate SDNC Response', isDebugLogEnabled) + 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(Execution execution, String response, WorkflowException workflowException, boolean success) { + def method = getClass().getSimpleName() + '.validateL3BondingSDNCResp(' + + 'execution=' + execution.getId() + + ', response=' + response + + ')' + def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') + taskProcessor.logDebug('Entered ' + method, isDebugLogEnabled) + def prefix = execution.getVariable('prefix') + TrinityExceptionUtil trinityExceptionUtil = new TrinityExceptionUtil() + + try { + execution.setVariable(prefix+'sdncResponseSuccess', false) + + taskProcessor.utils.log("sdncAdapter Success Indicator is: " + success, isDebugLogEnabled) + if (success == true) { + + // we need to look inside the request data for error + def String callbackRequestData = taskProcessor.utils.getNodeXml(response, 'RequestData', false) + def String decodedXml = decodeXML(callbackRequestData) + taskProcessor.utils.log("DEBUG","decodedXml:\n" + decodedXml, isDebugLogEnabled) + + 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.getNodeText1(decodedXml, "ResponseCode")).toInteger() + }else if(taskProcessor.utils.nodeExists(response, "ResponseCode")){ + requestDataResponseCode = ((String) taskProcessor.utils.getNodeText1(response, "ResponseCode")).toInteger() + requestDataResponseMessage = taskProcessor.utils.getNodeText(response, "ResponseMessage") + } + + taskProcessor.utils.log("DEBUG", "SDNC callback response-code: " + requestDataResponseCode, isDebugLogEnabled) + taskProcessor.utils.log("DEBUG", "SDNC callback response-message: " + requestDataResponseMessage, isDebugLogEnabled) + + // 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")) + taskProcessor.utils.log("DEBUG", "SDNC sent AAI STATUS code: " + aai_status, isDebugLogEnabled) + } + if (aai_status != null && !aai_status.equals("")) { + execution.setVariable(prefix+"AaiStatus",aai_status) + taskProcessor.utils.log("DEBUG", "Set variable " + prefix + "AaiStatus: " + execution.getVariable(prefix+"AaiStatus"), isDebugLogEnabled) + } + + // 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")) + taskProcessor.utils.log("DEBUG", "SDNC sent result: " + sdncResult, isDebugLogEnabled) + } + if (sdncResult != null && !sdncResult.equals("")) { + execution.setVariable(prefix+"SdncResult",sdncResult) + taskProcessor.utils.log("DEBUG", "Set variable " + prefix + "SdncResult: " + execution.getVariable(prefix+"SdncResult"), isDebugLogEnabled) + } + + try{ + intDataResponseCode = Integer.parseInt(String.valueOf(requestDataResponseCode)) + }catch(Exception e){ + intDataResponseCode = 400 + } + + taskProcessor.utils.log("DEBUG", "intDataResponseCode " + intDataResponseCode , isDebugLogEnabled) + + // if response-code is not Success (200, 201, etc) we need to throw an exception + if (intDataResponseCode != 200 && 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 { + taskProcessor.logWarn('sdncAdapter did not complete successfully, sdncAdapter Success Indicator was false ') + execution.setVariable("L3HLAB_rollback", true) + def msg = trinityExceptionUtil.mapSDNCAdapterExceptionToErrorResponse(response, execution) + exceptionUtil.buildAndThrowWorkflowException(execution, responseCode, msg) + } + + if (response == null || response.trim().equals("")) { + taskProcessor.logWarn('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) + taskProcessor.logDebug('Exited ' + method, isDebugLogEnabled) + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + taskProcessor.logError('Caught exception in ' + method, 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 modelInvariantId = jsonUtil.getJsonValue(jsonModelInfo, "modelInvariantId") + String modelVersionId = jsonUtil.getJsonValue(jsonModelInfo, "modelVersionId") + if (modelVersionId == null) { + modelVersionId = "" + } + String modelCustomizationUuid = jsonUtil.getJsonValue(jsonModelInfo, "modelCustomizationId") + String modelCustomizationString = "" + if (modelCustomizationUuid != null) { + modelCustomizationString = "${modelCustomizationUuid}" + } + String modelVersion = jsonUtil.getJsonValue(jsonModelInfo, "modelVersion") + String modelName = jsonUtil.getJsonValue(jsonModelInfo, "modelName") + String ecompModelInformation = + """ + ${modelInvariantId} + ${modelVersionId} + ${modelCustomizationString} + ${modelVersion} + ${modelName} + """ + + return ecompModelInformation + } + + /** + * Decode XML - replace & < and > with '&', '<' and '>' + * @param xml - the xml to be decoded + */ + private String decodeXML(String xml) { + def String decodedXml = xml.replaceAll("&", "&") + decodedXml = decodedXml.replaceAll("<", "<") + decodedXml = decodedXml.replaceAll(">", ">") + } + + + +} \ No newline at end of file diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/ServiceTaskProcessor.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/ServiceTaskProcessor.groovy index ef21818f81..975fdd3ae2 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/ServiceTaskProcessor.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/ServiceTaskProcessor.groovy @@ -1,32 +1,32 @@ -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - MSO - * ================================================================================ - * 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.openecomp.mso.bpmn.common.scripts; - -import org.camunda.bpm.engine.runtime.Execution - - -/** - * @version 1.0 - * - */ -public interface ServiceTaskProcessor { - public void preProcessRequest(Execution execution); -} +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.bpmn.common.scripts; + +import org.camunda.bpm.engine.runtime.Execution + + +/** + * @version 1.0 + * + */ +public interface ServiceTaskProcessor { + public void preProcessRequest(Execution execution); +} diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/TrinityExceptionUtil.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/TrinityExceptionUtil.groovy new file mode 100644 index 0000000000..03fa63e93b --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/TrinityExceptionUtil.groovy @@ -0,0 +1,382 @@ +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.bpmn.common.scripts + +import org.camunda.bpm.engine.runtime.Execution +import org.apache.commons.lang3.* + +class TrinityExceptionUtil { + + + + 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, Execution execution) + { + def utils=new MsoUtils() + def method = getClass().getSimpleName() + '.mapAdapterExecptionToCommonException(' + + 'execution=' + execution.getId() + + ')' + + def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') + utils.log("DEBUG",'Entered ' + method, isDebugLogEnabled) + + + def errorCode + + + try { + errorCode = MapCategoryToErrorCode(utils.getNodeText(response, "category")) + execution.setVariable(prefix+"err",errorCode) + String message = buildException(response, execution) + utils.log("DEBUG","=========== End MapAdapterExecptionToWorkflowException ===========",isDebugLogEnabled) + return message + }catch (Exception ex) { + //Ignore the exception - cases include non xml payload + utils.log("DEBUG","error mapping error, ignoring: " + ex,isDebugLogEnabled) + utils.log("DEBUG","=========== End MapAdapterExecptionToWorkflowException ===========",isDebugLogEnabled) + return buildException(response, execution) + } + } + + /** + * @param response + * @param execution + * @return mapped exception + */ + String mapAOTSExecptionToCommonException(String response, Execution execution) + { + def utils=new MsoUtils() + + def prefix=execution.getVariable("prefix") + def method = getClass().getSimpleName() + '.mapAOTSExecptionToCommonException(' + + 'execution=' + execution.getId() + + ')' + + def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') + utils.log("DEBUG",'Entered ' + method, isDebugLogEnabled) + + + 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) + utils.log("DEBUG","=========== End MapAOTSExecptionToCommonException ===========",isDebugLogEnabled) + return message + }catch (Exception ex) { + //Ignore the exception - cases include non xml payload + utils.log("DEBUG","error mapping error, ignoring: " + ex,isDebugLogEnabled) + utils.log("DEBUG","=========== End MapAOTSExecptionToCommonException ===========",isDebugLogEnabled) + return buildException(response, execution) + } + } + + String mapSDNCAdapterExceptionToErrorResponse(String sdncAdapterCallbackRequest, Execution execution) { + def utils=new MsoUtils() + def prefix=execution.getVariable("prefix") + def method = getClass().getSimpleName() + '.mapSDNCAdapterExceptionToErrorResponse(' + + 'execution=' + execution.getId() + + ')' + + def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') + utils.log("DEBUG",'Entered ' + method, isDebugLogEnabled) + + def sdncResponseCode + String responseCode = execution.getVariable(prefix+"ResponseCode") + utils.log("DEBUG",'responseCode to map: ' + responseCode, isDebugLogEnabled) + def errorMessage + + try { + + if(utils.nodeExists(sdncAdapterCallbackRequest, "RequestData")) { + def reqDataXml = StringEscapeUtils.unescapeXml(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.replace("&", "&").replace("<", "<").replace(">", ">") + 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) + + + utils.log("DEBUG","=========== End MapSDNCAdapterException ===========",isDebugLogEnabled) + return message + }catch (Exception ex) { + //Ignore the exception - cases include non xml payload + utils.log("DEBUG","error mapping sdnc error, ignoring: " + ex,isDebugLogEnabled) + utils.log("DEBUG","=========== End MapSDNCAdapterException ===========",isDebugLogEnabled) + return null + } + + } + + /** + * @param response message from called component (ex: AAI) + * @param execution + * @return an error response conforming to the common + */ + String mapAAIExceptionTCommonException(String response, Execution execution) + { + def utils=new MsoUtils() + def isDebugLogEnabled=execution.getVariable("isDebugLogEnabled") + def prefix=execution.getVariable("prefix") + def method = getClass().getSimpleName() + '.mapAAIExceptionTCommonException(' + + 'execution=' + execution.getId() + + ')' + + utils.log("DEBUG",'Entered ' + method, isDebugLogEnabled) + def variables + def message + String errorCode = 'SVC0001' + utils.log("DEBUG","response: " + response, isDebugLogEnabled) + //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) + utils.log("DEBUG","error mapping error, ignoring: " + ex,isDebugLogEnabled) + } + + if(message != null) { + execution.setVariable(prefix+"ErrorResponse",message) + utils.log("ERROR","Fault:"+ 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() + + ')' + + def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') + utils.log("DEBUG",'Entered ' + method, isDebugLogEnabled) + def prefix=execution.getVariable("prefix") + def responseCode = String.valueOf(execution.getVariable(prefix+"ResponseCode")) + def variables + utils.log("DEBUG","response: " + response, isDebugLogEnabled) + + try { + utils.log("DEBUG","formatting error message" ,isDebugLogEnabled) + def msgVars = execution.getVariable(prefix+"errVariables") + def myErr = execution.getVariable(prefix+"err") + def messageTxt = execution.getVariable(prefix+"errTxt") + def messageId = null + + if(myErr == null){ + utils.log("DEBUG","mapping response code: " + responseCode, isDebugLogEnabled) + 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( + """ + ${msgVar}""") + } + + } + def message = "" + if(messageId.startsWith("SVC")){ + message = """ + + ${messageId} + ${messageTxt}${msgVarsBuff} + +""" + }else{ + message =""" + + ${messageId} + ${messageTxt}${msgVarsBuff} + +""" + } + utils.log("DEBUG", "message " + message, isDebugLogEnabled) + execution.setVariable(prefix+"ErrorResponse",message) + execution.setVariable(prefix+"err", myErr) + execution.setVariable(prefix+"errTxt", messageTxt) + execution.setVariable(prefix+"errVariables", msgVars) + utils.log("ERROR","Fault:"+ execution.getVariable(prefix+"ErrorResponse")) + return message + }catch(Exception ex) { + utils.log("DEBUG","error mapping error, return null: " + ex,isDebugLogEnabled) + return null + } + + } + + String parseError(Execution execution){ + def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') + def utils=new MsoUtils() + def prefix=execution.getVariable("prefix") + def text = execution.getVariable(prefix+"errTxt") + def msgVars = execution.getVariable(prefix+"errVariables") + utils.log("DEBUG",'parsing message: ' + text, isDebugLogEnabled) + if(text == null){ + return 'failed' + } + if(msgVars!=null && !msgVars.isEmpty()){ + for(int i=0; i - ${networkRole} - ${networkName} - - """ - vnfNetworks = vnfNetworks + vnfNetwork - } - } - } catch (Exception e) { - logWarn('Exception transforming \'_network\' params to vnfNetworks', 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 = """ - - ${key} - ${value} - - """ - entries = entries + entry - } - } catch (Exception e) { - logWarn('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 = """ - - ${key} - ${value} - - """ - entries = entries + entry - } - } - } catch (Exception e) { - logWarn('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 - * @return a String of key/value entries for vfModuleParams - */ - - - protected String buildVfModuleParams(String vnfParams, String sdncGetResponse, String vnfId, String vnfName, - String vfModuleId, String vfModuleName) { - - //Get SDNC Response Data - - String data = utils.getNodeXml(sdncGetResponse, "response-data") - data = data.replaceAll("<", "<") - data = data.replaceAll(">", ">") - - 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.getNodeText1(serviceData, "vnf-id") - - // Add-on data - String vnfInfo = - """ - vnf_id - ${vnfId} - - - vnf_name - ${vnfName} - - - vf_module_id - ${vfModuleId} - - - vf_module_name - ${vfModuleName} - """ - - utils.logAudit("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 = - """ - availability_zone_${aZonePosition} - ${aZoneValue} - """ - aZones = sbAZone.append(aZoneXml) - } - } - - // 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") - 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 = - """ - ${vnfNetworkKey}_net_id - ${vnfNetworkNeutronIdValue} - """ - vnfNetworkNetId = sbNet.append(vnfNetworkNetIdXml) - String vnfNetworkNetNameXml = - """ - ${vnfNetworkKey}_net_name - ${vnfNetworkNetNameValue} - """ - vnfNetworkNetName = sbNet2.append(vnfNetworkNetNameXml) - String vnfNetworkSubNetIdXml = - """ - ${vnfNetworkKey}_subnet_id - ${vnfNetworkSubNetIdValue} - """ - vnfNetworkSubNetId = sbNet3.append(vnfNetworkSubNetIdXml) - String vnfNetworkV6SubNetIdXml = - """ - ${vnfNetworkKey}_v6_subnet_id - ${vnfNetworkV6SubNetIdValue} - """ - vnfNetworkV6SubNetId = sbNet5.append(vnfNetworkV6SubNetIdXml) - String vnfNetworkNetFqdnXml = - """ - ${vnfNetworkKey}_net_fqdn - ${vnfNetworkNetFqdnValue} - """ - 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 = - """ - ${vnfNetworkKey}_ATT_VF_VLAN_FILTER - ${values} - """ - 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 = - """ - ${key}_name_${position} - ${value} - """ - vnfVMSPositions = 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") - floatingIPKey = key + '_' + networkKey + '_floating_ip' - floatingIPKeyValue = utils.getElementText(eElementNetworkKey, "floating-ip") - if(!floatingIPKeyValue.isEmpty()){ - floatingIpKeyValueStr = """ - $floatingIPKey - $floatingIPKeyValue - """ - } - floatingIPV6Key = key + '_' + networkKey + '_floating_v6_ip' - floatingIPV6KeyValue = utils.getElementText(eElementNetworkKey, "floating-ip-v6") - if(!floatingIPV6KeyValue.isEmpty()){ - floatingIpV6KeyValueStr = """ - $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() - String vmNetworksPositionsXml = - """ - ${key}_${networkKey}_ip_${networkPosition} - ${ipAddressValue} - """ - vmNetworksPositions = sbNetworksPositions.append(vmNetworksPositionsXml) - } - } - vmNetworksPositions = sbNetworksPositions.append(floatingIpKeyValueStr).append(floatingIpV6KeyValueStr) - - String vmNetworksXml = - """ - ${key}_${networkKey}_ips - ${ipAddressValues} - """ - 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 = - """ - ${key}_${networkKey}_route_prefixes - ${interfaceRoutePrefixValues} - """ - 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 = - """ - ${key}_${networkKey}_v6_ip_${networkPosition} - ${ipV6AddressValue} - """ - vmNetworksPositionsV6 = sbNetworksPositionsV6.append(vmNetworksPositionsV6Xml) - } - } - String vmNetworksV6Xml = - """ - ${key}_${networkKey}_v6_ips - ${ipV6AddressValues} - """ - vmNetworks = sbVmNetworks.append(vmNetworksV6Xml) - } - } - String vnfXml = - """ - ${key}_names - ${values} - """ - vnfVMS = sb.append(vnfXml) - } - } - //SDNC Response Params - String sdncResponseParams = "" - List 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 = - """ - ${vnfParameterName} - ${vnfParameterValue} - """ - sdncResponseParams = sb.append(paraEntry) - } - } - } - - - def vfModuleParams = """ - ${vnfInfo} - ${aZones} - ${vnfNetworkNetId} - ${vnfNetworkNetName} - ${vnfNetworkSubNetId} - ${vnfNetworkV6SubNetId} - ${vnfNetworkNetFqdn} - ${vnfNetworksSriovVlanFilters} - ${vnfVMS} - ${vnfVMSPositions} - ${vmNetworks} - ${vmNetworksPositions} - ${vmNetworksPositionsV6} - ${interfaceRoutePrefixes} - ${vnfParams} - ${sdncResponseParams}""" - - return vfModuleParams - - } - - -} +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.bpmn.common.scripts; + +//import groovy.util.Node; + +import javax.xml.parsers.DocumentBuilder +import javax.xml.parsers.DocumentBuilderFactory + +import org.apache.commons.lang3.* +import org.camunda.bpm.engine.runtime.Execution +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 + + +public abstract class VfModuleBase extends AbstractServiceTaskProcessor { + + 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 = """ + + ${networkRole} + ${networkName} + + """ + vnfNetworks = vnfNetworks + vnfNetwork + } + } + } catch (Exception e) { + logWarn('Exception transforming \'_network\' params to vnfNetworks', 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 = """ + + ${key} + ${value} + + """ + entries = entries + entry + } + } catch (Exception e) { + logWarn('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 = """ + + ${key} + ${value} + + """ + entries = entries + entry + } + } + } catch (Exception e) { + logWarn('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(String vnfParams, String sdncGetResponse, String vnfId, String vnfName, + String vfModuleId, String vfModuleName, String vfModuleIndex) { + + //Get SDNC Response Data + + String data = utils.getNodeXml(sdncGetResponse, "response-data") + data = data.replaceAll("<", "<") + data = data.replaceAll(">", ">") + + 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.getNodeText1(serviceData, "vnf-id") + String vfModuleIndexParam = "" + + if (vfModuleIndex != null) { + vfModuleIndexParam = """ + vf_module_index + ${vfModuleIndex} + """ + } + + // Add-on data + String vnfInfo = + """ + vnf_id + ${vnfId} + + + vnf_name + ${vnfName} + + + vf_module_id + ${vfModuleId} + + + vf_module_name + ${vfModuleName} + + ${vfModuleIndexParam}""" + + utils.logAudit("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 = + """ + availability_zone_${aZonePosition} + ${aZoneValue} + """ + aZones = sbAZone.append(aZoneXml) + } + } + + // 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") + 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 = + """ + ${vnfNetworkKey}_net_id + ${vnfNetworkNeutronIdValue} + """ + vnfNetworkNetId = sbNet.append(vnfNetworkNetIdXml) + String vnfNetworkNetNameXml = + """ + ${vnfNetworkKey}_net_name + ${vnfNetworkNetNameValue} + """ + vnfNetworkNetName = sbNet2.append(vnfNetworkNetNameXml) + String vnfNetworkSubNetIdXml = + """ + ${vnfNetworkKey}_subnet_id + ${vnfNetworkSubNetIdValue} + """ + vnfNetworkSubNetId = sbNet3.append(vnfNetworkSubNetIdXml) + String vnfNetworkV6SubNetIdXml = + """ + ${vnfNetworkKey}_v6_subnet_id + ${vnfNetworkV6SubNetIdValue} + """ + vnfNetworkV6SubNetId = sbNet5.append(vnfNetworkV6SubNetIdXml) + String vnfNetworkNetFqdnXml = + """ + ${vnfNetworkKey}_net_fqdn + ${vnfNetworkNetFqdnValue} + """ + 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 = + """ + ${vnfNetworkKey}_ATT_VF_VLAN_FILTER + ${values} + """ + 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 = + """ + ${key}_name_${position} + ${value} + """ + vnfVMSPositions = 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") + floatingIPKey = key + '_' + networkKey + '_floating_ip' + floatingIPKeyValue = utils.getElementText(eElementNetworkKey, "floating-ip") + if(!floatingIPKeyValue.isEmpty()){ + floatingIpKeyValueStr = """ + $floatingIPKey + $floatingIPKeyValue + """ + } + floatingIPV6Key = key + '_' + networkKey + '_floating_v6_ip' + floatingIPV6KeyValue = utils.getElementText(eElementNetworkKey, "floating-ip-v6") + if(!floatingIPV6KeyValue.isEmpty()){ + floatingIpV6KeyValueStr = """ + $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() + String vmNetworksPositionsXml = + """ + ${key}_${networkKey}_ip_${networkPosition} + ${ipAddressValue} + """ + vmNetworksPositions = sbNetworksPositions.append(vmNetworksPositionsXml) + } + } + vmNetworksPositions = sbNetworksPositions.append(floatingIpKeyValueStr).append(floatingIpV6KeyValueStr) + + String vmNetworksXml = + """ + ${key}_${networkKey}_ips + ${ipAddressValues} + """ + 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 = + """ + ${key}_${networkKey}_route_prefixes + ${interfaceRoutePrefixValues} + """ + 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 = + """ + ${key}_${networkKey}_v6_ip_${networkPosition} + ${ipV6AddressValue} + """ + vmNetworksPositionsV6 = sbNetworksPositionsV6.append(vmNetworksPositionsV6Xml) + } + } + String vmNetworksV6Xml = + """ + ${key}_${networkKey}_v6_ips + ${ipV6AddressValues} + """ + vmNetworks = sbVmNetworks.append(vmNetworksV6Xml) + } + } + String vnfXml = + """ + ${key}_names + ${values} + """ + vnfVMS = sb.append(vnfXml) + } + } + //SDNC Response Params + String sdncResponseParams = "" + List 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 = + """ + ${vnfParameterName} + ${vnfParameterValue} + """ + sdncResponseParams = sb.append(paraEntry) + } + } + } + + + def vfModuleParams = """ + ${vnfInfo} + ${aZones} + ${vnfNetworkNetId} + ${vnfNetworkNetName} + ${vnfNetworkSubNetId} + ${vnfNetworkV6SubNetId} + ${vnfNetworkNetFqdn} + ${vnfNetworksSriovVlanFilters} + ${vnfVMS} + ${vnfVMSPositions} + ${vmNetworks} + ${vmNetworksPositions} + ${vmNetworksPositionsV6} + ${interfaceRoutePrefixes} + ${vnfParams} + ${sdncResponseParams}""" + + 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") + data = data.replaceAll("<", "<") + data = data.replaceAll(">", ">") + + + + // Add-on data + String vnfInfo = + """ + vnf_id + ${vnfId} + + + vnf_name + ${vnfName} + + + vf_module_id + ${vfModuleId} + + + vf_module_name + ${vfModuleName} + """ + + utils.logAudit("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 = + """ + availability_zone_${aZonePosition} + ${aZoneValue} + """ + aZones = sbAZone.append(aZoneXml) + } + } + + // 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") + 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 = + """ + ${vnfNetworkKey}_net_id + ${vnfNetworkNeutronIdValue} + """ + vnfNetworkNetId = sbNet.append(vnfNetworkNetIdXml) + String vnfNetworkNetNameXml = + """ + ${vnfNetworkKey}_net_name + ${vnfNetworkNetNameValue} + """ + vnfNetworkNetName = sbNet2.append(vnfNetworkNetNameXml) + String vnfNetworkSubNetIdXml = + """ + ${vnfNetworkKey}_subnet_id + ${vnfNetworkSubNetIdValue} + """ + vnfNetworkSubNetId = sbNet3.append(vnfNetworkSubNetIdXml) + String vnfNetworkV6SubNetIdXml = + """ + ${vnfNetworkKey}_v6_subnet_id + ${vnfNetworkV6SubNetIdValue} + """ + vnfNetworkV6SubNetId = sbNet5.append(vnfNetworkV6SubNetIdXml) + String vnfNetworkNetFqdnXml = + """ + ${vnfNetworkKey}_net_fqdn + ${vnfNetworkNetFqdnValue} + """ + 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 = + """ + ${vnfNetworkKey}_ATT_VF_VLAN_FILTER + ${values} + """ + 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 = + """ + ${key}_name_${position} + ${value} + """ + vnfVMSPositions = 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") + floatingIPKey = key + '_' + networkKey + '_floating_ip' + floatingIPKeyValue = utils.getElementText(eElementNetworkKey, "floating-ip") + if(!floatingIPKeyValue.isEmpty()){ + floatingIpKeyValueStr = """ + $floatingIPKey + $floatingIPKeyValue + """ + } + floatingIPV6Key = key + '_' + networkKey + '_floating_v6_ip' + floatingIPV6KeyValue = utils.getElementText(eElementNetworkKey, "floating-ip-v6") + if(!floatingIPV6KeyValue.isEmpty()){ + floatingIpV6KeyValueStr = """ + $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() + String vmNetworksPositionsXml = + """ + ${key}_${networkKey}_ip_${networkPosition} + ${ipAddressValue} + """ + vmNetworksPositions = sbNetworksPositions.append(vmNetworksPositionsXml) + } + } + vmNetworksPositions = sbNetworksPositions.append(floatingIpKeyValueStr).append(floatingIpV6KeyValueStr) + + String vmNetworksXml = + """ + ${key}_${networkKey}_ips + ${ipAddressValues} + """ + 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 = + """ + ${key}_${networkKey}_route_prefixes + ${interfaceRoutePrefixValues} + """ + 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 = + """ + ${key}_${networkKey}_v6_ip_${networkPosition} + ${ipV6AddressValue} + """ + vmNetworksPositionsV6 = sbNetworksPositionsV6.append(vmNetworksPositionsV6Xml) + } + } + String vmNetworksV6Xml = + """ + ${key}_${networkKey}_v6_ips + ${ipV6AddressValues} + """ + vmNetworks = sbVmNetworks.append(vmNetworksV6Xml) + } + } + String vnfXml = + """ + ${key}_names + ${values} + """ + vnfVMS = sb.append(vnfXml) + } + } + //SDNC Response Params + String sdncResponseParams = "" + List 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 = + """ + ${vnfParameterName} + ${vnfParameterValue} + """ + 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/openecomp/mso/bpmn/common/scripts/VidUtils.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/VidUtils.groovy index de59c68a7d..022a00c192 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/VidUtils.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/VidUtils.groovy @@ -1,550 +1,550 @@ -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - MSO - * ================================================================================ - * 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.openecomp.mso.bpmn.common.scripts - -import groovy.json.JsonBuilder -import groovy.json.JsonSlurper - -import org.json.JSONObject -import org.json.XML -import org.openecomp.mso.bpmn.core.xml.XmlTool - -class VidUtils { - - 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?.modelCustomizationName - } - } - - vnfType = serviceName + '/' + modelCustomizationName - - def userParams = requestMap.requestDetails?.requestParameters?.userParams - def userParamsNode = '' - if(userParams != null) { - userParamsNode = buildUserParams(userParams) - } - def modelCustomizationId = requestMap.requestDetails?.modelInfo?.modelCustomizationId ?: '' - - def xmlReq = """ - - - ${action} - ${requestMap.requestDetails.requestInfo.source} - ${serviceInstanceId} - - - ${volumeGroupId} - ${volGrpName} - ${vnfType} - ${requestMap.requestDetails.modelInfo.modelName} - ${asdcServiceModelVersion} - ${requestMap.requestDetails.cloudConfiguration.lcpCloudRegionId} - ${requestMap.requestDetails.cloudConfiguration.tenantId} - ${serviceId} - ${backoutOnFailure} - ${modelCustomizationId} - - - $userParamsNode - - - """ - // 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 += "${value}" - } - - 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 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 = "" - 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 = """ - - - ${requestId} - ${requestAction} - VID - ${serviceInstanceId} - - - ${networkId} - ${instanceName} - ${modelName} - ${lcpCloudRegionId} - ${tenantId} - ${serviceId} - ${backoutOnFailure} - ${sdncVersion} - - - ${userParamsNode} - - - """ - // 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) { - throw e - } - } - - /** - * Create a network-request XML using a map, - * @param execution - * @return - */ - public String createXmlNetworkRequestInstance(execution) { - - def networkModelVersionId = "" - def networkModelName = "" - def networkModelType = "" - def networkModelVersion = "" - def networkModelCustomizationId = "" - def networkModelInvariantId = "" - - // 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("modelVersionId")) { - networkModelVersionId = modelMap.modelVersionId !=null ? modelMap.modelVersionId : "" - } - if (networkModelInfo.contains("modelName")) { - networkModelName = modelMap.modelName !=null ? modelMap.modelName : "" - } - if (networkModelInfo.contains("modelType")) { - networkModelType = modelMap.modelType !=null ? modelMap.modelType : "" - } - if (networkModelInfo.contains("modelVersion")) { - networkModelVersion = modelMap.modelVersion !=null ? modelMap.modelVersion : "" - } - if (networkModelInfo.contains("modelCustomizationId")) { - networkModelCustomizationId = modelMap.modelCustomizationId !=null ? modelMap.modelCustomizationId : "" - } - if (networkModelInfo.contains("modelInvariantId")) { - networkModelInvariantId = modelMap.modelInvariantId !=null ? modelMap.modelInvariantId : "" - } - } - } catch (Exception ex) { - throw ex - } - } - - def serviceModelVersionId = "" - def serviceModelName = "" - def serviceModelType = "" - def serviceModelVersion = "" - def serviceModelCustomizationId = "" - def serviceModelInvariantId = "" - - // 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("modelVersionId")) { - serviceModelVersionId = modelMap.modelVersionId !=null ? modelMap.modelVersionId : "" - } - if (serviceModelInfo.contains("modelName")) { - serviceModelName = modelMap.modelName !=null ? modelMap.modelName : "" - } - if (serviceModelInfo.contains("modelType")) { - serviceModelType = modelMap.modelType !=null ? modelMap.modelType : "" - } - if (serviceModelInfo.contains("modelVersion")) { - serviceModelVersion = modelMap.modelVersion !=null ? modelMap.modelVersion : "" - } - if (serviceModelInfo.contains("modelCustomizationId")) { - serviceModelCustomizationId = modelMap.modelCustomizationId !=null ? modelMap.modelCustomizationId : "" - } - if (serviceModelInfo.contains("modelInvariantId")) { - serviceModelInvariantId = modelMap.modelInvariantId !=null ? modelMap.modelInvariantId : "" - } - } - } 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 = "" - 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 = """ - - - ${requestId} - ${action} - ${source} - ${serviceInstanceId} - - - ${networkId} - ${networkName} - ${networkModelType} - ${subscriptionServiceType} - ${globalSubscriberId} - ${aicCloudReqion} - ${tenantId} - ${serviceId} - ${backoutOnFailure} - ${failIfExist} - - ${networkModelName} - ${networkModelVersionId} - ${networkModelInvariantId} - ${networkModelVersion} - ${networkModelCustomizationId} - ${networkModelType} - - - ${serviceModelName} - ${serviceModelVersionId} - ${serviceModelInvariantId} - ${serviceModelVersion} - ${serviceModelCustomizationId} - ${serviceModelType} - - ${sdncVersion} - - - ${userParamsNode} - - - """ - // 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?.modelInvariantId ?: '' - def personaModelVersion = requestMap.requestDetails?.modelInfo?.modelVersion ?: '' - def modelCustomizationId = requestMap.requestDetails?.modelInfo?.modelCustomizationId ?: '' - - def xmlReq = """ - - - ${requestId} - ${action} - VID - - ${serviceInstanceId} - - - - ${vnfName} - ${vnfType} - ${vnfId} - ${volumeGroupId} - ${vfModuleId} - ${vfModuleName} - ${vfModuleModelName} - ${modelCustomizationId} - ${isBaseVfModule} - ${asdcServiceModelInfo} - ${aicCloudRegion} - ${tenantId} - ${serviceId} - ${backoutOnFailure} - ${personaModelId} - ${personaModelVersion} - - - $userParamsNode - - - """ - - // 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]*)?", "") - } - - -} +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.bpmn.common.scripts + +import groovy.json.JsonBuilder +import groovy.json.JsonSlurper + +import org.json.JSONObject +import org.json.XML +import org.openecomp.mso.bpmn.core.xml.XmlTool + +class VidUtils { + + 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?.modelCustomizationName + } + } + + vnfType = serviceName + '/' + modelCustomizationName + + def userParams = requestMap.requestDetails?.requestParameters?.userParams + def userParamsNode = '' + if(userParams != null) { + userParamsNode = buildUserParams(userParams) + } + def modelCustomizationId = requestMap.requestDetails?.modelInfo?.modelCustomizationId ?: '' + + def xmlReq = """ + + + ${action} + ${requestMap.requestDetails.requestInfo.source} + ${serviceInstanceId} + + + ${volumeGroupId} + ${volGrpName} + ${vnfType} + ${requestMap.requestDetails.modelInfo.modelName} + ${asdcServiceModelVersion} + ${requestMap.requestDetails.cloudConfiguration.lcpCloudRegionId} + ${requestMap.requestDetails.cloudConfiguration.tenantId} + ${serviceId} + ${backoutOnFailure} + ${modelCustomizationId} + + + $userParamsNode + + + """ + // 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 += "${value}" + } + + 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 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 = """ + + + ${requestId} + ${requestAction} + VID + ${serviceInstanceId} + + + ${networkId} + ${instanceName} + ${modelName} + ${lcpCloudRegionId} + ${tenantId} + ${serviceId} + ${backoutOnFailure} + ${sdncVersion} + + + ${userParamsNode} + + + """ + // 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) { + throw e + } + } + + /** + * Create a network-request XML using a map, + * @param execution + * @return + */ + public String createXmlNetworkRequestInstance(execution) { + + def networkModelVersionId = "" + def networkModelName = "" + def networkModelType = "" + def networkModelVersion = "" + def networkModelCustomizationId = "" + def networkModelInvariantId = "" + + // 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("modelVersionId")) { + networkModelVersionId = modelMap.modelVersionId !=null ? modelMap.modelVersionId : "" + } + if (networkModelInfo.contains("modelName")) { + networkModelName = modelMap.modelName !=null ? modelMap.modelName : "" + } + if (networkModelInfo.contains("modelType")) { + networkModelType = modelMap.modelType !=null ? modelMap.modelType : "" + } + if (networkModelInfo.contains("modelVersion")) { + networkModelVersion = modelMap.modelVersion !=null ? modelMap.modelVersion : "" + } + if (networkModelInfo.contains("modelCustomizationId")) { + networkModelCustomizationId = modelMap.modelCustomizationId !=null ? modelMap.modelCustomizationId : "" + } + if (networkModelInfo.contains("modelInvariantId")) { + networkModelInvariantId = modelMap.modelInvariantId !=null ? modelMap.modelInvariantId : "" + } + } + } catch (Exception ex) { + throw ex + } + } + + def serviceModelVersionId = "" + def serviceModelName = "" + def serviceModelType = "" + def serviceModelVersion = "" + def serviceModelCustomizationId = "" + def serviceModelInvariantId = "" + + // 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("modelVersionId")) { + serviceModelVersionId = modelMap.modelVersionId !=null ? modelMap.modelVersionId : "" + } + if (serviceModelInfo.contains("modelName")) { + serviceModelName = modelMap.modelName !=null ? modelMap.modelName : "" + } + if (serviceModelInfo.contains("modelType")) { + serviceModelType = modelMap.modelType !=null ? modelMap.modelType : "" + } + if (serviceModelInfo.contains("modelVersion")) { + serviceModelVersion = modelMap.modelVersion !=null ? modelMap.modelVersion : "" + } + if (serviceModelInfo.contains("modelCustomizationId")) { + serviceModelCustomizationId = modelMap.modelCustomizationId !=null ? modelMap.modelCustomizationId : "" + } + if (serviceModelInfo.contains("modelInvariantId")) { + serviceModelInvariantId = modelMap.modelInvariantId !=null ? modelMap.modelInvariantId : "" + } + } + } 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 = """ + + + ${requestId} + ${action} + ${source} + ${serviceInstanceId} + + + ${networkId} + ${networkName} + ${networkModelType} + ${subscriptionServiceType} + ${globalSubscriberId} + ${aicCloudReqion} + ${tenantId} + ${serviceId} + ${backoutOnFailure} + ${failIfExist} + + ${networkModelName} + ${networkModelVersionId} + ${networkModelInvariantId} + ${networkModelVersion} + ${networkModelCustomizationId} + ${networkModelType} + + + ${serviceModelName} + ${serviceModelVersionId} + ${serviceModelInvariantId} + ${serviceModelVersion} + ${serviceModelCustomizationId} + ${serviceModelType} + + ${sdncVersion} + + + ${userParamsNode} + + + """ + // 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?.modelInvariantId ?: '' + def personaModelVersion = requestMap.requestDetails?.modelInfo?.modelVersion ?: '' + def modelCustomizationId = requestMap.requestDetails?.modelInfo?.modelCustomizationId ?: '' + + def xmlReq = """ + + + ${requestId} + ${action} + VID + + ${serviceInstanceId} + + + + ${vnfName} + ${vnfType} + ${vnfId} + ${volumeGroupId} + ${vfModuleId} + ${vfModuleName} + ${vfModuleModelName} + ${modelCustomizationId} + ${isBaseVfModule} + ${asdcServiceModelInfo} + ${aicCloudRegion} + ${tenantId} + ${serviceId} + ${backoutOnFailure} + ${personaModelId} + ${personaModelVersion} + + + $userParamsNode + + + """ + + // 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/openecomp/mso/bpmn/common/scripts/VnfAdapterRestV1.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/VnfAdapterRestV1.groovy index 31c5596cbb..0ec9c93862 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/VnfAdapterRestV1.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/VnfAdapterRestV1.groovy @@ -1,404 +1,404 @@ -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - MSO - * ================================================================================ - * 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.openecomp.mso.bpmn.common.scripts - -import org.apache.commons.lang3.* -import org.camunda.bpm.engine.delegate.BpmnError -import org.camunda.bpm.engine.runtime.Execution -import org.openecomp.mso.rest.APIResponse -import org.openecomp.mso.rest.RESTClient -import org.openecomp.mso.rest.RESTConfig - -class VnfAdapterRestV1 extends AbstractServiceTaskProcessor { - - ExceptionUtil exceptionUtil = new ExceptionUtil() - - // VNF Response Processing - public void preProcessRequest (Execution execution) { - def method = getClass().getSimpleName() + '.preProcessRequest(' + - 'execution=' + execution.getId() + - ')' - def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') - logDebug('Entered ' + method, isDebugLogEnabled) - - 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) - logDebug(getProcessKey(execution) + ': ' + prefix + 'requestType = ' + requestType, isDebugLogEnabled) - - utils.logAudit('VnfAdapterRestV1, request: ' + request) - // Get the messageId from the request - - String messageId = getChildText(root, 'messageId') - - if (messageId == null || messageId.isEmpty()) { - String msg = getProcessKey(execution) + ': no messageId in ' + requestType - logError(msg) - exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg) - } - - execution.setVariable('VNFAResponse_CORRELATOR', messageId) - logDebug(getProcessKey(execution) + ': VNFAResponse_CORRELATOR = ' + messageId, isDebugLogEnabled) - - // Get the notificationUrl from the request - - String notificationUrl = getChildText(root, 'notificationUrl') - - if (notificationUrl == null || notificationUrl.isEmpty()) { - String msg = getProcessKey(execution) + ': no notificationUrl in ' + requestType - logError(msg) - exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg) - } - - execution.setVariable(prefix + 'notificationUrl', notificationUrl) - logDebug(getProcessKey(execution) + ': ' + prefix + 'notificationUrl = ' + notificationUrl, isDebugLogEnabled) - - // Determine the VnfAdapter endpoint - - String vnfAdapterEndpoint = execution.getVariable("URN_mso_adapters_vnf_rest_endpoint") - - if (vnfAdapterEndpoint == null || vnfAdapterEndpoint.isEmpty()) { - String msg = getProcessKey(execution) + ': mso:adapters:vnf:rest:endpoint URN mapping is not defined' - logError(msg) - 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 - logError(msg) - 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 - logError(msg) - exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg) - } - - String vfModuleId = getChildText(root, 'vfModuleId') - - if (vfModuleId == null || vfModuleId.isEmpty()) { - String msg = getProcessKey(execution) + ': no vfModuleId in ' + requestType - logError(msg) - 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 - logError(msg) - exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg) - } - - String vfModuleId = getChildText(root, 'vfModuleId') - - if (vfModuleId == null || vfModuleId.isEmpty()) { - String msg = getProcessKey(execution) + ': no vfModuleId in ' + requestType - logError(msg) - 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 - logError(msg) - exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg) - } - - String vnfId = getChildText(vfModuleRollbackNode, 'vnfId') - - if (vnfId == null || vnfId.isEmpty()) { - String msg = getProcessKey(execution) + ': no vnfId in ' + requestType - logError(msg) - exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg) - } - - String vfModuleId = getChildText(vfModuleRollbackNode, 'vfModuleId') - - if (vfModuleId == null || vfModuleId.isEmpty()) { - String msg = getProcessKey(execution) + ': no vfModuleId in ' + requestType - logError(msg) - 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 - logError(msg) - 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 - logError(msg) - 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 = getChildText(root, 'volumeGroupId') - - if (volumeGroupId == null || volumeGroupId.isEmpty()) { - String msg = getProcessKey(execution) + ': no volumeGroupId in ' + requestType - logError(msg) - createWorkflowException(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 - logError(msg) - exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg) - } - - execution.setVariable(prefix + 'vnfAdapterMethod', vnfAdapterMethod) - logDebug(getProcessKey(execution) + ': ' + prefix + 'vnfAdapterMethod = ' + vnfAdapterMethod, isDebugLogEnabled) - execution.setVariable(prefix + 'vnfAdapterUrl', vnfAdapterUrl) - logDebug(getProcessKey(execution) + ': ' + prefix + 'vnfAdapterUrl = ' + vnfAdapterUrl, isDebugLogEnabled) - execution.setVariable(prefix + 'vnfAdapterRequest', vnfAdapterRequest) - logDebug(getProcessKey(execution) + ': ' + prefix + 'vnfAdapterRequest = \n' + vnfAdapterRequest, isDebugLogEnabled) - - // Get the Basic Auth credentials for the VnfAdapter - - String basicAuthValue = execution.getVariable("URN_mso_adapters_po_auth") - - if (basicAuthValue == null || basicAuthValue.isEmpty()) { - logError(getProcessKey(execution) + ": mso:adapters:po:auth URN mapping is not defined") - } else { - logDebug(getProcessKey(execution) + ": Obtained BasicAuth credentials for VnfAdapter:" + - basicAuthValue, isDebugLogEnabled) - try { - def encodedString = utils.getBasicAuth(basicAuthValue, execution.getVariable("URN_mso_msoKey")) - execution.setVariable(prefix + 'basicAuthHeaderValue', encodedString) - } catch (IOException ex) { - logError(getProcessKey(execution) + ": Unable to encode BasicAuth credentials for VnfAdapter") - } - } - - } catch (BpmnError e) { - logDebug(" Rethrowing MSOWorkflowException", isDebugLogEnabled) - throw e - } catch (Exception e) { - String msg = 'Caught exception in ' + method + ": " + e - logError(msg) - exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg) - } - } - - /** - * This method is used instead of an HTTP Connector task because the - * connector does not allow DELETE with a body. - */ - public void sendRequestToVnfAdapter(Execution execution) { - def method = getClass().getSimpleName() + '.sendRequestToVnfAdapter(' + - 'execution=' + execution.getId() + - ')' - def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') - logDebug('Entered ' + method, isDebugLogEnabled) - - 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 - logError(msg) - 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 - logError(msg) - exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg) - } - } - - public void processCallback(Execution execution){ - def method = getClass().getSimpleName() + '.processCallback(' + - 'execution=' + execution.getId() + - ')' - def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') - logDebug('Entered ' + method, isDebugLogEnabled) - - String callback = execution.getVariable('VNFAResponse_MESSAGE') - - try { - logDebug(getProcessKey(execution) + ": received callback:\n" + callback, isDebugLogEnabled) - - // 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 - logDebug(getProcessKey(execution) + ': ' + msg, isDebugLogEnabled) - 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(Execution 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() - } -} +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.bpmn.common.scripts + +import org.apache.commons.lang3.* +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.runtime.Execution +import org.openecomp.mso.rest.APIResponse +import org.openecomp.mso.rest.RESTClient +import org.openecomp.mso.rest.RESTConfig + +class VnfAdapterRestV1 extends AbstractServiceTaskProcessor { + + ExceptionUtil exceptionUtil = new ExceptionUtil() + + // VNF Response Processing + public void preProcessRequest (Execution execution) { + def method = getClass().getSimpleName() + '.preProcessRequest(' + + 'execution=' + execution.getId() + + ')' + def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') + logDebug('Entered ' + method, isDebugLogEnabled) + + 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) + logDebug(getProcessKey(execution) + ': ' + prefix + 'requestType = ' + requestType, isDebugLogEnabled) + + utils.logAudit('VnfAdapterRestV1, request: ' + request) + // Get the messageId from the request + + String messageId = getChildText(root, 'messageId') + + if (messageId == null || messageId.isEmpty()) { + String msg = getProcessKey(execution) + ': no messageId in ' + requestType + logError(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg) + } + + execution.setVariable('VNFAResponse_CORRELATOR', messageId) + logDebug(getProcessKey(execution) + ': VNFAResponse_CORRELATOR = ' + messageId, isDebugLogEnabled) + + // Get the notificationUrl from the request + + String notificationUrl = getChildText(root, 'notificationUrl') + + if (notificationUrl == null || notificationUrl.isEmpty()) { + String msg = getProcessKey(execution) + ': no notificationUrl in ' + requestType + logError(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg) + } + + execution.setVariable(prefix + 'notificationUrl', notificationUrl) + logDebug(getProcessKey(execution) + ': ' + prefix + 'notificationUrl = ' + notificationUrl, isDebugLogEnabled) + + // Determine the VnfAdapter endpoint + + String vnfAdapterEndpoint = execution.getVariable("URN_mso_adapters_vnf_rest_endpoint") + + if (vnfAdapterEndpoint == null || vnfAdapterEndpoint.isEmpty()) { + String msg = getProcessKey(execution) + ': mso:adapters:vnf:rest:endpoint URN mapping is not defined' + logError(msg) + 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 + logError(msg) + 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 + logError(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg) + } + + String vfModuleId = getChildText(root, 'vfModuleId') + + if (vfModuleId == null || vfModuleId.isEmpty()) { + String msg = getProcessKey(execution) + ': no vfModuleId in ' + requestType + logError(msg) + 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 + logError(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg) + } + + String vfModuleId = getChildText(root, 'vfModuleId') + + if (vfModuleId == null || vfModuleId.isEmpty()) { + String msg = getProcessKey(execution) + ': no vfModuleId in ' + requestType + logError(msg) + 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 + logError(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg) + } + + String vnfId = getChildText(vfModuleRollbackNode, 'vnfId') + + if (vnfId == null || vnfId.isEmpty()) { + String msg = getProcessKey(execution) + ': no vnfId in ' + requestType + logError(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg) + } + + String vfModuleId = getChildText(vfModuleRollbackNode, 'vfModuleId') + + if (vfModuleId == null || vfModuleId.isEmpty()) { + String msg = getProcessKey(execution) + ': no vfModuleId in ' + requestType + logError(msg) + 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 + logError(msg) + 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 + logError(msg) + 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 = getChildText(root, 'volumeGroupId') + + if (volumeGroupId == null || volumeGroupId.isEmpty()) { + String msg = getProcessKey(execution) + ': no volumeGroupId in ' + requestType + logError(msg) + 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 + logError(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg) + } + + execution.setVariable(prefix + 'vnfAdapterMethod', vnfAdapterMethod) + logDebug(getProcessKey(execution) + ': ' + prefix + 'vnfAdapterMethod = ' + vnfAdapterMethod, isDebugLogEnabled) + execution.setVariable(prefix + 'vnfAdapterUrl', vnfAdapterUrl) + logDebug(getProcessKey(execution) + ': ' + prefix + 'vnfAdapterUrl = ' + vnfAdapterUrl, isDebugLogEnabled) + execution.setVariable(prefix + 'vnfAdapterRequest', vnfAdapterRequest) + logDebug(getProcessKey(execution) + ': ' + prefix + 'vnfAdapterRequest = \n' + vnfAdapterRequest, isDebugLogEnabled) + + // Get the Basic Auth credentials for the VnfAdapter + + String basicAuthValue = execution.getVariable("URN_mso_adapters_po_auth") + + if (basicAuthValue == null || basicAuthValue.isEmpty()) { + logError(getProcessKey(execution) + ": mso:adapters:po:auth URN mapping is not defined") + } else { + logDebug(getProcessKey(execution) + ": Obtained BasicAuth credentials for VnfAdapter:" + + basicAuthValue, isDebugLogEnabled) + try { + def encodedString = utils.getBasicAuth(basicAuthValue, execution.getVariable("URN_mso_msoKey")) + execution.setVariable(prefix + 'basicAuthHeaderValue', encodedString) + } catch (IOException ex) { + logError(getProcessKey(execution) + ": Unable to encode BasicAuth credentials for VnfAdapter") + } + } + + } catch (BpmnError e) { + logDebug(" Rethrowing MSOWorkflowException", isDebugLogEnabled) + throw e + } catch (Exception e) { + String msg = 'Caught exception in ' + method + ": " + e + logError(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg) + } + } + + /** + * This method is used instead of an HTTP Connector task because the + * connector does not allow DELETE with a body. + */ + public void sendRequestToVnfAdapter(Execution execution) { + def method = getClass().getSimpleName() + '.sendRequestToVnfAdapter(' + + 'execution=' + execution.getId() + + ')' + def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') + logDebug('Entered ' + method, isDebugLogEnabled) + + 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 + logError(msg) + 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 + logError(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg) + } + } + + public void processCallback(Execution execution){ + def method = getClass().getSimpleName() + '.processCallback(' + + 'execution=' + execution.getId() + + ')' + def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') + logDebug('Entered ' + method, isDebugLogEnabled) + + String callback = execution.getVariable('VNFAResponse_MESSAGE') + + try { + logDebug(getProcessKey(execution) + ": received callback:\n" + callback, isDebugLogEnabled) + + // 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 + logDebug(getProcessKey(execution) + ': ' + msg, isDebugLogEnabled) + 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(Execution 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/openecomp/mso/bpmn/common/scripts/VnfAdapterUtils.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/VnfAdapterUtils.groovy index cd8d2a3374..82b67ce3bf 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/VnfAdapterUtils.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/VnfAdapterUtils.groovy @@ -1,78 +1,86 @@ -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - MSO - * ================================================================================ - * 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.openecomp.mso.bpmn.common.scripts - -import org.camunda.bpm.engine.delegate.BpmnError -import org.camunda.bpm.engine.runtime.Execution; -import org.openecomp.mso.bpmn.core.WorkflowException - -class VnfAdapterUtils { - - private AbstractServiceTaskProcessor taskProcessor - - public VnfAdapterUtils(AbstractServiceTaskProcessor taskProcessor) { - this.taskProcessor = taskProcessor - } - - ExceptionUtil exceptionUtil = new ExceptionUtil() - - public void validateVnfResponse(Execution execution, String responseVar, String responseCodeVar, String errorResponseVar) { - def method = getClass().getSimpleName() + '.validateVnfResponse(' + - 'execution=' + execution.getId() + - ', responseVar=' + responseVar + - ', responseCodeVar=' + responseCodeVar + - ', errorResponseVar=' + errorResponseVar + - ')' - def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') - taskProcessor.logDebug('Entered ' + method, isDebugLogEnabled) - - 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) - taskProcessor.logDebug(" Sub Vnf flow Error WorkflowException Response - " + "\n" + response, isDebugLogEnabled) - 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()) - taskProcessor.logDebug("Sub Vnf flow Error WorkflowException " + prefix + "ErrorResponse" + " - " + - errorResponse.getErrorMessage(), isDebugLogEnabled) - // this is the important part to ensure we hit the Fallout Handler - throw new BpmnError("MSOWorkflowException") - } - } catch (BpmnError e) { - throw e; - } catch (Exception e) { - taskProcessor.logError('Caught exception in ' + method, e) - taskProcessor.workflowException(execution, 'Internal Error- Unable to validate VNF Response ' + e.getMessage(), 500) - } - } - -} +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.bpmn.common.scripts + +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.runtime.Execution; +import org.openecomp.mso.bpmn.core.WorkflowException + +class VnfAdapterUtils { + + private AbstractServiceTaskProcessor taskProcessor + + public VnfAdapterUtils(AbstractServiceTaskProcessor taskProcessor) { + this.taskProcessor = taskProcessor + } + + ExceptionUtil exceptionUtil = new ExceptionUtil() + + public void validateVnfResponse(Execution execution, String responseVar, String responseCodeVar, String errorResponseVar) { + def method = getClass().getSimpleName() + '.validateVnfResponse(' + + 'execution=' + execution.getId() + + ', responseVar=' + responseVar + + ', responseCodeVar=' + responseCodeVar + + ', errorResponseVar=' + errorResponseVar + + ')' + def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') + taskProcessor.logDebug('Entered ' + method, isDebugLogEnabled) + + 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) + taskProcessor.logDebug(" Sub Vnf flow Error WorkflowException Response - " + "\n" + response, isDebugLogEnabled) + 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()) + taskProcessor.logDebug("Sub Vnf flow Error WorkflowException " + prefix + "ErrorResponse" + " - " + + errorResponse.getErrorMessage(), isDebugLogEnabled) + // 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()) + taskProcessor.logDebug("Sub Vnf flow Error WorkflowException " + prefix + "ErrorResponse" + " - " + + errorResponse.getErrorMessage(), isDebugLogEnabled) + // this is the important part to ensure we hit the Fallout Handler + throw new BpmnError("MSOWorkflowException") + } + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + taskProcessor.logError('Caught exception in ' + method, e) + exceptionUtil.buildAndThrowWorkflowException(execution, 5000, 'Internal Error- Unable to validate VNF Response ' + e.getMessage()) + } + } + +} diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/MSOCommonApplication.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/MSOCommonApplication.java index 9931247885..9100974596 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/MSOCommonApplication.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/MSOCommonApplication.java @@ -1,59 +1,59 @@ -package org.openecomp.mso.bpmn.common; -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - MSO - * ================================================================================ - * 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========================================================= - */ - - - -import java.util.List; - -import org.camunda.bpm.application.PostDeploy; -import org.camunda.bpm.application.PreUndeploy; -import org.camunda.bpm.application.ProcessApplication; -import org.camunda.bpm.application.ProcessApplicationInfo; -import org.camunda.bpm.application.impl.ServletProcessApplication; -import org.camunda.bpm.engine.ProcessEngine; - -import org.openecomp.mso.logger.MsoLogger; - -/** - * @since Version 1.0 - * - */ -@ProcessApplication("MSO Common Application") -public class MSOCommonApplication extends ServletProcessApplication { - - private MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL); - - @PostDeploy - public void postDeploy(ProcessEngine processEngineInstance) { - long startTime = System.currentTimeMillis(); - - msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Post deployment complete..."); - } - - @PreUndeploy - public void cleanup(ProcessEngine processEngine, ProcessApplicationInfo processApplicationInfo, List processEngines) { - long startTime = System.currentTimeMillis(); - - msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Pre Undeploy complete..."); - - } - -} +package org.openecomp.mso.bpmn.common; +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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========================================================= + */ + + + +import java.util.List; + +import org.camunda.bpm.application.PostDeploy; +import org.camunda.bpm.application.PreUndeploy; +import org.camunda.bpm.application.ProcessApplication; +import org.camunda.bpm.application.ProcessApplicationInfo; +import org.camunda.bpm.application.impl.ServletProcessApplication; +import org.camunda.bpm.engine.ProcessEngine; + +import org.openecomp.mso.logger.MsoLogger; + +/** + * @since Version 1.0 + * + */ +@ProcessApplication(name="MSO Common Application", deploymentDescriptors={"../processes.xml"}) +public class MSOCommonApplication extends ServletProcessApplication { + + private MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL); + + @PostDeploy + public void postDeploy(ProcessEngine processEngineInstance) { + long startTime = System.currentTimeMillis(); + + msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Post deployment complete..."); + } + + @PreUndeploy + public void cleanup(ProcessEngine processEngine, ProcessApplicationInfo processApplicationInfo, List processEngines) { + long startTime = System.currentTimeMillis(); + + msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Pre Undeploy complete..."); + + } + +} diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/adapter/sdnc/ObjectFactory.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/adapter/sdnc/ObjectFactory.java index 2e0ae1b930..3d6570166d 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/adapter/sdnc/ObjectFactory.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/adapter/sdnc/ObjectFactory.java @@ -1,91 +1,91 @@ -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - MSO - * ================================================================================ - * 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.openecomp.mso.bpmn.common.adapter.sdnc; - -import javax.xml.bind.annotation.XmlRegistry; - - -/** - * This object contains factory methods for each - * Java content interface and Java element interface - * generated in the org.openecomp.domain2.workflow.sdnc.adapter.schema.v1 package. - *

An ObjectFactory allows you to programatically - * construct new instances of the Java representation - * for XML content. The Java representation of XML - * content can consist of schema derived interfaces - * and classes representing the binding of schema - * type definitions, element declarations and model - * groups. Factory methods for each of these are - * provided in this class. - * - */ -@XmlRegistry -public class ObjectFactory { - - - /** - * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: org.openecomp.domain2.workflow.sdnc.adapter.schema.v1 - * - */ - public ObjectFactory() { - } - - /** - * Create an instance of {@link RequestHeader } - * - */ - public RequestHeader createRequestHeader() { - return new RequestHeader(); - } - - /** - * Create an instance of {@link SDNCAdapterResponse } - * - */ - public SDNCAdapterResponse createSDNCAdapterResponse() { - return new SDNCAdapterResponse(); - } - - /** - * Create an instance of {@link SDNCAdapterCallbackRequest } - * - */ - public SDNCAdapterCallbackRequest createSDNCAdapterCallbackRequest() { - return new SDNCAdapterCallbackRequest(); - } - - /** - * Create an instance of {@link CallbackHeader } - * - */ - public CallbackHeader createCallbackHeader() { - return new CallbackHeader(); - } - - /** - * Create an instance of {@link SDNCAdapterRequest } - * - */ - public SDNCAdapterRequest createSDNCAdapterRequest() { - return new SDNCAdapterRequest(); - } - -} +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.bpmn.common.adapter.sdnc; + +import javax.xml.bind.annotation.XmlRegistry; + + +/** + * This object contains factory methods for each + * Java content interface and Java element interface + * generated in the org.openecomp.domain2.workflow.sdnc.adapter.schema.v1 package. + *

An ObjectFactory allows you to programatically + * construct new instances of the Java representation + * for XML content. The Java representation of XML + * content can consist of schema derived interfaces + * and classes representing the binding of schema + * type definitions, element declarations and model + * groups. Factory methods for each of these are + * provided in this class. + * + */ +@XmlRegistry +public class ObjectFactory { + + + /** + * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: org.openecomp.domain2.workflow.sdnc.adapter.schema.v1 + * + */ + public ObjectFactory() { + } + + /** + * Create an instance of {@link RequestHeader } + * + */ + public RequestHeader createRequestHeader() { + return new RequestHeader(); + } + + /** + * Create an instance of {@link SDNCAdapterResponse } + * + */ + public SDNCAdapterResponse createSDNCAdapterResponse() { + return new SDNCAdapterResponse(); + } + + /** + * Create an instance of {@link SDNCAdapterCallbackRequest } + * + */ + public SDNCAdapterCallbackRequest createSDNCAdapterCallbackRequest() { + return new SDNCAdapterCallbackRequest(); + } + + /** + * Create an instance of {@link CallbackHeader } + * + */ + public CallbackHeader createCallbackHeader() { + return new CallbackHeader(); + } + + /** + * Create an instance of {@link SDNCAdapterRequest } + * + */ + public SDNCAdapterRequest createSDNCAdapterRequest() { + return new SDNCAdapterRequest(); + } + +} diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/adapter/sdnc/RequestHeader.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/adapter/sdnc/RequestHeader.java index 27b1245856..f2e4de88d6 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/adapter/sdnc/RequestHeader.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/adapter/sdnc/RequestHeader.java @@ -1,223 +1,223 @@ -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - MSO - * ================================================================================ - * 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.openecomp.mso.bpmn.common.adapter.sdnc; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; -import javax.xml.bind.annotation.XmlType; - - -/** - *

Java class for anonymous complex type. - * - *

The following schema fragment specifies the expected content contained within this class. - * - *

- * <complexType>
- *   <complexContent>
- *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
- *       <sequence>
- *         <element name="RequestId" type="{http://www.w3.org/2001/XMLSchema}string"/>
- *         <element name="SvcInstanceId" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- *         <element name="SvcAction" type="{http://www.w3.org/2001/XMLSchema}string"/>
- *         <element name="SvcOperation" type="{http://www.w3.org/2001/XMLSchema}string"/>
- *         <element name="CallbackUrl" type="{http://www.w3.org/2001/XMLSchema}string"/>
- *         <element name="MsoAction" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- *       </sequence>
- *     </restriction>
- *   </complexContent>
- * </complexType>
- * 
- * - * - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "", propOrder = { - "requestId", - "svcInstanceId", - "svcAction", - "svcOperation", - "callbackUrl", - "msoAction" -}) -@XmlRootElement(name = "RequestHeader") -public class RequestHeader { - - @XmlElement(name = "RequestId", required = true) - protected String requestId; - @XmlElement(name = "SvcInstanceId") - protected String svcInstanceId; - @XmlElement(name = "SvcAction", required = true) - protected String svcAction; - @XmlElement(name = "SvcOperation", required = true) - protected String svcOperation; - @XmlElement(name = "CallbackUrl", required = true) - protected String callbackUrl; - @XmlElement(name = "MsoAction") - protected String msoAction; - - /** - * Gets the value of the requestId property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getRequestId() { - return requestId; - } - - /** - * Sets the value of the requestId property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setRequestId(String value) { - this.requestId = value; - } - - /** - * Gets the value of the svcInstanceId property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getSvcInstanceId() { - return svcInstanceId; - } - - /** - * Sets the value of the svcInstanceId property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setSvcInstanceId(String value) { - this.svcInstanceId = value; - } - - /** - * Gets the value of the svcAction property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getSvcAction() { - return svcAction; - } - - /** - * Sets the value of the svcAction property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setSvcAction(String value) { - this.svcAction = value; - } - - /** - * Gets the value of the svcOperation property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getSvcOperation() { - return svcOperation; - } - - /** - * Sets the value of the svcOperation property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setSvcOperation(String value) { - this.svcOperation = value; - } - - /** - * Gets the value of the callbackUrl property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getCallbackUrl() { - return callbackUrl; - } - - /** - * Sets the value of the callbackUrl property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setCallbackUrl(String value) { - this.callbackUrl = value; - } - - /** - * Gets the value of the msoAction property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getMsoAction() { - return msoAction; - } - - /** - * Sets the value of the msoAction property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setMsoAction(String value) { - this.msoAction = value; - } - -} +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.bpmn.common.adapter.sdnc; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlType; + + +/** + *

Java class for anonymous complex type. + * + *

The following schema fragment specifies the expected content contained within this class. + * + *

+ * <complexType>
+ *   <complexContent>
+ *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ *       <sequence>
+ *         <element name="RequestId" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ *         <element name="SvcInstanceId" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ *         <element name="SvcAction" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ *         <element name="SvcOperation" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ *         <element name="CallbackUrl" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ *         <element name="MsoAction" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ *       </sequence>
+ *     </restriction>
+ *   </complexContent>
+ * </complexType>
+ * 
+ * + * + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "", propOrder = { + "requestId", + "svcInstanceId", + "svcAction", + "svcOperation", + "callbackUrl", + "msoAction" +}) +@XmlRootElement(name = "RequestHeader") +public class RequestHeader { + + @XmlElement(name = "RequestId", required = true) + protected String requestId; + @XmlElement(name = "SvcInstanceId") + protected String svcInstanceId; + @XmlElement(name = "SvcAction", required = true) + protected String svcAction; + @XmlElement(name = "SvcOperation", required = true) + protected String svcOperation; + @XmlElement(name = "CallbackUrl", required = true) + protected String callbackUrl; + @XmlElement(name = "MsoAction") + protected String msoAction; + + /** + * Gets the value of the requestId property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getRequestId() { + return requestId; + } + + /** + * Sets the value of the requestId property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setRequestId(String value) { + this.requestId = value; + } + + /** + * Gets the value of the svcInstanceId property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getSvcInstanceId() { + return svcInstanceId; + } + + /** + * Sets the value of the svcInstanceId property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setSvcInstanceId(String value) { + this.svcInstanceId = value; + } + + /** + * Gets the value of the svcAction property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getSvcAction() { + return svcAction; + } + + /** + * Sets the value of the svcAction property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setSvcAction(String value) { + this.svcAction = value; + } + + /** + * Gets the value of the svcOperation property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getSvcOperation() { + return svcOperation; + } + + /** + * Sets the value of the svcOperation property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setSvcOperation(String value) { + this.svcOperation = value; + } + + /** + * Gets the value of the callbackUrl property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getCallbackUrl() { + return callbackUrl; + } + + /** + * Sets the value of the callbackUrl property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setCallbackUrl(String value) { + this.callbackUrl = value; + } + + /** + * Gets the value of the msoAction property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getMsoAction() { + return msoAction; + } + + /** + * Sets the value of the msoAction property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setMsoAction(String value) { + this.msoAction = value; + } + +} diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/adapter/sdnc/SDNCAdapterResponse.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/adapter/sdnc/SDNCAdapterResponse.java index 829af2c20b..2c38abe4ff 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/adapter/sdnc/SDNCAdapterResponse.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/adapter/sdnc/SDNCAdapterResponse.java @@ -1,51 +1,51 @@ -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - MSO - * ================================================================================ - * 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.openecomp.mso.bpmn.common.adapter.sdnc; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlRootElement; -import javax.xml.bind.annotation.XmlType; - - -/** - *

Java class for anonymous complex type. - * - *

The following schema fragment specifies the expected content contained within this class. - * - *

- * <complexType>
- *   <complexContent>
- *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
- *     </restriction>
- *   </complexContent>
- * </complexType>
- * 
- * - * - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "") -@XmlRootElement(name = "SDNCAdapterResponse") -public class SDNCAdapterResponse { - - -} +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.bpmn.common.adapter.sdnc; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlType; + + +/** + *

Java class for anonymous complex type. + * + *

The following schema fragment specifies the expected content contained within this class. + * + *

+ * <complexType>
+ *   <complexContent>
+ *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ *     </restriction>
+ *   </complexContent>
+ * </complexType>
+ * 
+ * + * + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "") +@XmlRootElement(name = "SDNCAdapterResponse") +public class SDNCAdapterResponse { + + +} diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/adapter/vnf/DeleteVnfNotification.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/adapter/vnf/DeleteVnfNotification.java index b408184ae3..0cbb988e3b 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/adapter/vnf/DeleteVnfNotification.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/adapter/vnf/DeleteVnfNotification.java @@ -1,198 +1,198 @@ -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - MSO - * ================================================================================ - * 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.openecomp.mso.bpmn.common.adapter.vnf; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlType; - - -/** - *

Java class for deleteVnfNotification complex type. - * - *

The following schema fragment specifies the expected content contained within this class. - * - *

- * <complexType name="deleteVnfNotification">
- *   <complexContent>
- *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
- *       <sequence>
- *         <element name="messageId" type="{http://www.w3.org/2001/XMLSchema}string"/>
- *         <element name="completed" type="{http://www.w3.org/2001/XMLSchema}boolean"/>
- *         <element name="exception" type="{http://org.openecomp.mso/vnfNotify}msoExceptionCategory" minOccurs="0"/>
- *         <element name="errorMessage" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- *       </sequence>
- *     </restriction>
- *   </complexContent>
- * </complexType>
- * 
- * - * - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "deleteVnfNotification1", propOrder = { - "messageId", - "completed", - "exception", - "errorMessage" -}) -public class DeleteVnfNotification { - - @XmlElement(required = true) - protected String messageId; - protected boolean completed; - protected MsoExceptionCategory exception; - protected String errorMessage; - - /** - * Gets the value of the messageId property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getMessageId() { - return messageId; - } - - /** - * Sets the value of the messageId property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setMessageId(String value) { - this.messageId = value; - } - - /** - * Gets the value of the completed property. - * - */ - public boolean isCompleted() { - return completed; - } - - /** - * Sets the value of the completed property. - * - */ - public void setCompleted(boolean value) { - this.completed = value; - } - - /** - * Gets the value of the exception property. - * - * @return - * possible object is - * {@link MsoExceptionCategory } - * - */ - public MsoExceptionCategory getException() { - return exception; - } - - /** - * Sets the value of the exception property. - * - * @param value - * allowed object is - * {@link MsoExceptionCategory } - * - */ - public void setException(MsoExceptionCategory value) { - this.exception = value; - } - - /** - * Gets the value of the errorMessage property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getErrorMessage() { - return errorMessage; - } - - /** - * Sets the value of the errorMessage property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setErrorMessage(String value) { - this.errorMessage = value; - } - - /** - * Overrides toString() method - * @return String type (deleteVnfNotification) - */ - - - public String toString() { - String deleteVnfNotification = ""; - if (exception==null) { - deleteVnfNotification = "" + '\n' + - " "+messageId+"" + '\n' + - " "+completed+"" + '\n' + - ""; - } else { - deleteVnfNotification = "" + '\n' + - " "+messageId+"" + '\n' + - " "+completed+"" + '\n' + - " "+exception+"" + '\n' + - " "+errorMessage+"" + '\n' + - ""; - } - return deleteVnfNotification; - } - -/* - public String toString() { - StringWriter writer = new StringWriter(); - try { - JAXBContext context = JAXBContext - .newInstance(DeleteVnfNotification.class); - Marshaller m = context.createMarshaller(); - m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); - m.marshal(this, writer); - //System.out.println("toString() - " + writer.getBuffer().toString()); - return writer.getBuffer().toString(); - } catch (JAXBException e) { - //System.out.println("JAXBException - " + e.getStackTrace()); - return ""; - } - } -*/ - -} +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.bpmn.common.adapter.vnf; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlType; + + +/** + *

Java class for deleteVnfNotification complex type. + * + *

The following schema fragment specifies the expected content contained within this class. + * + *

+ * <complexType name="deleteVnfNotification">
+ *   <complexContent>
+ *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ *       <sequence>
+ *         <element name="messageId" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ *         <element name="completed" type="{http://www.w3.org/2001/XMLSchema}boolean"/>
+ *         <element name="exception" type="{http://org.openecomp.mso/vnfNotify}msoExceptionCategory" minOccurs="0"/>
+ *         <element name="errorMessage" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ *       </sequence>
+ *     </restriction>
+ *   </complexContent>
+ * </complexType>
+ * 
+ * + * + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "deleteVnfNotification1", propOrder = { + "messageId", + "completed", + "exception", + "errorMessage" +}) +public class DeleteVnfNotification { + + @XmlElement(required = true) + protected String messageId; + protected boolean completed; + protected MsoExceptionCategory exception; + protected String errorMessage; + + /** + * Gets the value of the messageId property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getMessageId() { + return messageId; + } + + /** + * Sets the value of the messageId property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setMessageId(String value) { + this.messageId = value; + } + + /** + * Gets the value of the completed property. + * + */ + public boolean isCompleted() { + return completed; + } + + /** + * Sets the value of the completed property. + * + */ + public void setCompleted(boolean value) { + this.completed = value; + } + + /** + * Gets the value of the exception property. + * + * @return + * possible object is + * {@link MsoExceptionCategory } + * + */ + public MsoExceptionCategory getException() { + return exception; + } + + /** + * Sets the value of the exception property. + * + * @param value + * allowed object is + * {@link MsoExceptionCategory } + * + */ + public void setException(MsoExceptionCategory value) { + this.exception = value; + } + + /** + * Gets the value of the errorMessage property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getErrorMessage() { + return errorMessage; + } + + /** + * Sets the value of the errorMessage property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setErrorMessage(String value) { + this.errorMessage = value; + } + + /** + * Overrides toString() method + * @return String type (deleteVnfNotification) + */ + + + public String toString() { + String deleteVnfNotification = ""; + if (exception==null) { + deleteVnfNotification = "" + '\n' + + " "+messageId+"" + '\n' + + " "+completed+"" + '\n' + + ""; + } else { + deleteVnfNotification = "" + '\n' + + " "+messageId+"" + '\n' + + " "+completed+"" + '\n' + + " "+exception+"" + '\n' + + " "+errorMessage+"" + '\n' + + ""; + } + return deleteVnfNotification; + } + +/* + public String toString() { + StringWriter writer = new StringWriter(); + try { + JAXBContext context = JAXBContext + .newInstance(DeleteVnfNotification.class); + Marshaller m = context.createMarshaller(); + m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); + m.marshal(this, writer); + //System.out.println("toString() - " + writer.getBuffer().toString()); + return writer.getBuffer().toString(); + } catch (JAXBException e) { + //System.out.println("JAXBException - " + e.getStackTrace()); + return ""; + } + } +*/ + +} diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/adapter/vnf/MsoExceptionCategory.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/adapter/vnf/MsoExceptionCategory.java index 80673a0fb6..444ef982fd 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/adapter/vnf/MsoExceptionCategory.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/adapter/vnf/MsoExceptionCategory.java @@ -1,61 +1,61 @@ -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - MSO - * ================================================================================ - * 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.openecomp.mso.bpmn.common.adapter.vnf; - -import javax.xml.bind.annotation.XmlEnum; -import javax.xml.bind.annotation.XmlType; - - -/** - *

Java class for msoExceptionCategory. - * - *

The following schema fragment specifies the expected content contained within this class. - *

- *

- * <simpleType name="msoExceptionCategory">
- *   <restriction base="{http://www.w3.org/2001/XMLSchema}string">
- *     <enumeration value="OPENSTACK"/>
- *     <enumeration value="IO"/>
- *     <enumeration value="INTERNAL"/>
- *     <enumeration value="USERDATA"/>
- *   </restriction>
- * </simpleType>
- * 
- * - */ -@XmlType(name = "msoExceptionCategory") -@XmlEnum -public enum MsoExceptionCategory { - - OPENSTACK, - IO, - INTERNAL, - USERDATA; - - public String value() { - return name(); - } - - public static MsoExceptionCategory fromValue(String v) { - return valueOf(v); - } - -} +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.bpmn.common.adapter.vnf; + +import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlType; + + +/** + *

Java class for msoExceptionCategory. + * + *

The following schema fragment specifies the expected content contained within this class. + *

+ *

+ * <simpleType name="msoExceptionCategory">
+ *   <restriction base="{http://www.w3.org/2001/XMLSchema}string">
+ *     <enumeration value="OPENSTACK"/>
+ *     <enumeration value="IO"/>
+ *     <enumeration value="INTERNAL"/>
+ *     <enumeration value="USERDATA"/>
+ *   </restriction>
+ * </simpleType>
+ * 
+ * + */ +@XmlType(name = "msoExceptionCategory") +@XmlEnum +public enum MsoExceptionCategory { + + OPENSTACK, + IO, + INTERNAL, + USERDATA; + + public String value() { + return name(); + } + + public static MsoExceptionCategory fromValue(String v) { + return valueOf(v); + } + +} diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/adapter/vnf/MsoRequest.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/adapter/vnf/MsoRequest.java index f251a31ce8..01a6705898 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/adapter/vnf/MsoRequest.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/adapter/vnf/MsoRequest.java @@ -1,114 +1,114 @@ -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - MSO - * ================================================================================ - * 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.openecomp.mso.bpmn.common.adapter.vnf; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlType; - - -/** - *

Java class for msoRequest complex type. - * - *

The following schema fragment specifies the expected content contained within this class. - * - *

- * <complexType name="msoRequest">
- *   <complexContent>
- *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
- *       <sequence>
- *         <element name="requestId" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- *         <element name="serviceInstanceId" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- *       </sequence>
- *     </restriction>
- *   </complexContent>
- * </complexType>
- * 
- * - * - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "msoRequest", propOrder = { - "requestId", - "serviceInstanceId" -}) -public class MsoRequest { - - protected String requestId; - protected String serviceInstanceId; - - /** - * Gets the value of the requestId property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getRequestId() { - return requestId; - } - - /** - * Sets the value of the requestId property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setRequestId(String value) { - this.requestId = value; - } - - /** - * Gets the value of the serviceInstanceId property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getServiceInstanceId() { - return serviceInstanceId; - } - - /** - * Sets the value of the serviceInstanceId property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setServiceInstanceId(String value) { - this.serviceInstanceId = value; - } - - public String toString() { - String request = ""; - request = - ""+requestId+"" + '\n' + - ""+serviceInstanceId+""; - return request; - } - -} +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.bpmn.common.adapter.vnf; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlType; + + +/** + *

Java class for msoRequest complex type. + * + *

The following schema fragment specifies the expected content contained within this class. + * + *

+ * <complexType name="msoRequest">
+ *   <complexContent>
+ *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ *       <sequence>
+ *         <element name="requestId" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ *         <element name="serviceInstanceId" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ *       </sequence>
+ *     </restriction>
+ *   </complexContent>
+ * </complexType>
+ * 
+ * + * + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "msoRequest", propOrder = { + "requestId", + "serviceInstanceId" +}) +public class MsoRequest { + + protected String requestId; + protected String serviceInstanceId; + + /** + * Gets the value of the requestId property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getRequestId() { + return requestId; + } + + /** + * Sets the value of the requestId property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setRequestId(String value) { + this.requestId = value; + } + + /** + * Gets the value of the serviceInstanceId property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getServiceInstanceId() { + return serviceInstanceId; + } + + /** + * Sets the value of the serviceInstanceId property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setServiceInstanceId(String value) { + this.serviceInstanceId = value; + } + + public String toString() { + String request = ""; + request = + ""+requestId+"" + '\n' + + ""+serviceInstanceId+""; + return request; + } + +} diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/adapter/vnf/QueryVnfNotification.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/adapter/vnf/QueryVnfNotification.java index 47ae04577e..b7b93b7b5d 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/adapter/vnf/QueryVnfNotification.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/adapter/vnf/QueryVnfNotification.java @@ -1,488 +1,488 @@ -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - MSO - * ================================================================================ - * 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.openecomp.mso.bpmn.common.adapter.vnf; - -import java.util.ArrayList; -import java.util.List; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlType; - - -/** - *

Java class for queryVnfNotification complex type. - * - *

The following schema fragment specifies the expected content contained within this class. - * - *

- * <complexType name="queryVnfNotification">
- *   <complexContent>
- *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
- *       <sequence>
- *         <element name="messageId" type="{http://www.w3.org/2001/XMLSchema}string"/>
- *         <element name="completed" type="{http://www.w3.org/2001/XMLSchema}boolean"/>
- *         <element name="exception" type="{http://org.openecomp.mso/vnfNotify}msoExceptionCategory" minOccurs="0"/>
- *         <element name="errorMessage" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- *         <element name="vnfExists" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
- *         <element name="vnfId" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- *         <element name="status" type="{http://org.openecomp.mso/vnfNotify}vnfStatus" minOccurs="0"/>
- *         <element name="outputs" minOccurs="0">
- *           <complexType>
- *             <complexContent>
- *               <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
- *                 <sequence>
- *                   <element name="entry" maxOccurs="unbounded" minOccurs="0">
- *                     <complexType>
- *                       <complexContent>
- *                         <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
- *                           <sequence>
- *                             <element name="key" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- *                             <element name="value" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
- *                           </sequence>
- *                         </restriction>
- *                       </complexContent>
- *                     </complexType>
- *                   </element>
- *                 </sequence>
- *               </restriction>
- *             </complexContent>
- *           </complexType>
- *         </element>
- *       </sequence>
- *     </restriction>
- *   </complexContent>
- * </complexType>
- * 
- * - * - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "queryVnfNotification1", propOrder = { - "messageId", - "completed", - "exception", - "errorMessage", - "vnfExists", - "vnfId", - "status", - "outputs" -}) -public class QueryVnfNotification { - - @XmlElement(required = true) - protected String messageId; - protected boolean completed; - protected MsoExceptionCategory exception; - protected String errorMessage; - protected Boolean vnfExists; - protected String vnfId; - protected VnfStatus status; - protected QueryVnfNotification.Outputs outputs; - - /** - * Gets the value of the messageId property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getMessageId() { - return messageId; - } - - /** - * Sets the value of the messageId property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setMessageId(String value) { - this.messageId = value; - } - - /** - * Gets the value of the completed property. - * - */ - public boolean isCompleted() { - return completed; - } - - /** - * Sets the value of the completed property. - * - */ - public void setCompleted(boolean value) { - this.completed = value; - } - - /** - * Gets the value of the exception property. - * - * @return - * possible object is - * {@link MsoExceptionCategory } - * - */ - public MsoExceptionCategory getException() { - return exception; - } - - /** - * Sets the value of the exception property. - * - * @param value - * allowed object is - * {@link MsoExceptionCategory } - * - */ - public void setException(MsoExceptionCategory value) { - this.exception = value; - } - - /** - * Gets the value of the errorMessage property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getErrorMessage() { - return errorMessage; - } - - /** - * Sets the value of the errorMessage property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setErrorMessage(String value) { - this.errorMessage = value; - } - - /** - * Gets the value of the vnfExists property. - * - * @return - * possible object is - * {@link Boolean } - * - */ - public Boolean isVnfExists() { - return vnfExists; - } - - /** - * Sets the value of the vnfExists property. - * - * @param value - * allowed object is - * {@link Boolean } - * - */ - public void setVnfExists(Boolean value) { - this.vnfExists = value; - } - - /** - * Gets the value of the vnfId property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getVnfId() { - return vnfId; - } - - /** - * Sets the value of the vnfId property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setVnfId(String value) { - this.vnfId = value; - } - - /** - * Gets the value of the status property. - * - * @return - * possible object is - * {@link VnfStatus } - * - */ - public VnfStatus getStatus() { - return status; - } - - /** - * Sets the value of the status property. - * - * @param value - * allowed object is - * {@link VnfStatus } - * - */ - public void setStatus(VnfStatus value) { - this.status = value; - } - - /** - * Gets the value of the outputs property. - * - * @return - * possible object is - * {@link QueryVnfNotification.Outputs } - * - */ - public QueryVnfNotification.Outputs getOutputs() { - return outputs; - } - - /** - * Sets the value of the outputs property. - * - * @param value - * allowed object is - * {@link QueryVnfNotification.Outputs } - * - */ - public void setOutputs(QueryVnfNotification.Outputs value) { - this.outputs = value; - } - - - /** - *

Java class for anonymous complex type. - * - *

The following schema fragment specifies the expected content contained within this class. - * - *

-     * <complexType>
-     *   <complexContent>
-     *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
-     *       <sequence>
-     *         <element name="entry" maxOccurs="unbounded" minOccurs="0">
-     *           <complexType>
-     *             <complexContent>
-     *               <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
-     *                 <sequence>
-     *                   <element name="key" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
-     *                   <element name="value" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
-     *                 </sequence>
-     *               </restriction>
-     *             </complexContent>
-     *           </complexType>
-     *         </element>
-     *       </sequence>
-     *     </restriction>
-     *   </complexContent>
-     * </complexType>
-     * 
- * - * - */ - @XmlAccessorType(XmlAccessType.FIELD) - @XmlType(name = "", propOrder = { - "entry" - }) - public static class Outputs { - - protected List entry; - - /** - * Gets the value of the entry property. - * - *

- * This accessor method returns a reference to the live list, - * not a snapshot. Therefore any modification you make to the - * returned list will be present inside the JAXB object. - * This is why there is not a set method for the entry property. - * - *

- * For example, to add a new item, do as follows: - *

-         *    getEntry().add(newItem);
-         * 
- * - * - *

- * Objects of the following type(s) are allowed in the list - * {@link QueryVnfNotification.Outputs.Entry } - * - * - */ - public List getEntry() { - if (entry == null) { - entry = new ArrayList(); - } - return this.entry; - } - - // Not a generated method - public String toString() { - StringBuilder out = new StringBuilder(); - out.append("\n"); - if (entry != null) { - for (Entry e : entry) { - out.append(e.toString()); - out.append('\n'); - } - } - out.append(""); - return out.toString(); - } - - - /** - *

Java class for anonymous complex type. - * - *

The following schema fragment specifies the expected content contained within this class. - * - *

-         * <complexType>
-         *   <complexContent>
-         *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
-         *       <sequence>
-         *         <element name="key" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
-         *         <element name="value" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
-         *       </sequence>
-         *     </restriction>
-         *   </complexContent>
-         * </complexType>
-         * 
- * - * - */ - @XmlAccessorType(XmlAccessType.FIELD) - @XmlType(name = "", propOrder = { - "key", - "value" - }) - public static class Entry { - - protected String key; - protected String value; - - /** - * Gets the value of the key property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getKey() { - return key; - } - - /** - * Sets the value of the key property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setKey(String value) { - this.key = value; - } - - /** - * Gets the value of the value property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getValue() { - return value; - } - - /** - * Sets the value of the value property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setValue(String value) { - this.value = value; - } - - // Not a generated method - public String toString() { - String entry = ""; - entry = - ""+ '\n' + - " "+key+"" + '\n' + - " "+value+"" + '\n' + - ""; - return entry; - } - - } - - } - - // Not a generated method - public String toString() { - String queryVnfNotification = ""; - if (exception==null) { - queryVnfNotification = "" + '\n' + - " "+messageId+"" + '\n' + - " "+completed+"" + '\n' + - " "+vnfExists+"" + '\n' + - " "+vnfId+"" + '\n' + - " "+status+"" + '\n' + - (outputs == null ? "" : outputs.toString() + '\n') + - ""; - } else { - queryVnfNotification = "" + '\n' + - " "+messageId+"" + '\n' + - " "+completed+"" + '\n' + - (outputs == null ? "" : outputs.toString() + '\n') + - " "+exception+"" + '\n' + - " "+errorMessage+"" + '\n' + - ""; - } - return queryVnfNotification; - } - -} +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.bpmn.common.adapter.vnf; + +import java.util.ArrayList; +import java.util.List; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlType; + + +/** + *

Java class for queryVnfNotification complex type. + * + *

The following schema fragment specifies the expected content contained within this class. + * + *

+ * <complexType name="queryVnfNotification">
+ *   <complexContent>
+ *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ *       <sequence>
+ *         <element name="messageId" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ *         <element name="completed" type="{http://www.w3.org/2001/XMLSchema}boolean"/>
+ *         <element name="exception" type="{http://org.openecomp.mso/vnfNotify}msoExceptionCategory" minOccurs="0"/>
+ *         <element name="errorMessage" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ *         <element name="vnfExists" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
+ *         <element name="vnfId" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ *         <element name="status" type="{http://org.openecomp.mso/vnfNotify}vnfStatus" minOccurs="0"/>
+ *         <element name="outputs" minOccurs="0">
+ *           <complexType>
+ *             <complexContent>
+ *               <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ *                 <sequence>
+ *                   <element name="entry" maxOccurs="unbounded" minOccurs="0">
+ *                     <complexType>
+ *                       <complexContent>
+ *                         <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ *                           <sequence>
+ *                             <element name="key" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ *                             <element name="value" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+ *                           </sequence>
+ *                         </restriction>
+ *                       </complexContent>
+ *                     </complexType>
+ *                   </element>
+ *                 </sequence>
+ *               </restriction>
+ *             </complexContent>
+ *           </complexType>
+ *         </element>
+ *       </sequence>
+ *     </restriction>
+ *   </complexContent>
+ * </complexType>
+ * 
+ * + * + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "queryVnfNotification1", propOrder = { + "messageId", + "completed", + "exception", + "errorMessage", + "vnfExists", + "vnfId", + "status", + "outputs" +}) +public class QueryVnfNotification { + + @XmlElement(required = true) + protected String messageId; + protected boolean completed; + protected MsoExceptionCategory exception; + protected String errorMessage; + protected Boolean vnfExists; + protected String vnfId; + protected VnfStatus status; + protected QueryVnfNotification.Outputs outputs; + + /** + * Gets the value of the messageId property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getMessageId() { + return messageId; + } + + /** + * Sets the value of the messageId property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setMessageId(String value) { + this.messageId = value; + } + + /** + * Gets the value of the completed property. + * + */ + public boolean isCompleted() { + return completed; + } + + /** + * Sets the value of the completed property. + * + */ + public void setCompleted(boolean value) { + this.completed = value; + } + + /** + * Gets the value of the exception property. + * + * @return + * possible object is + * {@link MsoExceptionCategory } + * + */ + public MsoExceptionCategory getException() { + return exception; + } + + /** + * Sets the value of the exception property. + * + * @param value + * allowed object is + * {@link MsoExceptionCategory } + * + */ + public void setException(MsoExceptionCategory value) { + this.exception = value; + } + + /** + * Gets the value of the errorMessage property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getErrorMessage() { + return errorMessage; + } + + /** + * Sets the value of the errorMessage property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setErrorMessage(String value) { + this.errorMessage = value; + } + + /** + * Gets the value of the vnfExists property. + * + * @return + * possible object is + * {@link Boolean } + * + */ + public Boolean isVnfExists() { + return vnfExists; + } + + /** + * Sets the value of the vnfExists property. + * + * @param value + * allowed object is + * {@link Boolean } + * + */ + public void setVnfExists(Boolean value) { + this.vnfExists = value; + } + + /** + * Gets the value of the vnfId property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getVnfId() { + return vnfId; + } + + /** + * Sets the value of the vnfId property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setVnfId(String value) { + this.vnfId = value; + } + + /** + * Gets the value of the status property. + * + * @return + * possible object is + * {@link VnfStatus } + * + */ + public VnfStatus getStatus() { + return status; + } + + /** + * Sets the value of the status property. + * + * @param value + * allowed object is + * {@link VnfStatus } + * + */ + public void setStatus(VnfStatus value) { + this.status = value; + } + + /** + * Gets the value of the outputs property. + * + * @return + * possible object is + * {@link QueryVnfNotification.Outputs } + * + */ + public QueryVnfNotification.Outputs getOutputs() { + return outputs; + } + + /** + * Sets the value of the outputs property. + * + * @param value + * allowed object is + * {@link QueryVnfNotification.Outputs } + * + */ + public void setOutputs(QueryVnfNotification.Outputs value) { + this.outputs = value; + } + + + /** + *

Java class for anonymous complex type. + * + *

The following schema fragment specifies the expected content contained within this class. + * + *

+     * <complexType>
+     *   <complexContent>
+     *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+     *       <sequence>
+     *         <element name="entry" maxOccurs="unbounded" minOccurs="0">
+     *           <complexType>
+     *             <complexContent>
+     *               <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+     *                 <sequence>
+     *                   <element name="key" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+     *                   <element name="value" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+     *                 </sequence>
+     *               </restriction>
+     *             </complexContent>
+     *           </complexType>
+     *         </element>
+     *       </sequence>
+     *     </restriction>
+     *   </complexContent>
+     * </complexType>
+     * 
+ * + * + */ + @XmlAccessorType(XmlAccessType.FIELD) + @XmlType(name = "", propOrder = { + "entry" + }) + public static class Outputs { + + protected List entry; + + /** + * Gets the value of the entry property. + * + *

+ * This accessor method returns a reference to the live list, + * not a snapshot. Therefore any modification you make to the + * returned list will be present inside the JAXB object. + * This is why there is not a set method for the entry property. + * + *

+ * For example, to add a new item, do as follows: + *

+         *    getEntry().add(newItem);
+         * 
+ * + * + *

+ * Objects of the following type(s) are allowed in the list + * {@link QueryVnfNotification.Outputs.Entry } + * + * + */ + public List getEntry() { + if (entry == null) { + entry = new ArrayList(); + } + return this.entry; + } + + // Not a generated method + public String toString() { + StringBuilder out = new StringBuilder(); + out.append("\n"); + if (entry != null) { + for (Entry e : entry) { + out.append(e.toString()); + out.append('\n'); + } + } + out.append(""); + return out.toString(); + } + + + /** + *

Java class for anonymous complex type. + * + *

The following schema fragment specifies the expected content contained within this class. + * + *

+         * <complexType>
+         *   <complexContent>
+         *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+         *       <sequence>
+         *         <element name="key" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+         *         <element name="value" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
+         *       </sequence>
+         *     </restriction>
+         *   </complexContent>
+         * </complexType>
+         * 
+ * + * + */ + @XmlAccessorType(XmlAccessType.FIELD) + @XmlType(name = "", propOrder = { + "key", + "value" + }) + public static class Entry { + + protected String key; + protected String value; + + /** + * Gets the value of the key property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getKey() { + return key; + } + + /** + * Sets the value of the key property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setKey(String value) { + this.key = value; + } + + /** + * Gets the value of the value property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getValue() { + return value; + } + + /** + * Sets the value of the value property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setValue(String value) { + this.value = value; + } + + // Not a generated method + public String toString() { + String entry = ""; + entry = + ""+ '\n' + + " "+key+"" + '\n' + + " "+value+"" + '\n' + + ""; + return entry; + } + + } + + } + + // Not a generated method + public String toString() { + String queryVnfNotification = ""; + if (exception==null) { + queryVnfNotification = "" + '\n' + + " "+messageId+"" + '\n' + + " "+completed+"" + '\n' + + " "+vnfExists+"" + '\n' + + " "+vnfId+"" + '\n' + + " "+status+"" + '\n' + + (outputs == null ? "" : outputs.toString() + '\n') + + ""; + } else { + queryVnfNotification = "" + '\n' + + " "+messageId+"" + '\n' + + " "+completed+"" + '\n' + + (outputs == null ? "" : outputs.toString() + '\n') + + " "+exception+"" + '\n' + + " "+errorMessage+"" + '\n' + + ""; + } + return queryVnfNotification; + } + +} diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/adapter/vnf/VnfStatus.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/adapter/vnf/VnfStatus.java index a9b2ee2732..62026fb888 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/adapter/vnf/VnfStatus.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/adapter/vnf/VnfStatus.java @@ -1,61 +1,61 @@ -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - MSO - * ================================================================================ - * 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.openecomp.mso.bpmn.common.adapter.vnf; - -import javax.xml.bind.annotation.XmlEnum; -import javax.xml.bind.annotation.XmlType; - - -/** - *

Java class for vnfStatus. - * - *

The following schema fragment specifies the expected content contained within this class. - *

- *

- * <simpleType name="vnfStatus">
- *   <restriction base="{http://www.w3.org/2001/XMLSchema}string">
- *     <enumeration value="ACTIVE"/>
- *     <enumeration value="FAILED"/>
- *     <enumeration value="NOTFOUND"/>
- *     <enumeration value="UNKNOWN"/>
- *   </restriction>
- * </simpleType>
- * 
- * - */ -@XmlType(name = "vnfStatus") -@XmlEnum -public enum VnfStatus { - - ACTIVE, - FAILED, - NOTFOUND, - UNKNOWN; - - public String value() { - return name(); - } - - public static VnfStatus fromValue(String v) { - return valueOf(v); - } - -} +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.bpmn.common.adapter.vnf; + +import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlType; + + +/** + *

Java class for vnfStatus. + * + *

The following schema fragment specifies the expected content contained within this class. + *

+ *

+ * <simpleType name="vnfStatus">
+ *   <restriction base="{http://www.w3.org/2001/XMLSchema}string">
+ *     <enumeration value="ACTIVE"/>
+ *     <enumeration value="FAILED"/>
+ *     <enumeration value="NOTFOUND"/>
+ *     <enumeration value="UNKNOWN"/>
+ *   </restriction>
+ * </simpleType>
+ * 
+ * + */ +@XmlType(name = "vnfStatus") +@XmlEnum +public enum VnfStatus { + + ACTIVE, + FAILED, + NOTFOUND, + UNKNOWN; + + public String value() { + return name(); + } + + public static VnfStatus fromValue(String v) { + return valueOf(v); + } + +} diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/util/CryptoHandler.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/util/CryptoHandler.java index 1759b208b7..da1f177ea2 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/util/CryptoHandler.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/util/CryptoHandler.java @@ -1,57 +1,57 @@ -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - MSO - * ================================================================================ - * 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.openecomp.mso.bpmn.common.util; - -import java.security.GeneralSecurityException; - -public class CryptoHandler implements ICryptoHandler { - - private static String msoKey = "aa3871669d893c7fb8abbcda31b88b4f"; - //private static String msoAaiPwd = "mso0206"; - private static String msoAaiEncryptedPwd = "C1FC4A39E16419DD41DFC1212843F440"; - - public String getMsoAaiPassword() { - try { - return CryptoUtils.decrypt(msoAaiEncryptedPwd, msoKey); - } catch (GeneralSecurityException e) { - return null; - } - } - - - public String encryptMsoPassword(String plainMsoPwd) { - try { - return CryptoUtils.encrypt(plainMsoPwd, msoKey); - } catch (GeneralSecurityException e) { - return null; - } - } - - - public String decryptMsoPassword(String encryptedPwd) { - try { - return CryptoUtils.decrypt(encryptedPwd, msoKey); - } catch (GeneralSecurityException e) { - return null; - } - } - -} +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.bpmn.common.util; + +import java.security.GeneralSecurityException; + +public class CryptoHandler implements ICryptoHandler { + + private static String msoKey = "aa3871669d893c7fb8abbcda31b88b4f"; + //private static String msoAaiPwd = "mso0206"; + private static String msoAaiEncryptedPwd = "C1FC4A39E16419DD41DFC1212843F440"; + + public String getMsoAaiPassword() { + try { + return CryptoUtils.decrypt(msoAaiEncryptedPwd, msoKey); + } catch (GeneralSecurityException e) { + return null; + } + } + + + public String encryptMsoPassword(String plainMsoPwd) { + try { + return CryptoUtils.encrypt(plainMsoPwd, msoKey); + } catch (GeneralSecurityException e) { + return null; + } + } + + + public String decryptMsoPassword(String encryptedPwd) { + try { + return CryptoUtils.decrypt(encryptedPwd, msoKey); + } catch (GeneralSecurityException e) { + return null; + } + } + +} diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/util/CryptoUtils.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/util/CryptoUtils.java index 70aeda01b0..6237735691 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/util/CryptoUtils.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/util/CryptoUtils.java @@ -1,118 +1,118 @@ -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - MSO - * ================================================================================ - * 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.openecomp.mso.bpmn.common.util; - - -import java.security.GeneralSecurityException; -import java.security.NoSuchAlgorithmException; - -import javax.crypto.Cipher; -import javax.crypto.spec.SecretKeySpec; - -//Need to add BPM error handler - -/** - * CryptoUtils adapted from RTTP client. - * - */ -public class CryptoUtils { - - public static final String AES = "AES"; - - /** - * encrypt a value and generate a keyfile - * if the keyfile is not found then a new one is created - * @throws GeneralSecurityException - * @throws IOException - */ - public static String encrypt(String value, String keyString) throws GeneralSecurityException - { - SecretKeySpec sks = getSecretKeySpec(keyString); - Cipher cipher = Cipher.getInstance(CryptoUtils.AES); - cipher.init(Cipher.ENCRYPT_MODE, sks, cipher.getParameters()); - byte[] encrypted = cipher.doFinal(value.getBytes()); - return byteArrayToHexString(encrypted); - } - - /** - * decrypt a value - * @throws GeneralSecurityException - * @throws IOException - */ - public static String decrypt(String message, String keyString) throws GeneralSecurityException - { - SecretKeySpec sks = getSecretKeySpec(keyString); - Cipher cipher = Cipher.getInstance(CryptoUtils.AES); - cipher.init(Cipher.DECRYPT_MODE, sks); - byte[] decrypted = cipher.doFinal(hexStringToByteArray(message)); - return new String(decrypted); - } - - private static SecretKeySpec getSecretKeySpec(String keyString) throws NoSuchAlgorithmException - { - byte [] key = hexStringToByteArray(keyString); - SecretKeySpec sks = new SecretKeySpec(key, CryptoUtils.AES); - return sks; - } - - - private static String byteArrayToHexString(byte[] b){ - StringBuffer sb = new StringBuffer(b.length * 2); - for (int i = 0; i < b.length; i++){ - int v = b[i] & 0xff; - if (v < 16) { - sb.append('0'); - } - sb.append(Integer.toHexString(v)); - } - return sb.toString().toUpperCase(); - } - - private static byte[] hexStringToByteArray(String s) { - byte[] b = new byte[s.length() / 2]; - for (int i = 0; i < b.length; i++){ - int index = i * 2; - int v = Integer.parseInt(s.substring(index, index + 2), 16); - b[i] = (byte)v; - } - return b; - } - - /** - * Not Used... - * - * Call Rttp utility jar to encrypt pwd - * @param clearPassword - * @return - * @throws GeneralSecurityException - * @throws Exception - * - public static String encryptRttpPwd(String clearPassword) throws GeneralSecurityException { - try { - return RttpBasicAuth.encrypt(clearPassword); - } catch (Exception e) { - // wrap generic exception - throw new GeneralSecurityException(e); - } - } - */ -} - +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.bpmn.common.util; + + +import java.security.GeneralSecurityException; +import java.security.NoSuchAlgorithmException; + +import javax.crypto.Cipher; +import javax.crypto.spec.SecretKeySpec; + +//Need to add BPM error handler + +/** + * CryptoUtils adapted from RTTP client. + * + */ +public class CryptoUtils { + + public static final String AES = "AES"; + + /** + * encrypt a value and generate a keyfile + * if the keyfile is not found then a new one is created + * @throws GeneralSecurityException + * @throws IOException + */ + public static String encrypt(String value, String keyString) throws GeneralSecurityException + { + SecretKeySpec sks = getSecretKeySpec(keyString); + Cipher cipher = Cipher.getInstance(CryptoUtils.AES); + cipher.init(Cipher.ENCRYPT_MODE, sks, cipher.getParameters()); + byte[] encrypted = cipher.doFinal(value.getBytes()); + return byteArrayToHexString(encrypted); + } + + /** + * decrypt a value + * @throws GeneralSecurityException + * @throws IOException + */ + public static String decrypt(String message, String keyString) throws GeneralSecurityException + { + SecretKeySpec sks = getSecretKeySpec(keyString); + Cipher cipher = Cipher.getInstance(CryptoUtils.AES); + cipher.init(Cipher.DECRYPT_MODE, sks); + byte[] decrypted = cipher.doFinal(hexStringToByteArray(message)); + return new String(decrypted); + } + + private static SecretKeySpec getSecretKeySpec(String keyString) throws NoSuchAlgorithmException + { + byte [] key = hexStringToByteArray(keyString); + SecretKeySpec sks = new SecretKeySpec(key, CryptoUtils.AES); + return sks; + } + + + private static String byteArrayToHexString(byte[] b){ + StringBuffer sb = new StringBuffer(b.length * 2); + for (int i = 0; i < b.length; i++){ + int v = b[i] & 0xff; + if (v < 16) { + sb.append('0'); + } + sb.append(Integer.toHexString(v)); + } + return sb.toString().toUpperCase(); + } + + private static byte[] hexStringToByteArray(String s) { + byte[] b = new byte[s.length() / 2]; + for (int i = 0; i < b.length; i++){ + int index = i * 2; + int v = Integer.parseInt(s.substring(index, index + 2), 16); + b[i] = (byte)v; + } + return b; + } + + /** + * Not Used... + * + * Call Rttp utility jar to encrypt pwd + * @param clearPassword + * @return + * @throws GeneralSecurityException + * @throws Exception + * + public static String encryptRttpPwd(String clearPassword) throws GeneralSecurityException { + try { + return RttpBasicAuth.encrypt(clearPassword); + } catch (Exception e) { + // wrap generic exception + throw new GeneralSecurityException(e); + } + } + */ +} + diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/util/ICryptoHandler.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/util/ICryptoHandler.java index 8d4f167596..bc74be05a7 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/util/ICryptoHandler.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/util/ICryptoHandler.java @@ -1,27 +1,27 @@ -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - MSO - * ================================================================================ - * 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.openecomp.mso.bpmn.common.util; - -public interface ICryptoHandler { - public String getMsoAaiPassword(); - public String encryptMsoPassword(String plainPwd); - public String decryptMsoPassword(String encryptedPwd); -} +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.bpmn.common.util; + +public interface ICryptoHandler { + public String getMsoAaiPassword(); + public String encryptMsoPassword(String plainPwd); + public String decryptMsoPassword(String encryptedPwd); +} diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/SDNCAdapterCallbackServiceImpl.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/SDNCAdapterCallbackServiceImpl.java index 02a471c971..4585d620ac 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/SDNCAdapterCallbackServiceImpl.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/SDNCAdapterCallbackServiceImpl.java @@ -1,254 +1,280 @@ -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - MSO - * ================================================================================ - * 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.openecomp.mso.bpmn.common.workflow.service; - -import java.util.HashMap; -import java.util.Map; - -import javax.jws.WebMethod; -import javax.jws.WebParam; -import javax.jws.WebResult; -import javax.jws.WebService; -import javax.ws.rs.core.Context; -import javax.xml.ws.WebServiceContext; - -import org.camunda.bpm.BpmPlatform; -import org.camunda.bpm.engine.MismatchingMessageCorrelationException; -import org.camunda.bpm.engine.ProcessEngineServices; -import org.camunda.bpm.engine.RuntimeService; -import org.openecomp.mso.bpmn.common.adapter.sdnc.SDNCAdapterCallbackRequest; -import org.openecomp.mso.bpmn.common.adapter.sdnc.SDNCAdapterResponse; -import org.openecomp.mso.bpmn.common.adapter.sdnc.SDNCCallbackAdapterPortType; -import org.openecomp.mso.bpmn.core.PropertyConfiguration; -import org.openecomp.mso.logger.MessageEnum; -import org.openecomp.mso.logger.MsoLogger; -/** - * @version 1.0 - * - */ -@WebService(serviceName="SDNCAdapterCallbackService", targetNamespace="http://org.openecomp/workflow/sdnc/adapter/schema/v1") -public class SDNCAdapterCallbackServiceImpl implements SDNCCallbackAdapterPortType { - - private static MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL); - private final int DEFAULT_RETRY_ATTEMPTS = 60; - private final int DEFAULT_SLEEP_TIME = 500; - - private final String logMarker = "[SDNC-CALLBACK]"; - - @Context WebServiceContext wsContext; - - private volatile ProcessEngineServices pes4junit = null; - - @WebMethod(operationName = "SDNCAdapterCallback") - @WebResult(name = "SDNCAdapterResponse", targetNamespace = "http://org.openecomp/workflow/sdnc/adapter/schema/v1", partName = "SDNCAdapterCallbackResponse") - public SDNCAdapterResponse sdncAdapterCallback( - @WebParam(name = "SDNCAdapterCallbackRequest", targetNamespace = "http://org.openecomp/workflow/sdnc/adapter/schema/v1", partName = "SDNCAdapterCallbackRequest") - SDNCAdapterCallbackRequest sdncAdapterCallbackRequest) { - - //Callback URL to use http://localhost:28080/mso/SDNCAdapterCallbackService - ProcessEngineServices pes = getProcessEngineServices(); - RuntimeService runtimeService = pes.getRuntimeService(); - String receivedRequestId = sdncAdapterCallbackRequest.getCallbackHeader().getRequestId(); - MsoLogger.setServiceName("MSO." + "sdncAdapter"); - MsoLogger.setLogContext(receivedRequestId, "N/A"); - msoLogger.debug(logMarker + "Received callback response:" + sdncAdapterCallbackRequest.toString()); - SDNCAdapterResponse sdncAdapterResponse; - long startTime = System.currentTimeMillis(); - - /* Check to make sure the process instance is reay for correlation*/ - isReadyforCorrelation(runtimeService, receivedRequestId); - - msoLogger.debug(logMarker + "*** Received MSO sdncAdapterCallbackService ******"); - - msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Call to MSO sdncAdapterCallbackService"); - - msoLogger.debug(logMarker + "Callback response string:\n" + sdncAdapterCallbackRequest.toString()); - - String reqId = receivedRequestId; - Map variables = new HashMap(); - variables.put("SDNCA_requestId", reqId ); - variables.put("sdncAdapterCallbackRequest", sdncAdapterCallbackRequest.toString()); - - /*Correlating the response with the running instance*/ - - // NOTE: the following loop is a workaround for problems we've had - // with reliability of the runtime service. It seems that queries - // sometimes return results, and sometimes they don't. This might - // be a problem in mysql only. We aren't sure if it affects camunda - // on oracle or mariadb. The workaround is to repeat the request - // a number of times until it succeeds. If it doesn't succeed after - // 60 tries, then we give up. - - int maxAttempts = DEFAULT_RETRY_ATTEMPTS; - int attempt = 1; - int sleepTime = DEFAULT_SLEEP_TIME; - - Map bpmnProperties = getMSOBPMNURNProperties(); - if (bpmnProperties != null) { - try { - maxAttempts = Integer.parseInt(bpmnProperties.get("mso.callbackRetryAttempts")); - msoLogger.debug(logMarker + "mso.callbackRetryAttempts=" + maxAttempts); - sleepTime = Integer.parseInt(bpmnProperties.get("mso.callbackRetrySleepTime")); - msoLogger.debug(logMarker + "mso.callbackRetrySleepTime:" + sleepTime); - } catch (Exception ex) { - - msoLogger.info (MessageEnum.BPMN_SDNC_CALLBACK_EXCEPTION, "BPMN", logMarker - + "Error parsing mso.callbackRetrySleepTime/mso.callbackRetryAttempts:" - + sleepTime + ":" - + maxAttempts); - - msoLogger.error (MessageEnum.BPMN_SDNC_CALLBACK_EXCEPTION, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, logMarker - + "Error parsing mso.callbackRetrySleepTime/mso.callbackRetryAttempts:" - + sleepTime + ":" - + maxAttempts); - - } - } - - while (true) { - try { - // sdncAdapterCallbackRequest is the message event name (defined in the bpmn process) - runtimeService.createMessageCorrelation("sdncAdapterCallbackRequest") - .setVariables(variables) - .processInstanceVariableEquals("SDNCA_requestId", reqId).correlate(); - sdncAdapterResponse = new SDNCAdapterResponse(); - msoLogger.debug(logMarker + "***** Completed processing of MSO sdncAdapterCallbackService ******"); - - msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, logMarker - + "Completed the execution of MSO SDNCAdapterCallbackService."); - - msoLogger.recordMetricEvent ( startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, - logMarker + "Completed the execution of MSO SDNCAdapterCallbackService.", "BPMN", - MsoLogger.getServiceName(), "sdncAdapterCallback"); - - return sdncAdapterResponse; - } catch(MismatchingMessageCorrelationException e) { - msoLogger.debug(logMarker + "[CORM]correlation id mismatch (attempt " + attempt + "/" + maxAttempts + ")"); - if (attempt == maxAttempts) { - // Couldn't correlate requestId to any active flow - //MsoLogger logger = MsoLogger.getMsoLogger("SDNCAdapterCallbackService"); - String msg = - "SDNC Adapter Callback Service received a SDNC Adapter Callback Request with RequestId '" - + receivedRequestId - + "' but that RequestId could not be correlated to any active process - ignoring the Request"; - sdncAdapterResponse = new SDNCAdapterExceptionResponse(e); - - msoLogger.error (MessageEnum.BPMN_SDNC_CALLBACK_EXCEPTION, "BPMN", MsoLogger.getServiceName(), - MsoLogger.ErrorCode.UnknownError, logMarker + ":" + msg, e); - - msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, logMarker - + "Completed the execution of MSO SDNCAdapterCallbackService." ); - - msoLogger.recordMetricEvent ( startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, - logMarker + "Completed the execution of MSO SDNCAdapterCallbackService.", "BPMN", - MsoLogger.getServiceName(), "sdncAdapterCallback"); - - return sdncAdapterResponse; - } - - try { - Thread.sleep(sleepTime); - } catch (InterruptedException e2) { - String msg = - "SDNC Adapter Callback Service received a SDNC Adapter Callback Request with RequestId '" - + receivedRequestId - + "' but correlation was interrupted"; - sdncAdapterResponse = new SDNCAdapterExceptionResponse(e); - - msoLogger.error (MessageEnum.BPMN_SDNC_CALLBACK_EXCEPTION, "BPMN", MsoLogger.getServiceName(), - MsoLogger.ErrorCode.UnknownError, logMarker + ":" + msg, e); - - msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, logMarker - + "Completed the execution of MSO SDNCAdapterCallbackService."); - - msoLogger.recordMetricEvent ( startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, - logMarker + "Completed the execution of MSO SDNCAdapterCallbackService.", "BPMN", - MsoLogger.getServiceName(), "sdncAdapterCallback"); - - return sdncAdapterResponse; - } - } - - attempt++; - } - } - - - private Map getMSOBPMNURNProperties() { - PropertyConfiguration propertyConfiguration = PropertyConfiguration.getInstance(); - Map props = propertyConfiguration.getProperties("mso.bpmn.urn.properties"); - return props; - } - - private void isReadyforCorrelation(RuntimeService runtimeService, - String receivedRequestId) { - long waitingInstances = runtimeService.createExecutionQuery() // - .messageEventSubscriptionName("sdncAdapterCallbackRequest") - .processVariableValueEquals("SDNCA_requestId", receivedRequestId).count(); - //Workaround for performance testing, explicit wait for a second for the transactions to be committed - try { - Thread.sleep(1000); - } catch (InterruptedException e1) { - } - - int retries = 50; - while (waitingInstances==0 && retries > 0) { - try { - Thread.sleep(100); - } catch (InterruptedException e) { - - msoLogger.error (MessageEnum.BPMN_SDNC_CALLBACK_EXCEPTION, "BPMN", MsoLogger.getServiceName(), - MsoLogger.ErrorCode.UnknownError, logMarker, e); - - } // you can still play with the numbers - waitingInstances = runtimeService.createExecutionQuery() // - .messageEventSubscriptionName("sdncAdapterCallbackRequest") - .processVariableValueEquals("SDNCA_requestId", receivedRequestId).count(); - retries--; - } - } - - private ProcessEngineServices getProcessEngineServices() { - if (pes4junit == null) { - return BpmPlatform.getDefaultProcessEngine(); - } else { - return pes4junit; - } - } - - @WebMethod(exclude=true) - public void setProcessEngineServices4junit(ProcessEngineServices pes) { - pes4junit = pes; - } - - public class SDNCAdapterExceptionResponse extends SDNCAdapterResponse { - private Exception ex; - - public SDNCAdapterExceptionResponse(Exception ex) { - super(); - this.ex = ex; - } - - public Exception getException() { - return ex; - } - } -} +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.bpmn.common.workflow.service; + +import java.util.HashMap; +import java.util.Map; + +import javax.jws.WebMethod; +import javax.jws.WebParam; +import javax.jws.WebResult; +import javax.jws.WebService; +import javax.ws.rs.core.Context; +import javax.xml.ws.WebServiceContext; + +import org.camunda.bpm.BpmPlatform; +import org.camunda.bpm.engine.MismatchingMessageCorrelationException; +import org.camunda.bpm.engine.ProcessEngineServices; +import org.camunda.bpm.engine.RuntimeService; +import org.camunda.bpm.engine.runtime.ExecutionQuery; +import org.openecomp.mso.bpmn.common.adapter.sdnc.SDNCAdapterCallbackRequest; +import org.openecomp.mso.bpmn.common.adapter.sdnc.SDNCAdapterResponse; +import org.openecomp.mso.bpmn.common.adapter.sdnc.SDNCCallbackAdapterPortType; +import org.openecomp.mso.bpmn.core.PropertyConfiguration; +import org.openecomp.mso.logger.MessageEnum; +import org.openecomp.mso.logger.MsoLogger; +/** + * @version 1.0 + * + */ +@WebService(serviceName="SDNCAdapterCallbackService", targetNamespace="http://org.openecomp/workflow/sdnc/adapter/schema/v1") +public class SDNCAdapterCallbackServiceImpl implements SDNCCallbackAdapterPortType { + + private static MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL); + private final int DEFAULT_RETRY_ATTEMPTS = 60; + private final int DEFAULT_SLEEP_TIME = 500; + + private final String logMarker = "[SDNC-CALLBACK]"; + + @Context WebServiceContext wsContext; + + private volatile ProcessEngineServices pes4junit = null; + + @WebMethod(operationName = "SDNCAdapterCallback") + @WebResult(name = "SDNCAdapterResponse", targetNamespace = "http://org.openecomp/workflow/sdnc/adapter/schema/v1", partName = "SDNCAdapterCallbackResponse") + public SDNCAdapterResponse sdncAdapterCallback( + @WebParam(name = "SDNCAdapterCallbackRequest", targetNamespace = "http://org.openecomp/workflow/sdnc/adapter/schema/v1", partName = "SDNCAdapterCallbackRequest") + SDNCAdapterCallbackRequest sdncAdapterCallbackRequest) { + + //Callback URL to use http://localhost:28080/mso/SDNCAdapterCallbackService + ProcessEngineServices pes = getProcessEngineServices(); + RuntimeService runtimeService = pes.getRuntimeService(); + String receivedRequestId = sdncAdapterCallbackRequest.getCallbackHeader().getRequestId(); + MsoLogger.setServiceName("MSO." + "sdncAdapter"); + MsoLogger.setLogContext(receivedRequestId, "N/A"); + msoLogger.debug(logMarker + "Received callback response:" + sdncAdapterCallbackRequest.toString()); + SDNCAdapterResponse sdncAdapterResponse; + long startTime = System.currentTimeMillis(); + + /*Correlating the response with the running instance*/ + + // NOTE: the following loop is a workaround for problems we've had + // with reliability of the runtime service. It seems that queries + // sometimes return results, and sometimes they don't. This might + // be a problem in mysql only. We aren't sure if it affects camunda + // on oracle or mariadb. The workaround is to repeat the request + // a number of times until it succeeds. If it doesn't succeed after + // 60 tries, then we give up. + + int maxAttempts = DEFAULT_RETRY_ATTEMPTS; + int attempt = 1; + int sleepTime = DEFAULT_SLEEP_TIME; + + Map bpmnProperties = getMSOBPMNURNProperties(); + if (bpmnProperties != null) { + try { + maxAttempts = Integer.parseInt(bpmnProperties.get("mso.callbackRetryAttempts")); + msoLogger.debug(logMarker + "mso.callbackRetryAttempts=" + maxAttempts); + sleepTime = Integer.parseInt(bpmnProperties.get("mso.callbackRetrySleepTime")); + msoLogger.debug(logMarker + "mso.callbackRetrySleepTime:" + sleepTime); + } catch (Exception ex) { + + msoLogger.debug (logMarker + + "Error parsing mso.callbackRetrySleepTime/mso.callbackRetryAttempts:" + + sleepTime + ":" + + maxAttempts); + + } + } + + /* Check to make sure the process instance is reay for correlation*/ + try{ + isReadyforCorrelation(runtimeService, receivedRequestId, maxAttempts, sleepTime ); + }catch(Exception e){ + String msg = + "SDNC Adapter Callback Service received a SDNC Adapter Callback Request with RequestId '" + + receivedRequestId + + "' but that RequestId doesn't exist or has timed out waiting for the callback"; + sdncAdapterResponse = new SDNCAdapterExceptionResponse(e); + + msoLogger.error (MessageEnum.BPMN_SDNC_CALLBACK_EXCEPTION, "BPMN", MsoLogger.getServiceName(), + MsoLogger.ErrorCode.UnknownError, logMarker + ":" + msg, e); + + msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, logMarker + + "Completed the execution of MSO SDNCAdapterCallbackService." ); + + msoLogger.recordMetricEvent ( startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, + logMarker + "Completed the execution of MSO SDNCAdapterCallbackService.", "BPMN", + MsoLogger.getServiceName(), "sdncAdapterCallback"); + + return sdncAdapterResponse; + } + + msoLogger.debug(logMarker + "*** Received MSO sdncAdapterCallbackService ******"); + + msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Call to MSO sdncAdapterCallbackService"); + + msoLogger.debug(logMarker + "Callback response string:\n" + sdncAdapterCallbackRequest.toString()); + + String reqId = receivedRequestId; + Map variables = new HashMap(); + variables.put("SDNCA_requestId", reqId ); + variables.put("sdncAdapterCallbackRequest", sdncAdapterCallbackRequest.toString()); + while (true) { + try { + // sdncAdapterCallbackRequest is the message event name (defined in the bpmn process) + runtimeService.createMessageCorrelation("sdncAdapterCallbackRequest") + .setVariables(variables) + .processInstanceVariableEquals("SDNCA_requestId", reqId).correlate(); + sdncAdapterResponse = new SDNCAdapterResponse(); + msoLogger.debug(logMarker + "***** Completed processing of MSO sdncAdapterCallbackService ******"); + + msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, logMarker + + "Completed the execution of MSO SDNCAdapterCallbackService."); + + msoLogger.recordMetricEvent ( startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, + logMarker + "Completed the execution of MSO SDNCAdapterCallbackService.", "BPMN", + MsoLogger.getServiceName(), "sdncAdapterCallback"); + + return sdncAdapterResponse; + } catch(MismatchingMessageCorrelationException e) { + msoLogger.debug(logMarker + "[CORM]correlation id mismatch (attempt " + attempt + "/" + maxAttempts + ")"); + if (attempt == maxAttempts) { + // Couldn't correlate requestId to any active flow + //MsoLogger logger = MsoLogger.getMsoLogger("SDNCAdapterCallbackService"); + String msg = + "SDNC Adapter Callback Service received a SDNC Adapter Callback Request with RequestId '" + + receivedRequestId + + "' but that RequestId could not be correlated to any active process - ignoring the Request"; + sdncAdapterResponse = new SDNCAdapterExceptionResponse(e); + + msoLogger.error (MessageEnum.BPMN_SDNC_CALLBACK_EXCEPTION, "BPMN", MsoLogger.getServiceName(), + MsoLogger.ErrorCode.UnknownError, logMarker + ":" + msg, e); + + msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, logMarker + + "Completed the execution of MSO SDNCAdapterCallbackService." ); + + msoLogger.recordMetricEvent ( startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, + logMarker + "Completed the execution of MSO SDNCAdapterCallbackService.", "BPMN", + MsoLogger.getServiceName(), "sdncAdapterCallback"); + + return sdncAdapterResponse; + } + + try { + Thread.sleep(sleepTime); + } catch (InterruptedException e2) { + String msg = + "SDNC Adapter Callback Service received a SDNC Adapter Callback Request with RequestId '" + + receivedRequestId + + "' but correlation was interrupted"; + sdncAdapterResponse = new SDNCAdapterExceptionResponse(e); + + msoLogger.error (MessageEnum.BPMN_SDNC_CALLBACK_EXCEPTION, "BPMN", MsoLogger.getServiceName(), + MsoLogger.ErrorCode.UnknownError, logMarker + ":" + msg, e); + + msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, logMarker + + "Completed the execution of MSO SDNCAdapterCallbackService."); + + msoLogger.recordMetricEvent ( startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, + logMarker + "Completed the execution of MSO SDNCAdapterCallbackService.", "BPMN", + MsoLogger.getServiceName(), "sdncAdapterCallback"); + + return sdncAdapterResponse; + } + } + + attempt++; + } + } + + + private Map getMSOBPMNURNProperties() { + PropertyConfiguration propertyConfiguration = PropertyConfiguration.getInstance(); + Map props = propertyConfiguration.getProperties("mso.bpmn.urn.properties"); + return props; + } + + private void isReadyforCorrelation(RuntimeService runtimeService, + String receivedRequestId, int retries, int sleepTime){ + ExecutionQuery waitingInstances = null; + long waitingInstancesCount = 0; + + //Workaround for performance testing, explicit wait for a second for the transactions to be committed + //Also check to make sure the process didn't timeout before trying to correlate + + do{ + waitingInstances = runtimeService.createExecutionQuery() // + .messageEventSubscriptionName("sdncAdapterCallbackRequest") + .processVariableValueEquals("SDNCA_requestId", receivedRequestId); + waitingInstancesCount = waitingInstances.count(); + retries--; + msoLogger.debug(logMarker + "waitingInstancesCount: " + waitingInstancesCount); + try { + Thread.sleep(sleepTime); + } catch (InterruptedException e) { + + msoLogger.error (MessageEnum.BPMN_SDNC_CALLBACK_EXCEPTION, "BPMN", MsoLogger.getServiceName(), + MsoLogger.ErrorCode.UnknownError, logMarker, e); + + } + }while (waitingInstancesCount==0 && retries > 0); + if(waitingInstancesCount > 0){ + msoLogger.debug(logMarker + "waitingInstancesCount before timeout check: " + waitingInstancesCount); + waitingInstancesCount = waitingInstances.processVariableValueEquals("asynchronousResponseTimeout", false).count(); + msoLogger.debug(logMarker + "waitingInstancesCount after timeout check: " + waitingInstancesCount); + if(waitingInstancesCount<=0){ + msoLogger.debug(logMarker + "detected timeout on flow to correlate"); + throw new IllegalStateException("process timed out"); + } + }else{ + //flow may have already ended, so can't check timeout variable. Throw exception? + msoLogger.debug(logMarker + "no flow to correlate to"); + throw new IllegalStateException("no flow to correlate to"); + } + } + + private ProcessEngineServices getProcessEngineServices() { + if (pes4junit == null) { + return BpmPlatform.getDefaultProcessEngine(); + } else { + return pes4junit; + } + } + + @WebMethod(exclude=true) + public void setProcessEngineServices4junit(ProcessEngineServices pes) { + pes4junit = pes; + } + + public class SDNCAdapterExceptionResponse extends SDNCAdapterResponse { + private Exception ex; + + public SDNCAdapterExceptionResponse(Exception ex) { + super(); + this.ex = ex; + } + + public Exception getException() { + return ex; + } + } +} diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/WorkflowAsyncCommonResource.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/WorkflowAsyncCommonResource.java index 5abd4e91da..c0ea0cf874 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/WorkflowAsyncCommonResource.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/WorkflowAsyncCommonResource.java @@ -1,36 +1,36 @@ -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - MSO - * ================================================================================ - * 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.openecomp.mso.bpmn.common.workflow.service; - -import org.camunda.bpm.engine.ProcessEngineServices; -import org.camunda.bpm.engine.ProcessEngines; - - -public class WorkflowAsyncCommonResource extends WorkflowAsyncResource { - - protected ProcessEngineServices getProcessEngineServices() { - if (pes4junit == null) { - return ProcessEngines.getProcessEngine("common"); - } else { - return pes4junit; - } - } -} +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.bpmn.common.workflow.service; + +import org.camunda.bpm.engine.ProcessEngineServices; +import org.camunda.bpm.engine.ProcessEngines; + + +public class WorkflowAsyncCommonResource extends WorkflowAsyncResource { + + protected ProcessEngineServices getProcessEngineServices() { + if (pes4junit == null) { + return ProcessEngines.getProcessEngine("common"); + } else { + return pes4junit; + } + } +} diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/WorkflowAsyncResource.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/WorkflowAsyncResource.java index 28541930ab..b13ac46784 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/WorkflowAsyncResource.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/WorkflowAsyncResource.java @@ -1,293 +1,293 @@ -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - MSO - * ================================================================================ - * 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.openecomp.mso.bpmn.common.workflow.service; - -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; - -import javax.ws.rs.Consumes; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.core.Response; - -import org.camunda.bpm.engine.ProcessEngineServices; -import org.camunda.bpm.engine.ProcessEngines; -import org.camunda.bpm.engine.RuntimeService; -import org.camunda.bpm.engine.runtime.ProcessInstance; -import org.camunda.bpm.engine.variable.impl.VariableMapImpl; -import org.jboss.resteasy.annotations.Suspend; -import org.jboss.resteasy.spi.AsynchronousResponse; -import org.openecomp.mso.logger.MessageEnum; -import org.openecomp.mso.logger.MsoLogger; -import org.slf4j.MDC; - -/** - * - * @version 1.0 - * Asynchronous Workflow processing using JAX RS RESTeasy implementation - * Both Synchronous and Asynchronous BPMN process can benefit from this implementation since the workflow gets executed in the background - * and the server thread is freed up, server scales better to process more incoming requests - * - * Usage: For synchronous process, when you are ready to send the response invoke the callback to write the response - * For asynchronous process - the activity may send a acknowledgement response and then proceed further on executing the process - */ -@Path("/async") +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.bpmn.common.workflow.service; + +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +import javax.ws.rs.Consumes; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.core.Response; + +import org.camunda.bpm.engine.ProcessEngineServices; +import org.camunda.bpm.engine.ProcessEngines; +import org.camunda.bpm.engine.RuntimeService; +import org.camunda.bpm.engine.runtime.ProcessInstance; +import org.camunda.bpm.engine.variable.impl.VariableMapImpl; +import org.jboss.resteasy.annotations.Suspend; +import org.jboss.resteasy.spi.AsynchronousResponse; +import org.openecomp.mso.logger.MessageEnum; +import org.openecomp.mso.logger.MsoLogger; +import org.slf4j.MDC; + +/** + * + * @version 1.0 + * Asynchronous Workflow processing using JAX RS RESTeasy implementation + * Both Synchronous and Asynchronous BPMN process can benefit from this implementation since the workflow gets executed in the background + * and the server thread is freed up, server scales better to process more incoming requests + * + * Usage: For synchronous process, when you are ready to send the response invoke the callback to write the response + * For asynchronous process - the activity may send a acknowledgement response and then proceed further on executing the process + */ +@Path("/async") public abstract class WorkflowAsyncResource { - - private WorkflowContextHolder contextHolder = WorkflowContextHolder.getInstance(); - protected ProcessEngineServices pes4junit = null; - - private MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL); - - private static final String logMarker = "[WRKFLOW-RESOURCE]"; - private static final int DEFAULT_WAIT_TIME = 30000; //default wait time - - /** - * Asynchronous JAX-RS method that starts a process instance. - * @param asyncResponse an object that will receive the asynchronous response - * @param processKey the process key - * @param variableMap input variables to the process - */ - @POST - @Path("/services/{processKey}") - @Produces("application/json") - @Consumes("application/json") - public void startProcessInstanceByKey(final @Suspend(180000) AsynchronousResponse asyncResponse, - @PathParam("processKey") String processKey, VariableMapImpl variableMap) { - - WorkflowResponse response = new WorkflowResponse(); - long startTime = System.currentTimeMillis(); - Map inputVariables = null; - WorkflowContext workflowContext = null; - - try { - inputVariables = getInputVariables(variableMap); - setLogContext(processKey, inputVariables); - - // This variable indicates that the flow was invoked asynchronously - inputVariables.put("isAsyncProcess", "true"); - - workflowContext = new WorkflowContext(processKey, getRequestId(inputVariables), - asyncResponse, getWaitTime(inputVariables)); - - msoLogger.debug("Adding the workflow context into holder: " - + workflowContext.getProcessKey() + ":" - + workflowContext.getRequestId() + ":" - + workflowContext.getTimeout()); - - contextHolder.put(workflowContext); - - ProcessThread processThread = new ProcessThread(processKey, inputVariables); - processThread.start(); - } catch (Exception e) { - setLogContext(processKey, inputVariables); - - if (workflowContext != null) { - contextHolder.remove(workflowContext); - } - - msoLogger.debug(logMarker + "Exception in startProcessInstance by key"); - response.setMessage("Fail" ); - response.setResponse("Error occurred while executing the process: " + e); - response.setMessageCode(500); - recordEvents(processKey, response, startTime); - - msoLogger.error (MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, logMarker - + response.getMessage() + " for processKey: " - + processKey + " with response: " + response.getResponse()); - - Response errorResponse = Response.serverError().entity(response).build(); - asyncResponse.setResponse(errorResponse); - } - } - - /** - * - * @version 1.0 - * - */ - class ProcessThread extends Thread { - private final String processKey; - private final Map inputVariables; - - public ProcessThread(String processKey, Map inputVariables) { - this.processKey = processKey; - this.inputVariables = inputVariables; - } - - public void run() { - - String processInstanceId = null; - long startTime = System.currentTimeMillis(); - - try { - setLogContext(processKey, inputVariables); - - // Note: this creates a random businessKey if it wasn't specified. - String businessKey = getBusinessKey(inputVariables); - - msoLogger.debug(logMarker + "***Received MSO startProcessInstanceByKey with processKey: " - + processKey + " and variables: " + inputVariables); - - msoLogger.recordAuditEvent(startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, logMarker - + "Call to MSO workflow/services in Camunda. Received MSO startProcessInstanceByKey with processKey:" - + processKey + " and variables: " + inputVariables); - - RuntimeService runtimeService = getProcessEngineServices().getRuntimeService(); - ProcessInstance processInstance = runtimeService.startProcessInstanceByKey( - processKey, businessKey, inputVariables); - processInstanceId = processInstance.getId(); - - msoLogger.debug(logMarker + "Process " + processKey + ":" + processInstanceId + " " + - (processInstance.isEnded() ? "ENDED" : "RUNNING")); - } catch (Exception e) { - - msoLogger.recordAuditEvent(startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.InternalError, - logMarker + "Error in starting the process: "+ e.getMessage()); - - WorkflowCallbackResponse callbackResponse = new WorkflowCallbackResponse(); - callbackResponse.setStatusCode(500); - callbackResponse.setMessage("Fail"); - callbackResponse.setResponse("Error occurred while executing the process: " + e); - - // TODO: is the processInstanceId used by the API handler? I don't think so. - // It may be null here. - WorkflowContextHolder.getInstance().processCallback( - processKey, processInstanceId, - getRequestId(inputVariables), - callbackResponse); - } - } - } - - - /** - * Callback resource which is invoked from BPMN to process to send the workflow response - * - * @param processKey - * @param processInstanceId - * @param requestId - * @param callbackResponse - * @return - */ - @POST - @Path("/services/callback/{processKey}/{processInstanceId}/{requestId}") - @Produces("application/json") - @Consumes("application/json") - public Response processWorkflowCallback( - @PathParam("processKey") String processKey, - @PathParam("processInstanceId") String processInstanceId, - @PathParam("requestId")String requestId, - WorkflowCallbackResponse callbackResponse) { - - msoLogger.debug(logMarker + "Process instance ID:" + processInstanceId + ":" + requestId + ":" + processKey + ":" + isProcessEnded(processInstanceId)); - msoLogger.debug(logMarker + "About to process the callback request:" + callbackResponse.getResponse() + ":" + callbackResponse.getMessage() + ":" + callbackResponse.getStatusCode()); - return contextHolder.processCallback(processKey, processInstanceId, requestId, callbackResponse); - } - - // Note: the business key is used to identify the process in unit tests - private String getBusinessKey(Map inputVariables) { - Object businessKey = inputVariables.get("mso-business-key"); - if (businessKey == null ) { - businessKey = UUID.randomUUID().toString(); - inputVariables.put("mso-business-key", businessKey); - } - return businessKey.toString(); - } - - private String getRequestId(Map inputVariables) { - Object requestId = inputVariables.get("mso-request-id"); - if (requestId == null ) { - requestId = UUID.randomUUID().toString(); - inputVariables.put("mso-request-id", requestId); - } - return requestId.toString(); - } - - private long getWaitTime(Map inputVariables) - { - String timeout = inputVariables.get("mso-service-request-timeout") == null - ? null : inputVariables.get("mso-service-request-timeout").toString(); - - if (timeout != null) { - try { - return Long.parseLong(timeout)*1000; - } catch (NumberFormatException nex) { - msoLogger.debug("Invalid input for mso-service-request-timeout"); - } - } - - return DEFAULT_WAIT_TIME; - } - - private void recordEvents(String processKey, WorkflowResponse response, - long startTime) { - - msoLogger.recordMetricEvent ( startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, - logMarker + response.getMessage() + " for processKey: " - + processKey + " with response: " + response.getResponse(), "BPMN", MDC.get(processKey), null); - - msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, - logMarker + response.getMessage() + "for processKey: " + processKey + " with response: " + response.getResponse()); - - } - - private void setLogContext(String processKey, - Map inputVariables) { - MsoLogger.setServiceName("MSO." + processKey); - if (inputVariables != null) { - MsoLogger.setLogContext(getKeyValueFromInputVariables(inputVariables,"mso-request-id"), getKeyValueFromInputVariables(inputVariables,"mso-service-instance-id")); - } - } - - private String getKeyValueFromInputVariables(Map inputVariables, String key) { - if (inputVariables == null) return ""; - Object requestId = inputVariables.get(key); - if (requestId != null) return requestId.toString(); - return "N/A"; - } - - private boolean isProcessEnded(String processInstanceId) { - ProcessEngineServices pes = getProcessEngineServices(); - return pes.getRuntimeService().createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult() == null ? true : false ; - } - - + + private WorkflowContextHolder contextHolder = WorkflowContextHolder.getInstance(); + protected ProcessEngineServices pes4junit = null; + + private MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL); + + private static final String logMarker = "[WRKFLOW-RESOURCE]"; + private static final int DEFAULT_WAIT_TIME = 30000; //default wait time + + /** + * Asynchronous JAX-RS method that starts a process instance. + * @param asyncResponse an object that will receive the asynchronous response + * @param processKey the process key + * @param variableMap input variables to the process + */ + @POST + @Path("/services/{processKey}") + @Produces("application/json") + @Consumes("application/json") + public void startProcessInstanceByKey(final @Suspend(180000) AsynchronousResponse asyncResponse, + @PathParam("processKey") String processKey, VariableMapImpl variableMap) { + + WorkflowResponse response = new WorkflowResponse(); + long startTime = System.currentTimeMillis(); + Map inputVariables = null; + WorkflowContext workflowContext = null; + + try { + inputVariables = getInputVariables(variableMap); + setLogContext(processKey, inputVariables); + + // This variable indicates that the flow was invoked asynchronously + inputVariables.put("isAsyncProcess", "true"); + + workflowContext = new WorkflowContext(processKey, getRequestId(inputVariables), + asyncResponse, getWaitTime(inputVariables)); + + msoLogger.debug("Adding the workflow context into holder: " + + workflowContext.getProcessKey() + ":" + + workflowContext.getRequestId() + ":" + + workflowContext.getTimeout()); + + contextHolder.put(workflowContext); + + ProcessThread processThread = new ProcessThread(processKey, inputVariables); + processThread.start(); + } catch (Exception e) { + setLogContext(processKey, inputVariables); + + if (workflowContext != null) { + contextHolder.remove(workflowContext); + } + + msoLogger.debug(logMarker + "Exception in startProcessInstance by key"); + response.setMessage("Fail" ); + response.setResponse("Error occurred while executing the process: " + e); + response.setMessageCode(500); + recordEvents(processKey, response, startTime); + + msoLogger.error (MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, logMarker + + response.getMessage() + " for processKey: " + + processKey + " with response: " + response.getResponse()); + + Response errorResponse = Response.serverError().entity(response).build(); + asyncResponse.setResponse(errorResponse); + } + } + + /** + * + * @version 1.0 + * + */ + class ProcessThread extends Thread { + private final String processKey; + private final Map inputVariables; + + public ProcessThread(String processKey, Map inputVariables) { + this.processKey = processKey; + this.inputVariables = inputVariables; + } + + public void run() { + + String processInstanceId = null; + long startTime = System.currentTimeMillis(); + + try { + setLogContext(processKey, inputVariables); + + // Note: this creates a random businessKey if it wasn't specified. + String businessKey = getBusinessKey(inputVariables); + + msoLogger.debug(logMarker + "***Received MSO startProcessInstanceByKey with processKey: " + + processKey + " and variables: " + inputVariables); + + msoLogger.recordAuditEvent(startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, logMarker + + "Call to MSO workflow/services in Camunda. Received MSO startProcessInstanceByKey with processKey:" + + processKey + " and variables: " + inputVariables); + + RuntimeService runtimeService = getProcessEngineServices().getRuntimeService(); + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey( + processKey, businessKey, inputVariables); + processInstanceId = processInstance.getId(); + + msoLogger.debug(logMarker + "Process " + processKey + ":" + processInstanceId + " " + + (processInstance.isEnded() ? "ENDED" : "RUNNING")); + } catch (Exception e) { + + msoLogger.recordAuditEvent(startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.InternalError, + logMarker + "Error in starting the process: "+ e.getMessage()); + + WorkflowCallbackResponse callbackResponse = new WorkflowCallbackResponse(); + callbackResponse.setStatusCode(500); + callbackResponse.setMessage("Fail"); + callbackResponse.setResponse("Error occurred while executing the process: " + e); + + // TODO: is the processInstanceId used by the API handler? I don't think so. + // It may be null here. + WorkflowContextHolder.getInstance().processCallback( + processKey, processInstanceId, + getRequestId(inputVariables), + callbackResponse); + } + } + } + + + /** + * Callback resource which is invoked from BPMN to process to send the workflow response + * + * @param processKey + * @param processInstanceId + * @param requestId + * @param callbackResponse + * @return + */ + @POST + @Path("/services/callback/{processKey}/{processInstanceId}/{requestId}") + @Produces("application/json") + @Consumes("application/json") + public Response processWorkflowCallback( + @PathParam("processKey") String processKey, + @PathParam("processInstanceId") String processInstanceId, + @PathParam("requestId")String requestId, + WorkflowCallbackResponse callbackResponse) { + + msoLogger.debug(logMarker + "Process instance ID:" + processInstanceId + ":" + requestId + ":" + processKey + ":" + isProcessEnded(processInstanceId)); + msoLogger.debug(logMarker + "About to process the callback request:" + callbackResponse.getResponse() + ":" + callbackResponse.getMessage() + ":" + callbackResponse.getStatusCode()); + return contextHolder.processCallback(processKey, processInstanceId, requestId, callbackResponse); + } + + // Note: the business key is used to identify the process in unit tests + private String getBusinessKey(Map inputVariables) { + Object businessKey = inputVariables.get("mso-business-key"); + if (businessKey == null ) { + businessKey = UUID.randomUUID().toString(); + inputVariables.put("mso-business-key", businessKey); + } + return businessKey.toString(); + } + + private String getRequestId(Map inputVariables) { + Object requestId = inputVariables.get("mso-request-id"); + if (requestId == null ) { + requestId = UUID.randomUUID().toString(); + inputVariables.put("mso-request-id", requestId); + } + return requestId.toString(); + } + + private long getWaitTime(Map inputVariables) + { + String timeout = inputVariables.get("mso-service-request-timeout") == null + ? null : inputVariables.get("mso-service-request-timeout").toString(); + + if (timeout != null) { + try { + return Long.parseLong(timeout)*1000; + } catch (NumberFormatException nex) { + msoLogger.debug("Invalid input for mso-service-request-timeout"); + } + } + + return DEFAULT_WAIT_TIME; + } + + private void recordEvents(String processKey, WorkflowResponse response, + long startTime) { + + msoLogger.recordMetricEvent ( startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, + logMarker + response.getMessage() + " for processKey: " + + processKey + " with response: " + response.getResponse(), "BPMN", MDC.get(processKey), null); + + msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, + logMarker + response.getMessage() + "for processKey: " + processKey + " with response: " + response.getResponse()); + + } + + private void setLogContext(String processKey, + Map inputVariables) { + MsoLogger.setServiceName("MSO." + processKey); + if (inputVariables != null) { + MsoLogger.setLogContext(getKeyValueFromInputVariables(inputVariables,"mso-request-id"), getKeyValueFromInputVariables(inputVariables,"mso-service-instance-id")); + } + } + + private String getKeyValueFromInputVariables(Map inputVariables, String key) { + if (inputVariables == null) return ""; + Object requestId = inputVariables.get(key); + if (requestId != null) return requestId.toString(); + return "N/A"; + } + + private boolean isProcessEnded(String processInstanceId) { + ProcessEngineServices pes = getProcessEngineServices(); + return pes.getRuntimeService().createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult() == null ? true : false ; + } + + protected abstract ProcessEngineServices getProcessEngineServices(); - - public void setProcessEngineServices4junit(ProcessEngineServices pes) { - pes4junit = pes; - } - - private Map getInputVariables(VariableMapImpl variableMap) { - Map inputVariables = new HashMap(); - @SuppressWarnings("unchecked") - Map vMap = (Map) variableMap.get("variables"); - for (String vName : vMap.keySet()) { - @SuppressWarnings("unchecked") - Map valueMap = (Map)vMap.get(vName); // value, type - inputVariables.put(vName, valueMap.get("value")); - } - return inputVariables; - } -} + + public void setProcessEngineServices4junit(ProcessEngineServices pes) { + pes4junit = pes; + } + + private Map getInputVariables(VariableMapImpl variableMap) { + Map inputVariables = new HashMap(); + @SuppressWarnings("unchecked") + Map vMap = (Map) variableMap.get("variables"); + for (String vName : vMap.keySet()) { + @SuppressWarnings("unchecked") + Map valueMap = (Map)vMap.get(vName); // value, type + inputVariables.put(vName, valueMap.get("value")); + } + return inputVariables; + } +} diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/WorkflowCallbackResponse.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/WorkflowCallbackResponse.java index b3e5ad1c58..945d64d81a 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/WorkflowCallbackResponse.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/WorkflowCallbackResponse.java @@ -1,52 +1,52 @@ -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - MSO - * ================================================================================ - * 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.openecomp.mso.bpmn.common.workflow.service; - -/** - * @version 1.0 - * Workflow Response bean to generate workflow response in JSON format - */ -public class WorkflowCallbackResponse { - - private String response; - private int statusCode; - private String message; - - public String getResponse() { - return response; - } - public void setResponse(String response) { - this.response = response; - } - public int getStatusCode() { - return statusCode; - } - public void setStatusCode(int statusCode) { - this.statusCode = statusCode; - } - public String getMessage() { - return message; - } - public void setMessage(String message) { - this.message = message; - } - -} +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.bpmn.common.workflow.service; + +/** + * @version 1.0 + * Workflow Response bean to generate workflow response in JSON format + */ +public class WorkflowCallbackResponse { + + private String response; + private int statusCode; + private String message; + + public String getResponse() { + return response; + } + public void setResponse(String response) { + this.response = response; + } + public int getStatusCode() { + return statusCode; + } + public void setStatusCode(int statusCode) { + this.statusCode = statusCode; + } + public String getMessage() { + return message; + } + public void setMessage(String message) { + this.message = message; + } + +} diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/WorkflowContext.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/WorkflowContext.java index 867226c02a..3d7e333fdf 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/WorkflowContext.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/WorkflowContext.java @@ -1,96 +1,96 @@ -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - MSO - * ================================================================================ - * 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.openecomp.mso.bpmn.common.workflow.service; - -import java.util.concurrent.Delayed; -import java.util.concurrent.TimeUnit; - -import org.jboss.resteasy.spi.AsynchronousResponse; - -/** - * @version 1.0 - * Workflow context object used to send timeout response, if workflow instance does not write the response in time - */ -public class WorkflowContext implements Delayed { - private final String processKey; - private final String requestId; - private final AsynchronousResponse asynchronousResponse; - private final long startTime; - private final long timeout; - - public WorkflowContext(String processKey, String requestId, - AsynchronousResponse asynchronousResponse, long timeout) { - this.processKey = processKey; - this.requestId = requestId; - this.asynchronousResponse = asynchronousResponse; - this.timeout = timeout; - this.startTime = System.currentTimeMillis(); - } - - public String getRequestId() { - return requestId; - } - - public String getProcessKey() { - return processKey; - } - - public AsynchronousResponse getAsynchronousResponse() { - return asynchronousResponse; - } - - public long getTimeout() { - return timeout; - } - - public long getStartTime() { - return startTime; - } - - /** - * Required implementation by Delay queue - * Returns the elapsed time for this context - */ - @Override - public long getDelay(TimeUnit unit) { - // 0 or negative means this object is considered to be expired - return unit.convert(startTime + timeout - System.currentTimeMillis(), unit); - } - - /** - * Required implementation by Delay queue - * Compares the object to determine whether the object can be marked as expired - */ - @Override - public int compareTo(Delayed object) { - WorkflowContext that = (WorkflowContext) object; - long thisEndTime = startTime + timeout; - long thatEndTime = that.startTime + that.timeout; - - if (thisEndTime < thatEndTime) { - return -1; - } else if (thisEndTime > thatEndTime) { - return 1; - } else { - return 0; - } - } -} +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.bpmn.common.workflow.service; + +import java.util.concurrent.Delayed; +import java.util.concurrent.TimeUnit; + +import org.jboss.resteasy.spi.AsynchronousResponse; + +/** + * @version 1.0 + * Workflow context object used to send timeout response, if workflow instance does not write the response in time + */ +public class WorkflowContext implements Delayed { + private final String processKey; + private final String requestId; + private final AsynchronousResponse asynchronousResponse; + private final long startTime; + private final long timeout; + + public WorkflowContext(String processKey, String requestId, + AsynchronousResponse asynchronousResponse, long timeout) { + this.processKey = processKey; + this.requestId = requestId; + this.asynchronousResponse = asynchronousResponse; + this.timeout = timeout; + this.startTime = System.currentTimeMillis(); + } + + public String getRequestId() { + return requestId; + } + + public String getProcessKey() { + return processKey; + } + + public AsynchronousResponse getAsynchronousResponse() { + return asynchronousResponse; + } + + public long getTimeout() { + return timeout; + } + + public long getStartTime() { + return startTime; + } + + /** + * Required implementation by Delay queue + * Returns the elapsed time for this context + */ + @Override + public long getDelay(TimeUnit unit) { + // 0 or negative means this object is considered to be expired + return unit.convert(startTime + timeout - System.currentTimeMillis(), unit); + } + + /** + * Required implementation by Delay queue + * Compares the object to determine whether the object can be marked as expired + */ + @Override + public int compareTo(Delayed object) { + WorkflowContext that = (WorkflowContext) object; + long thisEndTime = startTime + timeout; + long thatEndTime = that.startTime + that.timeout; + + if (thisEndTime < thatEndTime) { + return -1; + } else if (thisEndTime > thatEndTime) { + return 1; + } else { + return 0; + } + } +} diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/WorkflowContextHolder.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/WorkflowContextHolder.java index 1c48e7173a..ca3b1f1390 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/WorkflowContextHolder.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/WorkflowContextHolder.java @@ -1,188 +1,188 @@ -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - MSO - * ================================================================================ - * 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.openecomp.mso.bpmn.common.workflow.service; - -import java.util.concurrent.DelayQueue; -import java.util.concurrent.TimeUnit; - -import javax.ws.rs.core.Response; - -import org.jboss.resteasy.spi.AsynchronousResponse; -import org.slf4j.MDC; - -import org.openecomp.mso.logger.MessageEnum; -import org.openecomp.mso.logger.MsoLogger; - -/** - * Workflow Context Holder instance which can be accessed elsewhere either in groovy scripts or Java - * @version 1.0 - * - */ -public class WorkflowContextHolder { - - private static MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL); - private static final String logMarker = "[WORKFLOW-CONTEXT-HOLDER]"; - private static WorkflowContextHolder instance = null; - - /** - * Delay Queue which holds workflow context holder objects - */ - private final DelayQueue responseQueue = new DelayQueue(); - private final TimeoutThread timeoutThread = new TimeoutThread(); - - private WorkflowContextHolder() { - timeoutThread.start(); - } - - /** - * Singleton holder which eliminates hot lock - * Since the JVM synchronizes static method there is no synchronization needed for this method - * @return - */ - public static synchronized WorkflowContextHolder getInstance() { - if (instance == null) { - instance = new WorkflowContextHolder(); - } - return instance; - } - - public void put(WorkflowContext context) { - msoLogger.debug(logMarker + " Adding context to the queue: " - + context.getRequestId()); - responseQueue.put(context); - } - - public void remove(WorkflowContext context) { - msoLogger.debug(logMarker + " Removing context from the queue: " - + context.getRequestId()); - responseQueue.remove(context); - } - - public WorkflowContext getWorkflowContext(String requestId) { - // Note: DelayQueue interator is threadsafe - for (WorkflowContext context : responseQueue) { - if (requestId.equals(context.getRequestId())) { - msoLogger.debug("Found context for request id: " + requestId); - return context; - } - } - - msoLogger.debug("Unable to find context for request id: " + requestId); - return null; - } - - /** - * Builds the callback response object to respond to client - * @param processKey - * @param processInstanceId - * @param requestId - * @param callbackResponse - * @return - */ - public Response processCallback(String processKey, String processInstanceId, - String requestId, WorkflowCallbackResponse callbackResponse) { - WorkflowResponse workflowResponse = new WorkflowResponse(); - WorkflowContext workflowContext = getWorkflowContext(requestId); - - if (workflowContext == null) { - msoLogger.debug("Unable to correlate workflow context for request id: " + requestId - + ":processInstance Id:" + processInstanceId - + ":process key:" + processKey); - workflowResponse.setMessage("Fail"); - workflowResponse.setMessageCode(400); - workflowResponse.setResponse("Unable to correlate workflow context, bad request. Request Id: " + requestId); - return Response.serverError().entity(workflowResponse).build(); - } - - responseQueue.remove(workflowContext); - - msoLogger.debug("Using callback response for request id: " + requestId); - workflowResponse.setResponse(callbackResponse.getResponse()); - workflowResponse.setProcessInstanceID(processInstanceId); - workflowResponse.setMessageCode(callbackResponse.getStatusCode()); - workflowResponse.setMessage(callbackResponse.getMessage()); - sendWorkflowResponseToClient(processKey, workflowContext, workflowResponse); - return Response.ok().entity(workflowResponse).build(); - } - - /** - * Send the response to client asynchronously when invoked by the BPMN process - * @param processKey - * @param workflowContext - * @param workflowResponse - */ - private void sendWorkflowResponseToClient(String processKey, WorkflowContext workflowContext, - WorkflowResponse workflowResponse) { - msoLogger.debug(logMarker + "Sending the response for request id: " + workflowContext.getRequestId()); - recordEvents(processKey, workflowResponse, workflowContext.getStartTime()); - Response response = Response.status(workflowResponse.getMessageCode()).entity(workflowResponse).build(); - AsynchronousResponse asyncResp = workflowContext.getAsynchronousResponse(); - asyncResp.setResponse(response); - } - - /** - * Timeout thread which monitors the delay queue for expired context and send timeout response - * to client - * - * */ - private class TimeoutThread extends Thread { - public void run() { - while (!isInterrupted()) { - try { - WorkflowContext requestObject = responseQueue.take(); - msoLogger.debug("Time remaining for request id: " + requestObject.getRequestId() + ":" + requestObject.getDelay(TimeUnit.MILLISECONDS)); - msoLogger.debug("Preparing timeout response for " + requestObject.getProcessKey() + ":" + ":" + requestObject.getRequestId()); - WorkflowResponse response = new WorkflowResponse(); - response.setMessage("Fail"); - response.setResponse("Request timedout, request id:" + requestObject.getRequestId()); - //response.setProcessInstanceID(requestObject.getProcessInstance().getProcessInstanceId()); - recordEvents(requestObject.getProcessKey(), response, requestObject.getStartTime()); - response.setMessageCode(500); - Response result = Response.status(500).entity(response).build(); - requestObject.getAsynchronousResponse().setResponse(result); - msoLogger.debug("Sending timeout response for request id:" + requestObject.getRequestId() + ":response:" + response); - } catch (InterruptedException e) { - break; - } catch (Exception e) { - msoLogger.debug("WorkflowContextHolder timeout thread caught exception: " + e); - msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION, "BPMN", MsoLogger.getServiceName(), - MsoLogger.ErrorCode.UnknownError, "Error in WorkflowContextHolder timeout thread"); - - } - } - - msoLogger.debug("WorkflowContextHolder timeout thread interrupted, quitting"); - } - } - - private static void recordEvents(String processKey, WorkflowResponse response, - long startTime) { - - msoLogger.recordMetricEvent ( startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, - logMarker + response.getMessage() + " for processKey: " - + processKey + " with response: " + response.getResponse(), "BPMN", MDC.get(processKey), null); - - msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, logMarker - + response.getMessage() + " for processKey: " - + processKey + " with response: " + response.getResponse()); - - } -} +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.bpmn.common.workflow.service; + +import java.util.concurrent.DelayQueue; +import java.util.concurrent.TimeUnit; + +import javax.ws.rs.core.Response; + +import org.jboss.resteasy.spi.AsynchronousResponse; +import org.slf4j.MDC; + +import org.openecomp.mso.logger.MessageEnum; +import org.openecomp.mso.logger.MsoLogger; + +/** + * Workflow Context Holder instance which can be accessed elsewhere either in groovy scripts or Java + * @version 1.0 + * + */ +public class WorkflowContextHolder { + + private static MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL); + private static final String logMarker = "[WORKFLOW-CONTEXT-HOLDER]"; + private static WorkflowContextHolder instance = null; + + /** + * Delay Queue which holds workflow context holder objects + */ + private final DelayQueue responseQueue = new DelayQueue(); + private final TimeoutThread timeoutThread = new TimeoutThread(); + + private WorkflowContextHolder() { + timeoutThread.start(); + } + + /** + * Singleton holder which eliminates hot lock + * Since the JVM synchronizes static method there is no synchronization needed for this method + * @return + */ + public static synchronized WorkflowContextHolder getInstance() { + if (instance == null) { + instance = new WorkflowContextHolder(); + } + return instance; + } + + public void put(WorkflowContext context) { + msoLogger.debug(logMarker + " Adding context to the queue: " + + context.getRequestId()); + responseQueue.put(context); + } + + public void remove(WorkflowContext context) { + msoLogger.debug(logMarker + " Removing context from the queue: " + + context.getRequestId()); + responseQueue.remove(context); + } + + public WorkflowContext getWorkflowContext(String requestId) { + // Note: DelayQueue interator is threadsafe + for (WorkflowContext context : responseQueue) { + if (requestId.equals(context.getRequestId())) { + msoLogger.debug("Found context for request id: " + requestId); + return context; + } + } + + msoLogger.debug("Unable to find context for request id: " + requestId); + return null; + } + + /** + * Builds the callback response object to respond to client + * @param processKey + * @param processInstanceId + * @param requestId + * @param callbackResponse + * @return + */ + public Response processCallback(String processKey, String processInstanceId, + String requestId, WorkflowCallbackResponse callbackResponse) { + WorkflowResponse workflowResponse = new WorkflowResponse(); + WorkflowContext workflowContext = getWorkflowContext(requestId); + + if (workflowContext == null) { + msoLogger.debug("Unable to correlate workflow context for request id: " + requestId + + ":processInstance Id:" + processInstanceId + + ":process key:" + processKey); + workflowResponse.setMessage("Fail"); + workflowResponse.setMessageCode(400); + workflowResponse.setResponse("Unable to correlate workflow context, bad request. Request Id: " + requestId); + return Response.serverError().entity(workflowResponse).build(); + } + + responseQueue.remove(workflowContext); + + msoLogger.debug("Using callback response for request id: " + requestId); + workflowResponse.setResponse(callbackResponse.getResponse()); + workflowResponse.setProcessInstanceID(processInstanceId); + workflowResponse.setMessageCode(callbackResponse.getStatusCode()); + workflowResponse.setMessage(callbackResponse.getMessage()); + sendWorkflowResponseToClient(processKey, workflowContext, workflowResponse); + return Response.ok().entity(workflowResponse).build(); + } + + /** + * Send the response to client asynchronously when invoked by the BPMN process + * @param processKey + * @param workflowContext + * @param workflowResponse + */ + private void sendWorkflowResponseToClient(String processKey, WorkflowContext workflowContext, + WorkflowResponse workflowResponse) { + msoLogger.debug(logMarker + "Sending the response for request id: " + workflowContext.getRequestId()); + recordEvents(processKey, workflowResponse, workflowContext.getStartTime()); + Response response = Response.status(workflowResponse.getMessageCode()).entity(workflowResponse).build(); + AsynchronousResponse asyncResp = workflowContext.getAsynchronousResponse(); + asyncResp.setResponse(response); + } + + /** + * Timeout thread which monitors the delay queue for expired context and send timeout response + * to client + * + * */ + private class TimeoutThread extends Thread { + public void run() { + while (!isInterrupted()) { + try { + WorkflowContext requestObject = responseQueue.take(); + msoLogger.debug("Time remaining for request id: " + requestObject.getRequestId() + ":" + requestObject.getDelay(TimeUnit.MILLISECONDS)); + msoLogger.debug("Preparing timeout response for " + requestObject.getProcessKey() + ":" + ":" + requestObject.getRequestId()); + WorkflowResponse response = new WorkflowResponse(); + response.setMessage("Fail"); + response.setResponse("Request timedout, request id:" + requestObject.getRequestId()); + //response.setProcessInstanceID(requestObject.getProcessInstance().getProcessInstanceId()); + recordEvents(requestObject.getProcessKey(), response, requestObject.getStartTime()); + response.setMessageCode(500); + Response result = Response.status(500).entity(response).build(); + requestObject.getAsynchronousResponse().setResponse(result); + msoLogger.debug("Sending timeout response for request id:" + requestObject.getRequestId() + ":response:" + response); + } catch (InterruptedException e) { + break; + } catch (Exception e) { + msoLogger.debug("WorkflowContextHolder timeout thread caught exception: " + e); + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION, "BPMN", MsoLogger.getServiceName(), + MsoLogger.ErrorCode.UnknownError, "Error in WorkflowContextHolder timeout thread"); + + } + } + + msoLogger.debug("WorkflowContextHolder timeout thread interrupted, quitting"); + } + } + + private static void recordEvents(String processKey, WorkflowResponse response, + long startTime) { + + msoLogger.recordMetricEvent ( startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, + logMarker + response.getMessage() + " for processKey: " + + processKey + " with response: " + response.getResponse(), "BPMN", MDC.get(processKey), null); + + msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, logMarker + + response.getMessage() + " for processKey: " + + processKey + " with response: " + response.getResponse()); + + } +} diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/WorkflowMessageResource.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/WorkflowMessageResource.java index da9376ddc0..5afbded982 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/WorkflowMessageResource.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/WorkflowMessageResource.java @@ -1,141 +1,141 @@ -package org.openecomp.mso.bpmn.common.workflow.service; - -import java.util.HashMap; -import java.util.Map; - -import javax.ws.rs.Consumes; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - -import org.camunda.bpm.BpmPlatform; -import org.camunda.bpm.engine.ProcessEngineServices; -import org.camunda.bpm.engine.RuntimeService; - -import org.openecomp.mso.logger.MessageEnum; -import org.openecomp.mso.logger.MsoLogger; - -/** - * Generalized REST interface that injects a message event into a waiting BPMN process. - * Examples: - *
- *     /WorkflowMessage/SDNCAResponse/6d10d075-100c-42d0-9d84-a52432681cae-1478486185286
- *     /WorkflowMessage/SDNCAEvent/USOSTCDALTX0101UJZZ01
- * 
- */ -@Path("/") -public class WorkflowMessageResource { - private static final MsoLogger LOGGER = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL); - private static final String LOGMARKER = "[WORKFLOW-MESSAGE]"; - - private ProcessEngineServices pes4junit = null; - - @POST - @Path("/WorkflowMessage/{messageType}/{correlator}") - @Consumes("*/*") - @Produces(MediaType.TEXT_PLAIN) - public Response deliver(@PathParam("messageType") String messageType, - @PathParam("correlator") String correlator, String message) { - - LOGGER.debug(LOGMARKER + " Received workflow message" - + " type='" + messageType + "'" - + " correlator='" + correlator + "'" - + System.lineSeparator() + message); - - MsoLogger.setServiceName("MSO." + "WorkflowMessage"); - - if (messageType == null || messageType.isEmpty()) { - String msg = "Missing message type"; - LOGGER.debug(LOGMARKER + " " + msg); - LOGGER.error(MessageEnum.BPMN_GENERAL_EXCEPTION, "BPMN", MsoLogger.getServiceName(), - MsoLogger.ErrorCode.DataError, LOGMARKER + ":" + msg); - return Response.status(400).entity(msg).build(); - } - - if (correlator == null || correlator.isEmpty()) { - String msg = "Missing correlator"; - LOGGER.debug(LOGMARKER + " " + msg); - LOGGER.error(MessageEnum.BPMN_GENERAL_EXCEPTION, "BPMN", MsoLogger.getServiceName(), - MsoLogger.ErrorCode.DataError, LOGMARKER + ":" + msg); - return Response.status(400).entity(msg).build(); - } - - String correlatorVariable = messageType + "_CORRELATOR"; - String messageVariable = messageType + "_MESSAGE"; - - long startTime = System.currentTimeMillis(); - - try { - RuntimeService runtimeService = getProcessEngineServices().getRuntimeService(); - - if (!isReadyforCorrelation(runtimeService, correlatorVariable, correlator)) { - String msg = "No process is waiting to receive '" + messageType + "' WorkflowMessage with correlator '" + correlator + "'"; - LOGGER.debug(LOGMARKER + " " + msg); - LOGGER.error(MessageEnum.BPMN_GENERAL_EXCEPTION, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, LOGMARKER + ":" + msg); - LOGGER.recordMetricEvent(startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.BusinessProcesssError, msg, "BPMN", MsoLogger.getServiceName(), messageType); - LOGGER.recordAuditEvent(startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.BusinessProcesssError, msg); - return Response.status(500).entity(msg).build(); - } - - Map variables = new HashMap(); - variables.put(correlatorVariable, correlator); - variables.put(messageVariable, message); - - runtimeService.createMessageCorrelation("WorkflowMessage").setVariables(variables) - .processInstanceVariableEquals(correlatorVariable, correlator).correlate(); - - String msg = "Completed delivery of '" + messageType + "' WorkflowMessage with correlator '" + correlator + "'"; - LOGGER.debug(LOGMARKER + msg); - LOGGER.recordMetricEvent(startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, msg, "BPMN", MsoLogger.getServiceName(), messageType); - LOGGER.recordAuditEvent(startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, msg); - return Response.status(204).build(); - } catch (Exception e) { - // For example: MismatchingMessageCorrelationException - String msg = "Caught " + e.getClass().getSimpleName() + " processing '" + messageType + "' WorkflowMessage with " + correlatorVariable + "='" + correlator + "'"; - LOGGER.debug(LOGMARKER + " " + msg); - LOGGER.error(MessageEnum.BPMN_GENERAL_EXCEPTION, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, LOGMARKER + ":" + msg, e); - LOGGER.recordMetricEvent(startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.UnknownError, msg, "BPMN", MsoLogger.getServiceName(), messageType); - LOGGER.recordAuditEvent(startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.UnknownError, msg); - return Response.status(500).entity(msg).build(); - } - } - - private boolean isReadyforCorrelation(RuntimeService runtimeService, - String correlationVariable, String correlationValue) - throws InterruptedException { - - long waitingInstances = runtimeService.createExecutionQuery() - .messageEventSubscriptionName("WorkflowMessage") - .processVariableValueEquals(correlationVariable, correlationValue) - .count(); - - int retries = 50; - while (waitingInstances == 0 && retries > 0) { - Thread.sleep(100); - - waitingInstances = runtimeService.createExecutionQuery() - .messageEventSubscriptionName("WorkflowMessage") - .processVariableValueEquals(correlationVariable, correlationValue) - .count(); - - retries--; - } - - return waitingInstances != 0; - } - - private ProcessEngineServices getProcessEngineServices() { - if (pes4junit == null) { - return BpmPlatform.getDefaultProcessEngine(); - } else { - return pes4junit; - } - } - - public void setProcessEngineServices4junit(ProcessEngineServices pes) { - pes4junit = pes; - } +package org.openecomp.mso.bpmn.common.workflow.service; + +import java.util.HashMap; +import java.util.Map; + +import javax.ws.rs.Consumes; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + +import org.camunda.bpm.BpmPlatform; +import org.camunda.bpm.engine.ProcessEngineServices; +import org.camunda.bpm.engine.RuntimeService; + +import org.openecomp.mso.logger.MessageEnum; +import org.openecomp.mso.logger.MsoLogger; + +/** + * Generalized REST interface that injects a message event into a waiting BPMN process. + * Examples: + *
+ *     /WorkflowMessage/SDNCAResponse/6d10d075-100c-42d0-9d84-a52432681cae-1478486185286
+ *     /WorkflowMessage/SDNCAEvent/USOSTCDALTX0101UJZZ01
+ * 
+ */ +@Path("/") +public class WorkflowMessageResource { + private static final MsoLogger LOGGER = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL); + private static final String LOGMARKER = "[WORKFLOW-MESSAGE]"; + + private ProcessEngineServices pes4junit = null; + + @POST + @Path("/WorkflowMessage/{messageType}/{correlator}") + @Consumes("*/*") + @Produces(MediaType.TEXT_PLAIN) + public Response deliver(@PathParam("messageType") String messageType, + @PathParam("correlator") String correlator, String message) { + + LOGGER.debug(LOGMARKER + " Received workflow message" + + " type='" + messageType + "'" + + " correlator='" + correlator + "'" + + System.lineSeparator() + message); + + MsoLogger.setServiceName("MSO." + "WorkflowMessage"); + + if (messageType == null || messageType.isEmpty()) { + String msg = "Missing message type"; + LOGGER.debug(LOGMARKER + " " + msg); + LOGGER.error(MessageEnum.BPMN_GENERAL_EXCEPTION, "BPMN", MsoLogger.getServiceName(), + MsoLogger.ErrorCode.DataError, LOGMARKER + ":" + msg); + return Response.status(400).entity(msg).build(); + } + + if (correlator == null || correlator.isEmpty()) { + String msg = "Missing correlator"; + LOGGER.debug(LOGMARKER + " " + msg); + LOGGER.error(MessageEnum.BPMN_GENERAL_EXCEPTION, "BPMN", MsoLogger.getServiceName(), + MsoLogger.ErrorCode.DataError, LOGMARKER + ":" + msg); + return Response.status(400).entity(msg).build(); + } + + String correlatorVariable = messageType + "_CORRELATOR"; + String messageVariable = messageType + "_MESSAGE"; + + long startTime = System.currentTimeMillis(); + + try { + RuntimeService runtimeService = getProcessEngineServices().getRuntimeService(); + + if (!isReadyforCorrelation(runtimeService, correlatorVariable, correlator)) { + String msg = "No process is waiting to receive '" + messageType + "' WorkflowMessage with correlator '" + correlator + "'"; + LOGGER.debug(LOGMARKER + " " + msg); + LOGGER.error(MessageEnum.BPMN_GENERAL_EXCEPTION, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, LOGMARKER + ":" + msg); + LOGGER.recordMetricEvent(startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.BusinessProcesssError, msg, "BPMN", MsoLogger.getServiceName(), messageType); + LOGGER.recordAuditEvent(startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.BusinessProcesssError, msg); + return Response.status(500).entity(msg).build(); + } + + Map variables = new HashMap(); + variables.put(correlatorVariable, correlator); + variables.put(messageVariable, message); + + runtimeService.createMessageCorrelation("WorkflowMessage").setVariables(variables) + .processInstanceVariableEquals(correlatorVariable, correlator).correlate(); + + String msg = "Completed delivery of '" + messageType + "' WorkflowMessage with correlator '" + correlator + "'"; + LOGGER.debug(LOGMARKER + msg); + LOGGER.recordMetricEvent(startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, msg, "BPMN", MsoLogger.getServiceName(), messageType); + LOGGER.recordAuditEvent(startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, msg); + return Response.status(204).build(); + } catch (Exception e) { + // For example: MismatchingMessageCorrelationException + String msg = "Caught " + e.getClass().getSimpleName() + " processing '" + messageType + "' WorkflowMessage with " + correlatorVariable + "='" + correlator + "'"; + LOGGER.debug(LOGMARKER + " " + msg); + LOGGER.error(MessageEnum.BPMN_GENERAL_EXCEPTION, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, LOGMARKER + ":" + msg, e); + LOGGER.recordMetricEvent(startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.UnknownError, msg, "BPMN", MsoLogger.getServiceName(), messageType); + LOGGER.recordAuditEvent(startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.UnknownError, msg); + return Response.status(500).entity(msg).build(); + } + } + + private boolean isReadyforCorrelation(RuntimeService runtimeService, + String correlationVariable, String correlationValue) + throws InterruptedException { + + long waitingInstances = runtimeService.createExecutionQuery() + .messageEventSubscriptionName("WorkflowMessage") + .processVariableValueEquals(correlationVariable, correlationValue) + .count(); + + int retries = 50; + while (waitingInstances == 0 && retries > 0) { + Thread.sleep(100); + + waitingInstances = runtimeService.createExecutionQuery() + .messageEventSubscriptionName("WorkflowMessage") + .processVariableValueEquals(correlationVariable, correlationValue) + .count(); + + retries--; + } + + return waitingInstances != 0; + } + + private ProcessEngineServices getProcessEngineServices() { + if (pes4junit == null) { + return BpmPlatform.getDefaultProcessEngine(); + } else { + return pes4junit; + } + } + + public void setProcessEngineServices4junit(ProcessEngineServices pes) { + pes4junit = pes; + } } \ No newline at end of file diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/WorkflowResource.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/WorkflowResource.java index d15bc31625..a9a9f4b12d 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/WorkflowResource.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/WorkflowResource.java @@ -1,609 +1,625 @@ -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - MSO - * ================================================================================ - * 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.openecomp.mso.bpmn.common.workflow.service; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.UUID; -import java.util.concurrent.atomic.AtomicLong; - -import javax.ws.rs.Consumes; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.UriInfo; - -import org.camunda.bpm.engine.HistoryService; -import org.camunda.bpm.engine.ProcessEngineException; -import org.camunda.bpm.engine.ProcessEngineServices; -import org.camunda.bpm.engine.ProcessEngines; -import org.camunda.bpm.engine.RuntimeService; -import org.camunda.bpm.engine.history.HistoricVariableInstance; -import org.camunda.bpm.engine.runtime.ProcessInstance; -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.VariableMapImpl; -import org.openecomp.mso.bpmn.core.WorkflowException; -import org.openecomp.mso.logger.MessageEnum; -import org.openecomp.mso.logger.MsoLogger; -import org.slf4j.MDC; - -@Path("/workflow") -public class WorkflowResource { - - private ProcessEngineServices pes4junit = null; - - private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL); - private static final String LOGMARKER = "[WRKFLOW-RESOURCE]"; - - private static final int DEFAULT_WAIT_TIME = 30000; - - @Context - private UriInfo uriInfo = null; - - /** - * Starts the process instance and responds to client synchronously - * If the request does not contain mso-service-request-timeout then it waits for the value specified in DEFAULT_WAIT_TIME - * Note: value specified in mso-service-request-timeout is in seconds - * During polling time, if there is an exception encountered in the process execution then polling is stopped and the error response is - * returned to the client - * @param processKey - * @param variableMap - * @return - */ - @POST - @Path("/services/{processKey}") - @Produces("application/json") - @Consumes("application/json") - public Response startProcessInstanceByKey(@PathParam("processKey") String processKey, - VariableMapImpl variableMap) { - - Map inputVariables = getInputVariables(variableMap); - setLogContext(processKey, inputVariables); - - WorkflowResponse workflowResponse = new WorkflowResponse(); - long startTime = System.currentTimeMillis(); - ProcessInstance processInstance = null; - - try { - //Kickoff the process - ProcessThread thread = new ProcessThread(inputVariables,processKey,msoLogger); - thread.start(); - - Map responseMap = null; - - //wait for process to be completed - long waitTime = getWaitTime(inputVariables); - long now = System.currentTimeMillis(); - long start = now; - long endTime = start + waitTime; - long pollingInterval = 500; - - // TEMPORARY LOGIC FOR UNIT TEST REFACTORING - // If this is a unit test (method is invoked directly), wait a max - // of 5 seconds after process ended for a result. In production, - // wait up to 60 seconds. - long timeToWaitAfterProcessEnded = uriInfo == null ? 5000 : 60000; - AtomicLong timeProcessEnded = new AtomicLong(0); - boolean endedWithNoResponse = false; - - while (now <= endTime) { - Thread.sleep(pollingInterval); - - now = System.currentTimeMillis(); - - // Increase the polling interval over time - - long elapsed = now - start; - - if (elapsed > 60000) { - pollingInterval = 5000; - } else if (elapsed > 10000) { - pollingInterval = 1000; - } - Exception exception = thread.getException(); - if (exception != null) { - throw new Exception(exception); - } - - processInstance = thread.getProcessInstance(); - - if (processInstance == null) { - msoLogger.debug(LOGMARKER + processKey + " process has not been created yet"); - continue; - } - - String processInstanceId = processInstance.getId(); - workflowResponse.setProcessInstanceID(processInstanceId); - - responseMap = getResponseMap(processInstance, processKey, timeProcessEnded); - - if (responseMap == null) { - msoLogger.debug(LOGMARKER + processKey + " has not produced a response yet"); - - if (timeProcessEnded.longValue() != 0) { - long elapsedSinceEnded = System.currentTimeMillis() - timeProcessEnded.longValue(); - - if (elapsedSinceEnded > timeToWaitAfterProcessEnded) { - endedWithNoResponse = true; - break; - } - } - } else { - processResponseMap(workflowResponse, responseMap); - recordEvents(processKey, workflowResponse, startTime); - return Response.status(workflowResponse.getMessageCode()).entity(workflowResponse).build(); - } - } - - //if we dont get response after waiting then send timeout response - - String state; - String processInstanceId; - - if (processInstance == null) { - processInstanceId = "N/A"; - state = "NOT STARTED"; - } else { - processInstanceId = processInstance.getProcessInstanceId(); - state = isProcessEnded(processInstanceId) ? "ENDED" : "NOT ENDED"; - } - - workflowResponse.setMessage("Fail"); - if (endedWithNoResponse) { - workflowResponse.setResponse("Process ended without producing a response"); - } else { - workflowResponse.setResponse("Request timed out, process state: " + state); - } - workflowResponse.setProcessInstanceID(processInstanceId); - recordEvents(processKey, workflowResponse, startTime); - workflowResponse.setMessageCode(500); - return Response.status(500).entity(workflowResponse).build(); - } catch (Exception ex) { - msoLogger.debug(LOGMARKER + "Exception in startProcessInstance by key"); - ex.printStackTrace(); - workflowResponse.setMessage("Fail" ); - workflowResponse.setResponse("Error occurred while executing the process: " + ex.getMessage()); - if (processInstance != null) workflowResponse.setProcessInstanceID(processInstance.getId()); - - msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "BPMN", MDC.get(processKey), - MsoLogger.ErrorCode.UnknownError, LOGMARKER + workflowResponse.getMessage() - + " for processKey: " + processKey + " with response: " + workflowResponse.getResponse()); - - workflowResponse.setMessageCode(500); - recordEvents(processKey, workflowResponse, startTime); - return Response.status(500).entity(workflowResponse).build(); - } - } - - /** - * Returns the wait time, this is used by the resource on how long it should wait to send a response - * If none specified DEFAULT_WAIT_TIME is used - * @param inputVariables - * @return - */ - private int getWaitTime(Map inputVariables) - { - String timeout = inputVariables.get("mso-service-request-timeout") == null - ? null : inputVariables.get("mso-service-request-timeout").toString(); - - if (timeout != null) { - try { - return Integer.parseInt(timeout)*1000; - } catch (NumberFormatException nex) { - msoLogger.debug("Invalid input for mso-service-request-timeout"); - } - } - return DEFAULT_WAIT_TIME; - } - - private void recordEvents(String processKey, WorkflowResponse response, long startTime) { - - msoLogger.recordMetricEvent ( startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, - LOGMARKER + response.getMessage() + " for processKey: " - + processKey + " with response: " + response.getResponse(), "BPMN", MDC.get(processKey), null); - - msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, - LOGMARKER + response.getMessage() + " for processKey: " - + processKey + " with response: " + response.getResponse()); - } - - private void setLogContext(String processKey, Map inputVariables) { - MsoLogger.setServiceName("MSO." + processKey); - if (inputVariables != null) { - MsoLogger.setLogContext(getValueFromInputVariables(inputVariables, "mso-request-id"), - getValueFromInputVariables(inputVariables, "mso-service-instance-id")); - } - } - - private String getValueFromInputVariables(Map inputVariables, String key) { - Object value = inputVariables.get(key); - if (value == null) { - return "N/A"; - } else { - return value.toString(); - } - } - - /** - * Checks to see if the specified process is ended. - * @param processInstanceId the process instance ID - * @return true if the process is ended - */ - private boolean isProcessEnded(String processInstanceId) { - ProcessEngineServices pes = getProcessEngineServices(); - return pes.getRuntimeService().createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult() == null ? true : false ; - } - - private void processResponseMap(WorkflowResponse workflowResponse, Map responseMap) { - Object object = responseMap.get("Response"); - String response = object == null ? null : String.valueOf(object); - if(response == null){ - object = responseMap.get("WorkflowResponse"); - response = object == null ? null : String.valueOf(object); - } - - workflowResponse.setResponse(response); - - object = responseMap.get("ResponseCode"); - String responseCode = object == null ? null : String.valueOf(object); - - try { - workflowResponse.setMessageCode(Integer.parseInt(responseCode)); - } catch(NumberFormatException nex) { - msoLogger.debug(LOGMARKER + "Failed to parse ResponseCode: " + responseCode); - workflowResponse.setMessageCode(-1); - } - - Object status = responseMap.get("Status"); - - if ("Success".equalsIgnoreCase(String.valueOf(status))) { - workflowResponse.setMessage("Success"); - } else if ("Fail".equalsIgnoreCase(String.valueOf(status))) { - workflowResponse.setMessage("Fail"); - } else { - msoLogger.debug(LOGMARKER + "Unrecognized Status: " + responseCode); - workflowResponse.setMessage("Fail"); - } - } - - /** - * @version 1.0 - * Triggers the workflow in a separate thread - */ - private class ProcessThread extends Thread { - private final Map inputVariables; - private final String processKey; - private final MsoLogger msoLogger; - private final String businessKey; - private ProcessInstance processInstance = null; - private Exception exception = null; - - public ProcessThread(Map inputVariables, String processKey, MsoLogger msoLogger) { - this.inputVariables = inputVariables; - this.processKey = processKey; - this.msoLogger = msoLogger; - this.businessKey = UUID.randomUUID().toString(); - } - - /** - * If an exception occurs when starting the process instance, it may - * be obtained by calling this method. Note that exceptions are only - * recorded while the process is executing in its original thread. - * Once a process is suspended, exception recording stops. - * @return the exception, or null if none has occurred - */ - public Exception getException() { - return exception; - } - - - public ProcessInstance getProcessInstance() { - return this.processInstance; - } - - /** - * Sets the process instance exception. - * @param exception the exception - */ - private void setException(Exception exception) { - this.exception = exception; - } - - public void run() { - setLogContext(processKey, inputVariables); - - long startTime = System.currentTimeMillis(); - - try { - msoLogger.debug(LOGMARKER + "***Received MSO startProcessInstanceByKey with processKey:" - + processKey + " and variables: " + inputVariables); - - msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, LOGMARKER - + "Call to MSO workflow/services in Camunda. Received MSO startProcessInstanceByKey with" - + " processKey:" + processKey - + " businessKey:" + businessKey - + " variables: " + inputVariables); - - RuntimeService runtimeService = getProcessEngineServices().getRuntimeService(); - - // Note that this method doesn't return until the process suspends - // itself or finishes. We provide a business key so we can identify - // the process instance immediately. - processInstance = runtimeService.startProcessInstanceByKey( - processKey, inputVariables); - - } catch (Exception e) { - msoLogger.debug(LOGMARKER + "ProcessThread caught an exception executing " - + processKey + ": " + e); - setException(e); - } - } - - } - - private Map getInputVariables(VariableMapImpl variableMap) { - VariableMap inputVariables = Variables.createVariables(); - @SuppressWarnings("unchecked") - Map vMap = (Map) variableMap.get("variables"); - for (String key : vMap.keySet()) { //variabe name vn - @SuppressWarnings("unchecked") - Map valueMap = (Map)vMap.get(key); //value, type - inputVariables.putValueTyped(key, Variables - .objectValue(valueMap.get("value")) - .serializationDataFormat(SerializationDataFormats.JAVA) // tells the engine to use java serialization for persisting the value - .create()); - } - return inputVariables; - } - - /** - * Attempts to get a response map from the specified process instance. - * @return the response map, or null if it is unavailable - */ - private Map getResponseMap(ProcessInstance processInstance, - String processKey, AtomicLong timeProcessEnded) { - - String responseMapVariable = processKey + "ResponseMap"; - String processInstanceId = processInstance.getId(); - - // Query the runtime service to see if a response map is ready. - -/* RuntimeService runtimeService = getProcessEngineServices().getRuntimeService(); - List executions = runtimeService.createExecutionQuery() - .processInstanceId(processInstanceId).list(); - - for (Execution execution : executions) { - @SuppressWarnings("unchecked") - Map responseMap = (Map) - getVariableFromExecution(runtimeService, execution.getId(), - responseMapVariable); - - if (responseMap != null) { - msoLogger.debug(LOGMARKER + "Obtained " + responseMapVariable - + " from process " + processInstanceId + " execution " - + execution.getId()); - return responseMap; - } - } -*/ - //Querying history seem to return consistent results compared to querying the runtime service - - boolean alreadyEnded = timeProcessEnded.longValue() != 0; - - if (alreadyEnded || isProcessEnded(processInstance.getId())) { - if (!alreadyEnded) { - timeProcessEnded.set(System.currentTimeMillis()); - } - - // Query the history service to see if a response map exists. - - HistoryService historyService = getProcessEngineServices().getHistoryService(); - @SuppressWarnings("unchecked") - Map responseMap = (Map) - getVariableFromHistory(historyService, processInstance.getId(), - responseMapVariable); - - if (responseMap != null) { - msoLogger.debug(LOGMARKER + "Obtained " + responseMapVariable - + " from process " + processInstanceId + " history"); - return responseMap; - } - - // Query the history service for old-style response variables. - - String prefix = (String) getVariableFromHistory(historyService, processInstanceId, "prefix"); - - if (prefix != null) { - - // Check for 'WorkflowResponse' variable - Object workflowResponseObject = getVariableFromHistory(historyService, processInstanceId, "WorkflowResponse"); - String workflowResponse = workflowResponseObject == null ? null : String.valueOf(workflowResponseObject); - msoLogger.debug(LOGMARKER + "WorkflowResponse: " + workflowResponse); - - if (workflowResponse != null) { - Object responseCodeObject = getVariableFromHistory(historyService, processInstanceId, prefix + "ResponseCode"); - String responseCode = responseCodeObject == null ? null : String.valueOf(responseCodeObject); - msoLogger.debug(LOGMARKER + prefix + "ResponseCode: " + responseCode); - responseMap = new HashMap(); - responseMap.put("WorkflowResponse", workflowResponse); - responseMap.put("ResponseCode", responseCode); - responseMap.put("Status", "Success"); - return responseMap; - } - - - // Check for 'WorkflowException' variable - WorkflowException workflowException = null; - String workflowExceptionText = null; - - Object workflowExceptionObject = getVariableFromHistory(historyService, processInstanceId, "WorkflowException"); - if(workflowExceptionObject != null) { - if(workflowExceptionObject instanceof WorkflowException) { - workflowException = (WorkflowException) workflowExceptionObject; - workflowExceptionText = workflowException.toString(); - responseMap = new HashMap(); - responseMap.put("WorkflowException", workflowExceptionText); - responseMap.put("ResponseCode", workflowException.getErrorCode()); - responseMap.put("Status", "Fail"); - return responseMap; - } - else if (workflowExceptionObject instanceof String) { - Object object = getVariableFromHistory(historyService, processInstanceId, prefix + "ResponseCode"); - String responseCode = object == null ? null : String.valueOf(object); - workflowExceptionText = (String) workflowExceptionObject; - responseMap = new HashMap(); - responseMap.put("WorkflowException", workflowExceptionText); - responseMap.put("ResponseCode", responseCode); - responseMap.put("Status", "Fail"); - return responseMap; - } - - } - msoLogger.debug(LOGMARKER + "WorkflowException: " + workflowExceptionText); - - // BEGIN LEGACY SUPPORT. TODO: REMOVE THIS CODE - Object object = getVariableFromHistory(historyService, processInstanceId, processKey + "Response"); - String response = object == null ? null : String.valueOf(object); - msoLogger.debug(LOGMARKER + processKey + "Response: " + response); - - if (response != null) { - object = getVariableFromHistory(historyService, processInstanceId, prefix + "ResponseCode"); - String responseCode = object == null ? null : String.valueOf(object); - msoLogger.debug(LOGMARKER + prefix + "ResponseCode: " + responseCode); - responseMap = new HashMap(); - responseMap.put("Response", response); - responseMap.put("ResponseCode", responseCode); - responseMap.put("Status", "Success"); - return responseMap; - } - - object = getVariableFromHistory(historyService, processInstanceId, prefix + "ErrorResponse"); - String errorResponse = object == null ? null : String.valueOf(object); - msoLogger.debug(LOGMARKER + prefix + "ErrorResponse: " + errorResponse); - - if (errorResponse != null) { - object = getVariableFromHistory(historyService, processInstanceId, prefix + "ResponseCode"); - String responseCode = object == null ? null : String.valueOf(object); - msoLogger.debug(LOGMARKER + prefix + "ResponseCode: " + responseCode); - responseMap = new HashMap(); - responseMap.put("Response", errorResponse); - responseMap.put("ResponseCode", responseCode); - responseMap.put("Status", "Fail"); - return responseMap; - } - // END LEGACY SUPPORT. TODO: REMOVE THIS CODE - } - } - return null; - } - - /** - * Gets a variable value from specified historical process instance. - * @return the variable value, or null if the variable could not be - * obtained - */ - private Object getVariableFromHistory(HistoryService historyService, - String processInstanceId, String variableName) { - try { - HistoricVariableInstance v = historyService.createHistoricVariableInstanceQuery() - .processInstanceId(processInstanceId).variableName(variableName).singleResult(); - return v == null ? null : v.getValue(); - } catch (Exception e) { - msoLogger.debug("Error retrieving process " + processInstanceId - + " variable " + variableName + " from history: " + e); - return null; - } - } - - @POST - @Path("/services/{processKey}/{processInstanceId}") - @Produces("application/json") - @Consumes("application/json") - public WorkflowResponse getProcessVariables(@PathParam("processKey") String processKey, @PathParam("processInstanceId") String processInstanceId) { - //TODO filter only set of variables - WorkflowResponse response = new WorkflowResponse(); - - long startTime = System.currentTimeMillis(); - try { - ProcessEngineServices engine = getProcessEngineServices(); - List variables = engine.getHistoryService().createHistoricVariableInstanceQuery().processInstanceId(processInstanceId).list(); - Map variablesMap = new HashMap(); - for (HistoricVariableInstance variableInstance: variables) { - variablesMap.put(variableInstance.getName(), variableInstance.getValue().toString()); - } - - msoLogger.debug(LOGMARKER + "***Received MSO getProcessVariables with processKey:" + processKey + " and variables: " + variablesMap.toString()); - - msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, LOGMARKER - + "Call to MSO workflow/services in Camunda. Received MSO getProcessVariables with processKey:" - + processKey + " and variables: " - + variablesMap.toString()); - - - response.setVariables(variablesMap); - response.setMessage("Success"); - response.setResponse("Successfully retrieved the variables"); - response.setProcessInstanceID(processInstanceId); - - msoLogger.debug(LOGMARKER + response.getMessage() + " for processKey: " + processKey + " with response: " + response.getResponse()); - } catch (Exception ex) { - response.setMessage("Fail"); - response.setResponse("Failed to retrieve the variables," + ex.getMessage()); - response.setProcessInstanceID(processInstanceId); - - msoLogger.error (MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "BPMN", MDC.get(processKey), MsoLogger.ErrorCode.UnknownError, LOGMARKER - + response.getMessage() - + " for processKey: " - + processKey - + " with response: " - + response.getResponse()); - - } - - msoLogger.recordMetricEvent ( startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, - LOGMARKER + response.getMessage() + " for processKey: " - + processKey + " with response: " + response.getResponse(), "BPMN", MDC.get(processKey), null); - - msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, - LOGMARKER + response.getMessage() + " for processKey: " - + processKey + " with response: " + response.getResponse()); - - return response; - } - - private ProcessEngineServices getProcessEngineServices() { - if (pes4junit == null) { - return ProcessEngines.getDefaultProcessEngine(); - } else { - return pes4junit; - } - } - - public void setProcessEngineServices4junit(ProcessEngineServices pes) { - pes4junit = pes; - } -} +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.bpmn.common.workflow.service; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicLong; + +import javax.ws.rs.Consumes; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.UriInfo; + +import org.camunda.bpm.engine.HistoryService; +import org.camunda.bpm.engine.ProcessEngineException; +import org.camunda.bpm.engine.ProcessEngineServices; +import org.camunda.bpm.engine.ProcessEngines; +import org.camunda.bpm.engine.RuntimeService; +import org.camunda.bpm.engine.history.HistoricVariableInstance; +import org.camunda.bpm.engine.runtime.ProcessInstance; +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.VariableMapImpl; +import org.openecomp.mso.bpmn.core.WorkflowException; +import org.openecomp.mso.logger.MessageEnum; +import org.openecomp.mso.logger.MsoLogger; +import org.slf4j.MDC; + +@Path("/workflow") +public class WorkflowResource { + + private ProcessEngineServices pes4junit = null; + + private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL); + private static final String LOGMARKER = "[WRKFLOW-RESOURCE]"; + + private static final int DEFAULT_WAIT_TIME = 30000; + + @Context + private UriInfo uriInfo = null; + + /** + * Starts the process instance and responds to client synchronously + * If the request does not contain mso-service-request-timeout then it waits for the value specified in DEFAULT_WAIT_TIME + * Note: value specified in mso-service-request-timeout is in seconds + * During polling time, if there is an exception encountered in the process execution then polling is stopped and the error response is + * returned to the client + * @param processKey + * @param variableMap + * @return + */ + @POST + @Path("/services/{processKey}") + @Produces("application/json") + @Consumes("application/json") + public Response startProcessInstanceByKey(@PathParam("processKey") String processKey, + VariableMapImpl variableMap) { + + Map inputVariables = getInputVariables(variableMap); + setLogContext(processKey, inputVariables); + + WorkflowResponse workflowResponse = new WorkflowResponse(); + long startTime = System.currentTimeMillis(); + ProcessInstance processInstance = null; + + try { + //Kickoff the process + ProcessThread thread = new ProcessThread(inputVariables,processKey,msoLogger); + thread.start(); + + Map responseMap = null; + + //wait for process to be completed + long waitTime = getWaitTime(inputVariables); + long now = System.currentTimeMillis(); + long start = now; + long endTime = start + waitTime; + long pollingInterval = 500; + + // TEMPORARY LOGIC FOR UNIT TEST REFACTORING + // If this is a unit test (method is invoked directly), wait a max + // of 5 seconds after process ended for a result. In production, + // wait up to 60 seconds. + long timeToWaitAfterProcessEnded = uriInfo == null ? 5000 : 60000; + AtomicLong timeProcessEnded = new AtomicLong(0); + boolean endedWithNoResponse = false; + + while (now <= endTime) { + Thread.sleep(pollingInterval); + + now = System.currentTimeMillis(); + + // Increase the polling interval over time + + long elapsed = now - start; + + if (elapsed > 60000) { + pollingInterval = 5000; + } else if (elapsed > 10000) { + pollingInterval = 1000; + } + Exception exception = thread.getException(); + if (exception != null) { + throw new Exception(exception); + } + + processInstance = thread.getProcessInstance(); + + if (processInstance == null) { + msoLogger.debug(LOGMARKER + processKey + " process has not been created yet"); + continue; + } + + String processInstanceId = processInstance.getId(); + workflowResponse.setProcessInstanceID(processInstanceId); + + responseMap = getResponseMap(processInstance, processKey, timeProcessEnded); + + if (responseMap == null) { + msoLogger.debug(LOGMARKER + processKey + " has not produced a response yet"); + + if (timeProcessEnded.longValue() != 0) { + long elapsedSinceEnded = System.currentTimeMillis() - timeProcessEnded.longValue(); + + if (elapsedSinceEnded > timeToWaitAfterProcessEnded) { + endedWithNoResponse = true; + break; + } + } + } else { + processResponseMap(workflowResponse, responseMap); + recordEvents(processKey, workflowResponse, startTime); + return Response.status(workflowResponse.getMessageCode()).entity(workflowResponse).build(); + } + } + + //if we dont get response after waiting then send timeout response + + String state; + String processInstanceId; + + if (processInstance == null) { + processInstanceId = "N/A"; + state = "NOT STARTED"; + } else { + processInstanceId = processInstance.getProcessInstanceId(); + state = isProcessEnded(processInstanceId) ? "ENDED" : "NOT ENDED"; + } + + workflowResponse.setMessage("Fail"); + if (endedWithNoResponse) { + workflowResponse.setResponse("Process ended without producing a response"); + } else { + workflowResponse.setResponse("Request timed out, process state: " + state); + } + workflowResponse.setProcessInstanceID(processInstanceId); + recordEvents(processKey, workflowResponse, startTime); + workflowResponse.setMessageCode(500); + return Response.status(500).entity(workflowResponse).build(); + } catch (Exception ex) { + msoLogger.debug(LOGMARKER + "Exception in startProcessInstance by key"); + ex.printStackTrace(); + workflowResponse.setMessage("Fail" ); + workflowResponse.setResponse("Error occurred while executing the process: " + ex.getMessage()); + if (processInstance != null) workflowResponse.setProcessInstanceID(processInstance.getId()); + + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "BPMN", MDC.get(processKey), + MsoLogger.ErrorCode.UnknownError, LOGMARKER + workflowResponse.getMessage() + + " for processKey: " + processKey + " with response: " + workflowResponse.getResponse()); + + workflowResponse.setMessageCode(500); + recordEvents(processKey, workflowResponse, startTime); + return Response.status(500).entity(workflowResponse).build(); + } + } + + /** + * Returns the wait time, this is used by the resource on how long it should wait to send a response + * If none specified DEFAULT_WAIT_TIME is used + * @param inputVariables + * @return + */ + private int getWaitTime(Map inputVariables) + { + String timeout = inputVariables.get("mso-service-request-timeout") == null + ? null : inputVariables.get("mso-service-request-timeout").toString(); + + if (timeout != null) { + try { + return Integer.parseInt(timeout)*1000; + } catch (NumberFormatException nex) { + msoLogger.debug("Invalid input for mso-service-request-timeout"); + } + } + return DEFAULT_WAIT_TIME; + } + + private void recordEvents(String processKey, WorkflowResponse response, long startTime) { + + msoLogger.recordMetricEvent ( startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, + LOGMARKER + response.getMessage() + " for processKey: " + + processKey + " with response: " + response.getResponse(), "BPMN", MDC.get(processKey), null); + + msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, + LOGMARKER + response.getMessage() + " for processKey: " + + processKey + " with response: " + response.getResponse()); + } + + private void setLogContext(String processKey, Map inputVariables) { + MsoLogger.setServiceName("MSO." + processKey); + if (inputVariables != null) { + MsoLogger.setLogContext(getValueFromInputVariables(inputVariables, "mso-request-id"), + getValueFromInputVariables(inputVariables, "mso-service-instance-id")); + } + } + + private String getValueFromInputVariables(Map inputVariables, String key) { + Object value = inputVariables.get(key); + if (value == null) { + return "N/A"; + } else { + return value.toString(); + } + } + + /** + * Checks to see if the specified process is ended. + * @param processInstanceId the process instance ID + * @return true if the process is ended + */ + private boolean isProcessEnded(String processInstanceId) { + ProcessEngineServices pes = getProcessEngineServices(); + return pes.getRuntimeService().createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult() == null ? true : false ; + } + + private void processResponseMap(WorkflowResponse workflowResponse, Map responseMap) { + Object object = responseMap.get("Response"); + String response = object == null ? null : String.valueOf(object); + if(response == null){ + object = responseMap.get("WorkflowResponse"); + response = object == null ? null : String.valueOf(object); + } + + workflowResponse.setResponse(response); + + object = responseMap.get("ResponseCode"); + String responseCode = object == null ? null : String.valueOf(object); + + try { + workflowResponse.setMessageCode(Integer.parseInt(responseCode)); + } catch(NumberFormatException nex) { + msoLogger.debug(LOGMARKER + "Failed to parse ResponseCode: " + responseCode); + workflowResponse.setMessageCode(-1); + } + + Object status = responseMap.get("Status"); + + if ("Success".equalsIgnoreCase(String.valueOf(status))) { + workflowResponse.setMessage("Success"); + } else if ("Fail".equalsIgnoreCase(String.valueOf(status))) { + workflowResponse.setMessage("Fail"); + } else { + msoLogger.debug(LOGMARKER + "Unrecognized Status: " + responseCode); + workflowResponse.setMessage("Fail"); + } + } + + /** + * @version 1.0 + * Triggers the workflow in a separate thread + */ + private class ProcessThread extends Thread { + private final Map inputVariables; + private final String processKey; + private final MsoLogger msoLogger; + private final String businessKey; + private ProcessInstance processInstance = null; + private Exception exception = null; + + public ProcessThread(Map inputVariables, String processKey, MsoLogger msoLogger) { + this.inputVariables = inputVariables; + this.processKey = processKey; + this.msoLogger = msoLogger; + this.businessKey = UUID.randomUUID().toString(); + } + + /** + * If an exception occurs when starting the process instance, it may + * be obtained by calling this method. Note that exceptions are only + * recorded while the process is executing in its original thread. + * Once a process is suspended, exception recording stops. + * @return the exception, or null if none has occurred + */ + public Exception getException() { + return exception; + } + + + public ProcessInstance getProcessInstance() { + return this.processInstance; + } + + /** + * Sets the process instance exception. + * @param exception the exception + */ + private void setException(Exception exception) { + this.exception = exception; + } + + public void run() { + setLogContext(processKey, inputVariables); + + long startTime = System.currentTimeMillis(); + + try { + msoLogger.debug(LOGMARKER + "***Received MSO startProcessInstanceByKey with processKey:" + + processKey + " and variables: " + inputVariables); + + msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, LOGMARKER + + "Call to MSO workflow/services in Camunda. Received MSO startProcessInstanceByKey with" + + " processKey:" + processKey + + " businessKey:" + businessKey + + " variables: " + inputVariables); + + RuntimeService runtimeService = getProcessEngineServices().getRuntimeService(); + + // Note that this method doesn't return until the process suspends + // itself or finishes. We provide a business key so we can identify + // the process instance immediately. + processInstance = runtimeService.startProcessInstanceByKey( + processKey, inputVariables); + + } catch (Exception e) { + msoLogger.debug(LOGMARKER + "ProcessThread caught an exception executing " + + processKey + ": " + e); + setException(e); + } + } + + } + + private Map getInputVariables(VariableMapImpl variableMap) { + VariableMap inputVariables = Variables.createVariables(); + @SuppressWarnings("unchecked") + Map vMap = (Map) variableMap.get("variables"); + for (String key : vMap.keySet()) { //variabe name vn + @SuppressWarnings("unchecked") + Map valueMap = (Map)vMap.get(key); //value, type + inputVariables.putValueTyped(key, Variables + .objectValue(valueMap.get("value")) + .serializationDataFormat(SerializationDataFormats.JAVA) // tells the engine to use java serialization for persisting the value + .create()); + } + return inputVariables; + } + + /** + * Attempts to get a response map from the specified process instance. + * @return the response map, or null if it is unavailable + */ + private Map getResponseMap(ProcessInstance processInstance, + String processKey, AtomicLong timeProcessEnded) { + + String responseMapVariable = processKey + "ResponseMap"; + String processInstanceId = processInstance.getId(); + + // Query the runtime service to see if a response map is ready. + +/* RuntimeService runtimeService = getProcessEngineServices().getRuntimeService(); + List executions = runtimeService.createExecutionQuery() + .processInstanceId(processInstanceId).list(); + + for (Execution execution : executions) { + @SuppressWarnings("unchecked") + Map responseMap = (Map) + getVariableFromExecution(runtimeService, execution.getId(), + responseMapVariable); + + if (responseMap != null) { + msoLogger.debug(LOGMARKER + "Obtained " + responseMapVariable + + " from process " + processInstanceId + " execution " + + execution.getId()); + return responseMap; + } + } +*/ + //Querying history seem to return consistent results compared to querying the runtime service + + boolean alreadyEnded = timeProcessEnded.longValue() != 0; + + if (alreadyEnded || isProcessEnded(processInstance.getId())) { + if (!alreadyEnded) { + timeProcessEnded.set(System.currentTimeMillis()); + } + + // Query the history service to see if a response map exists. + + HistoryService historyService = getProcessEngineServices().getHistoryService(); + @SuppressWarnings("unchecked") + Map responseMap = (Map) + getVariableFromHistory(historyService, processInstance.getId(), + responseMapVariable); + + if (responseMap != null) { + msoLogger.debug(LOGMARKER + "Obtained " + responseMapVariable + + " from process " + processInstanceId + " history"); + return responseMap; + } + + // Query the history service for old-style response variables. + + String prefix = (String) getVariableFromHistory(historyService, processInstanceId, "prefix"); + + if (prefix != null) { + + // Check for 'WorkflowResponse' variable + Object workflowResponseObject = getVariableFromHistory(historyService, processInstanceId, "WorkflowResponse"); + String workflowResponse = workflowResponseObject == null ? null : String.valueOf(workflowResponseObject); + msoLogger.debug(LOGMARKER + "WorkflowResponse: " + workflowResponse); + + if (workflowResponse != null) { + Object responseCodeObject = getVariableFromHistory(historyService, processInstanceId, prefix + "ResponseCode"); + String responseCode = responseCodeObject == null ? null : String.valueOf(responseCodeObject); + msoLogger.debug(LOGMARKER + prefix + "ResponseCode: " + responseCode); + responseMap = new HashMap(); + responseMap.put("WorkflowResponse", workflowResponse); + responseMap.put("ResponseCode", responseCode); + responseMap.put("Status", "Success"); + return responseMap; + } + + + // Check for 'WorkflowException' variable + WorkflowException workflowException = null; + String workflowExceptionText = null; + + Object workflowExceptionObject = getVariableFromHistory(historyService, processInstanceId, "WorkflowException"); + if(workflowExceptionObject != null) { + if(workflowExceptionObject instanceof WorkflowException) { + workflowException = (WorkflowException) workflowExceptionObject; + workflowExceptionText = workflowException.toString(); + responseMap = new HashMap(); + responseMap.put("WorkflowException", workflowExceptionText); + responseMap.put("ResponseCode", workflowException.getErrorCode()); + responseMap.put("Status", "Fail"); + return responseMap; + } + else if (workflowExceptionObject instanceof String) { + Object object = getVariableFromHistory(historyService, processInstanceId, prefix + "ResponseCode"); + String responseCode = object == null ? null : String.valueOf(object); + workflowExceptionText = (String) workflowExceptionObject; + responseMap = new HashMap(); + responseMap.put("WorkflowException", workflowExceptionText); + responseMap.put("ResponseCode", responseCode); + responseMap.put("Status", "Fail"); + return responseMap; + } + + } + msoLogger.debug(LOGMARKER + "WorkflowException: " + workflowExceptionText); + + // BEGIN LEGACY SUPPORT. TODO: REMOVE THIS CODE + Object object = getVariableFromHistory(historyService, processInstanceId, processKey + "Response"); + String response = object == null ? null : String.valueOf(object); + msoLogger.debug(LOGMARKER + processKey + "Response: " + response); + + if (response != null) { + object = getVariableFromHistory(historyService, processInstanceId, prefix + "ResponseCode"); + String responseCode = object == null ? null : String.valueOf(object); + msoLogger.debug(LOGMARKER + prefix + "ResponseCode: " + responseCode); + responseMap = new HashMap(); + responseMap.put("Response", response); + responseMap.put("ResponseCode", responseCode); + responseMap.put("Status", "Success"); + return responseMap; + } + + object = getVariableFromHistory(historyService, processInstanceId, prefix + "ErrorResponse"); + String errorResponse = object == null ? null : String.valueOf(object); + msoLogger.debug(LOGMARKER + prefix + "ErrorResponse: " + errorResponse); + + if (errorResponse != null) { + object = getVariableFromHistory(historyService, processInstanceId, prefix + "ResponseCode"); + String responseCode = object == null ? null : String.valueOf(object); + msoLogger.debug(LOGMARKER + prefix + "ResponseCode: " + responseCode); + responseMap = new HashMap(); + responseMap.put("Response", errorResponse); + responseMap.put("ResponseCode", responseCode); + responseMap.put("Status", "Fail"); + return responseMap; + } + // END LEGACY SUPPORT. TODO: REMOVE THIS CODE + } + } + return null; + } + + /** + * Gets a variable value from the specified execution. + * @return the variable value, or null if the variable could not be + * obtained + */ + private Object getVariableFromExecution(RuntimeService runtimeService, + String executionId, String variableName) { + try { + return runtimeService.getVariable(executionId, variableName); + } catch (ProcessEngineException e) { + // Most likely cause is that the execution no longer exists. + msoLogger.debug("Error retrieving execution " + executionId + + " variable " + variableName + ": " + e); + return null; + } + } + /** + * Gets a variable value from specified historical process instance. + * @return the variable value, or null if the variable could not be + * obtained + */ + private Object getVariableFromHistory(HistoryService historyService, + String processInstanceId, String variableName) { + try { + HistoricVariableInstance v = historyService.createHistoricVariableInstanceQuery() + .processInstanceId(processInstanceId).variableName(variableName).singleResult(); + return v == null ? null : v.getValue(); + } catch (Exception e) { + msoLogger.debug("Error retrieving process " + processInstanceId + + " variable " + variableName + " from history: " + e); + return null; + } + } + + @POST + @Path("/services/{processKey}/{processInstanceId}") + @Produces("application/json") + @Consumes("application/json") + public WorkflowResponse getProcessVariables(@PathParam("processKey") String processKey, @PathParam("processInstanceId") String processInstanceId) { + //TODO filter only set of variables + WorkflowResponse response = new WorkflowResponse(); + + long startTime = System.currentTimeMillis(); + try { + ProcessEngineServices engine = getProcessEngineServices(); + List variables = engine.getHistoryService().createHistoricVariableInstanceQuery().processInstanceId(processInstanceId).list(); + Map variablesMap = new HashMap(); + for (HistoricVariableInstance variableInstance: variables) { + variablesMap.put(variableInstance.getName(), variableInstance.getValue().toString()); + } + + msoLogger.debug(LOGMARKER + "***Received MSO getProcessVariables with processKey:" + processKey + " and variables: " + variablesMap.toString()); + + msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, LOGMARKER + + "Call to MSO workflow/services in Camunda. Received MSO getProcessVariables with processKey:" + + processKey + " and variables: " + + variablesMap.toString()); + + + response.setVariables(variablesMap); + response.setMessage("Success"); + response.setResponse("Successfully retrieved the variables"); + response.setProcessInstanceID(processInstanceId); + + msoLogger.debug(LOGMARKER + response.getMessage() + " for processKey: " + processKey + " with response: " + response.getResponse()); + } catch (Exception ex) { + response.setMessage("Fail"); + response.setResponse("Failed to retrieve the variables," + ex.getMessage()); + response.setProcessInstanceID(processInstanceId); + + msoLogger.error (MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "BPMN", MDC.get(processKey), MsoLogger.ErrorCode.UnknownError, LOGMARKER + + response.getMessage() + + " for processKey: " + + processKey + + " with response: " + + response.getResponse()); + + } + + msoLogger.recordMetricEvent ( startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, + LOGMARKER + response.getMessage() + " for processKey: " + + processKey + " with response: " + response.getResponse(), "BPMN", MDC.get(processKey), null); + + msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, + LOGMARKER + response.getMessage() + " for processKey: " + + processKey + " with response: " + response.getResponse()); + + return response; + } + + private ProcessEngineServices getProcessEngineServices() { + if (pes4junit == null) { + return ProcessEngines.getDefaultProcessEngine(); + } else { + return pes4junit; + } + } + + public void setProcessEngineServices4junit(ProcessEngineServices pes) { + pes4junit = pes; + } +} diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/WorkflowResourceApplication.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/WorkflowResourceApplication.java index afc7bdb128..d6c9b51cd6 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/WorkflowResourceApplication.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/WorkflowResourceApplication.java @@ -1,57 +1,57 @@ -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - MSO - * ================================================================================ - * 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.openecomp.mso.bpmn.common.workflow.service; - -import java.util.HashSet; -import java.util.Set; - -import javax.ws.rs.ApplicationPath; -import javax.ws.rs.core.Application; - -import org.openecomp.mso.bpmn.common.workflow.service.WorkflowMessageResource; -import org.openecomp.mso.bpmn.common.workflow.service.WorkflowResource; - -/** - * @version 1.0 - * RESTeasy workflow application which wires synchronous and asynchronous response - * - */ -@ApplicationPath("/") -public class WorkflowResourceApplication extends Application { - private Set singletons = new HashSet(); - private Set> classes = new HashSet>(); - - public WorkflowResourceApplication() { - singletons.add(new WorkflowResource()); - singletons.add(new WorkflowAsyncCommonResource()); - singletons.add(new WorkflowMessageResource()); - } - - @Override - public Set> getClasses() { - return classes; - } - - @Override - public Set getSingletons() { - return singletons; - } -} +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.bpmn.common.workflow.service; + +import java.util.HashSet; +import java.util.Set; + +import javax.ws.rs.ApplicationPath; +import javax.ws.rs.core.Application; + +import org.openecomp.mso.bpmn.common.workflow.service.WorkflowMessageResource; +import org.openecomp.mso.bpmn.common.workflow.service.WorkflowResource; + +/** + * @version 1.0 + * RESTeasy workflow application which wires synchronous and asynchronous response + * + */ +@ApplicationPath("/") +public class WorkflowResourceApplication extends Application { + private Set singletons = new HashSet(); + private Set> classes = new HashSet>(); + + public WorkflowResourceApplication() { + singletons.add(new WorkflowResource()); + singletons.add(new WorkflowAsyncCommonResource()); + singletons.add(new WorkflowMessageResource()); + } + + @Override + public Set> getClasses() { + return classes; + } + + @Override + public Set getSingletons() { + return singletons; + } +} diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/WorkflowResponse.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/WorkflowResponse.java index 5da7c8fef4..79e29e6770 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/WorkflowResponse.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/WorkflowResponse.java @@ -1,69 +1,69 @@ -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - MSO - * ================================================================================ - * 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.openecomp.mso.bpmn.common.workflow.service; - -import java.util.Map; - -/** - * @version 1.0 - * Synchronous workflow response bean - * - */ -public class WorkflowResponse { - - private String response; - private String message; - private String processInstanceID; - private Map variables; - private int messageCode; - - public String getResponse() { - return response; - } - public void setResponse(String response) { - this.response = response; - } - public String getMessage() { - return message; - } - public void setMessage(String message) { - this.message = message; - } - public String getProcessInstanceID() { - return processInstanceID; - } - public void setProcessInstanceID(String pID) { - this.processInstanceID = pID; - } - public Map getVariables() { - return variables; - } - public void setVariables(Map variables) { - this.variables = variables; - } - public void setMessageCode(int messageCode) { - this.messageCode = messageCode; - } - - public int getMessageCode() { - return messageCode; - } -} +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.bpmn.common.workflow.service; + +import java.util.Map; + +/** + * @version 1.0 + * Synchronous workflow response bean + * + */ +public class WorkflowResponse { + + private String response; + private String message; + private String processInstanceID; + private Map variables; + private int messageCode; + + public String getResponse() { + return response; + } + public void setResponse(String response) { + this.response = response; + } + public String getMessage() { + return message; + } + public void setMessage(String message) { + this.message = message; + } + public String getProcessInstanceID() { + return processInstanceID; + } + public void setProcessInstanceID(String pID) { + this.processInstanceID = pID; + } + public Map getVariables() { + return variables; + } + public void setVariables(Map variables) { + this.variables = variables; + } + public void setMessageCode(int messageCode) { + this.messageCode = messageCode; + } + + public int getMessageCode() { + return messageCode; + } +} diff --git a/bpmn/MSOCommonBPMN/src/main/resources/META-INF/persistence.xml b/bpmn/MSOCommonBPMN/src/main/resources/META-INF/persistence.xml index fb027b8ed0..d7166d81a9 100644 --- a/bpmn/MSOCommonBPMN/src/main/resources/META-INF/persistence.xml +++ b/bpmn/MSOCommonBPMN/src/main/resources/META-INF/persistence.xml @@ -1,37 +1,37 @@ - - - - - - - java:jboss/datasources/ProcessEngine - - - - - - - - + + + + + + + java:jboss/datasources/ProcessEngine + + + + + + + + diff --git a/bpmn/MSOCommonBPMN/src/main/resources/processes.xml b/bpmn/MSOCommonBPMN/src/main/resources/processes.xml new file mode 100644 index 0000000000..f4f8efdbc4 --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/main/resources/processes.xml @@ -0,0 +1,81 @@ + + + + + + + org.camunda.bpm.engine.impl.cfg.StandaloneProcessEngineConfiguration + java:jboss/datasources/ProcessEngine + + full + true + true + true + true + + + + + + org.camunda.bpm.application.impl.event.ProcessApplicationEventListenerPlugin + + + + + org.camunda.spin.plugin.impl.SpinProcessEnginePlugin + + + + + org.camunda.connect.plugin.impl.ConnectProcessEnginePlugin + + + + org.openecomp.mso.bpmn.core.plugins.LoggingAndURNMappingPlugin + + + + + org.openecomp.mso.bpmn.core.plugins.WorkflowExceptionPlugin + + + + + + + + + + common + + false + true + + + + diff --git a/bpmn/MSOCommonBPMN/src/main/resources/subprocess/CompleteMsoProcess.bpmn b/bpmn/MSOCommonBPMN/src/main/resources/subprocess/CompleteMsoProcess.bpmn index caf39010a7..cd977e3ae6 100644 --- a/bpmn/MSOCommonBPMN/src/main/resources/subprocess/CompleteMsoProcess.bpmn +++ b/bpmn/MSOCommonBPMN/src/main/resources/subprocess/CompleteMsoProcess.bpmn @@ -1,19 +1,34 @@ - + - SequenceFlow_1s593bx - SequenceFlow_1epmndu + SequenceFlow_18 + SequenceFlow_2 + - SequenceFlow_1s593bx + SequenceFlow_18 + + + SequenceFlow_2 + SequenceFlow_45 + SequenceFlow_46 + + + + + SequenceFlow_45 + SequenceFlow_40 + if_notifcationURLExists + + @@ -23,28 +38,26 @@ preProcessRequestData.preProcessRequest(execution) - SequenceFlow_19 + SequenceFlow_1i1h3il - SequenceFlow_19 + SequenceFlow_1i1h3il - + - - SequenceFlow_21 - SequenceFlow_7 SequenceFlow_24 - SequenceFlow_0fni7aq + SequenceFlow_39 + SequenceFlow_9 - + SequenceFlow_72 SequenceFlow_10 - SequenceFlow_1epmndu + SequenceFlow_46 SequenceFlow_72 SequenceFlow_81 @@ -67,6 +80,7 @@ completeMsoProcess.setUpdateDBstatustoSuccessPayload(execution)]]> SequenceFlow_25 + SequenceFlow_1q7eer1 SequenceFlow_13 Build Error Message @@@@" import org.openecomp.mso.bpmn.common.scripts.* @@ -74,7 +88,7 @@ def buildDataErrorMessage = new CompleteMsoProcess() buildDataErrorMessage.buildDataError(execution, "Complete --Update DB status to SUCCESS-- Failed")]]> - + SequenceFlow_81 SequenceFlow_49 - SequenceFlow_14 + SequenceFlow_1q7eer1 - SequenceFlow_1 + SequenceFlow_0mipf25 SequenceFlow_9 Build Error Message @@@@" //println "CMSO_updateRequestResponse IS --> " + execution.getVariable("CMSO_updateRequestResponse") @@ -161,16 +175,24 @@ buildDataErrorMessage.buildDataError(execution, "Complete MSO -- Update DB stat SequenceFlow_23 - - SequenceFlow_14 - - SequenceFlow_21 + SequenceFlow_0mipf25 - + + SequenceFlow_40 + SequenceFlow_13qdn1s + SequenceFlow_32 + + + + SequenceFlow_32 + SequenceFlow_39 + SequenceFlow_33 + + - SequenceFlow_0fni7aq + SequenceFlow_33 SequenceFlow_17 Complete MSO Process Done SUCCESSFULLY" import org.openecomp.mso.bpmn.common.scripts.* @@ -183,9 +205,22 @@ println "CompleteMsoProcess Response -->" + "\n" + execution.getVariable("Comple SequenceFlow_17 - - - + + + + + + + + + + if_notifcationURLExists + SequenceFlow_13qdn1s + + + + + @@ -193,253 +228,325 @@ println "CompleteMsoProcess Response -->" + "\n" + execution.getVariable("Comple - + - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - + + + + + + + + + + + + + + + - + - + - + - + + + + + + + + + + + + + + + + + + - + - + + + + + + + + + - + + + + + + + + + - - + + - + - - - + + + - + - - - + + + - + - + - + - + - + - + - + - + - - + + - + - - - + + + - + - + - + - + - - + + - + - - + + - + - + - + - + - - + + - + - - - + + + - + - + - - + + - + - + - + + + + + + + + - - + + - + - + - + - - + + - + - + - + - + - + - - - - - - - - - - - - - - - - - - + + - - - + + + - + - - - - - - + + + + - + - - - + + + + - + - - - + + + + + + + - + - - - + + + - + - - - - - + + + + - + diff --git a/bpmn/MSOCommonBPMN/src/main/resources/subprocess/ConfirmVolumeGroupTenant.bpmn b/bpmn/MSOCommonBPMN/src/main/resources/subprocess/ConfirmVolumeGroupTenant.bpmn index fee4dbd2d3..df55046a7b 100644 --- a/bpmn/MSOCommonBPMN/src/main/resources/subprocess/ConfirmVolumeGroupTenant.bpmn +++ b/bpmn/MSOCommonBPMN/src/main/resources/subprocess/ConfirmVolumeGroupTenant.bpmn @@ -1,190 +1,190 @@ - - - - - SequenceFlow_1 - SequenceFlow_2 + + + + + SequenceFlow_1 + SequenceFlow_2 - - - SequenceFlow_2 - idsMatchNo - idsMatchYes - - - - - - - - SequenceFlow_7 - - - - idsMatchNo - SequenceFlow_8 +volume.preProcessRequest(execution)]]> + + + SequenceFlow_2 + idsMatchNo + idsMatchYes + + + + + + + + SequenceFlow_7 + + + + idsMatchNo + SequenceFlow_8 - - - - SequenceFlow_8 - - - - groupNamesMatchYes - SequenceFlow_7 +volume.assignWorkflowException(execution, "does not belong to your tenant")]]> + + + + SequenceFlow_8 + + + + groupNamesMatchYes + SequenceFlow_7 - - - - groupNamesMatchNo - SequenceFlow_9 +volume.assignVolumeHeatId(execution)]]> + + + + groupNamesMatchNo + SequenceFlow_9 - - - - SequenceFlow_9 - - - - idsMatchYes - groupNamesMatchNo - groupNamesMatchYes - - - - - - - SequenceFlow_1 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +volume.assignWorkflowException(execution, "name does not match")]]> + + + + SequenceFlow_9 + + + + idsMatchYes + groupNamesMatchNo + groupNamesMatchYes + + + + + + + SequenceFlow_1 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/bpmn/MSOCommonBPMN/src/main/resources/subprocess/CreateAAIVfModule.bpmn b/bpmn/MSOCommonBPMN/src/main/resources/subprocess/CreateAAIVfModule.bpmn index 2ca2693b7c..3ac1fe7781 100644 --- a/bpmn/MSOCommonBPMN/src/main/resources/subprocess/CreateAAIVfModule.bpmn +++ b/bpmn/MSOCommonBPMN/src/main/resources/subprocess/CreateAAIVfModule.bpmn @@ -1,519 +1,519 @@ - - - - - SequenceFlow_24 - SequenceFlow_6 - SequenceFlow_7 - SequenceFlow_28 - - - - - - - SequenceFlow_39 - SequenceFlow_22 - SequenceFlow_23 - - - - - - - SequenceFlow_23 - SequenceFlow_18 - - - - - SequenceFlow_18 - - - - SequenceFlow_22 - SequenceFlow_24 - - - - - SequenceFlow_8 - SequenceFlow_5 - SequenceFlow_10 - - - SequenceFlow_4 - SequenceFlow_35 - SequenceFlow_8 - - - - - - SequenceFlow_28 - SequenceFlow_26 - SequenceFlow_33 - SequenceFlow_29 - - - - SequenceFlow_29 - - - - - SequenceFlow_7 - SequenceFlow_31 - - - - - SequenceFlow_34 - SequenceFlow_35 - - - - - SequenceFlow_31 - SequenceFlow_33 - SequenceFlow_34 - - - - - - - SequenceFlow_38 - SequenceFlow_39 - - - - - SequenceFlow_1 - SequenceFlow_38 - - - - - SequenceFlow_2 - - - - SequenceFlow_5 - SequenceFlow_2 - - - - - - - SequenceFlow_10 - - - - - - SequenceFlow_20 - SequenceFlow_13 - SequenceFlow_26 - SequenceFlow_27 - - - - - - - SequenceFlow_6 - SequenceFlow_9 - SequenceFlow_11 - - - - SequenceFlow_9 - SequenceFlow_20 - - - - - - - - SequenceFlow_27 - SequenceFlow_12 - SequenceFlow_4 - - - - - SequenceFlow_1 - - - - - SequenceFlow_11 - SequenceFlow_3 - - - - - SequenceFlow_3 - SequenceFlow_12 - SequenceFlow_13 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + SequenceFlow_24 + SequenceFlow_6 + SequenceFlow_7 + SequenceFlow_28 + + + + + + + SequenceFlow_39 + SequenceFlow_22 + SequenceFlow_23 + + + + + + + SequenceFlow_23 + SequenceFlow_18 + + + + + SequenceFlow_18 + + + + SequenceFlow_22 + SequenceFlow_24 + + + + + SequenceFlow_8 + SequenceFlow_5 + SequenceFlow_10 + + + SequenceFlow_4 + SequenceFlow_35 + SequenceFlow_8 + + + + + + SequenceFlow_28 + SequenceFlow_26 + SequenceFlow_33 + SequenceFlow_29 + + + + SequenceFlow_29 + + + + + SequenceFlow_7 + SequenceFlow_31 + + + + + SequenceFlow_34 + SequenceFlow_35 + + + + + SequenceFlow_31 + SequenceFlow_33 + SequenceFlow_34 + + + + + + + SequenceFlow_38 + SequenceFlow_39 + + + + + SequenceFlow_1 + SequenceFlow_38 + + + + + SequenceFlow_2 + + + + SequenceFlow_5 + SequenceFlow_2 + + + + + + + SequenceFlow_10 + + + + + + SequenceFlow_20 + SequenceFlow_13 + SequenceFlow_26 + SequenceFlow_27 + + + + + + + SequenceFlow_6 + SequenceFlow_9 + SequenceFlow_11 + + + + SequenceFlow_9 + SequenceFlow_20 + + + + + + + + SequenceFlow_27 + SequenceFlow_12 + SequenceFlow_4 + + + + + SequenceFlow_1 + + + + + SequenceFlow_11 + SequenceFlow_3 + + + + + SequenceFlow_3 + SequenceFlow_12 + SequenceFlow_13 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/bpmn/MSOCommonBPMN/src/main/resources/subprocess/DeleteAAIVfModule.bpmn b/bpmn/MSOCommonBPMN/src/main/resources/subprocess/DeleteAAIVfModule.bpmn index 0fce6d846f..297e04c0f7 100644 --- a/bpmn/MSOCommonBPMN/src/main/resources/subprocess/DeleteAAIVfModule.bpmn +++ b/bpmn/MSOCommonBPMN/src/main/resources/subprocess/DeleteAAIVfModule.bpmn @@ -1,482 +1,482 @@ - - - - - SequenceFlow_24 - SequenceFlow_6 - SequenceFlow_8 - - - - - - SequenceFlow_39 - SequenceFlow_22 - SequenceFlow_23 - - - - - - - SequenceFlow_23 - SequenceFlow_18 + + + + + SequenceFlow_24 + SequenceFlow_6 + SequenceFlow_8 + + + + + + SequenceFlow_39 + SequenceFlow_22 + SequenceFlow_23 + + + + + + + SequenceFlow_23 + SequenceFlow_18 - - - - SequenceFlow_18 - - - - SequenceFlow_22 - SequenceFlow_24 +dvm.handleAAIQueryFailure(execution)]]> + + + + SequenceFlow_18 + + + + SequenceFlow_22 + SequenceFlow_24 - - - - SequenceFlow_6 - SequenceFlow_20 +dvm.parseForVfModule(execution)]]> + + + + SequenceFlow_6 + SequenceFlow_20 - - - - SequenceFlow_20 - SequenceFlow_26 - SequenceFlow_27 - SequenceFlow_11 - - - - - - - SequenceFlow_26 - SequenceFlow_8 - SequenceFlow_29 +dvm.deleteVfModule(execution)]]> + + + + SequenceFlow_20 + SequenceFlow_26 + SequenceFlow_27 + SequenceFlow_11 + + + + + + + SequenceFlow_26 + SequenceFlow_8 + SequenceFlow_29 - - - - SequenceFlow_38 - SequenceFlow_39 +dvm.handleDeleteVfModuleFailure(execution)]]> + + + + SequenceFlow_38 + SequenceFlow_39 - - - - - SequenceFlow_29 - - - - - - - SequenceFlow_3 - SequenceFlow_9 +dvm.queryAAIForGenericVnf(execution)]]> + + + + + SequenceFlow_29 + + + + + + + SequenceFlow_3 + SequenceFlow_9 - - - - SequenceFlow_5 - SequenceFlow_2 +dvm.queryAAIForGenericVnf(execution)]]> + + + + SequenceFlow_5 + SequenceFlow_2 - - - - SequenceFlow_2 - - - - SequenceFlow_11 - SequenceFlow_4 - SequenceFlow_5 - SequenceFlow_7 - - - - - - - SequenceFlow_7 - SequenceFlow_15 - - - SequenceFlow_10 - SequenceFlow_12 +dvm.handleDeleteGenericVnfFailure(execution)]]> + + + + SequenceFlow_2 + + + + SequenceFlow_11 + SequenceFlow_4 + SequenceFlow_5 + SequenceFlow_7 + + + + + + + SequenceFlow_7 + SequenceFlow_15 + + + SequenceFlow_10 + SequenceFlow_12 - - - - SequenceFlow_12 - - - - SequenceFlow_14 - SequenceFlow_4 +dvm.handleAAIQueryFailure(execution)]]> + + + + SequenceFlow_12 + + + + SequenceFlow_14 + SequenceFlow_4 - - - - SequenceFlow_13 - SequenceFlow_14 +dvm.deleteGenericVnf(execution)]]> + + + + SequenceFlow_13 + SequenceFlow_14 - - - - SequenceFlow_9 - SequenceFlow_10 - SequenceFlow_13 - - - - - - - SequenceFlow_1 - - - - - SequenceFlow_1 - SequenceFlow_38 +dvm.parseForResourceVersion(execution)]]> + + + + SequenceFlow_9 + SequenceFlow_10 + SequenceFlow_13 + + + + + + + SequenceFlow_1 + + + + + SequenceFlow_1 + SequenceFlow_38 - - - - SequenceFlow_27 - SequenceFlow_3 - SequenceFlow_15 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +dvm.preProcessRequest(execution)]]> + + + + SequenceFlow_27 + SequenceFlow_3 + SequenceFlow_15 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/bpmn/MSOCommonBPMN/src/main/resources/subprocess/FalloutHandler.bpmn b/bpmn/MSOCommonBPMN/src/main/resources/subprocess/FalloutHandler.bpmn index 5f5fd3daae..75e05cb58e 100644 --- a/bpmn/MSOCommonBPMN/src/main/resources/subprocess/FalloutHandler.bpmn +++ b/bpmn/MSOCommonBPMN/src/main/resources/subprocess/FalloutHandler.bpmn @@ -1,28 +1,58 @@ - + + + SequenceFlow_12 + SequenceFlow_2 + SequenceFlow_24 + + + + + SequenceFlow_2 + SequenceFlow_3 + SequenceFlow_23 + + + + + SequenceFlow_10 - SequenceFlow_1nn37a8 + SequenceFlow_12 + SequenceFlow_10 + + SequenceFlow_37 + SequenceFlow_38 + SequenceFlow_8 + + - SequenceFlow_0fg02po - SequenceFlow_0x2jgo4 + SequenceFlow_8 + SequenceFlow_9 + + + SequenceFlow_23 + SequenceFlow_0m7gwor + SequenceFlow_38 + + - SequenceFlow_1nn37a8 + SequenceFlow_24 SequenceFlow_25 SequenceFlow_26 @@ -65,10 +95,11 @@ return updateRequestGamma.updateRequestGammaPayload(execution)]]> SequenceFlow_35 SequenceFlow_36 - SequenceFlow_0fg02po + SequenceFlow_37 + - SequenceFlow_0x2jgo4 + SequenceFlow_9 @@ -142,8 +173,8 @@ return updateRequestInfra.updateRequestInfraPayload(execution)]]> - SequenceFlow_1k7it63 - SequenceFlow_0celhl1 + SequenceFlow_1ko8ggw + SequenceFlow_1pm9r7h - SequenceFlow_1k7it63 + SequenceFlow_1ko8ggw - SequenceFlow_0celhl1 + SequenceFlow_1pm9r7h - - + + SequenceFlow_73 @@ -175,247 +206,337 @@ execution.setVariable("FH_WorkflowException", wfe)]]> SequenceFlow_79 - - - + + + + + + + + + SequenceFlow_3 + SequenceFlow_0m7gwor + - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - + + + + + + + + + + - + - + + + + + + + + + - - - + + + - + - - - + + + - + - + - + - + - + - - + + - + - + - + - - - - + + + + - + - - + + - + - - - + + + - + - + - + - - - + + + - + - - - + + + - + + + + + + + + + + + + + + + + + + + + + + + - - + + - + - + - + - + - + - + - + + + + + + + + + + + + + + + - + - + + + + + + + + - + - + - + - + - - - + + + - + - - + + - + - + - + - - + + - + - - - + + + - + - + - + - + - + - + - + - - - - - - - - - - - - - - - - - - - + + + + - + - - - + + + - + - - - + + + - + + + + diff --git a/bpmn/MSOCommonBPMN/src/main/resources/subprocess/GenericDeleteService.bpmn b/bpmn/MSOCommonBPMN/src/main/resources/subprocess/GenericDeleteService.bpmn index f4edac612c..15929b87eb 100644 --- a/bpmn/MSOCommonBPMN/src/main/resources/subprocess/GenericDeleteService.bpmn +++ b/bpmn/MSOCommonBPMN/src/main/resources/subprocess/GenericDeleteService.bpmn @@ -1,303 +1,304 @@ - - - - - - SequenceFlow_9 - SequenceFlow_10 + + + + + + SequenceFlow_9 + SequenceFlow_10 - - - - SequenceFlow_9 - - - - - SequenceFlow_10 - - - - - - SequenceFlow_12 - - - SequenceFlow_11 - SequenceFlow_12 - - - - SequenceFlow_11 - - - - - - - SequenceFlow_1 - - - - SequenceFlow_1 - SequenceFlow_3 - - - - - SequenceFlow_3 - no - yes - - - - - - - SequenceFlow_7 - SequenceFlow_4 - - - - - yes - siExistYes - SequenceFlow_6 - - - - SequenceFlow_4 - - - - SequenceFlow_6 - SequenceFlow_7 - - - - - no - SequenceFlow_5 - - - - - SequenceFlow_5 - siExistYes - siExistNo - - - - - - - siExistNo - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file +]]> + + + + SequenceFlow_9 + + + + + SequenceFlow_10 + + + + + + SequenceFlow_12 + + + SequenceFlow_11 + SequenceFlow_12 + + + + SequenceFlow_11 + + + + + + + SequenceFlow_1 + + + + SequenceFlow_1 + SequenceFlow_3 + + + + + SequenceFlow_3 + no + yes + + + + + + + SequenceFlow_7 + SequenceFlow_4 + + + + + yes + siExistYes + SequenceFlow_6 + + + + SequenceFlow_4 + + + + SequenceFlow_6 + SequenceFlow_7 + + + + + no + SequenceFlow_5 + + + + + SequenceFlow_5 + siExistYes + siExistNo + + + + + + + siExistNo + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/bpmn/MSOCommonBPMN/src/main/resources/subprocess/GenericDeleteVnf.bpmn b/bpmn/MSOCommonBPMN/src/main/resources/subprocess/GenericDeleteVnf.bpmn index e68f6ec227..f46f86613f 100644 --- a/bpmn/MSOCommonBPMN/src/main/resources/subprocess/GenericDeleteVnf.bpmn +++ b/bpmn/MSOCommonBPMN/src/main/resources/subprocess/GenericDeleteVnf.bpmn @@ -1,251 +1,251 @@ - - - - - SequenceFlow_1 - - - SequenceFlow_1 - SequenceFlow_9 - - - - - - SequenceFlow_9 - resourceVariableNotProvided - resourceVersionProvided - - - - - - - - SequenceFlow_2 - SequenceFlow_3 - - - - - SequenceFlow_2 - - - - - SequenceFlow_3 - - - - - resourceVariableNotProvided - SequenceFlow_5 - - - - - SequenceFlow_7 - SequenceFlow_8 - - - - - SequenceFlow_6 - SequenceFlow_7 - - - - - vnfFoundNo - - - - SequenceFlow_5 - vnfFoundYes - vnfFoundNo - - - - - - - resourceVersionProvided - vnfFoundYes - SequenceFlow_6 - - - - SequenceFlow_8 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + SequenceFlow_1 + + + SequenceFlow_1 + SequenceFlow_9 + + + + + + SequenceFlow_9 + resourceVariableNotProvided + resourceVersionProvided + + + + + + + + SequenceFlow_2 + SequenceFlow_3 + + + + + SequenceFlow_2 + + + + + SequenceFlow_3 + + + + + resourceVariableNotProvided + SequenceFlow_5 + + + + + SequenceFlow_7 + SequenceFlow_8 + + + + + SequenceFlow_6 + SequenceFlow_7 + + + + + vnfFoundNo + + + + SequenceFlow_5 + vnfFoundYes + vnfFoundNo + + + + + + + resourceVersionProvided + vnfFoundYes + SequenceFlow_6 + + + + SequenceFlow_8 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/bpmn/MSOCommonBPMN/src/main/resources/subprocess/GenericGetVnf.bpmn b/bpmn/MSOCommonBPMN/src/main/resources/subprocess/GenericGetVnf.bpmn index db0d35d9ce..3300d86084 100644 --- a/bpmn/MSOCommonBPMN/src/main/resources/subprocess/GenericGetVnf.bpmn +++ b/bpmn/MSOCommonBPMN/src/main/resources/subprocess/GenericGetVnf.bpmn @@ -1,212 +1,212 @@ - - - - - SequenceFlow_1 - - - SequenceFlow_1 - SequenceFlow_2 + + + + + SequenceFlow_1 + + + SequenceFlow_1 + SequenceFlow_2 - - - - - SequenceFlow_2 - noVnfId - haveVnfId - - - - - - - noVnfId - SequenceFlow_9 +]]> + + + + + SequenceFlow_2 + noVnfId + haveVnfId + + + + + + + noVnfId + SequenceFlow_9 - - - - SequenceFlow_9 - SequenceFlow_10 - SequenceFlow_7 - - - - haveVnfId - SequenceFlow_10 +genericGetVnf.getVnfByName(execution)]]> + + + + SequenceFlow_9 + SequenceFlow_10 + SequenceFlow_7 + + + + haveVnfId + SequenceFlow_10 - - - - - SequenceFlow_12 - - - - SequenceFlow_11 - SequenceFlow_12 +genericGetVnf.getVnfById(execution)]]> + + + + + SequenceFlow_12 + + + + SequenceFlow_11 + SequenceFlow_12 - - - - SequenceFlow_11 - - - - - - SequenceFlow_7 - SequenceFlow_8 +ex.processSubflowsBPMNException(execution)]]> + + + + SequenceFlow_11 + + + + + + SequenceFlow_7 + SequenceFlow_8 - - - - SequenceFlow_8 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +]]> + + + + SequenceFlow_8 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/bpmn/MSOCommonBPMN/src/main/resources/subprocess/GenericNotificationService.bpmn b/bpmn/MSOCommonBPMN/src/main/resources/subprocess/GenericNotificationService.bpmn new file mode 100644 index 0000000000..23351eb1b1 --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/main/resources/subprocess/GenericNotificationService.bpmn @@ -0,0 +1,48 @@ + + + + + SequenceFlow_0zigcpk + + + SequenceFlow_1122k97 + + + + SequenceFlow_0zigcpk + SequenceFlow_1122k97 + GenericNotificationService Process"]]> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/bpmn/MSOCommonBPMN/src/main/resources/subprocess/GenericPutService.bpmn b/bpmn/MSOCommonBPMN/src/main/resources/subprocess/GenericPutService.bpmn index 8c8412dcac..ca03a9560c 100644 --- a/bpmn/MSOCommonBPMN/src/main/resources/subprocess/GenericPutService.bpmn +++ b/bpmn/MSOCommonBPMN/src/main/resources/subprocess/GenericPutService.bpmn @@ -1,201 +1,201 @@ - - - - - SequenceFlow_1 - - - - SequenceFlow_5 - - - - SequenceFlow_4 - SequenceFlow_5 - - - - - SequenceFlow_3 - SequenceFlow_4 - - - - - SequenceFlow_1 - SequenceFlow_3 - - - - - - SequenceFlow_6 - - - - - SequenceFlow_7 - - - SequenceFlow_6 - SequenceFlow_7 - - - - - - - SequenceFlow_9 - - - - - SequenceFlow_9 - SequenceFlow_10 - - - - SequenceFlow_10 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file + + + + + SequenceFlow_1 + + + + SequenceFlow_5 + + + + SequenceFlow_4 + SequenceFlow_5 + + + + + SequenceFlow_3 + SequenceFlow_4 + + + + + SequenceFlow_1 + SequenceFlow_3 + + + + + + SequenceFlow_6 + + + + + SequenceFlow_7 + + + SequenceFlow_6 + SequenceFlow_7 + + + + + + + SequenceFlow_9 + + + + + SequenceFlow_9 + SequenceFlow_10 + + + + SequenceFlow_10 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/bpmn/MSOCommonBPMN/src/main/resources/subprocess/GenericPutVnf.bpmn b/bpmn/MSOCommonBPMN/src/main/resources/subprocess/GenericPutVnf.bpmn index bb73c09619..f155783e3a 100644 --- a/bpmn/MSOCommonBPMN/src/main/resources/subprocess/GenericPutVnf.bpmn +++ b/bpmn/MSOCommonBPMN/src/main/resources/subprocess/GenericPutVnf.bpmn @@ -1,135 +1,135 @@ - - - - - SequenceFlow_1 - - - SequenceFlow_1 - SequenceFlow_2 + + + + + SequenceFlow_1 + + + SequenceFlow_1 + SequenceFlow_2 - - - - - - SequenceFlow_6 - - - - SequenceFlow_5 - - - - SequenceFlow_5 - SequenceFlow_6 - - - - - - - SequenceFlow_2 - SequenceFlow_3 +genericPutVnf.preProcessRequest(execution)]]> + + + + + + SequenceFlow_6 + + + + SequenceFlow_5 + + + + SequenceFlow_5 + SequenceFlow_6 + + + + + + + SequenceFlow_2 + SequenceFlow_3 - - - - SequenceFlow_3 - SequenceFlow_4 +genericPutVnf.putVnf(execution)]]> + + + + SequenceFlow_3 + SequenceFlow_4 - - - - SequenceFlow_4 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +execution.setVariable("WorkflowResponse", " ") //for junits]]> + + + + SequenceFlow_4 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/bpmn/MSOCommonBPMN/src/main/resources/subprocess/SDNCAdapterRestV1.bpmn b/bpmn/MSOCommonBPMN/src/main/resources/subprocess/SDNCAdapterRestV1.bpmn new file mode 100644 index 0000000000..c52612bb95 --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/main/resources/subprocess/SDNCAdapterRestV1.bpmn @@ -0,0 +1,470 @@ + + + + + SequenceFlow_3 + SequenceFlow_14 + + + + SequenceFlow_17 + SequenceFlow_35 + + + + SequenceFlow_23 + SequenceFlow_36 + + + + + SequenceFlow_14 + SequenceFlow_17 + SequenceFlow_23 + SequenceFlow_24 + + + + + + + + + + + SequenceFlow_35 + + + + SequenceFlow_36 + + + + + SequenceFlow_2 + SequenceFlow_3 + + + + + SequenceFlow_9 + SequenceFlow_2 + + + + + SequenceFlow_9 + + + + SequenceFlow_27 + SequenceFlow_34 + + + + + SequenceFlow_34 + + + + SequenceFlow_44 + SequenceFlow_1 + + + + + SequenceFlow_1 + + + SequenceFlow_27 + + ${SDNCREST_timeout} + + + + + SequenceFlow_24 + SequenceFlow_44 + + SequenceFlow_41 + SequenceFlow_42 + + + + + SequenceFlow_25 + + + + SequenceFlow_30 + SequenceFlow_39 + SequenceFlow_43 + + + + + + + SequenceFlow_42 + SequenceFlow_8 + SequenceFlow_30 + + + + + + + SequenceFlow_25 + SequenceFlow_43 + SequenceFlow_41 + + + + + SequenceFlow_39 + + + SequenceFlow_8 + + + + + + + SequenceFlow_4 + + + + + SequenceFlow_4 + SequenceFlow_11 + + + + + SequenceFlow_11 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/bpmn/MSOCommonBPMN/src/main/resources/subprocess/SDNCAdapterV1.bpmn b/bpmn/MSOCommonBPMN/src/main/resources/subprocess/SDNCAdapterV1.bpmn index c94842382b..e0fc14e933 100644 --- a/bpmn/MSOCommonBPMN/src/main/resources/subprocess/SDNCAdapterV1.bpmn +++ b/bpmn/MSOCommonBPMN/src/main/resources/subprocess/SDNCAdapterV1.bpmn @@ -1,5 +1,5 @@ - + SequenceFlow_15 @@ -10,7 +10,7 @@ - + badSynchronousResponse Exception - + @@ -71,13 +71,9 @@ sdnc.preProcessRequest(execution) ]]> - - SequenceFlow_9 - timeOut - SequenceFlow_29 - - SequenceFlow_29 + SequenceFlow_9 + SequenceFlow_11ah5pw SequenceFlow_14 SequenceFlow_19 - + SequenceFlow_2 SequenceFlow_9 - - SequenceFlow_16 - - - SequenceFlow_18 + SequenceFlow_1eciucn - - SequenceFlow_18 + SequenceFlow_1eciucn SequenceFlow_16 + + + SequenceFlow_16 + - - - timeOut - - ${sdncTimeoutValue} - - - - - SequenceFlow_19 - Error + + + SequenceFlow_0mzs1ze + SequenceFlow_11ah5pw +def sdnc= new SDNCAdapter() +sdnc.setTimeout(execution)]]> - - - Error - - goodSynchronousResponse SequenceFlow_26 @@ -198,15 +179,46 @@ sdnc.assignError(execution)]]> SequenceFlow_21 - SequenceFlow_15c4h5f + SequenceFlow_31 + + + SequenceFlow_31 + SequenceFlow_4 + SequenceFlow_23 + + + + + - SequenceFlow_15c4h5f + SequenceFlow_23 - + + this is a non interupting time to prevent an Optimistic Locking Exception if timer expires the same time we correlate a message + SequenceFlow_0mzs1ze + + ${sdncTimeoutValue} + + + + SequenceFlow_19 + + + + + + + + + + + + SequenceFlow_4 + @@ -294,52 +306,25 @@ sdnc.toggleSuccessIndicator(execution)]]> - + - + - + - - - - - - - - - - - - - - - - - - - - - - - - - - + - + - - - - - + + + - + @@ -353,35 +338,15 @@ sdnc.toggleSuccessIndicator(execution)]]> - + - - - - - - - - - - - - - - - - - + + + - + - - - - - - @@ -397,16 +362,16 @@ sdnc.toggleSuccessIndicator(execution)]]> - - + + - + - + @@ -421,18 +386,13 @@ sdnc.toggleSuccessIndicator(execution)]]> - - + + + - + - - - - - - @@ -440,6 +400,19 @@ sdnc.toggleSuccessIndicator(execution)]]> + + + + + + + + + + + + + @@ -454,17 +427,24 @@ sdnc.toggleSuccessIndicator(execution)]]> - + - + + + + + + + + - + @@ -478,47 +458,93 @@ sdnc.toggleSuccessIndicator(execution)]]> - + - + - + - + - + - + - - + + - + - - + + - + - + - + + + + + + + + + + + + + + + + + + + + + + - + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/bpmn/MSOCommonBPMN/src/main/resources/subprocess/VnfAdapterRestV1.bpmn b/bpmn/MSOCommonBPMN/src/main/resources/subprocess/VnfAdapterRestV1.bpmn index 90964e5466..82d89b0c64 100644 --- a/bpmn/MSOCommonBPMN/src/main/resources/subprocess/VnfAdapterRestV1.bpmn +++ b/bpmn/MSOCommonBPMN/src/main/resources/subprocess/VnfAdapterRestV1.bpmn @@ -1,442 +1,442 @@ - - - - - SequenceFlow_3 - SequenceFlow_14 - - - - SequenceFlow_17 - SequenceFlow_35 - - - - SequenceFlow_23 - SequenceFlow_36 - - - - - SequenceFlow_14 - SequenceFlow_17 - SequenceFlow_23 - SequenceFlow_24 - - - - - - - - - - SequenceFlow_27 - - ${URN_mso_po_timeout} - - - - SequenceFlow_24 - SequenceFlow_28 - - SequenceFlow_25 - SequenceFlow_26 - - - - - SequenceFlow_25 - - - - SequenceFlow_26 - - - - - SequenceFlow_27 - SequenceFlow_34 - - - - - SequenceFlow_28 - SequenceFlow_33 - - - - - - SequenceFlow_34 - - - - - SequenceFlow_35 - - - - SequenceFlow_36 - - - - - SequenceFlow_32 - - - - SequenceFlow_33 - SequenceFlow_31 - SequenceFlow_32 - - - - - - - SequenceFlow_31 - SequenceFlow_1 - - - - - SequenceFlow_1 - - - SequenceFlow_2 - SequenceFlow_3 - - - - - - SequenceFlow_4 - SequenceFlow_5 - - - - - SequenceFlow_5 - - - SequenceFlow_4 - - - - - - SequenceFlow_9 - SequenceFlow_2 - - - - - SequenceFlow_9 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + SequenceFlow_3 + SequenceFlow_14 + + + + SequenceFlow_17 + SequenceFlow_35 + + + + SequenceFlow_23 + SequenceFlow_36 + + + + + SequenceFlow_14 + SequenceFlow_17 + SequenceFlow_23 + SequenceFlow_24 + + + + + + + + + + SequenceFlow_27 + + ${URN_mso_po_timeout} + + + + SequenceFlow_24 + SequenceFlow_28 + + SequenceFlow_25 + SequenceFlow_26 + + + + + SequenceFlow_25 + + + + SequenceFlow_26 + + + + + SequenceFlow_27 + SequenceFlow_34 + + + + + SequenceFlow_28 + SequenceFlow_33 + + + + + + SequenceFlow_34 + + + + + SequenceFlow_35 + + + + SequenceFlow_36 + + + + + SequenceFlow_32 + + + + SequenceFlow_33 + SequenceFlow_31 + SequenceFlow_32 + + + + + + + SequenceFlow_31 + SequenceFlow_1 + + + + + SequenceFlow_1 + + + SequenceFlow_2 + SequenceFlow_3 + + + + + + SequenceFlow_4 + SequenceFlow_5 + + + + + SequenceFlow_5 + + + SequenceFlow_4 + + + + + + SequenceFlow_9 + SequenceFlow_2 + + + + + SequenceFlow_9 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/bpmn/MSOCommonBPMN/src/main/webapp/WEB-INF/jboss-deployment-structure.xml b/bpmn/MSOCommonBPMN/src/main/webapp/WEB-INF/jboss-deployment-structure.xml index 130f95e171..3dbfcce36f 100644 --- a/bpmn/MSOCommonBPMN/src/main/webapp/WEB-INF/jboss-deployment-structure.xml +++ b/bpmn/MSOCommonBPMN/src/main/webapp/WEB-INF/jboss-deployment-structure.xml @@ -1,31 +1,31 @@ - - - - - - - - - - - - - + + + + + + + + + + + + + diff --git a/bpmn/MSOCommonBPMN/src/main/webapp/WEB-INF/jboss-web.xml b/bpmn/MSOCommonBPMN/src/main/webapp/WEB-INF/jboss-web.xml index f15ade0a70..a9a263b684 100644 --- a/bpmn/MSOCommonBPMN/src/main/webapp/WEB-INF/jboss-web.xml +++ b/bpmn/MSOCommonBPMN/src/main/webapp/WEB-INF/jboss-web.xml @@ -1,26 +1,26 @@ - - - - - - other - /mso/common - + + + + + + other + /mso/common + diff --git a/bpmn/MSOCommonBPMN/src/main/webapp/WEB-INF/web.xml b/bpmn/MSOCommonBPMN/src/main/webapp/WEB-INF/web.xml index 0b3e4cf10b..6c822a9be5 100644 --- a/bpmn/MSOCommonBPMN/src/main/webapp/WEB-INF/web.xml +++ b/bpmn/MSOCommonBPMN/src/main/webapp/WEB-INF/web.xml @@ -1,74 +1,74 @@ - - - - MSO Common BPMN Workflow Servlet - - resteasy-servlet - org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher - - javax.ws.rs.Application - org.openecomp.mso.bpmn.common.workflow.service.WorkflowResourceApplication - - - - resteasy-servlet - /* - - - mso.configuration - MSO_PROP_TOPOLOGY=topology.properties - - - log.configuration - logback.bpmn.xml - - - resteasy.resources - org.openecomp.mso.logger.MsoLoggingServlet,org.openecomp.mso.bpmn.core.HealthCheckHandler - - - LogFilter - org.openecomp.mso.logger.LogFilter - - - LogFilter - /* - - - - HTTPBasicAuth - Authentication for Client Apps - /workflow/* - GET - POST - - - BPMN-Client - - - - BASIC - ApplicationRealm - - - BPMN-Client - + + + + MSO Common BPMN Workflow Servlet + + resteasy-servlet + org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher + + javax.ws.rs.Application + org.openecomp.mso.bpmn.common.workflow.service.WorkflowResourceApplication + + + + resteasy-servlet + /* + + + mso.configuration + MSO_PROP_TOPOLOGY=topology.properties + + + log.configuration + logback.bpmn.xml + + + resteasy.resources + org.openecomp.mso.logger.MsoLoggingServlet,org.openecomp.mso.bpmn.core.HealthCheckHandler + + + LogFilter + org.openecomp.mso.logger.LogFilter + + + LogFilter + /* + + + + HTTPBasicAuth + Authentication for Client Apps + /workflow/* + GET + POST + + + BPMN-Client + + + + BASIC + ApplicationRealm + + + BPMN-Client + \ No newline at end of file diff --git a/bpmn/MSOCommonBPMN/src/test/groovy/org/openecomp/mso/bpmn/common/scripts/AaiUtilTest.groovy b/bpmn/MSOCommonBPMN/src/test/groovy/org/openecomp/mso/bpmn/common/scripts/AaiUtilTest.groovy index 7d698f8916..914725ca1f 100644 --- a/bpmn/MSOCommonBPMN/src/test/groovy/org/openecomp/mso/bpmn/common/scripts/AaiUtilTest.groovy +++ b/bpmn/MSOCommonBPMN/src/test/groovy/org/openecomp/mso/bpmn/common/scripts/AaiUtilTest.groovy @@ -1,318 +1,306 @@ -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - MSO - * ================================================================================ - * 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.openecomp.mso.bpmn.common.scripts; - -import static org.junit.Assert.*; -import static org.mockito.Mockito.* - -import org.openecomp.mso.rest.HttpHeader -import org.mockito.MockitoAnnotations -import org.mockito.runners.MockitoJUnitRunner -import org.mockito.internal.debugging.MockitoDebuggerImpl -import org.junit.Before -import org.openecomp.mso.bpmn.common.scripts.AaiUtil; -import org.junit.Rule; -import org.junit.Test -import org.junit.Ignore -import org.junit.runner.RunWith -import org.junit.Before; -import org.junit.Test; -import org.camunda.bpm.engine.ProcessEngineServices -import org.camunda.bpm.engine.RepositoryService -import org.camunda.bpm.engine.impl.persistence.entity.ExecutionEntity -import org.camunda.bpm.engine.impl.pvm.process.ProcessDefinitionImpl -import org.camunda.bpm.engine.repository.ProcessDefinition - -@RunWith(MockitoJUnitRunner.class) -class AaiUtilTest extends MsoGroovyTest { - - @Test - public void testGetVersionDefault() { - ExecutionEntity mockExecution = setupMock('CreateAAIVfModule') - when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn('true') - when(mockExecution.getVariable("URN_mso_workflow_global_default_aai_version")).thenReturn('8') - CreateAAIVfModule myproc = new CreateAAIVfModule() - AaiUtil aaiUtil = new AaiUtil(myproc) - def version = aaiUtil.getVersion(mockExecution, 'l3-network', 'CreateAAIVfModule') - assertEquals('8', version) - } - - @Test - public void testGetVersionResourceSpecific() { - ExecutionEntity mockExecution = setupMock('CreateAAIVfModule') - when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn('true') - when(mockExecution.getVariable("URN_mso_workflow_default_aai_l3_network_version")).thenReturn('7') - when(mockExecution.getVariable("URN_mso_workflow_global_default_aai_version")).thenReturn('8') - CreateAAIVfModule myproc = new CreateAAIVfModule() - AaiUtil aaiUtil = new AaiUtil(myproc) - def version = aaiUtil.getVersion(mockExecution, 'l3-network', 'CreateAAIVfModule') - assertEquals('7', version) - } - - @Test - public void testGetVersionFlowSpecific() { - ExecutionEntity mockExecution = setupMock('CreateAAIVfModule') - when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn('true') - when(mockExecution.getVariable("URN_mso_workflow_custom_CreateAAIVfModule_aai_version")).thenReturn('6') - when(mockExecution.getVariable("URN_mso_workflow_default_aai_l3_network_version")).thenReturn('7') - when(mockExecution.getVariable("URN_mso_workflow_global_default_aai_version")).thenReturn('8') - CreateAAIVfModule myproc = new CreateAAIVfModule() - AaiUtil aaiUtil = new AaiUtil(myproc) - def version = aaiUtil.getVersion(mockExecution, 'l3-network', 'CreateAAIVfModule') - assertEquals('6', version) - } - - @Test(expected=java.lang.Exception.class) - public void testGetVersionNotDefined() { - ExecutionEntity mockExecution = setupMock('CreateAAIVfModule') - when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn('true') - CreateAAIVfModule myproc = new CreateAAIVfModule() - AaiUtil aaiUtil = new AaiUtil(myproc) - def version = aaiUtil.getVersion(mockExecution, 'l3-network', 'CreateAAIVfModule') - } - - @Test - public void testGetUriDefaultVersion() { - ExecutionEntity mockExecution = setupMock('CreateAAIVfModule') - when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn('true') - when(mockExecution.getVariable("URN_mso_workflow_default_aai_v8_l3_network_uri")).thenReturn('/aai/v8/network/l3-networks/l3-network') - when(mockExecution.getVariable("URN_mso_workflow_global_default_aai_version")).thenReturn('8') - - CreateAAIVfModule myproc = new CreateAAIVfModule() - AaiUtil aaiUtil = new AaiUtil(myproc) - def uri = aaiUtil.getUri(mockExecution, 'l3-network') - assertEquals('/aai/v8/network/l3-networks/l3-network', uri) - } - - @Test - public void testGetUriFlowAndResourceSpecific() { - ExecutionEntity mockExecution = setupMock('CreateAAIVfModule') - when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn('true') - when(mockExecution.getVariable("URN_mso_workflow_CreateAAIVfModule_aai_l3_network_uri")).thenReturn('/aai/v6/network/l3-networks/l3-network') - when(mockExecution.getVariable("URN_mso_workflow_default_aai_v8_l3_network_uri")).thenReturn('/aai/v8/network/l3-networks/l3-network') - when(mockExecution.getVariable("URN_mso_workflow_global_default_aai_version")).thenReturn('8') - - CreateAAIVfModule myproc = new CreateAAIVfModule() - AaiUtil aaiUtil = new AaiUtil(myproc) - def uri = aaiUtil.getUri(mockExecution, 'l3-network') - assertEquals('/aai/v6/network/l3-networks/l3-network', uri) - } - - @Test - public void testGetNetworkGenericVnfEndpoint() { - ExecutionEntity mockExecution = setupMock('CreateAAIVfModule') - when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn('true') - when(mockExecution.getVariable("URN_mso_workflow_global_default_aai_version")).thenReturn('8') - when(mockExecution.getVariable("URN_mso_workflow_default_aai_v8_generic_vnf_uri")).thenReturn('/aai/v8/network/generic-vnfs/generic-vnf') - when(mockExecution.getVariable('URN_aai_endpoint')).thenReturn('http://localhost:28090') - - CreateAAIVfModule myproc = new CreateAAIVfModule() - AaiUtil aaiUtil = new AaiUtil(myproc) - def endpoint = aaiUtil.getNetworkGenericVnfEndpoint(mockExecution) - assertEquals('http://localhost:28090/aai/v8/network/generic-vnfs/generic-vnf', endpoint) - } - - @Test - public void testGetNetworkGenericVnfUri() { - ExecutionEntity mockExecution = setupMock('CreateAAIVfModule') - when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn('true') - when(mockExecution.getVariable("URN_mso_workflow_global_default_aai_version")).thenReturn('8') - when(mockExecution.getVariable("URN_mso_workflow_default_aai_v8_generic_vnf_uri")).thenReturn('/aai/v8/network/generic-vnfs/generic-vnf') - - CreateAAIVfModule myproc = new CreateAAIVfModule() - AaiUtil aaiUtil = new AaiUtil(myproc) - def uri = aaiUtil.getNetworkGenericVnfUri(mockExecution) - assertEquals('/aai/v8/network/generic-vnfs/generic-vnf', uri) - } - - @Test - public void testGetNetworkVpnBindingUri() { - ExecutionEntity mockExecution = setupMock('CreateAAIVfModule') - when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn('true') - when(mockExecution.getVariable("URN_mso_workflow_global_default_aai_version")).thenReturn('8') - when(mockExecution.getVariable("URN_mso_workflow_default_aai_v8_vpn_binding_uri")).thenReturn('/aai/v8/network/vpn-bindings/vpn-binding') - - CreateAAIVfModule myproc = new CreateAAIVfModule() - AaiUtil aaiUtil = new AaiUtil(myproc) - def uri = aaiUtil.getNetworkVpnBindingUri(mockExecution) - assertEquals('/aai/v8/network/vpn-bindings/vpn-binding', uri) - } - - @Test - public void testGetNetworkPolicyUri() { - ExecutionEntity mockExecution = setupMock('CreateAAIVfModule') - when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn('true') - when(mockExecution.getVariable("URN_mso_workflow_global_default_aai_version")).thenReturn('8') - when(mockExecution.getVariable("URN_mso_workflow_default_aai_v8_network_policy_uri")).thenReturn('/aai/v8/network/network-policies/network-policy') - - CreateAAIVfModule myproc = new CreateAAIVfModule() - AaiUtil aaiUtil = new AaiUtil(myproc) - def uri = aaiUtil.getNetworkPolicyUri(mockExecution) - assertEquals('/aai/v8/network/network-policies/network-policy', uri) - } - - @Test - public void testGetNetworkTableReferencesUri() { - ExecutionEntity mockExecution = setupMock('CreateAAIVfModule') - when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn('true') - when(mockExecution.getVariable("URN_mso_workflow_global_default_aai_version")).thenReturn('8') - when(mockExecution.getVariable("URN_mso_workflow_default_aai_v8_route_table_reference_uri")).thenReturn('/aai/v8/network/route-table-references/route-table-reference') - - CreateAAIVfModule myproc = new CreateAAIVfModule() - AaiUtil aaiUtil = new AaiUtil(myproc) - def uri = aaiUtil.getNetworkTableReferencesUri(mockExecution) - assertEquals('/aai/v8/network/route-table-references/route-table-reference', uri) - } - - @Test - public void testGetNetworkVceUri() { - ExecutionEntity mockExecution = setupMock('CreateAAIVfModule') - when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn('true') - when(mockExecution.getVariable("URN_mso_workflow_global_default_aai_version")).thenReturn('8') - when(mockExecution.getVariable("URN_mso_workflow_default_aai_v8_vce_uri")).thenReturn('/aai/v8/network/vces/vce') - - CreateAAIVfModule myproc = new CreateAAIVfModule() - AaiUtil aaiUtil = new AaiUtil(myproc) - def uri = aaiUtil.getNetworkVceUri(mockExecution) - assertEquals('/aai/v8/network/vces/vce', uri) - } - - @Test - public void testGetNetworkL3NetworkUri() { - ExecutionEntity mockExecution = setupMock('CreateAAIVfModule') - when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn('true') - when(mockExecution.getVariable("URN_mso_workflow_global_default_aai_version")).thenReturn('8') - when(mockExecution.getVariable("URN_mso_workflow_default_aai_v8_l3_network_uri")).thenReturn('/aai/v8/network/l3-networks/l3-network') - CreateAAIVfModule myproc = new CreateAAIVfModule() - AaiUtil aaiUtil = new AaiUtil(myproc) - def uri = aaiUtil.getNetworkL3NetworkUri(mockExecution) - assertEquals('/aai/v8/network/l3-networks/l3-network', uri) - } - - @Test - public void testGetBusinessCustomerUri() { - ExecutionEntity mockExecution = setupMock('CreateAAIVfModule') - when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn('true') - when(mockExecution.getVariable("URN_mso_workflow_global_default_aai_version")).thenReturn('8') - when(mockExecution.getVariable("URN_mso_workflow_default_aai_v8_customer_uri")).thenReturn('/aai/v8/business/customers/customer') - CreateAAIVfModule myproc = new CreateAAIVfModule() - AaiUtil aaiUtil = new AaiUtil(myproc) - def uri = aaiUtil.getBusinessCustomerUri(mockExecution) - assertEquals('/aai/v8/business/customers/customer', uri) - } - - @Test - public void testGetCloudInfrastructureCloudRegionEndpoint() { - ExecutionEntity mockExecution = setupMock('CreateAAIVfModule') - when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn('true') - when(mockExecution.getVariable("URN_mso_workflow_global_default_aai_version")).thenReturn('8') - when(mockExecution.getVariable("URN_mso_workflow_default_aai_v8_cloud_region_uri")).thenReturn('/aai/v8/cloud-infrastructure/cloud-regions/cloud-region/att-aic') - when(mockExecution.getVariable('URN_aai_endpoint')).thenReturn('http://localhost:28090') - CreateAAIVfModule myproc = new CreateAAIVfModule() - AaiUtil aaiUtil = new AaiUtil(myproc) - def uri = aaiUtil.getCloudInfrastructureCloudRegionEndpoint(mockExecution) - assertEquals('http://localhost:28090/aai/v8/cloud-infrastructure/cloud-regions/cloud-region/att-aic', uri) - } - - @Test - public void testGetCloudInfrastructureCloudRegionUri() { - ExecutionEntity mockExecution = setupMock('CreateAAIVfModule') - when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn('true') - when(mockExecution.getVariable("URN_mso_workflow_global_default_aai_version")).thenReturn('8') - when(mockExecution.getVariable("URN_mso_workflow_default_aai_v8_cloud_region_uri")).thenReturn('/aai/v8/cloud-infrastructure/cloud-regions/cloud-region/att-aic') - CreateAAIVfModule myproc = new CreateAAIVfModule() - AaiUtil aaiUtil = new AaiUtil(myproc) - def uri = aaiUtil.getCloudInfrastructureCloudRegionUri(mockExecution) - assertEquals('/aai/v8/cloud-infrastructure/cloud-regions/cloud-region/att-aic', uri) - } - - @Test - public void testGetCloudInfrastructureVolumeGroupUri() { - ExecutionEntity mockExecution = setupMock('CreateAAIVfModule') - when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn('true') - when(mockExecution.getVariable("URN_mso_workflow_global_default_aai_version")).thenReturn('8') - when(mockExecution.getVariable("URN_mso_workflow_default_aai_v8_volume_group_uri")).thenReturn('/aai/v8/cloud-infrastructure/volume-groups/volume-group') - CreateAAIVfModule myproc = new CreateAAIVfModule() - AaiUtil aaiUtil = new AaiUtil(myproc) - def uri = aaiUtil.getCloudInfrastructureVolumeGroupUri(mockExecution) - assertEquals('/aai/v8/cloud-infrastructure/volume-groups/volume-group', uri) - } - - @Test - public void testGetCloudInfrastructureTenantUri() { - ExecutionEntity mockExecution = setupMock('CreateAAIVfModule') - when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn('true') - when(mockExecution.getVariable("URN_mso_workflow_global_default_aai_version")).thenReturn('8') - when(mockExecution.getVariable("URN_mso_workflow_default_aai_v8_tenant_uri")).thenReturn('/aai/v8/cloud-infrastructure/tenants/tenant') - CreateAAIVfModule myproc = new CreateAAIVfModule() - AaiUtil aaiUtil = new AaiUtil(myproc) - def uri = aaiUtil.getCloudInfrastructureTenantUri(mockExecution) - assertEquals('/aai/v8/cloud-infrastructure/tenants/tenant', uri) - } - - @Test - public void testGetSearchNodesQueryUri() { - ExecutionEntity mockExecution = setupMock('CreateAAIVfModule') - when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn('true') - when(mockExecution.getVariable("URN_mso_workflow_global_default_aai_version")).thenReturn('8') - when(mockExecution.getVariable("URN_mso_workflow_default_aai_v8_nodes_query_uri")).thenReturn('/aai/v8/search/nodes-query') - CreateAAIVfModule myproc = new CreateAAIVfModule() - AaiUtil aaiUtil = new AaiUtil(myproc) - def uri = aaiUtil.getSearchNodesQueryUri(mockExecution) - assertEquals('/aai/v8/search/nodes-query', uri) - } - - @Test - public void testGetSearchNodesQueryEndpoint() { - ExecutionEntity mockExecution = setupMock('CreateAAIVfModule') - when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn('true') - when(mockExecution.getVariable("URN_mso_workflow_global_default_aai_version")).thenReturn('8') - when(mockExecution.getVariable("URN_mso_workflow_default_aai_v8_nodes_query_uri")).thenReturn('/aai/v8/search/nodes-query') - when(mockExecution.getVariable('URN_aai_endpoint')).thenReturn('http://localhost:28090') - CreateAAIVfModule myproc = new CreateAAIVfModule() - AaiUtil aaiUtil = new AaiUtil(myproc) - def uri = aaiUtil.getSearchNodesQueryEndpoint(mockExecution) - assertEquals('http://localhost:28090/aai/v8/search/nodes-query', uri) - } - - @Test - public void testGetSearchGenericQueryUri() { - ExecutionEntity mockExecution = setupMock('CreateAAIVfModule') - when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn('true') - when(mockExecution.getVariable("URN_mso_workflow_global_default_aai_version")).thenReturn('8') - when(mockExecution.getVariable("URN_mso_workflow_default_aai_v8_generic_query_uri")).thenReturn('/aai/v8/search/generic-query') - CreateAAIVfModule myproc = new CreateAAIVfModule() - AaiUtil aaiUtil = new AaiUtil(myproc) - def uri = aaiUtil.getSearchGenericQueryUri(mockExecution) - assertEquals('/aai/v8/search/generic-query', uri) - } - - @Test - public void testGetNamespaceFromUri() { - ExecutionEntity mockExecution = setupMock('CreateAAIVfModule') - when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn('true') - CreateAAIVfModule myproc = new CreateAAIVfModule() - AaiUtil aaiUtil = new AaiUtil(myproc) - def ns = aaiUtil.getNamespaceFromUri('/aai/v6/search/generic-query') - assertEquals('http://org.openecomp.aai.inventory/v6', ns) - } - -} +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.bpmn.common.scripts; + +import static org.junit.Assert.*; +import static org.mockito.Mockito.* + +import org.openecomp.mso.rest.HttpHeader +import org.mockito.MockitoAnnotations +import org.mockito.runners.MockitoJUnitRunner +import org.mockito.internal.debugging.MockitoDebuggerImpl +import org.junit.Before +import org.openecomp.mso.bpmn.common.scripts.AaiUtil; +import org.junit.Rule; +import org.junit.Test +import org.junit.Ignore +import org.junit.runner.RunWith +import org.junit.Before; +import org.junit.Test; +import org.camunda.bpm.engine.ProcessEngineServices +import org.camunda.bpm.engine.RepositoryService +import org.camunda.bpm.engine.impl.persistence.entity.ExecutionEntity +import org.camunda.bpm.engine.impl.pvm.process.ProcessDefinitionImpl +import org.camunda.bpm.engine.repository.ProcessDefinition + +@RunWith(MockitoJUnitRunner.class) +class AaiUtilTest extends MsoGroovyTest { + + @Test + public void testGetVersionDefault() { + ExecutionEntity mockExecution = setupMock('CreateAAIVfModule') + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn('true') + when(mockExecution.getVariable("URN_mso_workflow_global_default_aai_version")).thenReturn('8') + CreateAAIVfModule myproc = new CreateAAIVfModule() + AaiUtil aaiUtil = new AaiUtil(myproc) + def version = aaiUtil.getVersion(mockExecution, 'l3-network', 'CreateAAIVfModule') + assertEquals('8', version) + } + + @Test + public void testGetVersionResourceSpecific() { + ExecutionEntity mockExecution = setupMock('CreateAAIVfModule') + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn('true') + when(mockExecution.getVariable("URN_mso_workflow_default_aai_l3_network_version")).thenReturn('7') + when(mockExecution.getVariable("URN_mso_workflow_global_default_aai_version")).thenReturn('8') + CreateAAIVfModule myproc = new CreateAAIVfModule() + AaiUtil aaiUtil = new AaiUtil(myproc) + def version = aaiUtil.getVersion(mockExecution, 'l3-network', 'CreateAAIVfModule') + assertEquals('7', version) + } + + @Test + public void testGetVersionFlowSpecific() { + ExecutionEntity mockExecution = setupMock('CreateAAIVfModule') + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn('true') + when(mockExecution.getVariable("URN_mso_workflow_custom_CreateAAIVfModule_aai_version")).thenReturn('6') + when(mockExecution.getVariable("URN_mso_workflow_default_aai_l3_network_version")).thenReturn('7') + when(mockExecution.getVariable("URN_mso_workflow_global_default_aai_version")).thenReturn('8') + CreateAAIVfModule myproc = new CreateAAIVfModule() + AaiUtil aaiUtil = new AaiUtil(myproc) + def version = aaiUtil.getVersion(mockExecution, 'l3-network', 'CreateAAIVfModule') + assertEquals('6', version) + } + + @Test(expected=java.lang.Exception.class) + public void testGetVersionNotDefined() { + ExecutionEntity mockExecution = setupMock('CreateAAIVfModule') + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn('true') + CreateAAIVfModule myproc = new CreateAAIVfModule() + AaiUtil aaiUtil = new AaiUtil(myproc) + def version = aaiUtil.getVersion(mockExecution, 'l3-network', 'CreateAAIVfModule') + } + + @Test + public void testGetUriDefaultVersion() { + ExecutionEntity mockExecution = setupMock('CreateAAIVfModule') + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn('true') + when(mockExecution.getVariable("URN_mso_workflow_default_aai_v8_l3_network_uri")).thenReturn('/aai/v8/network/l3-networks/l3-network') + when(mockExecution.getVariable("URN_mso_workflow_global_default_aai_version")).thenReturn('8') + + CreateAAIVfModule myproc = new CreateAAIVfModule() + AaiUtil aaiUtil = new AaiUtil(myproc) + def uri = aaiUtil.getUri(mockExecution, 'l3-network') + assertEquals('/aai/v8/network/l3-networks/l3-network', uri) + } + + @Test + public void testGetUriFlowAndResourceSpecific() { + ExecutionEntity mockExecution = setupMock('CreateAAIVfModule') + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn('true') + when(mockExecution.getVariable("URN_mso_workflow_CreateAAIVfModule_aai_l3_network_uri")).thenReturn('/aai/v6/network/l3-networks/l3-network') + when(mockExecution.getVariable("URN_mso_workflow_default_aai_v8_l3_network_uri")).thenReturn('/aai/v8/network/l3-networks/l3-network') + when(mockExecution.getVariable("URN_mso_workflow_global_default_aai_version")).thenReturn('8') + + CreateAAIVfModule myproc = new CreateAAIVfModule() + AaiUtil aaiUtil = new AaiUtil(myproc) + def uri = aaiUtil.getUri(mockExecution, 'l3-network') + assertEquals('/aai/v6/network/l3-networks/l3-network', uri) + } + + @Test + public void testGetNetworkGenericVnfEndpoint() { + ExecutionEntity mockExecution = setupMock('CreateAAIVfModule') + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn('true') + when(mockExecution.getVariable("URN_mso_workflow_global_default_aai_version")).thenReturn('8') + when(mockExecution.getVariable("URN_mso_workflow_default_aai_v8_generic_vnf_uri")).thenReturn('/aai/v8/network/generic-vnfs/generic-vnf') + when(mockExecution.getVariable('URN_aai_endpoint')).thenReturn('http://localhost:28090') + + CreateAAIVfModule myproc = new CreateAAIVfModule() + AaiUtil aaiUtil = new AaiUtil(myproc) + def endpoint = aaiUtil.getNetworkGenericVnfEndpoint(mockExecution) + assertEquals('http://localhost:28090/aai/v8/network/generic-vnfs/generic-vnf', endpoint) + } + + @Test + public void testGetNetworkGenericVnfUri() { + ExecutionEntity mockExecution = setupMock('CreateAAIVfModule') + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn('true') + when(mockExecution.getVariable("URN_mso_workflow_global_default_aai_version")).thenReturn('8') + when(mockExecution.getVariable("URN_mso_workflow_default_aai_v8_generic_vnf_uri")).thenReturn('/aai/v8/network/generic-vnfs/generic-vnf') + + CreateAAIVfModule myproc = new CreateAAIVfModule() + AaiUtil aaiUtil = new AaiUtil(myproc) + def uri = aaiUtil.getNetworkGenericVnfUri(mockExecution) + assertEquals('/aai/v8/network/generic-vnfs/generic-vnf', uri) + } + + @Test + public void testGetNetworkVpnBindingUri() { + ExecutionEntity mockExecution = setupMock('CreateAAIVfModule') + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn('true') + when(mockExecution.getVariable("URN_mso_workflow_global_default_aai_version")).thenReturn('8') + when(mockExecution.getVariable("URN_mso_workflow_default_aai_v8_vpn_binding_uri")).thenReturn('/aai/v8/network/vpn-bindings/vpn-binding') + + CreateAAIVfModule myproc = new CreateAAIVfModule() + AaiUtil aaiUtil = new AaiUtil(myproc) + def uri = aaiUtil.getNetworkVpnBindingUri(mockExecution) + assertEquals('/aai/v8/network/vpn-bindings/vpn-binding', uri) + } + + @Test + public void testGetNetworkPolicyUri() { + ExecutionEntity mockExecution = setupMock('CreateAAIVfModule') + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn('true') + when(mockExecution.getVariable("URN_mso_workflow_global_default_aai_version")).thenReturn('8') + when(mockExecution.getVariable("URN_mso_workflow_default_aai_v8_network_policy_uri")).thenReturn('/aai/v8/network/network-policies/network-policy') + + CreateAAIVfModule myproc = new CreateAAIVfModule() + AaiUtil aaiUtil = new AaiUtil(myproc) + def uri = aaiUtil.getNetworkPolicyUri(mockExecution) + assertEquals('/aai/v8/network/network-policies/network-policy', uri) + } + + @Test + public void testGetNetworkTableReferencesUri() { + ExecutionEntity mockExecution = setupMock('CreateAAIVfModule') + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn('true') + when(mockExecution.getVariable("URN_mso_workflow_global_default_aai_version")).thenReturn('8') + when(mockExecution.getVariable("URN_mso_workflow_default_aai_v8_route_table_reference_uri")).thenReturn('/aai/v8/network/route-table-references/route-table-reference') + + CreateAAIVfModule myproc = new CreateAAIVfModule() + AaiUtil aaiUtil = new AaiUtil(myproc) + def uri = aaiUtil.getNetworkTableReferencesUri(mockExecution) + assertEquals('/aai/v8/network/route-table-references/route-table-reference', uri) + } + + @Test + public void testGetNetworkVceUri() { + ExecutionEntity mockExecution = setupMock('CreateAAIVfModule') + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn('true') + when(mockExecution.getVariable("URN_mso_workflow_global_default_aai_version")).thenReturn('8') + when(mockExecution.getVariable("URN_mso_workflow_default_aai_v8_vce_uri")).thenReturn('/aai/v8/network/vces/vce') + + CreateAAIVfModule myproc = new CreateAAIVfModule() + AaiUtil aaiUtil = new AaiUtil(myproc) + def uri = aaiUtil.getNetworkVceUri(mockExecution) + assertEquals('/aai/v8/network/vces/vce', uri) + } + + @Test + public void testGetNetworkL3NetworkUri() { + ExecutionEntity mockExecution = setupMock('CreateAAIVfModule') + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn('true') + when(mockExecution.getVariable("URN_mso_workflow_global_default_aai_version")).thenReturn('8') + when(mockExecution.getVariable("URN_mso_workflow_default_aai_v8_l3_network_uri")).thenReturn('/aai/v8/network/l3-networks/l3-network') + CreateAAIVfModule myproc = new CreateAAIVfModule() + AaiUtil aaiUtil = new AaiUtil(myproc) + def uri = aaiUtil.getNetworkL3NetworkUri(mockExecution) + assertEquals('/aai/v8/network/l3-networks/l3-network', uri) + } + + @Test + public void testGetBusinessCustomerUri() { + ExecutionEntity mockExecution = setupMock('CreateAAIVfModule') + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn('true') + when(mockExecution.getVariable("URN_mso_workflow_global_default_aai_version")).thenReturn('8') + when(mockExecution.getVariable("URN_mso_workflow_default_aai_v8_customer_uri")).thenReturn('/aai/v8/business/customers/customer') + CreateAAIVfModule myproc = new CreateAAIVfModule() + AaiUtil aaiUtil = new AaiUtil(myproc) + def uri = aaiUtil.getBusinessCustomerUri(mockExecution) + assertEquals('/aai/v8/business/customers/customer', uri) + } + + @Test + public void testGetCloudInfrastructureCloudRegionEndpoint() { + ExecutionEntity mockExecution = setupMock('CreateAAIVfModule') + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn('true') + when(mockExecution.getVariable("URN_mso_workflow_global_default_aai_version")).thenReturn('8') + when(mockExecution.getVariable("URN_mso_workflow_default_aai_v8_cloud_region_uri")).thenReturn('/aai/v8/cloud-infrastructure/cloud-regions/cloud-region/att-aic') + when(mockExecution.getVariable('URN_aai_endpoint')).thenReturn('http://localhost:28090') + CreateAAIVfModule myproc = new CreateAAIVfModule() + AaiUtil aaiUtil = new AaiUtil(myproc) + def uri = aaiUtil.getCloudInfrastructureCloudRegionEndpoint(mockExecution) + assertEquals('http://localhost:28090/aai/v8/cloud-infrastructure/cloud-regions/cloud-region/att-aic', uri) + } + + @Test + public void testGetCloudInfrastructureCloudRegionUri() { + ExecutionEntity mockExecution = setupMock('CreateAAIVfModule') + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn('true') + when(mockExecution.getVariable("URN_mso_workflow_global_default_aai_version")).thenReturn('8') + when(mockExecution.getVariable("URN_mso_workflow_default_aai_v8_cloud_region_uri")).thenReturn('/aai/v8/cloud-infrastructure/cloud-regions/cloud-region/att-aic') + CreateAAIVfModule myproc = new CreateAAIVfModule() + AaiUtil aaiUtil = new AaiUtil(myproc) + def uri = aaiUtil.getCloudInfrastructureCloudRegionUri(mockExecution) + assertEquals('/aai/v8/cloud-infrastructure/cloud-regions/cloud-region/att-aic', uri) + } + + @Test + public void testGetCloudInfrastructureTenantUri() { + ExecutionEntity mockExecution = setupMock('CreateAAIVfModule') + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn('true') + when(mockExecution.getVariable("URN_mso_workflow_global_default_aai_version")).thenReturn('8') + when(mockExecution.getVariable("URN_mso_workflow_default_aai_v8_tenant_uri")).thenReturn('/aai/v8/cloud-infrastructure/tenants/tenant') + CreateAAIVfModule myproc = new CreateAAIVfModule() + AaiUtil aaiUtil = new AaiUtil(myproc) + def uri = aaiUtil.getCloudInfrastructureTenantUri(mockExecution) + assertEquals('/aai/v8/cloud-infrastructure/tenants/tenant', uri) + } + + @Test + public void testGetSearchNodesQueryUri() { + ExecutionEntity mockExecution = setupMock('CreateAAIVfModule') + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn('true') + when(mockExecution.getVariable("URN_mso_workflow_global_default_aai_version")).thenReturn('8') + when(mockExecution.getVariable("URN_mso_workflow_default_aai_v8_nodes_query_uri")).thenReturn('/aai/v8/search/nodes-query') + CreateAAIVfModule myproc = new CreateAAIVfModule() + AaiUtil aaiUtil = new AaiUtil(myproc) + def uri = aaiUtil.getSearchNodesQueryUri(mockExecution) + assertEquals('/aai/v8/search/nodes-query', uri) + } + + @Test + public void testGetSearchNodesQueryEndpoint() { + ExecutionEntity mockExecution = setupMock('CreateAAIVfModule') + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn('true') + when(mockExecution.getVariable("URN_mso_workflow_global_default_aai_version")).thenReturn('8') + when(mockExecution.getVariable("URN_mso_workflow_default_aai_v8_nodes_query_uri")).thenReturn('/aai/v8/search/nodes-query') + when(mockExecution.getVariable('URN_aai_endpoint')).thenReturn('http://localhost:28090') + CreateAAIVfModule myproc = new CreateAAIVfModule() + AaiUtil aaiUtil = new AaiUtil(myproc) + def uri = aaiUtil.getSearchNodesQueryEndpoint(mockExecution) + assertEquals('http://localhost:28090/aai/v8/search/nodes-query', uri) + } + + @Test + public void testGetSearchGenericQueryUri() { + ExecutionEntity mockExecution = setupMock('CreateAAIVfModule') + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn('true') + when(mockExecution.getVariable("URN_mso_workflow_global_default_aai_version")).thenReturn('8') + when(mockExecution.getVariable("URN_mso_workflow_default_aai_v8_generic_query_uri")).thenReturn('/aai/v8/search/generic-query') + CreateAAIVfModule myproc = new CreateAAIVfModule() + AaiUtil aaiUtil = new AaiUtil(myproc) + def uri = aaiUtil.getSearchGenericQueryUri(mockExecution) + assertEquals('/aai/v8/search/generic-query', uri) + } + + @Test + public void testGetNamespaceFromUri() { + ExecutionEntity mockExecution = setupMock('CreateAAIVfModule') + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn('true') + CreateAAIVfModule myproc = new CreateAAIVfModule() + AaiUtil aaiUtil = new AaiUtil(myproc) + def ns = aaiUtil.getNamespaceFromUri('/aai/v6/search/generic-query') + assertEquals('http://org.openecomp.aai.inventory/v6', ns) + } + +} diff --git a/bpmn/MSOCommonBPMN/src/test/groovy/org/openecomp/mso/bpmn/common/scripts/ExceptionUtilTest.groovy b/bpmn/MSOCommonBPMN/src/test/groovy/org/openecomp/mso/bpmn/common/scripts/ExceptionUtilTest.groovy index 98bbe7181e..a011ebb335 100644 --- a/bpmn/MSOCommonBPMN/src/test/groovy/org/openecomp/mso/bpmn/common/scripts/ExceptionUtilTest.groovy +++ b/bpmn/MSOCommonBPMN/src/test/groovy/org/openecomp/mso/bpmn/common/scripts/ExceptionUtilTest.groovy @@ -1,190 +1,66 @@ -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - MSO - * ================================================================================ - * 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.openecomp.mso.bpmn.common.scripts - -import org.junit.Assert -import org.junit.runner.RunWith; -import org.mockito.runners.MockitoJUnitRunner; - - -import org.junit.Ignore; - -import static org.mockito.Mockito.* - -import org.camunda.bpm.engine.impl.persistence.entity.ExecutionEntity -import org.junit.Before -import org.junit.runner.RunWith -import org.mockito.MockitoAnnotations -import org.mockito.internal.debugging.MockitoDebuggerImpl -import org.mockito.runners.MockitoJUnitRunner -import org.openecomp.mso.bpmn.common.scripts.ExceptionUtil; -@RunWith(MockitoJUnitRunner.class) -import org.junit.Test - - - -class ExceptionUtilTest { - - - @Before - public void init() - { - MockitoAnnotations.initMocks(this) - } - - @Test - public void testErrorMessageDetails() { - - - - String restFault = """ - - - -SVC3002 -Error writing output performing %1 on %2 (msg=%3) (ec=%4) - -PUTcustomer -SubName01 -Unexpected error reading/updating database:Adding this property for key [service-instance-id] and value [USSTU2CFCNC0101UJZZ01] violates a uniqueness constraint [service-instance-id] -ERR.5.4.5105 - - - - - """ - def errorString = """ - Received error from A&AI (Error writing output performing PUTcustomer on SubName01 (msg=Unexpected error reading/updating database:Adding this property for key [service-instance-id] and value [USSTU2CFCNC0101UJZZ01] violates a uniqueness constraint [service-instance-id]) (ec=ERR.5.4.5105)) - 5000 - """ as String - - ExecutionEntity mockExecution = mock(ExecutionEntity.class) - - ExceptionUtil util = new ExceptionUtil() - Assert.assertEquals(errorString, util.MapAAIExceptionToWorkflowExceptionOld(restFault, mockExecution)) - } - - - @Test - public void testErrorMessage() { - String restFault = """ - - 500 - HTTP method: GET Internal Server Error - - """ - def errorString = """ - Received error from A&AI (HTTP method: GET Internal Server Error) - 5000 - """ as String - - ExecutionEntity mockExecution = mock(ExecutionEntity.class) - when(mockExecution.getVariable("prefix")).thenReturn("test_") - when(mockExecution.getVariable("test_ErrorResponse")).thenReturn("HTTP method: GET Internal Server Error") - - ExceptionUtil util = new ExceptionUtil() - String msg = "HTTP method: GET Internal Server Error" - Assert.assertEquals(errorString, util.MapAAIExceptionToWorkflowExceptionOld(restFault, mockExecution)) - } - - @Test - public void testBadResponseErrorMessage() { - String restFault = "asfafasfasfd" - ExecutionEntity mockExecution = mock(ExecutionEntity.class) - when(mockExecution.getVariable("prefix")).thenReturn("test_") - when(mockExecution.getVariable("test_ErrorResponse")).thenReturn(null) - ExceptionUtil util = new ExceptionUtil() - String expected = ""+ - "\n Received error from A&AI ()"+ - "\n 5000"+ - "\n "; - Assert.assertEquals(expected,util.MapAAIExceptionToWorkflowExceptionOld(restFault, mockExecution)) - } - - @Test - public void testMapErrorCode5010(){ - String msg = "Connect to njcdtl20ew2988:8070 failed: Connection refused: connect" - ExceptionUtil util = new ExceptionUtil() - Assert.assertEquals("5010",util.MapErrorCode(msg)) - } - - @Test - public void testMapErrorCode5020(){ - String msg = "Connection timed out" - ExceptionUtil util = new ExceptionUtil() - Assert.assertEquals("5020",util.MapErrorCode(msg)) - } - - @Test - public void testMapCategoryToErrorCode5100 () { - String errorCategory = "OPENSTACK" - ExceptionUtil util = new ExceptionUtil() - Assert.assertEquals('5100', util.MapCategoryToErrorCode(errorCategory)) - } - - @Test - public void testMapCategoryToErrorCode5110 () { - String errorCategory = "IO" - ExceptionUtil util = new ExceptionUtil() - Assert.assertEquals('5110', util.MapCategoryToErrorCode(errorCategory)) - } - - @Test - public void testMapCategoryToErrorCode7020 () { - String errorCategory = "USERDATA" - ExceptionUtil util = new ExceptionUtil() - Assert.assertEquals('7020', util.MapCategoryToErrorCode(errorCategory)) - } - - @Test - @Ignore - public void testMapAdapterExecptionToWorkflowException_UserDataErrorMessage () { - String response = """USERDATACloud Site [CHCGILNE001] not found""" as String - String expected = """WorkflowException[processKey=ExceptionUtil,errorCode=7020,errorMessage=Received error from Tenant Adapter: Cloud Site [CHCGILNE001] not found]""" as String - - ExecutionEntity mockExecution = mock(ExecutionEntity.class) - when(mockExecution.getVariable("prefix")).thenReturn("test_") - when(mockExecution.getVariable("testProcessKey")).thenReturn("ExceptionUtil") - - ExceptionUtil util = new ExceptionUtil() - String actual = util.MapAdapterExecptionToWorkflowException(response, mockExecution, "Tenant Adapter") - - verify(mockExecution).setVariable("WorkflowException",expected) - } - - @Test - @Ignore - public void testMapAdapterExecptionToWorkflowException_IOErrorMessage () { - String response = """IO[TokenAuth] Connect to test.aic.cip.att.com:5000 [test.aic.cip.att.com/300.200.100.100] failed: Connection refused""" as String - String expected = """WorkflowException[processKey=ExceptionUtil,errorCode=5110,errorMessage=Could not communicate with Platform Orchestrator]""" as String - - ExecutionEntity mockExecution = mock(ExecutionEntity.class) - when(mockExecution.getVariable("prefix")).thenReturn("test_") - when(mockExecution.getVariable("testProcessKey")).thenReturn("ExceptionUtil") - - ExceptionUtil util = new ExceptionUtil() - String actual = util.MapAdapterExecptionToWorkflowException(response, mockExecution, "Tenant Adapter") - - verify(mockExecution).setVariable("WorkflowException",expected) - } - -} +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.bpmn.common.scripts + +import org.junit.Assert +import org.junit.runner.RunWith; +import org.mockito.runners.MockitoJUnitRunner; + + +import org.junit.Ignore; + +import static org.mockito.Mockito.* + +import org.camunda.bpm.engine.impl.persistence.entity.ExecutionEntity +import org.junit.Before +import org.junit.runner.RunWith +import org.mockito.MockitoAnnotations +import org.mockito.internal.debugging.MockitoDebuggerImpl +import org.mockito.runners.MockitoJUnitRunner +import org.openecomp.mso.bpmn.common.scripts.ExceptionUtil; +@RunWith(MockitoJUnitRunner.class) +import org.junit.Test + + + +class ExceptionUtilTest { + + + @Before + public void init() + { + MockitoAnnotations.initMocks(this) + } + + @Test + public void testMapErrorCode5010(){ + String msg = "Connect to njcdtl20ew2988:8070 failed: Connection refused: connect" + ExceptionUtil util = new ExceptionUtil() + Assert.assertEquals("5010",util.MapErrorCode(msg)) + } + + @Test + public void testMapErrorCode5020(){ + String msg = "Connection timed out" + ExceptionUtil util = new ExceptionUtil() + Assert.assertEquals("5020",util.MapErrorCode(msg)) + } +} diff --git a/bpmn/MSOCommonBPMN/src/test/groovy/org/openecomp/mso/bpmn/common/scripts/FalloutHandlerTest.groovy b/bpmn/MSOCommonBPMN/src/test/groovy/org/openecomp/mso/bpmn/common/scripts/FalloutHandlerTest.groovy index 7f691ca1b8..fcc55d0933 100644 --- a/bpmn/MSOCommonBPMN/src/test/groovy/org/openecomp/mso/bpmn/common/scripts/FalloutHandlerTest.groovy +++ b/bpmn/MSOCommonBPMN/src/test/groovy/org/openecomp/mso/bpmn/common/scripts/FalloutHandlerTest.groovy @@ -1,311 +1,311 @@ -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - MSO - * ================================================================================ - * 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.openecomp.mso.bpmn.common.scripts - -import org.junit.runner.RunWith; -import static org.mockito.Mockito.* -import static org.junit.Assert.*; - -import org.camunda.bpm.engine.impl.persistence.entity.ExecutionEntity -import org.junit.Before -import org.junit.Test -import org.junit.runner.RunWith -import org.mockito.ArgumentCaptor; -import org.mockito.MockitoAnnotations -import org.mockito.runners.MockitoJUnitRunner -import org.openecomp.mso.bpmn.common.scripts.MsoUtils; -import org.openecomp.mso.bpmn.common.scripts.FalloutHandler; - -@RunWith(MockitoJUnitRunner.class) -class FalloutHandlerTest { - - public MsoUtils utils = new MsoUtils() - - @Before - public void init() { - MockitoAnnotations.initMocks(this) - } - - private String falloutHandlerRequest = """ - - - uCPE1020_STUW105_5002 - Layer3ServiceActivateRequest - CANCEL - OMX - 10205000 - 1 - - - Some Error Message - Fallout Handler - Some Error Code - Fallout Handler - Some Source System Error Code- Fallout Handler - - - """ - - private String falloutHandlerResponse = """ - Fallout Handler Failed -""" - - @Test - public void testPreProcessRequest() { - - ExecutionEntity mockExecution = mock(ExecutionEntity.class) - - when(mockExecution.getVariable("FalloutHandlerRequest")).thenReturn(falloutHandlerRequest) - when(mockExecution.getVariable("URN_mso_adapters_db_auth")).thenReturn("757A94191D685FD2092AC1490730A4FC"); - when(mockExecution.getVariable("URN_mso_msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7"); - - FalloutHandler falloutHandler = new FalloutHandler() - falloutHandler.preProcessRequest(mockExecution) - - /* Initialize all the process request variables in this block */ - verify(mockExecution).setVariable("prefix","FH_") - //verify(mockExecution).setVariable("getLayer3ServiceDetailsV1Response","") - - //These variables are form the input Message to the BPMN - verify(mockExecution).setVariable("FH_request_id","") - verify(mockExecution).setVariable("FH_request_action","") - verify(mockExecution).setVariable("FH_notification-url","") - verify(mockExecution).setVariable("FH_mso-bpel-name","") - verify(mockExecution).setVariable("FH_ErrorCode", "") - verify(mockExecution).setVariable("FH_ErrorMessage", "") - - verify(mockExecution).setVariable("FH_notification-url-Ok", false) - verify(mockExecution).setVariable("FH_request_id-Ok", false) - - //These variables are for Get Mso Aai Password Adapter - verify(mockExecution).setVariable("FH_deliveryStatus", true) - - //update Response Status to pending ...Adapter variables - verify(mockExecution).setVariable("FH_updateResponseStatusPayload", null) - verify(mockExecution).setVariable("FH_updateResponseStatusResponse", null) - - //update Request Gamma ...Adapter variables - verify(mockExecution).setVariable("FH_updateRequestGammaPayload", "") - verify(mockExecution).setVariable("FH_updateRequestGammaResponse", null) - verify(mockExecution).setVariable("FH_updateRequestGammaResponseCode", null) - - //update Request Infra ...Adapter variables - verify(mockExecution).setVariable("FH_updateRequestInfraPayload", "") - verify(mockExecution).setVariable("FH_updateRequestInfraResponse", null) - verify(mockExecution).setVariable("FH_updateRequestInfraResponseCode", null) - - //assign False to success variable - verify(mockExecution).setVariable("FH_success", true) - - //Set notify status to Failed variable - verify(mockExecution).setVariable("FH_NOTIFY_STATUS", "SUCCESS") - - //Set DB update variable - verify(mockExecution).setVariable("FH_updateRequestPayload", "") - verify(mockExecution).setVariable("FH_updateRequestResponse", null) - verify(mockExecution).setVariable("FH_updateRequestResponseCode", null) - - //Auth variables - verify(mockExecution).setVariable("BasicAuthHeaderValue","") - - //Response variables - verify(mockExecution).setVariable("FalloutHandlerResponse","") - verify(mockExecution).setVariable("FH_ErrorResponse", null) - verify(mockExecution).setVariable("FH_ResponseCode", "") - - verify(mockExecution).setVariable("FH_request_id-Ok",true) - verify(mockExecution).setVariable("FH_request_id","uCPE1020_STUW105_5002") - verify(mockExecution).setVariable("FH_request_action","Layer3ServiceActivateRequest") - verify(mockExecution).setVariable("FH_source","OMX") - verify(mockExecution).setVariable("FH_ErrorCode","Some Error Code - Fallout Handler") - verify(mockExecution).setVariable("FH_ErrorMessage","Some Error Message - Fallout Handler") - - } - - @Test - public void testpostProcessResponse(){ - - ExecutionEntity mockExecution = mock(ExecutionEntity.class) - - when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") - when(mockExecution.getVariable("FH_success")).thenReturn(false) - - FalloutHandler falloutHandler = new FalloutHandler() - falloutHandler.postProcessResponse(mockExecution) - - // Capture the arguments to setVariable - ArgumentCaptor captor1 = ArgumentCaptor.forClass(String.class); - ArgumentCaptor captor2 = ArgumentCaptor.forClass(String.class); - - verify(mockExecution, times(4)).setVariable(captor1.capture(), captor2.capture()) - List arg2List = captor2.getAllValues() - String payloadResponseActual = arg2List.get(1) - - assertEquals(falloutHandlerResponse.replaceAll("\\s+", ""), payloadResponseActual.replaceAll("\\s+", "")) - - verify(mockExecution).setVariable("FH_ResponseCode","500") - } - - private String updateRequestPayload = """ - - - - - testReqId - BPEL - ErrorMessage - ErrorCode - FAILED - NotifyStatus - - - - """ - - @Test - public void testupdateRequestPayload(){ - - ExecutionEntity mockExecution = mock(ExecutionEntity.class) - when(mockExecution.getVariable("FH_request_id")).thenReturn("testReqId") - when(mockExecution.getVariable("FH_ErrorMessage")).thenReturn("ErrorMessage") - when(mockExecution.getVariable("FH_ErrorCode")).thenReturn("ErrorCode") - when(mockExecution.getVariable("FH_NOTIFY_STATUS")).thenReturn("NotifyStatus") - - FalloutHandler falloutHandler = new FalloutHandler() - falloutHandler.updateRequestPayload(mockExecution) - - // Capture the arguments to setVariable - ArgumentCaptor captor1 = ArgumentCaptor.forClass(String.class); - ArgumentCaptor captor2 = ArgumentCaptor.forClass(String.class); - - verify(mockExecution, times(1)).setVariable(captor1.capture(), captor2.capture()) - List arg2List = captor2.getAllValues() - String payloadRequestActual = arg2List.get(0) - - assertEquals(updateRequestPayload.replaceAll("\\s+", ""), payloadRequestActual.replaceAll("\\s+", "")) - } - - private String updateRequestInfraPayload = """ - - - - - testReqId - BPEL - ErrorMessage - FAILED - 100 - - - - """ - - @Test - public void testupdateRequestInfraPayload(){ - - ExecutionEntity mockExecution = mock(ExecutionEntity.class) - when(mockExecution.getVariable("FH_request_id")).thenReturn("testReqId") - when(mockExecution.getVariable("FH_ErrorMessage")).thenReturn("ErrorMessage") - - FalloutHandler falloutHandler = new FalloutHandler() - falloutHandler.updateRequestInfraPayload(mockExecution) - - // Capture the arguments to setVariable - ArgumentCaptor captor1 = ArgumentCaptor.forClass(String.class); - ArgumentCaptor captor2 = ArgumentCaptor.forClass(String.class); - - verify(mockExecution, times(1)).setVariable(captor1.capture(), captor2.capture()) - List arg2List = captor2.getAllValues() - String payloadRequestActual = arg2List.get(0) - - assertEquals(updateRequestInfraPayload.replaceAll("\\s+", ""), payloadRequestActual.replaceAll("\\s+", "")) - } - - private String updateRequestGammaPayload = """ - - - - - testReqId - BPEL - ErrorMessage - ErrorCode - FAILED - - - - """ - - @Test - public void testupdateRequestGammaPayload(){ - - ExecutionEntity mockExecution = mock(ExecutionEntity.class) - when(mockExecution.getVariable("FH_request_id")).thenReturn("testReqId") - when(mockExecution.getVariable("FH_ErrorMessage")).thenReturn("ErrorMessage") - when(mockExecution.getVariable("FH_ErrorCode")).thenReturn("ErrorCode") - - FalloutHandler falloutHandler = new FalloutHandler() - falloutHandler.updateRequestGammaPayload(mockExecution) - - // Capture the arguments to setVariable - ArgumentCaptor captor1 = ArgumentCaptor.forClass(String.class); - ArgumentCaptor captor2 = ArgumentCaptor.forClass(String.class); - - verify(mockExecution, times(1)).setVariable(captor1.capture(), captor2.capture()) - List arg2List = captor2.getAllValues() - String payloadRequestActual = arg2List.get(0) - - assertEquals(updateRequestGammaPayload.replaceAll("\\s+", ""), payloadRequestActual.replaceAll("\\s+", "")) - } - - - String updateResponseStatusPayload = """ - - - - - testReqId - BPEL - SENDING_FINAL_NOTIFY - - - - """ - - @Test - public void testupdateResponseStatusPayload(){ - - ExecutionEntity mockExecution = mock(ExecutionEntity.class) - when(mockExecution.getVariable("FH_request_id")).thenReturn("testReqId") - - FalloutHandler falloutHandler = new FalloutHandler() - falloutHandler.updateResponseStatusPayload(mockExecution) - - // Capture the arguments to setVariable - ArgumentCaptor captor1 = ArgumentCaptor.forClass(String.class); - ArgumentCaptor captor2 = ArgumentCaptor.forClass(String.class); - - verify(mockExecution, times(1)).setVariable(captor1.capture(), captor2.capture()) - List arg2List = captor2.getAllValues() - String payloadResponseActual = arg2List.get(0) - - assertEquals(updateResponseStatusPayload.replaceAll("\\s+", ""), payloadResponseActual.replaceAll("\\s+", "")) - } - +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.bpmn.common.scripts + +import org.junit.runner.RunWith; +import static org.mockito.Mockito.* +import static org.junit.Assert.*; + +import org.camunda.bpm.engine.impl.persistence.entity.ExecutionEntity +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.mockito.ArgumentCaptor; +import org.mockito.MockitoAnnotations +import org.mockito.runners.MockitoJUnitRunner +import org.openecomp.mso.bpmn.common.scripts.MsoUtils; +import org.openecomp.mso.bpmn.common.scripts.FalloutHandler; + +@RunWith(MockitoJUnitRunner.class) +class FalloutHandlerTest { + + public MsoUtils utils = new MsoUtils() + + @Before + public void init() { + MockitoAnnotations.initMocks(this) + } + + private String falloutHandlerRequest = """ + + + uCPE1020_STUW105_5002 + Layer3ServiceActivateRequest + CANCEL + OMX + 10205000 + 1 + + + Some Error Message - Fallout Handler + Some Error Code - Fallout Handler + Some Source System Error Code- Fallout Handler + + + """ + + private String falloutHandlerResponse = """ + Fallout Handler Failed +""" + + @Test + public void testPreProcessRequest() { + + ExecutionEntity mockExecution = mock(ExecutionEntity.class) + + when(mockExecution.getVariable("FalloutHandlerRequest")).thenReturn(falloutHandlerRequest) + when(mockExecution.getVariable("URN_mso_adapters_db_auth")).thenReturn("757A94191D685FD2092AC1490730A4FC"); + when(mockExecution.getVariable("URN_mso_msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7"); + + FalloutHandler falloutHandler = new FalloutHandler() + falloutHandler.preProcessRequest(mockExecution) + + /* Initialize all the process request variables in this block */ + verify(mockExecution).setVariable("prefix","FH_") + //verify(mockExecution).setVariable("getLayer3ServiceDetailsV1Response","") + + //These variables are form the input Message to the BPMN + verify(mockExecution).setVariable("FH_request_id","") + verify(mockExecution).setVariable("FH_request_action","") + verify(mockExecution).setVariable("FH_notification-url","") + verify(mockExecution).setVariable("FH_mso-bpel-name","") + verify(mockExecution).setVariable("FH_ErrorCode", "") + verify(mockExecution).setVariable("FH_ErrorMessage", "") + + verify(mockExecution).setVariable("FH_notification-url-Ok", false) + verify(mockExecution).setVariable("FH_request_id-Ok", false) + + //These variables are for Get Mso Aai Password Adapter + verify(mockExecution).setVariable("FH_deliveryStatus", true) + + //update Response Status to pending ...Adapter variables + verify(mockExecution).setVariable("FH_updateResponseStatusPayload", null) + verify(mockExecution).setVariable("FH_updateResponseStatusResponse", null) + + //update Request Gamma ...Adapter variables + verify(mockExecution).setVariable("FH_updateRequestGammaPayload", "") + verify(mockExecution).setVariable("FH_updateRequestGammaResponse", null) + verify(mockExecution).setVariable("FH_updateRequestGammaResponseCode", null) + + //update Request Infra ...Adapter variables + verify(mockExecution).setVariable("FH_updateRequestInfraPayload", "") + verify(mockExecution).setVariable("FH_updateRequestInfraResponse", null) + verify(mockExecution).setVariable("FH_updateRequestInfraResponseCode", null) + + //assign False to success variable + verify(mockExecution).setVariable("FH_success", true) + + //Set notify status to Failed variable + verify(mockExecution).setVariable("FH_NOTIFY_STATUS", "SUCCESS") + + //Set DB update variable + verify(mockExecution).setVariable("FH_updateRequestPayload", "") + verify(mockExecution).setVariable("FH_updateRequestResponse", null) + verify(mockExecution).setVariable("FH_updateRequestResponseCode", null) + + //Auth variables + verify(mockExecution).setVariable("BasicAuthHeaderValue","") + + //Response variables + verify(mockExecution).setVariable("FalloutHandlerResponse","") + verify(mockExecution).setVariable("FH_ErrorResponse", null) + verify(mockExecution).setVariable("FH_ResponseCode", "") + + verify(mockExecution).setVariable("FH_request_id-Ok",true) + verify(mockExecution).setVariable("FH_request_id","uCPE1020_STUW105_5002") + verify(mockExecution).setVariable("FH_request_action","Layer3ServiceActivateRequest") + verify(mockExecution).setVariable("FH_source","OMX") + verify(mockExecution).setVariable("FH_ErrorCode","Some Error Code - Fallout Handler") + verify(mockExecution).setVariable("FH_ErrorMessage","Some Error Message - Fallout Handler") + + } + + @Test + public void testpostProcessResponse(){ + + ExecutionEntity mockExecution = mock(ExecutionEntity.class) + + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("FH_success")).thenReturn(false) + + FalloutHandler falloutHandler = new FalloutHandler() + falloutHandler.postProcessResponse(mockExecution) + + // Capture the arguments to setVariable + ArgumentCaptor captor1 = ArgumentCaptor.forClass(String.class); + ArgumentCaptor captor2 = ArgumentCaptor.forClass(String.class); + + verify(mockExecution, times(4)).setVariable(captor1.capture(), captor2.capture()) + List arg2List = captor2.getAllValues() + String payloadResponseActual = arg2List.get(1) + + assertEquals(falloutHandlerResponse.replaceAll("\\s+", ""), payloadResponseActual.replaceAll("\\s+", "")) + + verify(mockExecution).setVariable("FH_ResponseCode","500") + } + + private String updateRequestPayload = """ + + + + + testReqId + BPEL + ErrorMessage + ErrorCode + FAILED + NotifyStatus + + + + """ + + @Test + public void testupdateRequestPayload(){ + + ExecutionEntity mockExecution = mock(ExecutionEntity.class) + when(mockExecution.getVariable("FH_request_id")).thenReturn("testReqId") + when(mockExecution.getVariable("FH_ErrorMessage")).thenReturn("ErrorMessage") + when(mockExecution.getVariable("FH_ErrorCode")).thenReturn("ErrorCode") + when(mockExecution.getVariable("FH_NOTIFY_STATUS")).thenReturn("NotifyStatus") + + FalloutHandler falloutHandler = new FalloutHandler() + falloutHandler.updateRequestPayload(mockExecution) + + // Capture the arguments to setVariable + ArgumentCaptor captor1 = ArgumentCaptor.forClass(String.class); + ArgumentCaptor captor2 = ArgumentCaptor.forClass(String.class); + + verify(mockExecution, times(1)).setVariable(captor1.capture(), captor2.capture()) + List arg2List = captor2.getAllValues() + String payloadRequestActual = arg2List.get(0) + + assertEquals(updateRequestPayload.replaceAll("\\s+", ""), payloadRequestActual.replaceAll("\\s+", "")) + } + + private String updateRequestInfraPayload = """ + + + + + testReqId + BPEL + ErrorMessage + FAILED + 100 + + + + """ + + @Test + public void testupdateRequestInfraPayload(){ + + ExecutionEntity mockExecution = mock(ExecutionEntity.class) + when(mockExecution.getVariable("FH_request_id")).thenReturn("testReqId") + when(mockExecution.getVariable("FH_ErrorMessage")).thenReturn("ErrorMessage") + + FalloutHandler falloutHandler = new FalloutHandler() + falloutHandler.updateRequestInfraPayload(mockExecution) + + // Capture the arguments to setVariable + ArgumentCaptor captor1 = ArgumentCaptor.forClass(String.class); + ArgumentCaptor captor2 = ArgumentCaptor.forClass(String.class); + + verify(mockExecution, times(1)).setVariable(captor1.capture(), captor2.capture()) + List arg2List = captor2.getAllValues() + String payloadRequestActual = arg2List.get(0) + + assertEquals(updateRequestInfraPayload.replaceAll("\\s+", ""), payloadRequestActual.replaceAll("\\s+", "")) + } + + private String updateRequestGammaPayload = """ + + + + + testReqId + BPEL + ErrorMessage + ErrorCode + FAILED + + + + """ + + @Test + public void testupdateRequestGammaPayload(){ + + ExecutionEntity mockExecution = mock(ExecutionEntity.class) + when(mockExecution.getVariable("FH_request_id")).thenReturn("testReqId") + when(mockExecution.getVariable("FH_ErrorMessage")).thenReturn("ErrorMessage") + when(mockExecution.getVariable("FH_ErrorCode")).thenReturn("ErrorCode") + + FalloutHandler falloutHandler = new FalloutHandler() + falloutHandler.updateRequestGammaPayload(mockExecution) + + // Capture the arguments to setVariable + ArgumentCaptor captor1 = ArgumentCaptor.forClass(String.class); + ArgumentCaptor captor2 = ArgumentCaptor.forClass(String.class); + + verify(mockExecution, times(1)).setVariable(captor1.capture(), captor2.capture()) + List arg2List = captor2.getAllValues() + String payloadRequestActual = arg2List.get(0) + + assertEquals(updateRequestGammaPayload.replaceAll("\\s+", ""), payloadRequestActual.replaceAll("\\s+", "")) + } + + + String updateResponseStatusPayload = """ + + + + + testReqId + BPEL + SENDING_FINAL_NOTIFY + + + + """ + + @Test + public void testupdateResponseStatusPayload(){ + + ExecutionEntity mockExecution = mock(ExecutionEntity.class) + when(mockExecution.getVariable("FH_request_id")).thenReturn("testReqId") + + FalloutHandler falloutHandler = new FalloutHandler() + falloutHandler.updateResponseStatusPayload(mockExecution) + + // Capture the arguments to setVariable + ArgumentCaptor captor1 = ArgumentCaptor.forClass(String.class); + ArgumentCaptor captor2 = ArgumentCaptor.forClass(String.class); + + verify(mockExecution, times(1)).setVariable(captor1.capture(), captor2.capture()) + List arg2List = captor2.getAllValues() + String payloadResponseActual = arg2List.get(0) + + assertEquals(updateResponseStatusPayload.replaceAll("\\s+", ""), payloadResponseActual.replaceAll("\\s+", "")) + } + } \ No newline at end of file diff --git a/bpmn/MSOCommonBPMN/src/test/groovy/org/openecomp/mso/bpmn/common/scripts/SDNCAdapterTest.groovy b/bpmn/MSOCommonBPMN/src/test/groovy/org/openecomp/mso/bpmn/common/scripts/SDNCAdapterTest.groovy index f71e4d2516..014dba6984 100644 --- a/bpmn/MSOCommonBPMN/src/test/groovy/org/openecomp/mso/bpmn/common/scripts/SDNCAdapterTest.groovy +++ b/bpmn/MSOCommonBPMN/src/test/groovy/org/openecomp/mso/bpmn/common/scripts/SDNCAdapterTest.groovy @@ -1,948 +1,948 @@ -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - MSO - * ================================================================================ - * 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.openecomp.mso.bpmn.common.scripts; - -import static org.mockito.Mockito.* - -import org.camunda.bpm.engine.ProcessEngineServices -import org.camunda.bpm.engine.RepositoryService -import org.camunda.bpm.engine.impl.persistence.entity.ExecutionEntity -import org.camunda.bpm.engine.repository.ProcessDefinition -import org.junit.Before -import org.junit.Test -import org.junit.runner.RunWith -import org.mockito.MockitoAnnotations -import org.mockito.runners.MockitoJUnitRunner -import org.mockito.internal.debugging.MockitoDebuggerImpl -import org.openecomp.mso.bpmn.common.scripts.SDNCAdapter; - -import org.openecomp.mso.bpmn.mock.FileUtil - -@RunWith(MockitoJUnitRunner.class) -public class SDNCAdapterTest { - - @Before - public void init() - { - MockitoAnnotations.initMocks(this) - System.setProperty("jboss.qualified.host.name","myhost.att.com") - } - - - def workflowResponse = """ - - - testRequestId - 200 - OK - - <layer3-service-list xmlns="com:att:sdnctl:l3api"> - <service-instance-id>FK/VLXM/003717//SW_INTERNET</service-instance-id> - <service-status> - <rpc-name>service-configuration-operation</rpc-name> - <rpc-action>activate</rpc-action> - <request-status>synccomplete</request-status> - <final-indicator>N</final-indicator> - <l3sdn-action>Layer3ServiceActivateRequest</l3sdn-action> - <l3sdn-subaction>SUPP</l3sdn-subaction> - <response-timestamp>2015-04-28T21:32:11.386Z</response-timestamp> - </service-status> - <service-data> - <internet-evc-access-information> - <ip-version>ds</ip-version> - <internet-evc-speed-value>8</internet-evc-speed-value> - <internet-evc-speed-units>Mbps</internet-evc-speed-units> - </internet-evc-access-information> - <vr-lan xmlns="com:att:sdnctl:l3api"> - <vr-lan-interface> - <static-routes> - <v6-static-routes> - <v6-next-hop-address>2001:1890:12e3:2da::</v6-next-hop-address> - <v6-static-route-prefix>2001:1890:12e3:2da::</v6-static-route-prefix> - <v6-static-route-prefix-length>28</v6-static-route-prefix-length> - </v6-static-routes> - <v4-static-routes> - <v4-static-route-prefix>255.255.252.1</v4-static-route-prefix> - <v4-next-hop-address>192.168.1.15</v4-next-hop-address> - <v4-static-route-prefix-length>28</v4-static-route-prefix-length> - </v4-static-routes> - <v6-static-routes> - <v6-next-hop-address>2001:1890:12e3:2da::</v6-next-hop-address> - <v6-static-route-prefix>2001:1890:12e3:2da::</v6-static-route-prefix> - <v6-static-route-prefix-length>28</v6-static-route-prefix-length> - </v6-static-routes> - <v4-static-routes> - <v4-static-route-prefix>255.255.252.2</v4-static-route-prefix> - <v4-next-hop-address>192.168.1.15</v4-next-hop-address> - <v4-static-route-prefix-length>28</v4-static-route-prefix-length> - </v4-static-routes> - <v4-static-routes> - <v4-static-route-prefix>255.255.252.3</v4-static-route-prefix> - <v4-next-hop-address>192.168.1.15</v4-next-hop-address> - <v4-static-route-prefix-length>28</v4-static-route-prefix-length> - </v4-static-routes> - </static-routes> - <dhcp> - <v6-dhcp-server-enabled>N</v6-dhcp-server-enabled> - <v4-dhcp-server-enabled>Y</v4-dhcp-server-enabled> - <use-v6-default-pool>N</use-v6-default-pool> - <excluded-v4-dhcp-addresses-from-default-pool> - <excluded-v4-address>192.168.1.7</excluded-v4-address> - </excluded-v4-dhcp-addresses-from-default-pool> - <excluded-v4-dhcp-addresses-from-default-pool> - <excluded-v4-address>192.168.1.8</excluded-v4-address> - </excluded-v4-dhcp-addresses-from-default-pool> - <v4-dhcp-pools> - <v4-dhcp-relay-next-hop-address>1.1.1.1</v4-dhcp-relay-next-hop-address> - <v4-dhcp-pool-prefix-length>28</v4-dhcp-pool-prefix-length> - <excluded-v4-addresses> - <excluded-v4-address>192.168.1.5</excluded-v4-address> - </excluded-v4-addresses> - <v4-dhcp-relay-gateway-address>2.2.2.1</v4-dhcp-relay-gateway-address> - <excluded-v4-addresses> - <excluded-v4-address>192.168.1.6</excluded-v4-address> - </excluded-v4-addresses> - <v4-dhcp-pool-prefix>192.155.2.3</v4-dhcp-pool-prefix> - </v4-dhcp-pools> - <v4-dhcp-pools> - <v4-dhcp-relay-next-hop-address>1.1.1.2</v4-dhcp-relay-next-hop-address> - <v4-dhcp-pool-prefix-length>28</v4-dhcp-pool-prefix-length> - <excluded-v4-addresses> - <excluded-v4-address>192.168.1.6</excluded-v4-address> - </excluded-v4-addresses> - <v4-dhcp-relay-gateway-address>2.2.2.2</v4-dhcp-relay-gateway-address> - <excluded-v4-addresses> - <excluded-v4-address>192.168.1.7</excluded-v4-address> - </excluded-v4-addresses> - <v4-dhcp-pool-prefix>192.155.2.4</v4-dhcp-pool-prefix> - </v4-dhcp-pools> - <use-v4-default-pool>Y</use-v4-default-pool> - <excluded-v6-dhcp-addresses-from-default-pool> - <excluded-v6-address>1:5</excluded-v6-address> - </excluded-v6-dhcp-addresses-from-default-pool> - <excluded-v6-dhcp-addresses-from-default-pool> - <excluded-v6-address>1:6</excluded-v6-address> - </excluded-v6-dhcp-addresses-from-default-pool> - <v6-dhcp-pools> - <v6-dhcp-relay-next-hop-address>4:4</v6-dhcp-relay-next-hop-address> - <v6-dhcp-pool-prefix-length>28</v6-dhcp-pool-prefix-length> - <excluded-v6-addresses> - <excluded-v6-address>1:1</excluded-v6-address> - </excluded-v6-addresses> - <v6-dhcp-relay-gateway-address>3:3</v6-dhcp-relay-gateway-address> - <excluded-v6-addresses> - <excluded-v6-address>2:2</excluded-v6-address> - </excluded-v6-addresses> - <v6-dhcp-pool-prefix>0:0</v6-dhcp-pool-prefix> - </v6-dhcp-pools> - <v6-dhcp-pools> - <v6-dhcp-relay-next-hop-address>4:4</v6-dhcp-relay-next-hop-address> - <v6-dhcp-pool-prefix-length>28</v6-dhcp-pool-prefix-length> - <excluded-v6-addresses> - <excluded-v6-address>1:1</excluded-v6-address> - </excluded-v6-addresses> - <v6-dhcp-relay-gateway-address>3:3</v6-dhcp-relay-gateway-address> - <excluded-v6-addresses> - <excluded-v6-address>2:2</excluded-v6-address> - </excluded-v6-addresses> - <v6-dhcp-pool-prefix>0:0</v6-dhcp-pool-prefix> - </v6-dhcp-pools> - </dhcp> - <firewall-lite> - <stateful-firewall-lite-v6-enabled>N</stateful-firewall-lite-v6-enabled> - <stateful-firewall-lite-v4-enabled>Y</stateful-firewall-lite-v4-enabled> - <v4-firewall-packet-filters> - <v4-firewall-prefix>0.0.0.1</v4-firewall-prefix> - <v4-firewall-prefix-length>1</v4-firewall-prefix-length> - <allow-icmp-ping>Y</allow-icmp-ping> - <udp-ports> - <port-number>1</port-number> - </udp-ports> - <tcp-ports> - <port-number>1</port-number> - </tcp-ports> - </v4-firewall-packet-filters> - <v4-firewall-packet-filters> - <v4-firewall-prefix>0.0.0.2</v4-firewall-prefix> - <v4-firewall-prefix-length>2</v4-firewall-prefix-length> - <allow-icmp-ping>Y</allow-icmp-ping> - <udp-ports> - <port-number>2</port-number> - </udp-ports> - <tcp-ports> - <port-number>2</port-number> - </tcp-ports> - </v4-firewall-packet-filters> - <v6-firewall-packet-filters> - <v6-firewall-prefix>:</v6-firewall-prefix> - <v6-firewall-prefix-length>0</v6-firewall-prefix-length> - <allow-icmp-ping>Y</allow-icmp-ping> - <udp-ports> - <port-number>3</port-number> - </udp-ports> - <tcp-ports> - <port-number>3</port-number> - </tcp-ports> - </v6-firewall-packet-filters> - <v6-firewall-packet-filters> - <v6-firewall-prefix>:</v6-firewall-prefix> - <v6-firewall-prefix-length>1</v6-firewall-prefix-length> - <allow-icmp-ping>Y</allow-icmp-ping> - <udp-ports> - <port-number>4</port-number> - </udp-ports> - <tcp-ports> - <port-number>4</port-number> - </tcp-ports> - </v6-firewall-packet-filters> - </firewall-lite> - <pat> - <v4-pat-pools> - <v4-pat-pool-prefix>192.168.1.44</v4-pat-pool-prefix> - <v4-pat-pool-next-hop-address>192.168.1.5</v4-pat-pool-next-hop-address> - <v4-pat-pool-prefix-length>0</v4-pat-pool-prefix-length> - </v4-pat-pools> - <use-v4-default-pool>Y</use-v4-default-pool> - <v4-pat-enabled>N</v4-pat-enabled> - <v4-pat-pools> - <v4-pat-pool-prefix>192.168.1.45</v4-pat-pool-prefix> - <v4-pat-pool-next-hop-address>192.168.1.6</v4-pat-pool-next-hop-address> - <v4-pat-pool-prefix-length>28</v4-pat-pool-prefix-length> - </v4-pat-pools> - </pat> - <nat> - <v4-nat-enabled>Y</v4-nat-enabled> - <v4-nat-mapping-entries> - <v4-nat-internal>0.0.0.0</v4-nat-internal> - <v4-nat-next-hop-address>0.0.0.0</v4-nat-next-hop-address> - <v4-nat-external>0.0.0.0</v4-nat-external> - </v4-nat-mapping-entries> - <v4-nat-mapping-entries> - <v4-nat-internal>0.0.0.1</v4-nat-internal> - <v4-nat-next-hop-address>0.0.0.1</v4-nat-next-hop-address> - <v4-nat-external>0.0.0.1</v4-nat-external> - </v4-nat-mapping-entries> - </nat> - <vr-designation>primary</vr-designation> - <v4-vce-loopback-address>162.200.3.144</v4-vce-loopback-address> - <v6-vr-lan-prefix-length>64</v6-vr-lan-prefix-length> - <v6-vce-wan-address>2001:1890:12e3:2da::</v6-vce-wan-address> - <v6-vr-lan-prefix>2620:0:10d0:f:ffff:ffff:ffff:fffe</v6-vr-lan-prefix> - <v4-vr-lan-prefix-length>24</v4-vr-lan-prefix-length> - <v4-vr-lan-prefix>10.192.27.254</v4-vr-lan-prefix> - <v4-public-lan-prefixes> - <t-provided-v4-lan-public-prefixes> - <request-index>1</request-index> - <v4-next-hop-address>192.168.1.2</v4-next-hop-address> - <v4-lan-public-prefix>192.168.1.1</v4-lan-public-prefix> - <v4-lan-public-prefix-length>28</v4-lan-public-prefix-length> - </t-provided-v4-lan-public-prefixes> - <t-provided-v4-lan-public-prefixes> - <request-index>1</request-index> - <v4-next-hop-address>192.168.1.72</v4-next-hop-address> - <v4-lan-public-prefix>192.168.1.71</v4-lan-public-prefix> - <v4-lan-public-prefix-length>28</v4-lan-public-prefix-length> - </t-provided-v4-lan-public-prefixes> - <t-provided-v4-lan-public-prefixes> - <request-index>1</request-index> - <v4-next-hop-address>192.168.1.68</v4-next-hop-address> - <v4-lan-public-prefix>192.168.1.67</v4-lan-public-prefix> - <v4-lan-public-prefix-length>28</v4-lan-public-prefix-length> - </t-provided-v4-lan-public-prefixes> - </v4-public-lan-prefixes> - <v6-public-lan-prefixes> - <t-provided-v6-lan-public-prefixes> - <request-index>1</request-index> - <v6-next-hop-address>2001:1890:12e3:2da::</v6-next-hop-address> - <v6-lan-public-prefix>2001:1890:12e3:2da::</v6-lan-public-prefix> - <v6-lan-public-prefix-length>28</v6-lan-public-prefix-length> - </t-provided-v6-lan-public-prefixes> - <t-provided-v6-lan-public-prefixes> - <request-index>1</request-index> - <v6-next-hop-address>2001:1890:12e3:2da::</v6-next-hop-address> - <v6-lan-public-prefix>2001:1890:12e3:3da::</v6-lan-public-prefix> - <v6-lan-public-prefix-length>28</v6-lan-public-prefix-length> - </t-provided-v6-lan-public-prefixes> - <t-provided-v6-lan-public-prefixes> - <request-index>1</request-index> - <v6-next-hop-address>2001:1890:12e3:2da::</v6-next-hop-address> - <v6-lan-public-prefix>2001:1890:12e3:4da::</v6-lan-public-prefix> - <v6-lan-public-prefix-length>28</v6-lan-public-prefix-length> - </t-provided-v6-lan-public-prefixes> - </v6-public-lan-prefixes> - </vr-lan-interface> - <routing-protocol>none</routing-protocol> - </vr-lan> -<ucpe-vms-service-information> - <transport-service-information> - <transport-service-type>AVPN</transport-service-type> - <access-circuit-info> - <access-circuit-id>1</access-circuit-id> - <dual-mode>Active</dual-mode> - </access-circuit-info> - <access-circuit-info> - <access-circuit-id>2</access-circuit-id> - <dual-mode>Standby</dual-mode> - </access-circuit-info> - </transport-service-information> - <ucpe-information> - <ucpe-host-name>hostname</ucpe-host-name> - <ucpe-activation-code>activecode</ucpe-activation-code> - <out-of-band-management-modem>OOB</out-of-band-management-modem> - </ucpe-information> - <vnf-list> - <vnf-information> - <vnf-instance-id>1</vnf-instance-id> - <vnf-sequence-number>1</vnf-sequence-number> - <vnf-type>ZZ</vnf-type> - <vnf-vendor>JUNIPER</vnf-vendor> - <vnf-model>MODEL1</vnf-model> - <vnf-id>1</vnf-id> - <prov-status>1</prov-status> - <operational-state>1</operational-state> - <orchestration-status>1</orchestration-status> - <equipment-role>1</equipment-role> - </vnf-information> - <vnf-information> - <vnf-instance-id>2</vnf-instance-id> - <vnf-sequence-number>2</vnf-sequence-number> - <vnf-type>HY</vnf-type> - <vnf-vendor>JUNIPER</vnf-vendor> - <vnf-model>MODEL2</vnf-model> - <vnf-id>2</vnf-id> - <prov-status>2</prov-status> - <operational-state>2</operational-state> - <orchestration-status>2</orchestration-status> - <equipment-role>2</equipment-role> - </vnf-information> - </vnf-list> - </ucpe-vms-service-information> - <request-information> - <request-action>Layer3ServiceActivateRequest</request-action> - <order-number>4281555</order-number> - <request-id>155415ab-b4a7-4382-b4c6-d17d9sm42855</request-id> - <notification-url>https://csi-tst-q22.it.att.com:22443/Services/com/cingular/csi/sdn/SendManagedNetworkStatusNotification.jws</notification-url> - <source>OMX</source> - <order-version>1</order-version> - </request-information> - <sdnc-request-header> - <svc-action>activate</svc-action> - <svc-notification-url>https://msojra.mtsnjdcp1.aic.cip.att.com:8443/adapters/rest/SDNCNotify</svc-notification-url> - <svc-request-id>5b1f3c5d-cdf9-488d-8a4b-d3f1229d7760</svc-request-id> - </sdnc-request-header> - <l2-homing-information> - <topology>MultiPoint</topology> - <preferred-aic-clli>MTSNJA4LCP1</preferred-aic-clli> - <evc-name>AS/VLXM/003717//SW</evc-name> - </l2-homing-information> - <service-information> - <service-instance-id>FK/VLXM/003717//SW_INTERNET</service-instance-id> - <subscriber-name>ST E2E Test42855_1300004281555</subscriber-name> - <service-type>SDN-ETHERNET-INTERNET</service-type> - </service-information> - <internet-service-change-details> - <internet-evc-speed-value>10</internet-evc-speed-value> - <internet-evc-speed-units>Kbps</internet-evc-speed-units> - <t-provided-v4-lan-public-prefixes> - <request-index>1</request-index> - <v4-next-hop-address>192.168.1.15</v4-next-hop-address> - <v4-lan-public-prefix>192.168.1.15</v4-lan-public-prefix> - <v4-lan-public-prefix-length>28</v4-lan-public-prefix-length> - </t-provided-v4-lan-public-prefixes> - <t-provided-v4-lan-public-prefixes> - <request-index>2</request-index> - <v4-next-hop-address>192.168.1.16</v4-next-hop-address> - <v4-lan-public-prefix>192.168.1.16</v4-lan-public-prefix> - <v4-lan-public-prefix-length>28</v4-lan-public-prefix-length> - </t-provided-v4-lan-public-prefixes> - <t-provided-v6-lan-public-prefixes> - <request-index>1</request-index> - <v6-next-hop-address>2001:1890:12e3:2da::</v6-next-hop-address> - <v6-lan-public-prefix>2001:1890:12e3:2da::</v6-lan-public-prefix> - <v6-lan-public-prefix-length>28</v6-lan-public-prefix-length> - </t-provided-v6-lan-public-prefixes> - <t-provided-v6-lan-public-prefixes> - <request-index>1</request-index> - <v6-next-hop-address>2001:1890:12e3:2da::</v6-next-hop-address> - <v6-lan-public-prefix>2001:1890:12e3:2da::</v6-lan-public-prefix> - <v6-lan-public-prefix-length>28</v6-lan-public-prefix-length> - </t-provided-v6-lan-public-prefixes> - </internet-service-change-details> - </service-data> - </layer3-service-list> - - -""" - - String sdncAdapterRequest = """ - - - - - 745b1b50-e39e-4685-9cc8-c71f0bde8bf0 - query - services/layer3-service-list/AS%2FVLXM%2F000199%2F%2FSB_INTERNET - http://myhost.att.com:28080/mso/sdncAdapterCallbackServiceImpl - - - - - 12570a36-7388-4c0a-bec4-189ce3kg9956 - GetLayer3ServiceDetailsRequest - OMX - - - SDN-ETHERNET-INTERNET - PD/VLXM/003717//SW_INTERNET - - -""" - -def sdncAdapterResponse = """ - - - 39542e39-ccc3-4d1a-8b79-04ce88526613 - 404 - Error processing request to SDNC. Not Found. - https://sdncodl.us.aic.cip.att.com:8443/restconf/config/L3SDN-API:services/layer3-service-list/MVM%2FVLXP%2F000855%2F%2FShakeout. - SDNC Returned-[error-type:application, error-tag:data-missing, - error-message:Request could not be completed because the relevant - data model content does not exist.] - - - -""" - -def workflowErrorResponse = """ - Received error from SDN-C: Error processing request to SDNC. Not Found. - https://sdncodl.us.aic.cip.att.com:8443/restconf/config/L3SDN-API:services/layer3-service-list/MVM%2FVLXP%2F000855%2F%2FShakeout. - SDNC Returned-[error-type:application, error-tag:data-missing, - error-message:Request could not be completed because the relevant - data model content does not exist.] - 5300 - 404 - """ - -def workflowErrorResponse1 = """ - Invalid Callback Response from SDNC Adapter - 5300 - """ - -def enhancedCallbackRequestData = - """ - FK/VLXM/003717//SW_INTERNET - - service-configuration-operation - activate - synccomplete - N - Layer3ServiceActivateRequest - SUPP - 2015-04-28T21:32:11.386Z - - - - ds - 8 - Mbps - - - - - - 2001:1890:12e3:2da:: - 2001:1890:12e3:2da:: - 28 - - - 255.255.252.1 - 192.168.1.15 - 28 - - - 2001:1890:12e3:2da:: - 2001:1890:12e3:2da:: - 28 - - - 255.255.252.2 - 192.168.1.15 - 28 - - - 255.255.252.3 - 192.168.1.15 - 28 - - - - N - Y - N - - 192.168.1.7 - - - 192.168.1.8 - - - 1.1.1.1 - 28 - - 192.168.1.5 - - 2.2.2.1 - - 192.168.1.6 - - 192.155.2.3 - - - 1.1.1.2 - 28 - - 192.168.1.6 - - 2.2.2.2 - - 192.168.1.7 - - 192.155.2.4 - - Y - - 1:5 - - - 1:6 - - - 4:4 - 28 - - 1:1 - - 3:3 - - 2:2 - - 0:0 - - - 4:4 - 28 - - 1:1 - - 3:3 - - 2:2 - - 0:0 - - - - N - Y - - 0.0.0.1 - 1 - Y - - 1 - - - 1 - - - - 0.0.0.2 - 2 - Y - - 2 - - - 2 - - - - : - 0 - Y - - 3 - - - 3 - - - - : - 1 - Y - - 4 - - - 4 - - - - - - 192.168.1.44 - 192.168.1.5 - 0 - - Y - N - - 192.168.1.45 - 192.168.1.6 - 28 - - - - Y - - 0.0.0.0 - 0.0.0.0 - 0.0.0.0 - - - 0.0.0.1 - 0.0.0.1 - 0.0.0.1 - - - primary - 162.200.3.144 - 64 - 2001:1890:12e3:2da:: - 2620:0:10d0:f:ffff:ffff:ffff:fffe - 24 - 10.192.27.254 - - - 1 - 192.168.1.2 - 192.168.1.1 - 28 - - - 1 - 192.168.1.72 - 192.168.1.71 - 28 - - - 1 - 192.168.1.68 - 192.168.1.67 - 28 - - - - - 1 - 2001:1890:12e3:2da:: - 2001:1890:12e3:2da:: - 28 - - - 1 - 2001:1890:12e3:2da:: - 2001:1890:12e3:3da:: - 28 - - - 1 - 2001:1890:12e3:2da:: - 2001:1890:12e3:4da:: - 28 - - - - none - - - - AVPN - - 1 - Active - - - 2 - Standby - - - - hostname - activecode - OOB - - - - 1 - 1 - ZZ - JUNIPER - MODEL1 - 1 - 1 - 1 - 1 - 1 - - - 2 - 2 - HY - JUNIPER - MODEL2 - 2 - 2 - 2 - 2 - 2 - - - - - Layer3ServiceActivateRequest - 4281555 - 155415ab-b4a7-4382-b4c6-d17d9sm42855 - https://csi-tst-q22.it.att.com:22443/Services/com/cingular/csi/sdn/SendManagedNetworkStatusNotification.jws - OMX - 1 - - - activate - https://msojra.mtsnjdcp1.aic.cip.att.com:8443/adapters/rest/SDNCNotify - 5b1f3c5d-cdf9-488d-8a4b-d3f1229d7760 - - - MultiPoint - MTSNJA4LCP1 - AS/VLXM/003717//SW - - - FK/VLXM/003717//SW_INTERNET - ST E2E Test42855_1300004281555 - SDN-ETHERNET-INTERNET - - - 10 - Kbps - - 1 - 192.168.1.15 - 192.168.1.15 - 28 - - - 2 - 192.168.1.16 - 192.168.1.16 - 28 - - - 1 - 2001:1890:12e3:2da:: - 2001:1890:12e3:2da:: - 28 - - - 1 - 2001:1890:12e3:2da:: - 2001:1890:12e3:2da:: - 28 - - - - - -""" - -def sdncAdapterResponseEmpty = -""" - -""" - -def sdncAdapterResponseError = -""" - - - 39542e39-ccc3-4d1a-8b79-04ce88526613 - 404 - Error processing request to SDNC. Not Found. - https://sdncodl.us.aic.cip.att.com:8443/restconf/config/L3SDN-API:services/layer3-service-list/MVM%2FVLXP%2F000855%2F%2FShakeout. - SDNC Returned-[error-type:application, error-tag:data-missing, - error-message:Request could not be completed because the relevant - data model content does not exist.] - - -""" - - - @Test - public void testPreProcessRequest() { - - String sdncAdapterWorkflowRequest = FileUtil.readResourceFile("__files/SDN-ETHERNET-INTERNET/SDNCAdapterV1/sdncadapterworkflowrequest.xml"); - ExecutionEntity mockExecution = mock(ExecutionEntity.class) - when(mockExecution.getVariable("URN_mso_adapters_po_auth")).thenReturn("3141634BF7E070AA289CF2892C986C0B") - when(mockExecution.getVariable("URN_mso_msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7") - when(mockExecution.getVariable("sdncAdapterWorkflowRequest")).thenReturn(sdncAdapterWorkflowRequest) - when(mockExecution.getVariable("URN_mso_workflow_sdncadapter_callback")).thenReturn("http://someurl.someting.com:28080/mso/sdncAdapterCallbackServiceImpl") - when(mockExecution.getVariable("URN_mso_use_qualified_host")).thenReturn("true") - when(mockExecution.getProcessInstanceId()).thenReturn("745b1b50-e39e-4685-9cc8-c71f0bde8bf0") - when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") - - - SDNCAdapter sdncAdapter = new SDNCAdapter() - sdncAdapter.preProcessRequest(mockExecution) - - MockitoDebuggerImpl debugger = new MockitoDebuggerImpl() - debugger.printInvocations(mockExecution) - - - verify(mockExecution).setVariable("prefix","SDNCA_") - verify(mockExecution).setVariable("sdncAdapterResponse","") - verify(mockExecution).setVariable("asynchronousResponseTimeout",false) - verify(mockExecution).setVariable("continueListening",false) - verify(mockExecution).setVariable("BasicAuthHeaderValue","Basic cGFzc3dvcmQ=") - verify(mockExecution).setVariable("serviceConfigActivate",false) - verify(mockExecution).setVariable("SDNCA_requestId", "745b1b50-e39e-4685-9cc8-c71f0bde8bf0") - verify(mockExecution).setVariable("SDNCA_SuccessIndicator",false) - verify(mockExecution).setVariable("source","") - verify(mockExecution).setVariable("sdncAdapterRequest", sdncAdapterRequest) - } - - @Test - public void testProcessResponse() - { - String sdncAdapterCallbackResponse = FileUtil.readResourceFile("__files/SDN-ETHERNET-INTERNET/SDNCAdapterV1mock/sdncadaptercallbackrequest.xml"); - ExecutionEntity mockExecution = mock(ExecutionEntity.class) - when(mockExecution.getVariable("sdncAdapterCallbackRequest")).thenReturn(sdncAdapterCallbackResponse) - SDNCAdapter sdncAdapter = new SDNCAdapter() - sdncAdapter.postProcessResponse(mockExecution) - -// MockitoDebuggerImpl debugger = new MockitoDebuggerImpl() -// debugger.printInvocations(mockExecution) - - verify(mockExecution).getVariable("isDebugLogEnabled") - verify(mockExecution,times(2)).getVariable("sdncAdapterCallbackRequest") - verify(mockExecution).setVariable("sdncAdapterResponse",workflowResponse) - verify(mockExecution).setVariable("enhancedCallbackRequestData",enhancedCallbackRequestData) - verify(mockExecution).setVariable("continueListening",false) - - } - - @Test - public void testProcessResponse_ErrorCase_404() - { - String sdncAdapterCallbackErrorResponse = FileUtil.readResourceFile("sdncadaptercallbackrequest_404CallBack.xml"); - ExecutionEntity mockExecution = mock(ExecutionEntity.class) - when(mockExecution.getVariable("sdncAdapterCallbackRequest")).thenReturn(sdncAdapterCallbackErrorResponse) - SDNCAdapter sdncAdapter = new SDNCAdapter() - sdncAdapter.postProcessResponse(mockExecution) - - verify(mockExecution, times(1)).getVariable("isDebugLogEnabled") - verify(mockExecution,times(2)).getVariable("sdncAdapterCallbackRequest") - verify(mockExecution).setVariable("sdncAdapterResponse", sdncAdapterResponseError) - verify(mockExecution).setVariable("enhancedCallbackRequestData", "") - verify(mockExecution).setVariable("continueListening",false) - - } - - @Test - public void testProcessResponse_ErrorCase_InvalidCallback() - { - ExecutionEntity mockExecution = mock(ExecutionEntity.class) - when(mockExecution.getVariable("sdncAdapterCallbackRequest")).thenReturn("

Service Unavailable

") - SDNCAdapter sdncAdapter = new SDNCAdapter() - sdncAdapter.postProcessResponse(mockExecution) - - verify(mockExecution).getVariable("isDebugLogEnabled") - verify(mockExecution,times(2)).getVariable("sdncAdapterCallbackRequest") - verify(mockExecution).setVariable("sdncAdapterResponse", sdncAdapterResponseEmpty) - verify(mockExecution).setVariable("enhancedCallbackRequestData", "") - verify(mockExecution).setVariable("continueListening",false) - - } - - @Test - public void postProcessResponse() - { - - String SDNCAdapterCallbackRequest = - """ - - - 3bb02798-b344-4d28-9bca-1f029954d1c9 - 404 - Error processing request to SDNC. Not Found. - https://sdncodl.us.infra.aic.att.net:8443/restconf/config/L3SDN-API:services/layer3-service-list/85%2FCSIP%2F141203%2FPT_CSI9999998693. - SDNC Returned-[error-type:application, error-tag:data-missing, - error-message:Request could not be completed because the relevant - data model content does not exist ] - -""" - - String sdncAdapterResponse = - """ - - - 3bb02798-b344-4d28-9bca-1f029954d1c9 - 404 - Error processing request to SDNC. Not Found. - https://sdncodl.us.infra.aic.att.net:8443/restconf/config/L3SDN-API:services/layer3-service-list/85%2FCSIP%2F141203%2FPT_CSI9999998693. - SDNC Returned-[error-type:application, error-tag:data-missing, - error-message:Request could not be completed because the relevant - data model content does not exist ] - - -""" - - ExecutionEntity mockExecution = mock(ExecutionEntity.class) - when(mockExecution.getVariable("sdncAdapterCallbackRequest")).thenReturn(SDNCAdapterCallbackRequest) - SDNCAdapter sdncAdapter = new SDNCAdapter() - sdncAdapter.postProcessResponse(mockExecution) - - verify(mockExecution).getVariable("isDebugLogEnabled") - verify(mockExecution,times(2)).getVariable("sdncAdapterCallbackRequest") - verify(mockExecution).setVariable("sdncAdapterResponse", sdncAdapterResponse) - verify(mockExecution).setVariable("enhancedCallbackRequestData", "") - verify(mockExecution).setVariable("continueListening",false) - - } - +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.bpmn.common.scripts; + +import static org.mockito.Mockito.* + +import org.camunda.bpm.engine.ProcessEngineServices +import org.camunda.bpm.engine.RepositoryService +import org.camunda.bpm.engine.impl.persistence.entity.ExecutionEntity +import org.camunda.bpm.engine.repository.ProcessDefinition +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.mockito.MockitoAnnotations +import org.mockito.runners.MockitoJUnitRunner +import org.mockito.internal.debugging.MockitoDebuggerImpl +import org.openecomp.mso.bpmn.common.scripts.SDNCAdapter; + +import org.openecomp.mso.bpmn.mock.FileUtil + +@RunWith(MockitoJUnitRunner.class) +public class SDNCAdapterTest { + + @Before + public void init() + { + MockitoAnnotations.initMocks(this) + System.setProperty("jboss.qualified.host.name","myhost.com") + } + + + def workflowResponse = """ + + + testRequestId + 200 + OK + + <layer3-service-list xmlns="com:att:sdnctl:l3api"> + <service-instance-id>FK/VLXM/003717//SW_INTERNET</service-instance-id> + <service-status> + <rpc-name>service-configuration-operation</rpc-name> + <rpc-action>activate</rpc-action> + <request-status>synccomplete</request-status> + <final-indicator>N</final-indicator> + <l3sdn-action>Layer3ServiceActivateRequest</l3sdn-action> + <l3sdn-subaction>SUPP</l3sdn-subaction> + <response-timestamp>2015-04-28T21:32:11.386Z</response-timestamp> + </service-status> + <service-data> + <internet-evc-access-information> + <ip-version>ds</ip-version> + <internet-evc-speed-value>8</internet-evc-speed-value> + <internet-evc-speed-units>Mbps</internet-evc-speed-units> + </internet-evc-access-information> + <vr-lan xmlns="com:att:sdnctl:l3api"> + <vr-lan-interface> + <static-routes> + <v6-static-routes> + <v6-next-hop-address>2001:1890:12e3:2da::</v6-next-hop-address> + <v6-static-route-prefix>2001:1890:12e3:2da::</v6-static-route-prefix> + <v6-static-route-prefix-length>28</v6-static-route-prefix-length> + </v6-static-routes> + <v4-static-routes> + <v4-static-route-prefix>255.255.252.1</v4-static-route-prefix> + <v4-next-hop-address>192.168.1.15</v4-next-hop-address> + <v4-static-route-prefix-length>28</v4-static-route-prefix-length> + </v4-static-routes> + <v6-static-routes> + <v6-next-hop-address>2001:1890:12e3:2da::</v6-next-hop-address> + <v6-static-route-prefix>2001:1890:12e3:2da::</v6-static-route-prefix> + <v6-static-route-prefix-length>28</v6-static-route-prefix-length> + </v6-static-routes> + <v4-static-routes> + <v4-static-route-prefix>255.255.252.2</v4-static-route-prefix> + <v4-next-hop-address>192.168.1.15</v4-next-hop-address> + <v4-static-route-prefix-length>28</v4-static-route-prefix-length> + </v4-static-routes> + <v4-static-routes> + <v4-static-route-prefix>255.255.252.3</v4-static-route-prefix> + <v4-next-hop-address>192.168.1.15</v4-next-hop-address> + <v4-static-route-prefix-length>28</v4-static-route-prefix-length> + </v4-static-routes> + </static-routes> + <dhcp> + <v6-dhcp-server-enabled>N</v6-dhcp-server-enabled> + <v4-dhcp-server-enabled>Y</v4-dhcp-server-enabled> + <use-v6-default-pool>N</use-v6-default-pool> + <excluded-v4-dhcp-addresses-from-default-pool> + <excluded-v4-address>192.168.1.7</excluded-v4-address> + </excluded-v4-dhcp-addresses-from-default-pool> + <excluded-v4-dhcp-addresses-from-default-pool> + <excluded-v4-address>192.168.1.8</excluded-v4-address> + </excluded-v4-dhcp-addresses-from-default-pool> + <v4-dhcp-pools> + <v4-dhcp-relay-next-hop-address>1.1.1.1</v4-dhcp-relay-next-hop-address> + <v4-dhcp-pool-prefix-length>28</v4-dhcp-pool-prefix-length> + <excluded-v4-addresses> + <excluded-v4-address>192.168.1.5</excluded-v4-address> + </excluded-v4-addresses> + <v4-dhcp-relay-gateway-address>2.2.2.1</v4-dhcp-relay-gateway-address> + <excluded-v4-addresses> + <excluded-v4-address>192.168.1.6</excluded-v4-address> + </excluded-v4-addresses> + <v4-dhcp-pool-prefix>192.155.2.3</v4-dhcp-pool-prefix> + </v4-dhcp-pools> + <v4-dhcp-pools> + <v4-dhcp-relay-next-hop-address>1.1.1.2</v4-dhcp-relay-next-hop-address> + <v4-dhcp-pool-prefix-length>28</v4-dhcp-pool-prefix-length> + <excluded-v4-addresses> + <excluded-v4-address>192.168.1.6</excluded-v4-address> + </excluded-v4-addresses> + <v4-dhcp-relay-gateway-address>2.2.2.2</v4-dhcp-relay-gateway-address> + <excluded-v4-addresses> + <excluded-v4-address>192.168.1.7</excluded-v4-address> + </excluded-v4-addresses> + <v4-dhcp-pool-prefix>192.155.2.4</v4-dhcp-pool-prefix> + </v4-dhcp-pools> + <use-v4-default-pool>Y</use-v4-default-pool> + <excluded-v6-dhcp-addresses-from-default-pool> + <excluded-v6-address>1:5</excluded-v6-address> + </excluded-v6-dhcp-addresses-from-default-pool> + <excluded-v6-dhcp-addresses-from-default-pool> + <excluded-v6-address>1:6</excluded-v6-address> + </excluded-v6-dhcp-addresses-from-default-pool> + <v6-dhcp-pools> + <v6-dhcp-relay-next-hop-address>4:4</v6-dhcp-relay-next-hop-address> + <v6-dhcp-pool-prefix-length>28</v6-dhcp-pool-prefix-length> + <excluded-v6-addresses> + <excluded-v6-address>1:1</excluded-v6-address> + </excluded-v6-addresses> + <v6-dhcp-relay-gateway-address>3:3</v6-dhcp-relay-gateway-address> + <excluded-v6-addresses> + <excluded-v6-address>2:2</excluded-v6-address> + </excluded-v6-addresses> + <v6-dhcp-pool-prefix>0:0</v6-dhcp-pool-prefix> + </v6-dhcp-pools> + <v6-dhcp-pools> + <v6-dhcp-relay-next-hop-address>4:4</v6-dhcp-relay-next-hop-address> + <v6-dhcp-pool-prefix-length>28</v6-dhcp-pool-prefix-length> + <excluded-v6-addresses> + <excluded-v6-address>1:1</excluded-v6-address> + </excluded-v6-addresses> + <v6-dhcp-relay-gateway-address>3:3</v6-dhcp-relay-gateway-address> + <excluded-v6-addresses> + <excluded-v6-address>2:2</excluded-v6-address> + </excluded-v6-addresses> + <v6-dhcp-pool-prefix>0:0</v6-dhcp-pool-prefix> + </v6-dhcp-pools> + </dhcp> + <firewall-lite> + <stateful-firewall-lite-v6-enabled>N</stateful-firewall-lite-v6-enabled> + <stateful-firewall-lite-v4-enabled>Y</stateful-firewall-lite-v4-enabled> + <v4-firewall-packet-filters> + <v4-firewall-prefix>0.0.0.1</v4-firewall-prefix> + <v4-firewall-prefix-length>1</v4-firewall-prefix-length> + <allow-icmp-ping>Y</allow-icmp-ping> + <udp-ports> + <port-number>1</port-number> + </udp-ports> + <tcp-ports> + <port-number>1</port-number> + </tcp-ports> + </v4-firewall-packet-filters> + <v4-firewall-packet-filters> + <v4-firewall-prefix>0.0.0.2</v4-firewall-prefix> + <v4-firewall-prefix-length>2</v4-firewall-prefix-length> + <allow-icmp-ping>Y</allow-icmp-ping> + <udp-ports> + <port-number>2</port-number> + </udp-ports> + <tcp-ports> + <port-number>2</port-number> + </tcp-ports> + </v4-firewall-packet-filters> + <v6-firewall-packet-filters> + <v6-firewall-prefix>:</v6-firewall-prefix> + <v6-firewall-prefix-length>0</v6-firewall-prefix-length> + <allow-icmp-ping>Y</allow-icmp-ping> + <udp-ports> + <port-number>3</port-number> + </udp-ports> + <tcp-ports> + <port-number>3</port-number> + </tcp-ports> + </v6-firewall-packet-filters> + <v6-firewall-packet-filters> + <v6-firewall-prefix>:</v6-firewall-prefix> + <v6-firewall-prefix-length>1</v6-firewall-prefix-length> + <allow-icmp-ping>Y</allow-icmp-ping> + <udp-ports> + <port-number>4</port-number> + </udp-ports> + <tcp-ports> + <port-number>4</port-number> + </tcp-ports> + </v6-firewall-packet-filters> + </firewall-lite> + <pat> + <v4-pat-pools> + <v4-pat-pool-prefix>192.168.1.44</v4-pat-pool-prefix> + <v4-pat-pool-next-hop-address>192.168.1.5</v4-pat-pool-next-hop-address> + <v4-pat-pool-prefix-length>0</v4-pat-pool-prefix-length> + </v4-pat-pools> + <use-v4-default-pool>Y</use-v4-default-pool> + <v4-pat-enabled>N</v4-pat-enabled> + <v4-pat-pools> + <v4-pat-pool-prefix>192.168.1.45</v4-pat-pool-prefix> + <v4-pat-pool-next-hop-address>192.168.1.6</v4-pat-pool-next-hop-address> + <v4-pat-pool-prefix-length>28</v4-pat-pool-prefix-length> + </v4-pat-pools> + </pat> + <nat> + <v4-nat-enabled>Y</v4-nat-enabled> + <v4-nat-mapping-entries> + <v4-nat-internal>0.0.0.0</v4-nat-internal> + <v4-nat-next-hop-address>0.0.0.0</v4-nat-next-hop-address> + <v4-nat-external>0.0.0.0</v4-nat-external> + </v4-nat-mapping-entries> + <v4-nat-mapping-entries> + <v4-nat-internal>0.0.0.1</v4-nat-internal> + <v4-nat-next-hop-address>0.0.0.1</v4-nat-next-hop-address> + <v4-nat-external>0.0.0.1</v4-nat-external> + </v4-nat-mapping-entries> + </nat> + <vr-designation>primary</vr-designation> + <v4-vce-loopback-address>162.200.3.144</v4-vce-loopback-address> + <v6-vr-lan-prefix-length>64</v6-vr-lan-prefix-length> + <v6-vce-wan-address>2001:1890:12e3:2da::</v6-vce-wan-address> + <v6-vr-lan-prefix>2620:0:10d0:f:ffff:ffff:ffff:fffe</v6-vr-lan-prefix> + <v4-vr-lan-prefix-length>24</v4-vr-lan-prefix-length> + <v4-vr-lan-prefix>10.192.27.254</v4-vr-lan-prefix> + <v4-public-lan-prefixes> + <t-provided-v4-lan-public-prefixes> + <request-index>1</request-index> + <v4-next-hop-address>192.168.1.2</v4-next-hop-address> + <v4-lan-public-prefix>192.168.1.1</v4-lan-public-prefix> + <v4-lan-public-prefix-length>28</v4-lan-public-prefix-length> + </t-provided-v4-lan-public-prefixes> + <t-provided-v4-lan-public-prefixes> + <request-index>1</request-index> + <v4-next-hop-address>192.168.1.72</v4-next-hop-address> + <v4-lan-public-prefix>192.168.1.71</v4-lan-public-prefix> + <v4-lan-public-prefix-length>28</v4-lan-public-prefix-length> + </t-provided-v4-lan-public-prefixes> + <t-provided-v4-lan-public-prefixes> + <request-index>1</request-index> + <v4-next-hop-address>192.168.1.68</v4-next-hop-address> + <v4-lan-public-prefix>192.168.1.67</v4-lan-public-prefix> + <v4-lan-public-prefix-length>28</v4-lan-public-prefix-length> + </t-provided-v4-lan-public-prefixes> + </v4-public-lan-prefixes> + <v6-public-lan-prefixes> + <t-provided-v6-lan-public-prefixes> + <request-index>1</request-index> + <v6-next-hop-address>2001:1890:12e3:2da::</v6-next-hop-address> + <v6-lan-public-prefix>2001:1890:12e3:2da::</v6-lan-public-prefix> + <v6-lan-public-prefix-length>28</v6-lan-public-prefix-length> + </t-provided-v6-lan-public-prefixes> + <t-provided-v6-lan-public-prefixes> + <request-index>1</request-index> + <v6-next-hop-address>2001:1890:12e3:2da::</v6-next-hop-address> + <v6-lan-public-prefix>2001:1890:12e3:3da::</v6-lan-public-prefix> + <v6-lan-public-prefix-length>28</v6-lan-public-prefix-length> + </t-provided-v6-lan-public-prefixes> + <t-provided-v6-lan-public-prefixes> + <request-index>1</request-index> + <v6-next-hop-address>2001:1890:12e3:2da::</v6-next-hop-address> + <v6-lan-public-prefix>2001:1890:12e3:4da::</v6-lan-public-prefix> + <v6-lan-public-prefix-length>28</v6-lan-public-prefix-length> + </t-provided-v6-lan-public-prefixes> + </v6-public-lan-prefixes> + </vr-lan-interface> + <routing-protocol>none</routing-protocol> + </vr-lan> +<ucpe-vms-service-information> + <transport-service-information> + <transport-service-type>AVPN</transport-service-type> + <access-circuit-info> + <access-circuit-id>1</access-circuit-id> + <dual-mode>Active</dual-mode> + </access-circuit-info> + <access-circuit-info> + <access-circuit-id>2</access-circuit-id> + <dual-mode>Standby</dual-mode> + </access-circuit-info> + </transport-service-information> + <ucpe-information> + <ucpe-host-name>hostname</ucpe-host-name> + <ucpe-activation-code>activecode</ucpe-activation-code> + <out-of-band-management-modem>OOB</out-of-band-management-modem> + </ucpe-information> + <vnf-list> + <vnf-information> + <vnf-instance-id>1</vnf-instance-id> + <vnf-sequence-number>1</vnf-sequence-number> + <vnf-type>ZZ</vnf-type> + <vnf-vendor>JUNIPER</vnf-vendor> + <vnf-model>MODEL1</vnf-model> + <vnf-id>1</vnf-id> + <prov-status>1</prov-status> + <operational-state>1</operational-state> + <orchestration-status>1</orchestration-status> + <equipment-role>1</equipment-role> + </vnf-information> + <vnf-information> + <vnf-instance-id>2</vnf-instance-id> + <vnf-sequence-number>2</vnf-sequence-number> + <vnf-type>HY</vnf-type> + <vnf-vendor>JUNIPER</vnf-vendor> + <vnf-model>MODEL2</vnf-model> + <vnf-id>2</vnf-id> + <prov-status>2</prov-status> + <operational-state>2</operational-state> + <orchestration-status>2</orchestration-status> + <equipment-role>2</equipment-role> + </vnf-information> + </vnf-list> + </ucpe-vms-service-information> + <request-information> + <request-action>Layer3ServiceActivateRequest</request-action> + <order-number>4281555</order-number> + <request-id>155415ab-b4a7-4382-b4c6-d17d9sm42855</request-id> + <notification-url>https://csi-tst-q22.it.com:22443/Services/com/cingular/csi/sdn/SendManagedNetworkStatusNotification.jws</notification-url> + <source>OMX</source> + <order-version>1</order-version> + </request-information> + <sdnc-request-header> + <svc-action>activate</svc-action> + <svc-notification-url>https://msojra.mtsnjdcp1.aic.cip.com:8443/adapters/rest/SDNCNotify</svc-notification-url> + <svc-request-id>5b1f3c5d-cdf9-488d-8a4b-d3f1229d7760</svc-request-id> + </sdnc-request-header> + <l2-homing-information> + <topology>MultiPoint</topology> + <preferred-aic-clli>MTSNJA4LCP1</preferred-aic-clli> + <evc-name>AS/VLXM/003717//SW</evc-name> + </l2-homing-information> + <service-information> + <service-instance-id>FK/VLXM/003717//SW_INTERNET</service-instance-id> + <subscriber-name>ST E2E Test42855_1300004281555</subscriber-name> + <service-type>SDN-ETHERNET-INTERNET</service-type> + </service-information> + <internet-service-change-details> + <internet-evc-speed-value>10</internet-evc-speed-value> + <internet-evc-speed-units>Kbps</internet-evc-speed-units> + <t-provided-v4-lan-public-prefixes> + <request-index>1</request-index> + <v4-next-hop-address>192.168.1.15</v4-next-hop-address> + <v4-lan-public-prefix>192.168.1.15</v4-lan-public-prefix> + <v4-lan-public-prefix-length>28</v4-lan-public-prefix-length> + </t-provided-v4-lan-public-prefixes> + <t-provided-v4-lan-public-prefixes> + <request-index>2</request-index> + <v4-next-hop-address>192.168.1.16</v4-next-hop-address> + <v4-lan-public-prefix>192.168.1.16</v4-lan-public-prefix> + <v4-lan-public-prefix-length>28</v4-lan-public-prefix-length> + </t-provided-v4-lan-public-prefixes> + <t-provided-v6-lan-public-prefixes> + <request-index>1</request-index> + <v6-next-hop-address>2001:1890:12e3:2da::</v6-next-hop-address> + <v6-lan-public-prefix>2001:1890:12e3:2da::</v6-lan-public-prefix> + <v6-lan-public-prefix-length>28</v6-lan-public-prefix-length> + </t-provided-v6-lan-public-prefixes> + <t-provided-v6-lan-public-prefixes> + <request-index>1</request-index> + <v6-next-hop-address>2001:1890:12e3:2da::</v6-next-hop-address> + <v6-lan-public-prefix>2001:1890:12e3:2da::</v6-lan-public-prefix> + <v6-lan-public-prefix-length>28</v6-lan-public-prefix-length> + </t-provided-v6-lan-public-prefixes> + </internet-service-change-details> + </service-data> + </layer3-service-list> + + +""" + + String sdncAdapterRequest = """ + + + + + 745b1b50-e39e-4685-9cc8-c71f0bde8bf0 + query + services/layer3-service-list/AS%2FVLXM%2F000199%2F%2FSB_INTERNET + http://myhost.com:28080/mso/sdncAdapterCallbackServiceImpl + + + + + 12570a36-7388-4c0a-bec4-189ce3kg9956 + GetLayer3ServiceDetailsRequest + OMX + + + SDN-ETHERNET-INTERNET + PD/VLXM/003717//SW_INTERNET + + +""" + +def sdncAdapterResponse = """ + + + 39542e39-ccc3-4d1a-8b79-04ce88526613 + 404 + Error processing request to SDNC. Not Found. + https://sdncodl.us.aic.cip.com:8443/restconf/config/L3SDN-API:services/layer3-service-list/MVM%2FVLXP%2F000855%2F%2FShakeout. + SDNC Returned-[error-type:application, error-tag:data-missing, + error-message:Request could not be completed because the relevant + data model content does not exist.] + + + +""" + +def workflowErrorResponse = """ + Received error from SDN-C: Error processing request to SDNC. Not Found. + https://sdncodl.us.aic.cip.com:8443/restconf/config/L3SDN-API:services/layer3-service-list/MVM%2FVLXP%2F000855%2F%2FShakeout. + SDNC Returned-[error-type:application, error-tag:data-missing, + error-message:Request could not be completed because the relevant + data model content does not exist.] + 5300 + 404 + """ + +def workflowErrorResponse1 = """ + Invalid Callback Response from SDNC Adapter + 5300 + """ + +def enhancedCallbackRequestData = + """ + FK/VLXM/003717//SW_INTERNET + + service-configuration-operation + activate + synccomplete + N + Layer3ServiceActivateRequest + SUPP + 2015-04-28T21:32:11.386Z + + + + ds + 8 + Mbps + + + + + + 2001:1890:12e3:2da:: + 2001:1890:12e3:2da:: + 28 + + + 255.255.252.1 + 192.168.1.15 + 28 + + + 2001:1890:12e3:2da:: + 2001:1890:12e3:2da:: + 28 + + + 255.255.252.2 + 192.168.1.15 + 28 + + + 255.255.252.3 + 192.168.1.15 + 28 + + + + N + Y + N + + 192.168.1.7 + + + 192.168.1.8 + + + 1.1.1.1 + 28 + + 192.168.1.5 + + 2.2.2.1 + + 192.168.1.6 + + 192.155.2.3 + + + 1.1.1.2 + 28 + + 192.168.1.6 + + 2.2.2.2 + + 192.168.1.7 + + 192.155.2.4 + + Y + + 1:5 + + + 1:6 + + + 4:4 + 28 + + 1:1 + + 3:3 + + 2:2 + + 0:0 + + + 4:4 + 28 + + 1:1 + + 3:3 + + 2:2 + + 0:0 + + + + N + Y + + 0.0.0.1 + 1 + Y + + 1 + + + 1 + + + + 0.0.0.2 + 2 + Y + + 2 + + + 2 + + + + : + 0 + Y + + 3 + + + 3 + + + + : + 1 + Y + + 4 + + + 4 + + + + + + 192.168.1.44 + 192.168.1.5 + 0 + + Y + N + + 192.168.1.45 + 192.168.1.6 + 28 + + + + Y + + 0.0.0.0 + 0.0.0.0 + 0.0.0.0 + + + 0.0.0.1 + 0.0.0.1 + 0.0.0.1 + + + primary + 162.200.3.144 + 64 + 2001:1890:12e3:2da:: + 2620:0:10d0:f:ffff:ffff:ffff:fffe + 24 + 10.192.27.254 + + + 1 + 192.168.1.2 + 192.168.1.1 + 28 + + + 1 + 192.168.1.72 + 192.168.1.71 + 28 + + + 1 + 192.168.1.68 + 192.168.1.67 + 28 + + + + + 1 + 2001:1890:12e3:2da:: + 2001:1890:12e3:2da:: + 28 + + + 1 + 2001:1890:12e3:2da:: + 2001:1890:12e3:3da:: + 28 + + + 1 + 2001:1890:12e3:2da:: + 2001:1890:12e3:4da:: + 28 + + + + none + + + + AVPN + + 1 + Active + + + 2 + Standby + + + + hostname + activecode + OOB + + + + 1 + 1 + ZZ + JUNIPER + MODEL1 + 1 + 1 + 1 + 1 + 1 + + + 2 + 2 + HY + JUNIPER + MODEL2 + 2 + 2 + 2 + 2 + 2 + + + + + Layer3ServiceActivateRequest + 4281555 + 155415ab-b4a7-4382-b4c6-d17d9sm42855 + https://csi-tst-q22.it.com:22443/Services/com/cingular/csi/sdn/SendManagedNetworkStatusNotification.jws + OMX + 1 + + + activate + https://msojra.mtsnjdcp1.aic.cip.com:8443/adapters/rest/SDNCNotify + 5b1f3c5d-cdf9-488d-8a4b-d3f1229d7760 + + + MultiPoint + MTSNJA4LCP1 + AS/VLXM/003717//SW + + + FK/VLXM/003717//SW_INTERNET + ST E2E Test42855_1300004281555 + SDN-ETHERNET-INTERNET + + + 10 + Kbps + + 1 + 192.168.1.15 + 192.168.1.15 + 28 + + + 2 + 192.168.1.16 + 192.168.1.16 + 28 + + + 1 + 2001:1890:12e3:2da:: + 2001:1890:12e3:2da:: + 28 + + + 1 + 2001:1890:12e3:2da:: + 2001:1890:12e3:2da:: + 28 + + + + + +""" + +def sdncAdapterResponseEmpty = +""" + +""" + +def sdncAdapterResponseError = +""" + + + 39542e39-ccc3-4d1a-8b79-04ce88526613 + 404 + Error processing request to SDNC. Not Found. + https://sdncodl.us.aic.cip.com:8443/restconf/config/L3SDN-API:services/layer3-service-list/MVM%2FVLXP%2F000855%2F%2FShakeout. + SDNC Returned-[error-type:application, error-tag:data-missing, + error-message:Request could not be completed because the relevant + data model content does not exist.] + + +""" + + + @Test + public void testPreProcessRequest() { + + String sdncAdapterWorkflowRequest = FileUtil.readResourceFile("__files/SDN-ETHERNET-INTERNET/SDNCAdapterV1/sdncadapterworkflowrequest.xml"); + ExecutionEntity mockExecution = mock(ExecutionEntity.class) + when(mockExecution.getVariable("URN_mso_adapters_po_auth")).thenReturn("3141634BF7E070AA289CF2892C986C0B") + when(mockExecution.getVariable("URN_mso_msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7") + when(mockExecution.getVariable("sdncAdapterWorkflowRequest")).thenReturn(sdncAdapterWorkflowRequest) + when(mockExecution.getVariable("URN_mso_workflow_sdncadapter_callback")).thenReturn("http://someurl.someting.com:28080/mso/sdncAdapterCallbackServiceImpl") + when(mockExecution.getVariable("URN_mso_use_qualified_host")).thenReturn("true") + when(mockExecution.getProcessInstanceId()).thenReturn("745b1b50-e39e-4685-9cc8-c71f0bde8bf0") + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + + + SDNCAdapter sdncAdapter = new SDNCAdapter() + sdncAdapter.preProcessRequest(mockExecution) + + MockitoDebuggerImpl debugger = new MockitoDebuggerImpl() + debugger.printInvocations(mockExecution) + + + verify(mockExecution).setVariable("prefix","SDNCA_") + verify(mockExecution).setVariable("sdncAdapterResponse","") + verify(mockExecution).setVariable("asynchronousResponseTimeout",false) + verify(mockExecution).setVariable("continueListening",false) + verify(mockExecution).setVariable("BasicAuthHeaderValue","Basic cGFzc3dvcmQ=") + verify(mockExecution).setVariable("serviceConfigActivate",false) + verify(mockExecution).setVariable("SDNCA_requestId", "745b1b50-e39e-4685-9cc8-c71f0bde8bf0") + verify(mockExecution).setVariable("SDNCA_SuccessIndicator",false) + verify(mockExecution).setVariable("source","") + verify(mockExecution).setVariable("sdncAdapterRequest", sdncAdapterRequest) + } + + @Test + public void testProcessResponse() + { + String sdncAdapterCallbackResponse = FileUtil.readResourceFile("__files/SDN-ETHERNET-INTERNET/SDNCAdapterV1mock/sdncadaptercallbackrequest.xml"); + ExecutionEntity mockExecution = mock(ExecutionEntity.class) + when(mockExecution.getVariable("sdncAdapterCallbackRequest")).thenReturn(sdncAdapterCallbackResponse) + SDNCAdapter sdncAdapter = new SDNCAdapter() + sdncAdapter.postProcessResponse(mockExecution) + +// MockitoDebuggerImpl debugger = new MockitoDebuggerImpl() +// debugger.printInvocations(mockExecution) + + verify(mockExecution).getVariable("isDebugLogEnabled") + verify(mockExecution,times(2)).getVariable("sdncAdapterCallbackRequest") + verify(mockExecution).setVariable("sdncAdapterResponse",workflowResponse) + verify(mockExecution).setVariable("enhancedCallbackRequestData",enhancedCallbackRequestData) + verify(mockExecution).setVariable("continueListening",false) + + } + + @Test + public void testProcessResponse_ErrorCase_404() + { + String sdncAdapterCallbackErrorResponse = FileUtil.readResourceFile("sdncadaptercallbackrequest_404CallBack.xml"); + ExecutionEntity mockExecution = mock(ExecutionEntity.class) + when(mockExecution.getVariable("sdncAdapterCallbackRequest")).thenReturn(sdncAdapterCallbackErrorResponse) + SDNCAdapter sdncAdapter = new SDNCAdapter() + sdncAdapter.postProcessResponse(mockExecution) + + verify(mockExecution, times(1)).getVariable("isDebugLogEnabled") + verify(mockExecution,times(2)).getVariable("sdncAdapterCallbackRequest") + verify(mockExecution).setVariable("sdncAdapterResponse", sdncAdapterResponseError) + verify(mockExecution).setVariable("enhancedCallbackRequestData", "") + verify(mockExecution).setVariable("continueListening",false) + + } + + @Test + public void testProcessResponse_ErrorCase_InvalidCallback() + { + ExecutionEntity mockExecution = mock(ExecutionEntity.class) + when(mockExecution.getVariable("sdncAdapterCallbackRequest")).thenReturn("

Service Unavailable

") + SDNCAdapter sdncAdapter = new SDNCAdapter() + sdncAdapter.postProcessResponse(mockExecution) + + verify(mockExecution).getVariable("isDebugLogEnabled") + verify(mockExecution,times(2)).getVariable("sdncAdapterCallbackRequest") + verify(mockExecution).setVariable("sdncAdapterResponse", sdncAdapterResponseEmpty) + verify(mockExecution).setVariable("enhancedCallbackRequestData", "") + verify(mockExecution).setVariable("continueListening",false) + + } + + @Test + public void postProcessResponse() + { + + String SDNCAdapterCallbackRequest = + """ + + + 3bb02798-b344-4d28-9bca-1f029954d1c9 + 404 + Error processing request to SDNC. Not Found. + https://sdncodl.us.infra.aic.net:8443/restconf/config/L3SDN-API:services/layer3-service-list/85%2FCSIP%2F141203%2FPT_CSI9999998693. + SDNC Returned-[error-type:application, error-tag:data-missing, + error-message:Request could not be completed because the relevant + data model content does not exist ] + +""" + + String sdncAdapterResponse = + """ + + + 3bb02798-b344-4d28-9bca-1f029954d1c9 + 404 + Error processing request to SDNC. Not Found. + https://sdncodl.us.infra.aic.net:8443/restconf/config/L3SDN-API:services/layer3-service-list/85%2FCSIP%2F141203%2FPT_CSI9999998693. + SDNC Returned-[error-type:application, error-tag:data-missing, + error-message:Request could not be completed because the relevant + data model content does not exist ] + + +""" + + ExecutionEntity mockExecution = mock(ExecutionEntity.class) + when(mockExecution.getVariable("sdncAdapterCallbackRequest")).thenReturn(SDNCAdapterCallbackRequest) + SDNCAdapter sdncAdapter = new SDNCAdapter() + sdncAdapter.postProcessResponse(mockExecution) + + verify(mockExecution).getVariable("isDebugLogEnabled") + verify(mockExecution,times(2)).getVariable("sdncAdapterCallbackRequest") + verify(mockExecution).setVariable("sdncAdapterResponse", sdncAdapterResponse) + verify(mockExecution).setVariable("enhancedCallbackRequestData", "") + verify(mockExecution).setVariable("continueListening",false) + + } + } \ No newline at end of file diff --git a/bpmn/MSOCommonBPMN/src/test/groovy/org/openecomp/mso/bpmn/common/scripts/TrinityExceptionUtilTest.groovy b/bpmn/MSOCommonBPMN/src/test/groovy/org/openecomp/mso/bpmn/common/scripts/TrinityExceptionUtilTest.groovy new file mode 100644 index 0000000000..b525967569 --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/test/groovy/org/openecomp/mso/bpmn/common/scripts/TrinityExceptionUtilTest.groovy @@ -0,0 +1,201 @@ +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.bpmn.common.scripts + +import org.junit.Assert +import org.junit.Ignore +import org.junit.runner.RunWith; +import org.mockito.runners.MockitoJUnitRunner; + + + +import static org.mockito.Mockito.* + +import org.camunda.bpm.engine.impl.persistence.entity.ExecutionEntity +import org.junit.Before +import org.junit.runner.RunWith +import org.mockito.MockitoAnnotations +import org.mockito.internal.debugging.MockitoDebuggerImpl +import org.mockito.runners.MockitoJUnitRunner +import org.openecomp.mso.bpmn.common.scripts.TrinityExceptionUtil; +@RunWith(MockitoJUnitRunner.class) +import org.junit.Test + +class TrinityExceptionUtilTest { + + def aotsFault =""" + xml:space + String + http://test.com + + + + 400 + bad stuff + + + String + *** ERROR *** + String + String + String + String + + String + String + + String + String + String + String + + + + + + String + *** ERROR *** + String + String + String + String + String + String + String + + +""" + + + @Before + public void init() + { + MockitoAnnotations.initMocks(this) + } + + @Test + @Ignore + public void testMapAAIExceptionTCommonException() { + + + + String restFault = """ + + + +SVC3002 +Error writing output performing %1 on %2 (msg=%3) (ec=%4) + +PUTcustomer +SubName01 +Unexpected error reading/updating database:Adding this property for key [service-instance-id] and value [USSTU2CFCNC0101UJZZ01] violates a uniqueness constraint [service-instance-id] +ERR.5.4.5105 + + + + + """ + def errorString = """ + +SVC3002 +Error writing output performing %1 on %2 (msg=%3) (ec=%4) + +PUTcustomer +SubName01 +Unexpected error reading/updating database:Adding this property for key [service-instance-id] and value [USSTU2CFCNC0101UJZZ01] violates a uniqueness constraint [service-instance-id] +ERR.5.4.5105 + + +""" as String + + + + ExecutionEntity mockExecution = mock(ExecutionEntity.class) + + TrinityExceptionUtil util = new TrinityExceptionUtil() + Assert.assertEquals(errorString, util.mapAAIExceptionTCommonException(restFault, mockExecution)) + } + + + + + @Test + public void testBuildException() { + ExecutionEntity mockExecution = mock(ExecutionEntity.class) + when(mockExecution.getVariable("prefix")).thenReturn("test_") + when(mockExecution.getVariable("test_ResponseCode")).thenReturn("400") + ArrayList msgVars = new ArrayList() + msgVars.add("var1") + msgVars.add("var2") + when(mockExecution.getVariable("test_errVariables")).thenReturn(msgVars) + + + TrinityExceptionUtil util = new TrinityExceptionUtil() + String msg = "Bad request" + String errorString = """ + + SVC2000 + The following service error occurred: %1. Error code is %2. + var1 + var2 + +""" + Assert.assertEquals(errorString, util.buildException(msg, mockExecution)) + } + + @Test + public void testMapAOTSExecptionToCommonException() { + ExecutionEntity mockExecution = mock(ExecutionEntity.class) + when(mockExecution.getVariable("prefix")).thenReturn("test_") + when(mockExecution.getVariable("test_ResponseCode")).thenReturn("400") + + TrinityExceptionUtil util = new TrinityExceptionUtil() + String errorString = """ + + SVC2000 + The following service error occurred: %1. Error code is %2. + Received error from AOTS: bad stuff + 400 + +""" + Assert.assertEquals(errorString, util.mapAOTSExecptionToCommonException(aotsFault, mockExecution)) + } + + + @Test + public void testParseError() { + ExecutionEntity mockExecution = mock(ExecutionEntity.class) + String errorString = "The following service error occurred: %1. Error code is %2." + ArrayList msgVars = new ArrayList() + msgVars.add("var1") + msgVars.add("var2") + when(mockExecution.getVariable("prefix")).thenReturn("test_") + when(mockExecution.getVariable("test_errTxt")).thenReturn(errorString) + when(mockExecution.getVariable("test_errVariables")).thenReturn(msgVars) + + TrinityExceptionUtil util = new TrinityExceptionUtil() + + Assert.assertEquals("The following service error occurred: var1. Error code is var2.", util.parseError(mockExecution)) +} + + + +} diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/BPMNUtil.java b/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/BPMNUtil.java index 4e2b1e121a..27f2479a7b 100644 --- a/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/BPMNUtil.java +++ b/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/BPMNUtil.java @@ -1,214 +1,214 @@ -package org.openecomp.mso.bpmn.common; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.spy; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.ws.rs.core.Response; - -import org.camunda.bpm.engine.ProcessEngineServices; -import org.camunda.bpm.engine.history.HistoricProcessInstance; -import org.camunda.bpm.engine.history.HistoricVariableInstance; -import org.camunda.bpm.engine.variable.impl.VariableMapImpl; -import org.jboss.resteasy.spi.AsynchronousResponse; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; -import org.openecomp.mso.bpmn.common.workflow.service.WorkflowAsyncCommonResource; -import org.openecomp.mso.bpmn.common.workflow.service.WorkflowResource; -import org.openecomp.mso.bpmn.common.workflow.service.WorkflowResponse; - -/** - * Set of utility methods used for Unit testing - * - */ -public class BPMNUtil { - - public static String getVariable(ProcessEngineServices processEngineServices, String processDefinitionID, String name) { - String pID = getProcessInstanceId(processEngineServices, - processDefinitionID); - assertProcessInstanceFinished(processEngineServices, pID); - HistoricVariableInstance responseData = processEngineServices.getHistoryService() - .createHistoricVariableInstanceQuery().processInstanceId(pID) - .variableName(name) - .singleResult(); - - if (responseData != null) { - return (responseData.getValue() != null ? responseData.getValue().toString(): null); - } - return null; - } - - @SuppressWarnings("unchecked") - public static T getRawVariable(ProcessEngineServices processEngineServices, String processDefinitionID, String name) { - String pID = getProcessInstanceId(processEngineServices, - processDefinitionID); - assertProcessInstanceFinished(processEngineServices, pID); - Object responseData = processEngineServices.getHistoryService() - .createHistoricVariableInstanceQuery().processInstanceId(pID) - .variableName(name) - .singleResult() - .getValue(); - return (T) responseData; - } - - - public static void assertProcessInstanceFinished(ProcessEngineServices processEngineServices, String pid) { - assertEquals(1, processEngineServices.getHistoryService().createHistoricProcessInstanceQuery().processInstanceId(pid).finished().count()); - } - - public static void assertProcessInstanceNotFinished(ProcessEngineServices processEngineServices, String processDefinitionID) { - String pID = getProcessInstanceId(processEngineServices, - processDefinitionID); - assertEquals(0, processEngineServices.getHistoryService().createHistoricProcessInstanceQuery().processInstanceId(pID).finished().count()); - } - - private static String getProcessInstanceId( - ProcessEngineServices processEngineServices, String processDefinitionID) { - List historyList = processEngineServices.getHistoryService().createHistoricProcessInstanceQuery().list(); - String pID = null; - for (HistoricProcessInstance hInstance: historyList) { - if (hInstance.getProcessDefinitionKey().equals(processDefinitionID)) { - pID = hInstance.getId(); - break; - } - } - return pID; - } - - public static boolean isProcessInstanceFinished(ProcessEngineServices processEngineServices, String pid) { - return processEngineServices.getHistoryService().createHistoricProcessInstanceQuery().processInstanceId(pid).finished().count() == 1 ? true: false; - } - - - private static void buildVariable(String key, String value, Map variableValueType) { - Map host = new HashMap(); - host.put("value", value); - host.put("type", "String"); - variableValueType.put(key, host); - } - - public static WorkflowResponse executeWorkFlow(ProcessEngineServices processEngineServices, String processKey, Map variables) { - WorkflowResource workflowResource = new WorkflowResource(); - VariableMapImpl variableMap = new VariableMapImpl(); - - Map variableValueType = new HashMap(); - for (String key : variables.keySet()) { - buildVariable(key, variables.get(key), variableValueType); - } - buildVariable("mso-service-request-timeout","600", variableValueType); - variableMap.put("variables", variableValueType); - - workflowResource.setProcessEngineServices4junit(processEngineServices); - Response response = workflowResource.startProcessInstanceByKey( - processKey, variableMap); - WorkflowResponse workflowResponse = (WorkflowResponse) response.getEntity(); - return workflowResponse; - } - - //Check the runtime service to see whether the process is completed - public static void waitForWorkflowToFinish(ProcessEngineServices processEngineServices, String pid) throws InterruptedException { - // Don't wait forever - long waitTime = 120000; - long endTime = System.currentTimeMillis() + waitTime; - - while (true) { - if (processEngineServices.getRuntimeService().createProcessInstanceQuery().processInstanceId(pid).singleResult() == null) { - break; - } - - if (System.currentTimeMillis() >= endTime) { - fail("Process " + pid + " did not finish in " + waitTime + "ms"); - } - - Thread.sleep(200); - } - } - - /** - * Executes the Asynchronous workflow in synchronous fashion and returns the WorkflowResponse object - * @param processEngineServices - * @param processKey - * @param variables - * @return - * @throws InterruptedException - */ - public static WorkflowResponse executeAsyncWorkflow(ProcessEngineServices processEngineServices, String processKey, Map variables) throws InterruptedException { - ProcessThread pthread = new ProcessThread(processKey, processEngineServices, variables); - pthread.start(); - BPMNUtil.assertProcessInstanceNotFinished(processEngineServices, processKey); - String pid = getProcessInstanceId(processEngineServices, processKey); - //Caution: If there is a problem with workflow, this may wait for ever - while (true) { - pid = getProcessInstanceId(processEngineServices, processKey); - if (!isProcessInstanceFinished(processEngineServices,pid)) { - Thread.sleep(200); - } else{ - break; - } - } - //need to retrieve for second time ? - pid = getProcessInstanceId(processEngineServices, processKey); - waitForWorkflowToFinish(processEngineServices, pid); - return pthread.workflowResponse; - } - - /** - * Execute workflow using async resource - * @param processEngineServices - * @param processKey - * @param asyncResponse - * @param variables - */ - private static void executeAsyncFlow(ProcessEngineServices processEngineServices, String processKey, AsynchronousResponse asyncResponse, Map variables) { - WorkflowAsyncCommonResource workflowResource = new WorkflowAsyncCommonResource(); - VariableMapImpl variableMap = new VariableMapImpl(); - - Map variableValueType = new HashMap(); - for (String key : variables.keySet()) { - buildVariable(key, variables.get(key), variableValueType); - } - buildVariable("mso-service-request-timeout","600", variableValueType); - variableMap.put("variables", variableValueType); - - workflowResource.setProcessEngineServices4junit(processEngineServices); - workflowResource.startProcessInstanceByKey(asyncResponse, processKey, variableMap); - } - - /** - * Helper class which executes workflow in a thread - * - */ - static class ProcessThread extends Thread { - - public WorkflowResponse workflowResponse = null; - public String processKey; - public AsynchronousResponse asyncResponse = spy(AsynchronousResponse.class); - public boolean started; - public ProcessEngineServices processEngineServices; - public Map variables; - - public ProcessThread(String processKey, ProcessEngineServices processEngineServices, Map variables) { - this.processKey = processKey; - this.processEngineServices = processEngineServices; - this.variables = variables; - } - - public void run() { - started = true; - doAnswer(new Answer() { - public Void answer(InvocationOnMock invocation) { - Response response = (Response) invocation.getArguments()[0]; - workflowResponse = (WorkflowResponse) response.getEntity(); - return null; - } - }).when(asyncResponse).setResponse(any(Response.class)); - executeAsyncFlow(processEngineServices, processKey, asyncResponse, variables); - } - } -} +package org.openecomp.mso.bpmn.common; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.spy; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.ws.rs.core.Response; + +import org.camunda.bpm.engine.ProcessEngineServices; +import org.camunda.bpm.engine.history.HistoricProcessInstance; +import org.camunda.bpm.engine.history.HistoricVariableInstance; +import org.camunda.bpm.engine.variable.impl.VariableMapImpl; +import org.jboss.resteasy.spi.AsynchronousResponse; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; +import org.openecomp.mso.bpmn.common.workflow.service.WorkflowAsyncCommonResource; +import org.openecomp.mso.bpmn.common.workflow.service.WorkflowResource; +import org.openecomp.mso.bpmn.common.workflow.service.WorkflowResponse; + +/** + * Set of utility methods used for Unit testing + * + */ +public class BPMNUtil { + + public static String getVariable(ProcessEngineServices processEngineServices, String processDefinitionID, String name) { + String pID = getProcessInstanceId(processEngineServices, + processDefinitionID); + assertProcessInstanceFinished(processEngineServices, pID); + HistoricVariableInstance responseData = processEngineServices.getHistoryService() + .createHistoricVariableInstanceQuery().processInstanceId(pID) + .variableName(name) + .singleResult(); + + if (responseData != null) { + return (responseData.getValue() != null ? responseData.getValue().toString(): null); + } + return null; + } + + @SuppressWarnings("unchecked") + public static T getRawVariable(ProcessEngineServices processEngineServices, String processDefinitionID, String name) { + String pID = getProcessInstanceId(processEngineServices, + processDefinitionID); + assertProcessInstanceFinished(processEngineServices, pID); + Object responseData = processEngineServices.getHistoryService() + .createHistoricVariableInstanceQuery().processInstanceId(pID) + .variableName(name) + .singleResult() + .getValue(); + return (T) responseData; + } + + + public static void assertProcessInstanceFinished(ProcessEngineServices processEngineServices, String pid) { + assertEquals(1, processEngineServices.getHistoryService().createHistoricProcessInstanceQuery().processInstanceId(pid).finished().count()); + } + + public static void assertProcessInstanceNotFinished(ProcessEngineServices processEngineServices, String processDefinitionID) { + String pID = getProcessInstanceId(processEngineServices, + processDefinitionID); + assertEquals(0, processEngineServices.getHistoryService().createHistoricProcessInstanceQuery().processInstanceId(pID).finished().count()); + } + + private static String getProcessInstanceId( + ProcessEngineServices processEngineServices, String processDefinitionID) { + List historyList = processEngineServices.getHistoryService().createHistoricProcessInstanceQuery().list(); + String pID = null; + for (HistoricProcessInstance hInstance: historyList) { + if (hInstance.getProcessDefinitionKey().equals(processDefinitionID)) { + pID = hInstance.getId(); + break; + } + } + return pID; + } + + public static boolean isProcessInstanceFinished(ProcessEngineServices processEngineServices, String pid) { + return processEngineServices.getHistoryService().createHistoricProcessInstanceQuery().processInstanceId(pid).finished().count() == 1 ? true: false; + } + + + private static void buildVariable(String key, String value, Map variableValueType) { + Map host = new HashMap(); + host.put("value", value); + host.put("type", "String"); + variableValueType.put(key, host); + } + + public static WorkflowResponse executeWorkFlow(ProcessEngineServices processEngineServices, String processKey, Map variables) { + WorkflowResource workflowResource = new WorkflowResource(); + VariableMapImpl variableMap = new VariableMapImpl(); + + Map variableValueType = new HashMap(); + for (String key : variables.keySet()) { + buildVariable(key, variables.get(key), variableValueType); + } + buildVariable("mso-service-request-timeout","600", variableValueType); + variableMap.put("variables", variableValueType); + + workflowResource.setProcessEngineServices4junit(processEngineServices); + Response response = workflowResource.startProcessInstanceByKey( + processKey, variableMap); + WorkflowResponse workflowResponse = (WorkflowResponse) response.getEntity(); + return workflowResponse; + } + + //Check the runtime service to see whether the process is completed + public static void waitForWorkflowToFinish(ProcessEngineServices processEngineServices, String pid) throws InterruptedException { + // Don't wait forever + long waitTime = 120000; + long endTime = System.currentTimeMillis() + waitTime; + + while (true) { + if (processEngineServices.getRuntimeService().createProcessInstanceQuery().processInstanceId(pid).singleResult() == null) { + break; + } + + if (System.currentTimeMillis() >= endTime) { + fail("Process " + pid + " did not finish in " + waitTime + "ms"); + } + + Thread.sleep(200); + } + } + + /** + * Executes the Asynchronous workflow in synchronous fashion and returns the WorkflowResponse object + * @param processEngineServices + * @param processKey + * @param variables + * @return + * @throws InterruptedException + */ + public static WorkflowResponse executeAsyncWorkflow(ProcessEngineServices processEngineServices, String processKey, Map variables) throws InterruptedException { + ProcessThread pthread = new ProcessThread(processKey, processEngineServices, variables); + pthread.start(); + BPMNUtil.assertProcessInstanceNotFinished(processEngineServices, processKey); + String pid = getProcessInstanceId(processEngineServices, processKey); + //Caution: If there is a problem with workflow, this may wait for ever + while (true) { + pid = getProcessInstanceId(processEngineServices, processKey); + if (!isProcessInstanceFinished(processEngineServices,pid)) { + Thread.sleep(200); + } else{ + break; + } + } + //need to retrieve for second time ? + pid = getProcessInstanceId(processEngineServices, processKey); + waitForWorkflowToFinish(processEngineServices, pid); + return pthread.workflowResponse; + } + + /** + * Execute workflow using async resource + * @param processEngineServices + * @param processKey + * @param asyncResponse + * @param variables + */ + private static void executeAsyncFlow(ProcessEngineServices processEngineServices, String processKey, AsynchronousResponse asyncResponse, Map variables) { + WorkflowAsyncCommonResource workflowResource = new WorkflowAsyncCommonResource(); + VariableMapImpl variableMap = new VariableMapImpl(); + + Map variableValueType = new HashMap(); + for (String key : variables.keySet()) { + buildVariable(key, variables.get(key), variableValueType); + } + buildVariable("mso-service-request-timeout","600", variableValueType); + variableMap.put("variables", variableValueType); + + workflowResource.setProcessEngineServices4junit(processEngineServices); + workflowResource.startProcessInstanceByKey(asyncResponse, processKey, variableMap); + } + + /** + * Helper class which executes workflow in a thread + * + */ + static class ProcessThread extends Thread { + + public WorkflowResponse workflowResponse = null; + public String processKey; + public AsynchronousResponse asyncResponse = spy(AsynchronousResponse.class); + public boolean started; + public ProcessEngineServices processEngineServices; + public Map variables; + + public ProcessThread(String processKey, ProcessEngineServices processEngineServices, Map variables) { + this.processKey = processKey; + this.processEngineServices = processEngineServices; + this.variables = variables; + } + + public void run() { + started = true; + doAnswer(new Answer() { + public Void answer(InvocationOnMock invocation) { + Response response = (Response) invocation.getArguments()[0]; + workflowResponse = (WorkflowResponse) response.getEntity(); + return null; + } + }).when(asyncResponse).setResponse(any(Response.class)); + executeAsyncFlow(processEngineServices, processKey, asyncResponse, variables); + } + } +} diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/CompleteMsoProcessTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/CompleteMsoProcessTest.java index 5cd59f38dd..e99f2a8917 100644 --- a/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/CompleteMsoProcessTest.java +++ b/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/CompleteMsoProcessTest.java @@ -1,207 +1,217 @@ -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - MSO - * ================================================================================ - * 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.openecomp.mso.bpmn.common; - -import static org.openecomp.mso.bpmn.common.BPMNUtil.executeWorkFlow; -import static org.openecomp.mso.bpmn.common.BPMNUtil.waitForWorkflowToFinish; -import static org.openecomp.mso.bpmn.mock.StubResponseDatabase.mockUpdateRequestDB; - -import java.util.HashMap; -import java.util.Map; - -import org.camunda.bpm.engine.test.Deployment; -import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Test; -import org.openecomp.mso.bpmn.common.workflow.service.WorkflowResponse; - -/** - * Unit test for CompleteMsoProcess.bpmn. - */ -public class CompleteMsoProcessTest extends WorkflowTest { - - private void executeFlow(String inputRequestFile) throws InterruptedException { - mockUpdateRequestDB(200, "Database/DBUpdateResponse.xml"); - - //String changeFeatureActivateRequest = FileUtil.readResourceFile("__files/SDN-ETHERNET-INTERNET/ChangeFeatureActivateV1/" + inputRequestFile); - Map variables = new HashMap(); - variables.put("CompleteMsoProcessRequest",inputRequestFile); - - WorkflowResponse workflowResponse = executeWorkFlow(processEngineRule, "CompleteMsoProcess", variables); - waitForWorkflowToFinish(processEngineRule, workflowResponse.getProcessInstanceID()); - logEnd(); - } - - @Test - @Deployment(resources = {"subprocess/CompleteMsoProcess.bpmn"}) - public void msoCompletionRequestWithNotificationurl_200() throws Exception { - logStart(); - - //Execute Flow - executeFlow(gMsoCompletionRequestWithNotificationurl()); - - //Verify Error - String CMSO_ResponseCode = BPMNUtil.getVariable(processEngineRule, "CompleteMsoProcess", "CMSO_ResponseCode"); - Assert.assertEquals("200", CMSO_ResponseCode); - Assert.assertTrue((boolean) BPMNUtil.getRawVariable(processEngineRule, "CompleteMsoProcess", "CMSO_SuccessIndicator")); - logEnd(); - } - - @Test - @Ignore // BROKEN TEST - @Deployment(resources = {"subprocess/CompleteMsoProcess.bpmn"}) - public void msoCompletionRequestWithNotificationurl_500() throws Exception { - logStart(); - - //Execute Flow - executeFlow(gMsoCompletionRequestWithNotificationurl()); - - //Verify Error - String CMSO_ResponseCode = BPMNUtil.getVariable(processEngineRule, "CompleteMsoProcess", "CMSO_ResponseCode"); - Assert.assertEquals("500", CMSO_ResponseCode); - Assert.assertFalse((boolean) BPMNUtil.getRawVariable(processEngineRule, "CompleteMsoProcess", "CMSO_SuccessIndicator")); - logEnd(); - } - - @Test - @Deployment(resources = {"subprocess/CompleteMsoProcess.bpmn"}) - public void msoCompletionRequestWithNoNotificationurl() throws Exception { - logStart(); - - //Execute Flow - executeFlow(gMsoCompletionRequestWithNoNotificationurl()); - - //Verify Error - String CMSO_ResponseCode = BPMNUtil.getVariable(processEngineRule, "CompleteMsoProcess", "CMSO_ResponseCode"); - Assert.assertEquals("200", CMSO_ResponseCode); - Assert.assertTrue((boolean) BPMNUtil.getRawVariable(processEngineRule, "CompleteMsoProcess", "CMSO_SuccessIndicator")); - logEnd(); - } - - @Test - @Deployment(resources = {"subprocess/CompleteMsoProcess.bpmn"}) - public void msoCompletionRequestWithNotificationurlNoRequestId() throws Exception { - logStart(); - - //Execute Flow - executeFlow(gMsoCompletionRequestWithNotificationurlNoRequestId()); - - //Verify Error - String CMSO_ResponseCode = BPMNUtil.getVariable(processEngineRule, "CompleteMsoProcess", "CMSO_ResponseCode"); - Assert.assertEquals("200", CMSO_ResponseCode); - Assert.assertTrue((boolean) BPMNUtil.getRawVariable(processEngineRule, "CompleteMsoProcess", "CMSO_SuccessIndicator")); - logEnd(); - } - - @Test - @Deployment(resources = {"subprocess/CompleteMsoProcess.bpmn"}) - public void msoCompletionRequestWithNoNotificationurlNoRequestId() throws Exception { - logStart(); - - //Execute Flow - executeFlow(gMsoCompletionRequestWithNoNotificationurlNoRequestId()); - - //Verify Error - String CMSO_ResponseCode = BPMNUtil.getVariable(processEngineRule, "CompleteMsoProcess", "CMSO_ResponseCode"); - Assert.assertEquals("200", CMSO_ResponseCode); - Assert.assertTrue((boolean) BPMNUtil.getRawVariable(processEngineRule, "CompleteMsoProcess", "CMSO_SuccessIndicator")); - logEnd(); - } - - public String gMsoCompletionRequestWithNotificationurl() { - //Generated the below XML from ActiveVOS moduler ... Using the generate sample XML feature in ActiveVOS - String xml = "" - + "" - + " " - + " uCPE1020_STUW105_5002" - + " Layer3ServiceActivateRequest" - + " COMPLETE" - + " OMX" - + " https://t3nap1a1.snt.bst.bls.com:9004/sdncontroller-sdncontroller-inbound-ws-war/sdncontroller-sdncontroller-inbound-ws.wsdl" - + " 10205000" - + " 1" - + " " - + " UCPELayer3ServiceActivateV1" - + ""; - - return xml; - } - - - - public String gMsoCompletionRequestWithNoNotificationurl() { - //Generated the below XML from ActiveVOS moduler ... Using the generate sample XML feature in ActiveVOS - String xml = "" - + "" - + " " - + " uCPE1020_STUW105_5002" - + " Layer3ServiceActivateRequest" - + " COMPLETE" - + " OMX" - + " " - + " 10205000" - + " 1" - + " " - + " UCPELayer3ServiceActivateV1" - + ""; - - return xml; - } - - public String gMsoCompletionRequestWithNoNotificationurlNoRequestId() { - //Generated the below XML from ActiveVOS moduler ... Using the generate sample XML feature in ActiveVOS - String xml = "" - + "" - + " " - + " " - + " Layer3ServiceActivateRequest" - + " COMPLETE" - + " OMX" - + " " - + " 10205000" - + " 1" - + " " - + " UCPELayer3ServiceActivateV1" - + ""; - - return xml; - } - - public String gMsoCompletionRequestWithNotificationurlNoRequestId() { - //Generated the below XML from ActiveVOS moduler ... Using the generate sample XML feature in ActiveVOS - String xml = "" - + "" - + " " - + " " - + " Layer3ServiceActivateRequest" - + " COMPLETE" - + " OMX" - + " https://t3nap1a1.snt.bst.bls.com:9004/sdncontroller-sdncontroller-inbound-ws-war/sdncontroller-sdncontroller-inbound-ws.wsdl" - + " 10205000" - + " 1" - + " " - + " UCPELayer3ServiceActivateV1" - + ""; - - return xml; - } -} - +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.bpmn.common; + +import static org.openecomp.mso.bpmn.common.BPMNUtil.executeWorkFlow; +import static org.openecomp.mso.bpmn.common.BPMNUtil.waitForWorkflowToFinish; +import static org.openecomp.mso.bpmn.mock.StubResponseDatabase.mockUpdateRequestDB; + +import java.util.HashMap; +import java.util.Map; + +import org.camunda.bpm.engine.test.Deployment; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; +import org.openecomp.mso.bpmn.common.workflow.service.WorkflowResponse; + +/** + * Unit test for CompleteMsoProcess.bpmn. + */ +public class CompleteMsoProcessTest extends WorkflowTest { + + private void executeFlow(String inputRequestFile) throws InterruptedException { + mockUpdateRequestDB(200, "Database/DBUpdateResponse.xml"); + + //String changeFeatureActivateRequest = FileUtil.readResourceFile("__files/SDN-ETHERNET-INTERNET/ChangeFeatureActivateV1/" + inputRequestFile); + Map variables = new HashMap(); + variables.put("CompleteMsoProcessRequest",inputRequestFile); + + WorkflowResponse workflowResponse = executeWorkFlow(processEngineRule, "CompleteMsoProcess", variables); + waitForWorkflowToFinish(processEngineRule, workflowResponse.getProcessInstanceID()); + logEnd(); + } + + @Test + @Deployment(resources = {"subprocess/CompleteMsoProcess.bpmn", + "subprocess/GenericNotificationService.bpmn" + }) + public void msoCompletionRequestWithNotificationurl_200() throws Exception { + logStart(); + + //Execute Flow + executeFlow(gMsoCompletionRequestWithNotificationurl()); + + //Verify Error + String CMSO_ResponseCode = BPMNUtil.getVariable(processEngineRule, "CompleteMsoProcess", "CMSO_ResponseCode"); + Assert.assertEquals("200", CMSO_ResponseCode); + Assert.assertTrue((boolean) BPMNUtil.getRawVariable(processEngineRule, "CompleteMsoProcess", "CMSO_SuccessIndicator")); + logEnd(); + } + + @Test + @Ignore // BROKEN TEST + @Deployment(resources = {"subprocess/CompleteMsoProcess.bpmn", + "subprocess/GenericNotificationService.bpmn" + }) + public void msoCompletionRequestWithNotificationurl_500() throws Exception { + logStart(); + + //Execute Flow + executeFlow(gMsoCompletionRequestWithNotificationurl()); + + //Verify Error + String CMSO_ResponseCode = BPMNUtil.getVariable(processEngineRule, "CompleteMsoProcess", "CMSO_ResponseCode"); + Assert.assertEquals("500", CMSO_ResponseCode); + Assert.assertFalse((boolean) BPMNUtil.getRawVariable(processEngineRule, "CompleteMsoProcess", "CMSO_SuccessIndicator")); + logEnd(); + } + + @Test + @Deployment(resources = {"subprocess/CompleteMsoProcess.bpmn", + "subprocess/GenericNotificationService.bpmn" + }) + public void msoCompletionRequestWithNoNotificationurl() throws Exception { + logStart(); + + //Execute Flow + executeFlow(gMsoCompletionRequestWithNoNotificationurl()); + + //Verify Error + String CMSO_ResponseCode = BPMNUtil.getVariable(processEngineRule, "CompleteMsoProcess", "CMSO_ResponseCode"); + Assert.assertEquals("200", CMSO_ResponseCode); + Assert.assertTrue((boolean) BPMNUtil.getRawVariable(processEngineRule, "CompleteMsoProcess", "CMSO_SuccessIndicator")); + logEnd(); + } + + @Test + @Deployment(resources = {"subprocess/CompleteMsoProcess.bpmn", + "subprocess/GenericNotificationService.bpmn" + }) + public void msoCompletionRequestWithNotificationurlNoRequestId() throws Exception { + logStart(); + + //Execute Flow + executeFlow(gMsoCompletionRequestWithNotificationurlNoRequestId()); + + //Verify Error + String CMSO_ResponseCode = BPMNUtil.getVariable(processEngineRule, "CompleteMsoProcess", "CMSO_ResponseCode"); + Assert.assertEquals("200", CMSO_ResponseCode); + Assert.assertTrue((boolean) BPMNUtil.getRawVariable(processEngineRule, "CompleteMsoProcess", "CMSO_SuccessIndicator")); + logEnd(); + } + + @Test + @Deployment(resources = {"subprocess/CompleteMsoProcess.bpmn", + "subprocess/GenericNotificationService.bpmn" + }) + public void msoCompletionRequestWithNoNotificationurlNoRequestId() throws Exception { + logStart(); + + //Execute Flow + executeFlow(gMsoCompletionRequestWithNoNotificationurlNoRequestId()); + + //Verify Error + String CMSO_ResponseCode = BPMNUtil.getVariable(processEngineRule, "CompleteMsoProcess", "CMSO_ResponseCode"); + Assert.assertEquals("200", CMSO_ResponseCode); + Assert.assertTrue((boolean) BPMNUtil.getRawVariable(processEngineRule, "CompleteMsoProcess", "CMSO_SuccessIndicator")); + logEnd(); + } + + public String gMsoCompletionRequestWithNotificationurl() { + //Generated the below XML from ActiveVOS moduler ... Using the generate sample XML feature in ActiveVOS + String xml = "" + + "" + + " " + + " uCPE1020_STUW105_5002" + + " Layer3ServiceActivateRequest" + + " COMPLETE" + + " OMX" + + " https://t3nap1a1.snt.bst.bls.com:9004/sdncontroller-sdncontroller-inbound-ws-war/sdncontroller-sdncontroller-inbound-ws.wsdl" + + " 10205000" + + " 1" + + " " + + " UCPELayer3ServiceActivateV1" + + ""; + + return xml; + } + + + + public String gMsoCompletionRequestWithNoNotificationurl() { + //Generated the below XML from ActiveVOS moduler ... Using the generate sample XML feature in ActiveVOS + String xml = "" + + "" + + " " + + " uCPE1020_STUW105_5002" + + " Layer3ServiceActivateRequest" + + " COMPLETE" + + " OMX" + + " " + + " 10205000" + + " 1" + + " " + + " UCPELayer3ServiceActivateV1" + + ""; + + return xml; + } + + public String gMsoCompletionRequestWithNoNotificationurlNoRequestId() { + //Generated the below XML from ActiveVOS moduler ... Using the generate sample XML feature in ActiveVOS + String xml = "" + + "" + + " " + + " " + + " Layer3ServiceActivateRequest" + + " COMPLETE" + + " OMX" + + " " + + " 10205000" + + " 1" + + " " + + " UCPELayer3ServiceActivateV1" + + ""; + + return xml; + } + + public String gMsoCompletionRequestWithNotificationurlNoRequestId() { + //Generated the below XML from ActiveVOS moduler ... Using the generate sample XML feature in ActiveVOS + String xml = "" + + "" + + " " + + " " + + " Layer3ServiceActivateRequest" + + " COMPLETE" + + " OMX" + + " https://t3nap1a1.snt.bst.bls.com:9004/sdncontroller-sdncontroller-inbound-ws-war/sdncontroller-sdncontroller-inbound-ws.wsdl" + + " 10205000" + + " 1" + + " " + + " UCPELayer3ServiceActivateV1" + + ""; + + return xml; + } +} + diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/CreateAAIVfModuleTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/CreateAAIVfModuleTest.java index b41d2d2558..63b1f77619 100644 --- a/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/CreateAAIVfModuleTest.java +++ b/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/CreateAAIVfModuleTest.java @@ -1,277 +1,277 @@ -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - MSO - * ================================================================================ - * 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.openecomp.mso.bpmn.common; - -import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; -import static com.github.tomakehurst.wiremock.client.WireMock.containing; -import static com.github.tomakehurst.wiremock.client.WireMock.put; -import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; -import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching; -import static org.openecomp.mso.bpmn.common.DeleteAAIVfModuleTest.MockAAIGenericVnfSearch; - -import java.util.HashMap; -import java.util.Map; - -import org.camunda.bpm.engine.RuntimeService; -import org.camunda.bpm.engine.test.Deployment; -import org.junit.Assert; -import org.junit.Test; -import org.openecomp.mso.bpmn.core.WorkflowException; - -/** - * Unit test for CreateAAIVfModule.bpmn. - */ -public class CreateAAIVfModuleTest extends WorkflowTest { - - @Test - @Deployment(resources = { - "subprocess/CreateAAIVfModule.bpmn" - }) - public void TestCreateGenericVnfSuccess_200() { - - MockAAIGenericVnfSearch(); - MockAAICreateGenericVnf(); - MockAAIVfModulePUT(true); - RuntimeService runtimeService = processEngineRule.getRuntimeService(); - Map variables = new HashMap(); - variables.put("isDebugLogEnabled","true"); - variables.put("isVidRequest", "false"); - variables.put("vnfName", "STMTN5MMSC22"); - variables.put("serviceId", "00000000-0000-0000-0000-000000000000"); - variables.put("personaModelId", "973ed047-d251-4fb9-bf1a-65b8949e0a73"); - variables.put("personaModelVersion", "1.0"); - variables.put("vfModuleName", "STMTN5MMSC22-MMSC::module-0-0"); - variables.put("vfModuleModelName", "MMSC::module-0"); - - runtimeService.startProcessInstanceByKey("CreateAAIVfModule", variables); - String response = BPMNUtil.getVariable(processEngineRule, "CreateAAIVfModule", "CAAIVfMod_createVfModuleResponseCode"); - String responseCode = BPMNUtil.getVariable(processEngineRule, "CreateAAIVfModule", "CAAIVfMod_createVfModuleResponseCode"); - Assert.assertEquals("201", responseCode); - System.out.println(response); - } - - @Test - @Deployment(resources = { - "subprocess/CreateAAIVfModule.bpmn" - }) - public void TestCreateVfModuleSuccess_200() { - // create Add-on VF Module for existing Generic VNF - MockAAIGenericVnfSearch(); - MockAAICreateGenericVnf(); - MockAAIVfModulePUT(true); - RuntimeService runtimeService = processEngineRule.getRuntimeService(); - Map variables = new HashMap(); - variables.put("isDebugLogEnabled","true"); - variables.put("isVidRequest", "false"); - variables.put("vnfId", "a27ce5a9-29c4-4c22-a017-6615ac73c721"); - variables.put("serviceId", "00000000-0000-0000-0000-000000000000"); - variables.put("personaModelId", "973ed047-d251-4fb9-bf1a-65b8949e0a73"); - variables.put("personaModelVersion", "1.0"); - variables.put("vfModuleName", "STMTN5MMSC21-MMSC::module-1-0"); - variables.put("vfModuleModelName", "STMTN5MMSC21-MMSC::model-1-0"); - runtimeService.startProcessInstanceByKey("CreateAAIVfModule", variables); - String response = BPMNUtil.getVariable(processEngineRule, "CreateAAIVfModule", "CAAIVfMod_createVfModuleResponseCode"); - String responseCode = BPMNUtil.getVariable(processEngineRule, "CreateAAIVfModule", "CAAIVfMod_createVfModuleResponseCode"); - Assert.assertEquals("201", responseCode); - System.out.println(response); - } - - @Test - @Deployment(resources = { - "subprocess/CreateAAIVfModule.bpmn" - }) - public void TestQueryGenericVnfFailure_5000() { - MockAAIGenericVnfSearch(); - MockAAICreateGenericVnf(); - MockAAIVfModulePUT(true); - RuntimeService runtimeService = processEngineRule.getRuntimeService(); - Map variables = new HashMap(); - variables.put("isDebugLogEnabled","true"); - variables.put("isVidRequest", "false"); - variables.put("vnfName", "STMTN5MMSC23"); - variables.put("serviceId", "00000000-0000-0000-0000-000000000000"); - variables.put("personaModelId", "973ed047-d251-4fb9-bf1a-65b8949e0a73"); - variables.put("personaModelVersion", "1.0"); - variables.put("vfModuleName", "STMTN5MMSC23-MMSC::module-0-0"); - variables.put("vfModuleModelName", "MMSC::module-0"); - runtimeService.startProcessInstanceByKey("CreateAAIVfModule", variables); - WorkflowException exception = BPMNUtil.getRawVariable(processEngineRule, "CreateAAIVfModule", "WorkflowException"); - Assert.assertEquals(5000, exception.getErrorCode()); - Assert.assertEquals(true, exception.getErrorMessage().contains("SVC3002")); - System.out.println(exception.getErrorMessage()); - } - - @Test - @Deployment(resources = { - "subprocess/CreateAAIVfModule.bpmn" - }) - public void TestCreateDupGenericVnfFailure_1002() { - MockAAIGenericVnfSearch(); - MockAAICreateGenericVnf(); - MockAAIVfModulePUT(true); - RuntimeService runtimeService = processEngineRule.getRuntimeService(); - Map variables = new HashMap(); - variables.put("isDebugLogEnabled","true"); - variables.put("isVidRequest", "false"); - variables.put("vnfName", "STMTN5MMSC21"); - variables.put("serviceId", "00000000-0000-0000-0000-000000000000"); - variables.put("personaModelId", "973ed047-d251-4fb9-bf1a-65b8949e0a73"); - variables.put("personaModelVersion", "1.0"); - variables.put("vfModuleName", "STMTN5MMSC21-MMSC::module-0-0"); - variables.put("vfModuleModelName", "MMSC::module-0"); - runtimeService.startProcessInstanceByKey("CreateAAIVfModule", variables); - WorkflowException exception = BPMNUtil.getRawVariable(processEngineRule, "CreateAAIVfModule", "WorkflowException"); - Assert.assertEquals(1002, exception.getErrorCode()); - Assert.assertEquals(true, exception.getErrorMessage().contains("Invalid request for new Generic VNF which already exists")); - System.out.println(exception.getErrorMessage()); - } - - @Test - @Deployment(resources = { - "subprocess/CreateAAIVfModule.bpmn" - }) - public void TestCreateDupVfModuleFailure_1002() { - MockAAIGenericVnfSearch(); - MockAAICreateGenericVnf(); - MockAAIVfModulePUT(true); - RuntimeService runtimeService = processEngineRule.getRuntimeService(); - Map variables = new HashMap(); - variables.put("isDebugLogEnabled","true"); - variables.put("isVidRequest", "false"); - variables.put("vnfId", "2f6aee38-1e2a-11e6-82d1-ffc7d9ee8aa4"); - variables.put("serviceId", "00000000-0000-0000-0000-000000000000"); - variables.put("personaModelId", "973ed047-d251-4fb9-bf1a-65b8949e0a73"); - variables.put("personaModelVersion", "1.0"); - variables.put("vfModuleName", "STMTN5MMSC20-MMSC::module-1-0"); - variables.put("vfModuleModelName", "STMTN5MMSC20-MMSC::model-1-0"); - runtimeService.startProcessInstanceByKey("CreateAAIVfModule", variables); - WorkflowException exception = BPMNUtil.getRawVariable(processEngineRule, "CreateAAIVfModule", "WorkflowException"); - Assert.assertEquals(1002, exception.getErrorCode()); - Assert.assertEquals(true, exception.getErrorMessage().contains("already exists for Generic VNF")); - System.out.println(exception.getErrorMessage()); - } - - @Test - @Deployment(resources = { - "subprocess/CreateAAIVfModule.bpmn" - }) - public void TestCreateGenericVnfFailure_5000() { - MockAAIGenericVnfSearch(); - MockAAICreateGenericVnf(); - MockAAIVfModulePUT(true); - RuntimeService runtimeService = processEngineRule.getRuntimeService(); - Map variables = new HashMap(); - variables.put("isDebugLogEnabled","true"); - variables.put("isVidRequest", "false"); - variables.put("vnfName", "STMTN5MMSC22"); - variables.put("serviceId", "99999999-9999-9999-9999-999999999999"); - variables.put("personaModelId", "973ed047-d251-4fb9-bf1a-65b8949e0a73"); - variables.put("personaModelVersion", "1.0"); - variables.put("vfModuleName", "STMTN5MMSC22-PCRF::module-1-0"); - variables.put("vfModuleModelName", "PCRF::module-0"); - runtimeService.startProcessInstanceByKey("CreateAAIVfModule", variables); - WorkflowException exception = BPMNUtil.getRawVariable(processEngineRule, "CreateAAIVfModule", "WorkflowException"); - Assert.assertEquals(5000, exception.getErrorCode()); - Assert.assertEquals(true, exception.getErrorMessage().contains("SVC3002")); - System.out.println(exception.getErrorMessage()); - } - - @Test - @Deployment(resources = { - "subprocess/CreateAAIVfModule.bpmn" - }) - public void TestCreateGenericVnfFailure_1002() { - MockAAIGenericVnfSearch(); - MockAAICreateGenericVnf(); - MockAAIVfModulePUT(true); - RuntimeService runtimeService = processEngineRule.getRuntimeService(); - Map variables = new HashMap(); - variables.put("isDebugLogEnabled","true"); - variables.put("isVidRequest", "false"); - variables.put("vnfId", "768073c7-f41f-4822-9323-b75962763d74"); - variables.put("serviceId", "00000000-0000-0000-0000-000000000000"); - variables.put("personaModelId", "973ed047-d251-4fb9-bf1a-65b8949e0a73"); - variables.put("personaModelVersion", "1.0"); - variables.put("vfModuleName", "STMTN5MMSC22-PCRF::module-1-0"); - variables.put("vfModuleModelName", "PCRF::module-0"); - runtimeService.startProcessInstanceByKey("CreateAAIVfModule", variables); - WorkflowException exception = BPMNUtil.getRawVariable(processEngineRule, "CreateAAIVfModule", "WorkflowException"); - Assert.assertEquals(1002, exception.getErrorCode()); - Assert.assertEquals(true, exception.getErrorMessage().contains("Generic VNF Not Found")); - System.out.println(exception.getErrorMessage()); - } - - @Test - @Deployment(resources = { - "subprocess/CreateAAIVfModule.bpmn" - }) - public void TestCreateVfModuleFailure_5000() { - MockAAIGenericVnfSearch(); - MockAAICreateGenericVnf(); - MockAAIVfModulePUT(true); - RuntimeService runtimeService = processEngineRule.getRuntimeService(); - Map variables = new HashMap(); - variables.put("isDebugLogEnabled","true"); - variables.put("isVidRequest", "false"); - variables.put("vnfId", "a27ce5a9-29c4-4c22-a017-6615ac73c721"); - variables.put("serviceId", "99999999-9999-9999-9999-999999999999"); - variables.put("personaModelId", "973ed047-d251-4fb9-bf1a-65b8949e0a73"); - variables.put("personaModelVersion", "1.0"); - variables.put("vfModuleName", "STMTN5MMSC21-PCRF::module-1-0"); - variables.put("vfModuleModelName", "STMTN5MMSC21-PCRF::model-1-0"); - runtimeService.startProcessInstanceByKey("CreateAAIVfModule", variables); - WorkflowException exception = BPMNUtil.getRawVariable(processEngineRule, "CreateAAIVfModule", "WorkflowException"); - Assert.assertEquals(5000, exception.getErrorCode()); - Assert.assertEquals(true, exception.getErrorMessage().contains("SVC3002")); - System.out.println(exception.getErrorMessage()); - } - - public static void MockAAICreateGenericVnf(){ - stubFor(put(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/.*")) - .withRequestBody(containing("00000000-0000-0000-0000-000000000000")) - .willReturn(aResponse() - .withStatus(201))); - stubFor(put(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/.*")) - .withRequestBody(containing("99999999-9999-9999-9999-999999999999")) - .willReturn(aResponse() - .withStatus(500) - .withHeader("Content-Type", "text/xml") - .withBodyFile("aaiFault.xml"))); - } - - // start of mocks used locally and by other VF Module unit tests - public static void MockAAIVfModulePUT(boolean isCreate){ - stubFor(put(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/.*/vf-modules/vf-module/.*")) - .withRequestBody(containing("MMSC")) - .willReturn(aResponse() - .withStatus(isCreate ? 201 : 200))); - stubFor(put(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/.*/vf-modules/vf-module/.*")) - .withRequestBody(containing("PCRF")) - .willReturn(aResponse() - .withStatus(500) - .withHeader("Content-Type", "text/xml") - .withBodyFile("aaiFault.xml"))); - stubFor(put(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c721")) - .willReturn(aResponse() - .withStatus(200))); - } - +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.bpmn.common; + +import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; +import static com.github.tomakehurst.wiremock.client.WireMock.containing; +import static com.github.tomakehurst.wiremock.client.WireMock.put; +import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; +import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching; +import static org.openecomp.mso.bpmn.common.DeleteAAIVfModuleTest.MockAAIGenericVnfSearch; + +import java.util.HashMap; +import java.util.Map; + +import org.camunda.bpm.engine.RuntimeService; +import org.camunda.bpm.engine.test.Deployment; +import org.junit.Assert; +import org.junit.Test; +import org.openecomp.mso.bpmn.core.WorkflowException; + +/** + * Unit test for CreateAAIVfModule.bpmn. + */ +public class CreateAAIVfModuleTest extends WorkflowTest { + + @Test + @Deployment(resources = { + "subprocess/CreateAAIVfModule.bpmn" + }) + public void TestCreateGenericVnfSuccess_200() { + + MockAAIGenericVnfSearch(); + MockAAICreateGenericVnf(); + MockAAIVfModulePUT(true); + RuntimeService runtimeService = processEngineRule.getRuntimeService(); + Map variables = new HashMap(); + variables.put("isDebugLogEnabled","true"); + variables.put("isVidRequest", "false"); + variables.put("vnfName", "STMTN5MMSC22"); + variables.put("serviceId", "00000000-0000-0000-0000-000000000000"); + variables.put("personaModelId", "973ed047-d251-4fb9-bf1a-65b8949e0a73"); + variables.put("personaModelVersion", "1.0"); + variables.put("vfModuleName", "STMTN5MMSC22-MMSC::module-0-0"); + variables.put("vfModuleModelName", "MMSC::module-0"); + + runtimeService.startProcessInstanceByKey("CreateAAIVfModule", variables); + String response = BPMNUtil.getVariable(processEngineRule, "CreateAAIVfModule", "CAAIVfMod_createVfModuleResponseCode"); + String responseCode = BPMNUtil.getVariable(processEngineRule, "CreateAAIVfModule", "CAAIVfMod_createVfModuleResponseCode"); + Assert.assertEquals("201", responseCode); + System.out.println(response); + } + + @Test + @Deployment(resources = { + "subprocess/CreateAAIVfModule.bpmn" + }) + public void TestCreateVfModuleSuccess_200() { + // create Add-on VF Module for existing Generic VNF + MockAAIGenericVnfSearch(); + MockAAICreateGenericVnf(); + MockAAIVfModulePUT(true); + RuntimeService runtimeService = processEngineRule.getRuntimeService(); + Map variables = new HashMap(); + variables.put("isDebugLogEnabled","true"); + variables.put("isVidRequest", "false"); + variables.put("vnfId", "a27ce5a9-29c4-4c22-a017-6615ac73c721"); + variables.put("serviceId", "00000000-0000-0000-0000-000000000000"); + variables.put("personaModelId", "973ed047-d251-4fb9-bf1a-65b8949e0a73"); + variables.put("personaModelVersion", "1.0"); + variables.put("vfModuleName", "STMTN5MMSC21-MMSC::module-1-0"); + variables.put("vfModuleModelName", "STMTN5MMSC21-MMSC::model-1-0"); + runtimeService.startProcessInstanceByKey("CreateAAIVfModule", variables); + String response = BPMNUtil.getVariable(processEngineRule, "CreateAAIVfModule", "CAAIVfMod_createVfModuleResponseCode"); + String responseCode = BPMNUtil.getVariable(processEngineRule, "CreateAAIVfModule", "CAAIVfMod_createVfModuleResponseCode"); + Assert.assertEquals("201", responseCode); + System.out.println(response); + } + + @Test + @Deployment(resources = { + "subprocess/CreateAAIVfModule.bpmn" + }) + public void TestQueryGenericVnfFailure_5000() { + MockAAIGenericVnfSearch(); + MockAAICreateGenericVnf(); + MockAAIVfModulePUT(true); + RuntimeService runtimeService = processEngineRule.getRuntimeService(); + Map variables = new HashMap(); + variables.put("isDebugLogEnabled","true"); + variables.put("isVidRequest", "false"); + variables.put("vnfName", "STMTN5MMSC23"); + variables.put("serviceId", "00000000-0000-0000-0000-000000000000"); + variables.put("personaModelId", "973ed047-d251-4fb9-bf1a-65b8949e0a73"); + variables.put("personaModelVersion", "1.0"); + variables.put("vfModuleName", "STMTN5MMSC23-MMSC::module-0-0"); + variables.put("vfModuleModelName", "MMSC::module-0"); + runtimeService.startProcessInstanceByKey("CreateAAIVfModule", variables); + WorkflowException exception = BPMNUtil.getRawVariable(processEngineRule, "CreateAAIVfModule", "WorkflowException"); + Assert.assertEquals(500, exception.getErrorCode()); + Assert.assertEquals(true, exception.getErrorMessage().contains("Error occurred attempting to query AAI")); + System.out.println(exception.getErrorMessage()); + } + + @Test + @Deployment(resources = { + "subprocess/CreateAAIVfModule.bpmn" + }) + public void TestCreateDupGenericVnfFailure_1002() { + MockAAIGenericVnfSearch(); + MockAAICreateGenericVnf(); + MockAAIVfModulePUT(true); + RuntimeService runtimeService = processEngineRule.getRuntimeService(); + Map variables = new HashMap(); + variables.put("isDebugLogEnabled","true"); + variables.put("isVidRequest", "false"); + variables.put("vnfName", "STMTN5MMSC21"); + variables.put("serviceId", "00000000-0000-0000-0000-000000000000"); + variables.put("personaModelId", "973ed047-d251-4fb9-bf1a-65b8949e0a73"); + variables.put("personaModelVersion", "1.0"); + variables.put("vfModuleName", "STMTN5MMSC21-MMSC::module-0-0"); + variables.put("vfModuleModelName", "MMSC::module-0"); + runtimeService.startProcessInstanceByKey("CreateAAIVfModule", variables); + WorkflowException exception = BPMNUtil.getRawVariable(processEngineRule, "CreateAAIVfModule", "WorkflowException"); + Assert.assertEquals(1002, exception.getErrorCode()); + Assert.assertEquals(true, exception.getErrorMessage().contains("Invalid request for new Generic VNF which already exists")); + System.out.println(exception.getErrorMessage()); + } + + @Test + @Deployment(resources = { + "subprocess/CreateAAIVfModule.bpmn" + }) + public void TestCreateDupVfModuleFailure_1002() { + MockAAIGenericVnfSearch(); + MockAAICreateGenericVnf(); + MockAAIVfModulePUT(true); + RuntimeService runtimeService = processEngineRule.getRuntimeService(); + Map variables = new HashMap(); + variables.put("isDebugLogEnabled","true"); + variables.put("isVidRequest", "false"); + variables.put("vnfId", "2f6aee38-1e2a-11e6-82d1-ffc7d9ee8aa4"); + variables.put("serviceId", "00000000-0000-0000-0000-000000000000"); + variables.put("personaModelId", "973ed047-d251-4fb9-bf1a-65b8949e0a73"); + variables.put("personaModelVersion", "1.0"); + variables.put("vfModuleName", "STMTN5MMSC20-MMSC::module-1-0"); + variables.put("vfModuleModelName", "STMTN5MMSC20-MMSC::model-1-0"); + runtimeService.startProcessInstanceByKey("CreateAAIVfModule", variables); + WorkflowException exception = BPMNUtil.getRawVariable(processEngineRule, "CreateAAIVfModule", "WorkflowException"); + Assert.assertEquals(1002, exception.getErrorCode()); + Assert.assertEquals(true, exception.getErrorMessage().contains("already exists for Generic VNF")); + System.out.println(exception.getErrorMessage()); + } + + @Test + @Deployment(resources = { + "subprocess/CreateAAIVfModule.bpmn" + }) + public void TestCreateGenericVnfFailure_5000() { + MockAAIGenericVnfSearch(); + MockAAICreateGenericVnf(); + MockAAIVfModulePUT(true); + RuntimeService runtimeService = processEngineRule.getRuntimeService(); + Map variables = new HashMap(); + variables.put("isDebugLogEnabled","true"); + variables.put("isVidRequest", "false"); + variables.put("vnfName", "STMTN5MMSC22"); + variables.put("serviceId", "99999999-9999-9999-9999-999999999999"); + variables.put("personaModelId", "973ed047-d251-4fb9-bf1a-65b8949e0a73"); + variables.put("personaModelVersion", "1.0"); + variables.put("vfModuleName", "STMTN5MMSC22-PCRF::module-1-0"); + variables.put("vfModuleModelName", "PCRF::module-0"); + runtimeService.startProcessInstanceByKey("CreateAAIVfModule", variables); + WorkflowException exception = BPMNUtil.getRawVariable(processEngineRule, "CreateAAIVfModule", "WorkflowException"); + Assert.assertEquals(5000, exception.getErrorCode()); + Assert.assertEquals(true, exception.getErrorMessage().contains("SVC3002")); + System.out.println(exception.getErrorMessage()); + } + + @Test + @Deployment(resources = { + "subprocess/CreateAAIVfModule.bpmn" + }) + public void TestCreateGenericVnfFailure_1002() { + MockAAIGenericVnfSearch(); + MockAAICreateGenericVnf(); + MockAAIVfModulePUT(true); + RuntimeService runtimeService = processEngineRule.getRuntimeService(); + Map variables = new HashMap(); + variables.put("isDebugLogEnabled","true"); + variables.put("isVidRequest", "false"); + variables.put("vnfId", "768073c7-f41f-4822-9323-b75962763d74"); + variables.put("serviceId", "00000000-0000-0000-0000-000000000000"); + variables.put("personaModelId", "973ed047-d251-4fb9-bf1a-65b8949e0a73"); + variables.put("personaModelVersion", "1.0"); + variables.put("vfModuleName", "STMTN5MMSC22-PCRF::module-1-0"); + variables.put("vfModuleModelName", "PCRF::module-0"); + runtimeService.startProcessInstanceByKey("CreateAAIVfModule", variables); + WorkflowException exception = BPMNUtil.getRawVariable(processEngineRule, "CreateAAIVfModule", "WorkflowException"); + Assert.assertEquals(1002, exception.getErrorCode()); + Assert.assertEquals(true, exception.getErrorMessage().contains("Generic VNF Not Found")); + System.out.println(exception.getErrorMessage()); + } + + @Test + @Deployment(resources = { + "subprocess/CreateAAIVfModule.bpmn" + }) + public void TestCreateVfModuleFailure_5000() { + MockAAIGenericVnfSearch(); + MockAAICreateGenericVnf(); + MockAAIVfModulePUT(true); + RuntimeService runtimeService = processEngineRule.getRuntimeService(); + Map variables = new HashMap(); + variables.put("isDebugLogEnabled","true"); + variables.put("isVidRequest", "false"); + variables.put("vnfId", "a27ce5a9-29c4-4c22-a017-6615ac73c721"); + variables.put("serviceId", "99999999-9999-9999-9999-999999999999"); + variables.put("personaModelId", "973ed047-d251-4fb9-bf1a-65b8949e0a73"); + variables.put("personaModelVersion", "1.0"); + variables.put("vfModuleName", "STMTN5MMSC21-PCRF::module-1-0"); + variables.put("vfModuleModelName", "STMTN5MMSC21-PCRF::model-1-0"); + runtimeService.startProcessInstanceByKey("CreateAAIVfModule", variables); + WorkflowException exception = BPMNUtil.getRawVariable(processEngineRule, "CreateAAIVfModule", "WorkflowException"); + Assert.assertEquals(5000, exception.getErrorCode()); + Assert.assertEquals(true, exception.getErrorMessage().contains("SVC3002")); + System.out.println(exception.getErrorMessage()); + } + + public static void MockAAICreateGenericVnf(){ + stubFor(put(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/.*")) + .withRequestBody(containing("00000000-0000-0000-0000-000000000000")) + .willReturn(aResponse() + .withStatus(201))); + stubFor(put(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/.*")) + .withRequestBody(containing("99999999-9999-9999-9999-999999999999")) + .willReturn(aResponse() + .withStatus(500) + .withHeader("Content-Type", "text/xml") + .withBodyFile("aaiFault.xml"))); + } + + // start of mocks used locally and by other VF Module unit tests + public static void MockAAIVfModulePUT(boolean isCreate){ + stubFor(put(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/.*/vf-modules/vf-module/.*")) + .withRequestBody(containing("MMSC")) + .willReturn(aResponse() + .withStatus(isCreate ? 201 : 200))); + stubFor(put(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/.*/vf-modules/vf-module/.*")) + .withRequestBody(containing("PCRF")) + .willReturn(aResponse() + .withStatus(500) + .withHeader("Content-Type", "text/xml") + .withBodyFile("aaiFault.xml"))); + stubFor(put(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c721")) + .willReturn(aResponse() + .withStatus(200))); + } + } \ No newline at end of file diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/DeleteAAIVfModuleTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/DeleteAAIVfModuleTest.java index 0136b675dd..d8e003766d 100644 --- a/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/DeleteAAIVfModuleTest.java +++ b/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/DeleteAAIVfModuleTest.java @@ -1,643 +1,643 @@ -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - MSO - * ================================================================================ - * 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.openecomp.mso.bpmn.common; - -import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; -import static com.github.tomakehurst.wiremock.client.WireMock.delete; -import static com.github.tomakehurst.wiremock.client.WireMock.get; -import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; -import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching; - -import java.util.HashMap; -import java.util.Map; - -import org.camunda.bpm.engine.RuntimeService; -import org.camunda.bpm.engine.test.Deployment; -import org.junit.Assert; -import org.junit.Test; -import org.openecomp.mso.bpmn.core.WorkflowException; - -/** - * Unit test for DeleteAAIVfModule.bpmn. - */ -public class DeleteAAIVfModuleTest extends WorkflowTest { - private static final String EOL = "\n"; - - @Test - @Deployment(resources = { - "subprocess/DeleteAAIVfModule.bpmn" - }) - public void TestDeleteGenericVnfSuccess_200() { - // delete the Base Module and Generic Vnf - // vnf-id=a27ce5a9-29c4-4c22-a017-6615ac73c721, vf-module-id=973ed047-d251-4fb9-bf1a-65b8949e0a73 - MockAAIGenericVnfSearch(); - MockAAIDeleteGenericVnf(); - MockAAIDeleteVfModule(); - RuntimeService runtimeService = processEngineRule.getRuntimeService(); - Map variables = new HashMap(); - variables.put("isDebugLogEnabled","true"); - variables.put("DeleteAAIVfModuleRequest"," DELETE_VF_MODULE PORTAL a27ce5a9-29c4-4c22-a017-6615ac73c721 STMTN5MMSC21 973ed047-d251-4fb9-bf1a-65b8949e0a73 STMTN5MMSC21-MMSC::module-0-0 "); - runtimeService.startProcessInstanceByKey("DeleteAAIVfModule", variables); - String response = BPMNUtil.getVariable(processEngineRule, "DeleteAAIVfModule", "DAAIVfMod_deleteGenericVnfResponseCode"); - String responseCode = BPMNUtil.getVariable(processEngineRule, "DeleteAAIVfModule", "DAAIVfMod_deleteGenericVnfResponseCode"); - Assert.assertEquals("200", responseCode); - System.out.println(response); - } - - @Test - @Deployment(resources = { - "subprocess/DeleteAAIVfModule.bpmn" - }) - public void TestDeleteVfModuleSuccess_200() { - // delete Add-on Vf Module for existing Generic Vnf - // vnf-id=a27ce5a9-29c4-4c22-a017-6615ac73c720, vf-module-id=973ed047-d251-4fb9-bf1a-65b8949e0a75 - String request = - "" + EOL + - " " + EOL + - " DELETE_VF_MODULE" + EOL + - " PORTAL" + EOL + - " " + EOL + - " " + EOL + - " a27ce5a9-29c4-4c22-a017-6615ac73c720" + EOL + - " STMTN5MMSC20" + EOL + - " 973ed047-d251-4fb9-bf1a-65b8949e0a75" + EOL + - " STMTN5MMSC20-MMSC::module-1-0" + EOL + - " " + EOL + - " " + EOL + - "" + EOL; - - MockAAIGenericVnfSearch(); - MockAAIDeleteGenericVnf(); - MockAAIDeleteVfModule(); - RuntimeService runtimeService = processEngineRule.getRuntimeService(); - Map variables = new HashMap(); - variables.put("isDebugLogEnabled","true"); - variables.put("DeleteAAIVfModuleRequest",request); - runtimeService.startProcessInstanceByKey("DeleteAAIVfModule", variables); - String response = BPMNUtil.getVariable(processEngineRule, "DeleteAAIVfModule", "DAAIVfMod_deleteVfModuleResponseCode"); - String responseCode = BPMNUtil.getVariable(processEngineRule, "DeleteAAIVfModule", "DAAIVfMod_deleteVfModuleResponseCode"); - Assert.assertEquals("200", responseCode); - System.out.println(response); - } - - @Test - @Deployment(resources = { - "subprocess/DeleteAAIVfModule.bpmn" - }) - public void TestQueryGenericVnfFailure_5000() { - // query Generic Vnf failure (non-404) with A&AI - // vnf-id=a27ce5a9-29c4-4c22-a017-6615ac73c723, vf-module-id=973ed047-d251-4fb9-bf1a-65b8949e0a71 - String request = - "" + EOL + - " " + EOL + - " DELETE_VF_MODULE" + EOL + - " PORTAL" + EOL + - " " + EOL + - " " + EOL + - " a27ce5a9-29c4-4c22-a017-6615ac73c723" + EOL + - " STMTN5MMSC23" + EOL + - " 973ed047-d251-4fb9-bf1a-65b8949e0a71" + EOL + - " STMTN5MMSC20-MMSC::module-1-0" + EOL + - " " + EOL + - " " + EOL + - "" + EOL; - MockAAIGenericVnfSearch(); - MockAAIDeleteGenericVnf(); - MockAAIDeleteVfModule(); - RuntimeService runtimeService = processEngineRule.getRuntimeService(); - Map variables = new HashMap(); - variables.put("isDebugLogEnabled","true"); - variables.put("DeleteAAIVfModuleRequest",request); - runtimeService.startProcessInstanceByKey("DeleteAAIVfModule", variables); - WorkflowException exception = BPMNUtil.getRawVariable(processEngineRule, "DeleteAAIVfModule", "WorkflowException"); - Assert.assertEquals(5000, exception.getErrorCode()); - Assert.assertEquals(true, exception.getErrorMessage().contains("SVC3002")); - System.out.println(exception.getErrorMessage()); - } - - @Test - @Deployment(resources = { - "subprocess/DeleteAAIVfModule.bpmn" - }) - public void TestQueryGenericVnfFailure_1002() { - // attempt to delete Vf Module for Generic Vnf that does not exist (A&AI returns 404) - // vnf-id=a27ce5a9-29c4-4c22-a017-6615ac73c722, vf-module-id=973ed047-d251-4fb9-bf1a-65b8949e0a72 - String request = - "" + EOL + - " " + EOL + - " DELETE_VF_MODULE" + EOL + - " PORTAL" + EOL + - " " + EOL + - " " + EOL + - " a27ce5a9-29c4-4c22-a017-6615ac73c722" + EOL + - " STMTN5MMSC22" + EOL + - " 973ed047-d251-4fb9-bf1a-65b8949e0a72" + EOL + - " STMTN5MMSC22-MMSC::module-1-0" + EOL + - " " + EOL + - " " + EOL + - "" + EOL; - MockAAIGenericVnfSearch(); - MockAAIDeleteGenericVnf(); - MockAAIDeleteVfModule(); - RuntimeService runtimeService = processEngineRule.getRuntimeService(); - Map variables = new HashMap(); - variables.put("isDebugLogEnabled","true"); - variables.put("DeleteAAIVfModuleRequest",request); - runtimeService.startProcessInstanceByKey("DeleteAAIVfModule", variables); - WorkflowException exception = BPMNUtil.getRawVariable(processEngineRule, "DeleteAAIVfModule", "WorkflowException"); - Assert.assertEquals(1002, exception.getErrorCode()); - Assert.assertEquals(true, exception.getErrorMessage().contains("Generic VNF Not Found")); - System.out.println(exception.getErrorMessage()); - } - - @Test - @Deployment(resources = { - "subprocess/DeleteAAIVfModule.bpmn" - }) - public void TestDeleteGenericVnfFailure_5000() { - // A&AI failure (non-200) when attempting to delete a Generic Vnf - // vnf-id=a27ce5a9-29c4-4c22-a017-6615ac73c718, vf-module-id=973ed047-d251-4fb9-bf1a-65b8949e0a78 - String request = - "" + EOL + - " " + EOL + - " DELETE_VF_MODULE" + EOL + - " PORTAL" + EOL + - " " + EOL + - " " + EOL + - " a27ce5a9-29c4-4c22-a017-6615ac73c718" + EOL + - " STMTN5MMSC18" + EOL + - " 973ed047-d251-4fb9-bf1a-65b8949e0a78" + EOL + - " STMTN5MMSC18-MMSC::module-0-0" + EOL + - " " + EOL + - " " + EOL + - "" + EOL; - MockAAIGenericVnfSearch(); - MockAAIDeleteGenericVnf(); - MockAAIDeleteVfModule(); - RuntimeService runtimeService = processEngineRule.getRuntimeService(); - Map variables = new HashMap(); - variables.put("isDebugLogEnabled","true"); - variables.put("DeleteAAIVfModuleRequest",request); - runtimeService.startProcessInstanceByKey("DeleteAAIVfModule", variables); - WorkflowException exception = BPMNUtil.getRawVariable(processEngineRule, "DeleteAAIVfModule", "WorkflowException"); - Assert.assertEquals(5000, exception.getErrorCode()); - Assert.assertEquals(true, exception.getErrorMessage().contains("SVC3002")); - System.out.println(exception.getErrorMessage()); - } - - @Test - @Deployment(resources = { - "subprocess/DeleteAAIVfModule.bpmn" - }) - public void TestDeleteVfModuleFailure_5000() { - // A&AI failure (non-200) when attempting to delete a Vf Module - // vnf-id=a27ce5a9-29c4-4c22-a017-6615ac73c719, vf-module-id=973ed047-d251-4fb9-bf1a-65b8949e0a77 - String request = - "" + EOL + - " " + EOL + - " DELETE_VF_MODULE" + EOL + - " PORTAL" + EOL + - " " + EOL + - " " + EOL + - " a27ce5a9-29c4-4c22-a017-6615ac73c719" + EOL + - " STMTN5MMSC19" + EOL + - " 973ed047-d251-4fb9-bf1a-65b8949e0a77" + EOL + - " STMTN5MMSC19-MMSC::module-1-0" + EOL + - " " + EOL + - " " + EOL + - "" + EOL; - MockAAIGenericVnfSearch(); - MockAAIDeleteGenericVnf(); - MockAAIDeleteVfModule(); - RuntimeService runtimeService = processEngineRule.getRuntimeService(); - Map variables = new HashMap(); - variables.put("isDebugLogEnabled","true"); - variables.put("DeleteAAIVfModuleRequest",request); - runtimeService.startProcessInstanceByKey("DeleteAAIVfModule", variables); - WorkflowException exception = BPMNUtil.getRawVariable(processEngineRule, "DeleteAAIVfModule", "WorkflowException"); - Assert.assertEquals(5000, exception.getErrorCode()); - Assert.assertEquals(true, exception.getErrorMessage().contains("SVC3002")); - System.out.println(exception.getErrorMessage()); - } - - @Test - @Deployment(resources = { - "subprocess/DeleteAAIVfModule.bpmn" - }) - public void TestDeleteVfModuleFailure_1002_1() { - // failure attempting to delete Base Module when not the last Vf Module - // vnf-id=a27ce5a9-29c4-4c22-a017-6615ac73c720, vf-module-id=973ed047-d251-4fb9-bf1a-65b8949e0a74 - String request = - "" + EOL + - " " + EOL + - " DELETE_VF_MODULE" + EOL + - " PORTAL" + EOL + - " " + EOL + - " " + EOL + - " a27ce5a9-29c4-4c22-a017-6615ac73c720" + EOL + - " STMTN5MMSC20" + EOL + - " 973ed047-d251-4fb9-bf1a-65b8949e0a74" + EOL + - " STMTN5MMSC20-MMSC::module-0-0" + EOL + - " " + EOL + - " " + EOL + - "" + EOL; - MockAAIGenericVnfSearch(); - MockAAIDeleteGenericVnf(); - MockAAIDeleteVfModule(); - RuntimeService runtimeService = processEngineRule.getRuntimeService(); - Map variables = new HashMap(); - variables.put("isDebugLogEnabled","true"); - variables.put("DeleteAAIVfModuleRequest",request); - runtimeService.startProcessInstanceByKey("DeleteAAIVfModule", variables); - WorkflowException exception = BPMNUtil.getRawVariable(processEngineRule, "DeleteAAIVfModule", "WorkflowException"); - Assert.assertEquals(1002, exception.getErrorCode()); - Assert.assertEquals(true, exception.getErrorMessage().contains("is Base Module, not Last Module")); - System.out.println(exception.getErrorMessage()); - } - - @Test - @Deployment(resources = { - "subprocess/DeleteAAIVfModule.bpmn" - }) - public void TestDeleteVfModuleFailure_1002_2() { - // failure attempting to delete a Vf Module that does not exist (A&AI returns 404) - // vnf-id=a27ce5a9-29c4-4c22-a017-6615ac73c720, vf-module-id=973ed047-d251-4fb9-bf1a-65b8949e0a76 - MockAAIGenericVnfSearch(); - MockAAIDeleteGenericVnf(); - MockAAIDeleteVfModule(); - RuntimeService runtimeService = processEngineRule.getRuntimeService(); - Map variables = new HashMap(); - variables.put("isDebugLogEnabled","true"); - variables.put("DeleteAAIVfModuleRequest"," DELETE_VF_MODULE PORTAL a27ce5a9-29c4-4c22-a017-6615ac73c720 STMTN5MMSC20 973ed047-d251-4fb9-bf1a-65b8949e0a76 STMTN5MMSC20-MMSC::module-2-0 "); - runtimeService.startProcessInstanceByKey("DeleteAAIVfModule", variables); - WorkflowException exception = BPMNUtil.getRawVariable(processEngineRule, "DeleteAAIVfModule", "WorkflowException"); - Assert.assertEquals(1002, exception.getErrorCode()); - Assert.assertEquals(true, exception.getErrorMessage().contains("does not exist for Generic Vnf Id")); - System.out.println(exception.getErrorMessage()); - } - - // Start of VF Modularization A&AI mocks - - public static void MockAAIGenericVnfSearch(){ - String body; - - // The following stubs are for CreateAAIVfModule and UpdateAAIVfModule - - stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/[?]vnf-name=STMTN5MMSC23&depth=1")) - .willReturn(aResponse() - .withStatus(500) - .withHeader("Content-Type", "text/xml") - .withBodyFile("aaiFault.xml"))); - - stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/[?]vnf-name=STMTN5MMSC22&depth=1")) - .willReturn(aResponse() - .withStatus(404) - .withHeader("Content-Type", "text/xml") - .withBody("Generic VNF Not Found"))); - stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/768073c7-f41f-4822-9323-b75962763d74[?]depth=1")) - .willReturn(aResponse() - .withStatus(404) - .withHeader("Content-Type", "text/xml") - .withBody("Generic VNF Not Found"))); - - body = - "" + EOL + - " a27ce5a9-29c4-4c22-a017-6615ac73c721" + EOL + - " STMTN5MMSC21" + EOL + - " mmsc-capacity" + EOL + - " SDN-MOBILITY" + EOL + - " vMMSC" + EOL + - " pending-create" + EOL + - " false" + EOL + - " false" + EOL + - " 1508691" + EOL + - " " + EOL + - " " + EOL + - " 973ed047-d251-4fb9-bf1a-65b8949e0a73" + EOL + - " STMTN5MMSC21-MMSC::module-0-0" + EOL + - " 973ed047-d251-4fb9-bf1a-65b8949e0a73" + EOL + - " 1.0" + EOL + - " true" + EOL + - " FILLED-IN-BY-MSO" + EOL + - " pending-create" + EOL + - " 1508692" + EOL + - " " + EOL + - " " + EOL + - " " + EOL + - " " + EOL + - " " + EOL + - "" + EOL; - stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/[?]vnf-name=STMTN5MMSC21&depth=1")) - .willReturn(aResponse() - .withStatus(200) - .withHeader("Content-Type", "text/xml") - .withBody(body))); - stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c721[?]depth=1")) - .willReturn(aResponse() - .withStatus(200) - .withHeader("Content-Type", "text/xml") - .withBody(body))); - - body = - "" + EOL + - " 2f6aee38-1e2a-11e6-82d1-ffc7d9ee8aa4" + EOL + - " STMTN5MMSC20" + EOL + - " mmsc-capacity" + EOL + - " SDN-MOBILITY" + EOL + - " vMMSC" + EOL + - " pending-create" + EOL + - " false" + EOL + - " false" + EOL + - " 1508691" + EOL + - " " + EOL + - " " + EOL + - " 973ed047-d251-4fb9-bf1a-65b8949e0a73" + EOL + - " STMTN5MMSC20-MMSC::module-0-0" + EOL + - " 973ed047-d251-4fb9-bf1a-65b8949e0a73" + EOL + - " 1.0" + EOL + - " true" + EOL + - " FILLED-IN-BY-MSO" + EOL + - " pending-create" + EOL + - " 1508692" + EOL + - " " + EOL + - " " + EOL + - " 973ed047-d251-4fb9-bf1a-65b8949e0a74" + EOL + - " STMTN5MMSC20-MMSC::module-1-0" + EOL + - " 973ed047-d251-4fb9-bf1a-65b8949e0a74" + EOL + - " 1.0" + EOL + - " false" + EOL + - " FILLED-IN-BY-MSO" + EOL + - " pending-create" + EOL + - " 1508692" + EOL + - " " + EOL + - " " + EOL + - " " + EOL + - " " + EOL + - " " + EOL + - "" + EOL; - stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/[?]vnf-name=STMTN5MMSC20&depth=1")) - .willReturn(aResponse() - .withStatus(200) - .withHeader("Content-Type", "text/xml") - .withBody(body))); - stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/2f6aee38-1e2a-11e6-82d1-ffc7d9ee8aa4[?]depth=1")) - .willReturn(aResponse() - .withStatus(200) - .withHeader("Content-Type", "text/xml") - .withBody(body))); - - // The following stubs are for DeleteAAIVfModule - - stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c723[?]depth=1")) - .willReturn(aResponse() - .withStatus(500) - .withHeader("Content-Type", "text/xml") - .withBodyFile("aaiFault.xml"))); - - stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c722[?]depth=1")) - .willReturn(aResponse() - .withStatus(404) - .withHeader("Content-Type", "text/xml") - .withBody("Generic VNF Not Found"))); - - body = - "" + EOL + - " a27ce5a9-29c4-4c22-a017-6615ac73c721" + EOL + - " STMTN5MMSC21" + EOL + - " mmsc-capacity" + EOL + - " SDN-MOBILITY" + EOL + - " vMMSC" + EOL + - " pending-create" + EOL + - " false" + EOL + - " false" + EOL + - " 0000021" + EOL + - " " + EOL + - " " + EOL + - " 973ed047-d251-4fb9-bf1a-65b8949e0a73" + EOL + - " STMTN5MMSC21-MMSC::module-0-0" + EOL + - " 973ed047-d251-4fb9-bf1a-65b8949e0a73" + EOL + - " 1.0" + EOL + - " true" + EOL + - " FILLED-IN-BY-MSO" + EOL + - " pending-create" + EOL + - " 0000073" + EOL + - " " + EOL + - " " + EOL + - " " + EOL + - " " + EOL + - " " + EOL + - "" + EOL; - stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c721[?]depth=1")) - .willReturn(aResponse() - .withStatus(200) - .withHeader("Content-Type", "text/xml") - .withBody(body))); - - body = - "" + EOL + - " a27ce5a9-29c4-4c22-a017-6615ac73c720" + EOL + - " STMTN5MMSC20" + EOL + - " mmsc-capacity" + EOL + - " SDN-MOBILITY" + EOL + - " vMMSC" + EOL + - " pending-create" + EOL + - " false" + EOL + - " false" + EOL + - " 0000020" + EOL + - " " + EOL + - " " + EOL + - " 973ed047-d251-4fb9-bf1a-65b8949e0a74" + EOL + - " STMTN5MMSC20-MMSC::module-0-0" + EOL + - " 973ed047-d251-4fb9-bf1a-65b8949e0a74" + EOL + - " 1.0" + EOL + - " true" + EOL + - " FILLED-IN-BY-MSO" + EOL + - " pending-create" + EOL + - " 0000074" + EOL + - " " + EOL + - " " + EOL + - " 973ed047-d251-4fb9-bf1a-65b8949e0a75" + EOL + - " STMTN5MMSC20-MMSC::module-1-0" + EOL + - " 973ed047-d251-4fb9-bf1a-65b8949e0a75" + EOL + - " 1.0" + EOL + - " false" + EOL + - " FILLED-IN-BY-MSO" + EOL + - " pending-create" + EOL + - " 0000075" + EOL + - " " + EOL + - " " + EOL + - " " + EOL + - " " + EOL + - " " + EOL + - "" + EOL; - stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c720[?]depth=1")) - .willReturn(aResponse() - .withStatus(200) - .withHeader("Content-Type", "text/xml") - .withBody(body))); - - body = - "" + EOL + - " a27ce5a9-29c4-4c22-a017-6615ac73c719" + EOL + - " STMTN5MMSC19" + EOL + - " mmsc-capacity" + EOL + - " SDN-MOBILITY" + EOL + - " vMMSC" + EOL + - " pending-create" + EOL + - " false" + EOL + - " false" + EOL + - " 0000019" + EOL + - " " + EOL + - " " + EOL + - " 973ed047-d251-4fb9-bf1a-65b8949e0a76" + EOL + - " STMTN5MMSC19-MMSC::module-0-0" + EOL + - " 973ed047-d251-4fb9-bf1a-65b8949e0a76" + EOL + - " 1.0" + EOL + - " true" + EOL + - " FILLED-IN-BY-MSO" + EOL + - " pending-create" + EOL + - " 0000076" + EOL + - " " + EOL + - " " + EOL + - " 973ed047-d251-4fb9-bf1a-65b8949e0a77" + EOL + - " STMTN5MMSC19-MMSC::module-1-0" + EOL + - " 973ed047-d251-4fb9-bf1a-65b8949e0a77" + EOL + - " 1.0" + EOL + - " false" + EOL + - " FILLED-IN-BY-MSO" + EOL + - " pending-create" + EOL + - " 0000077" + EOL + - " " + EOL + - " " + EOL + - " " + EOL + - " " + EOL + - " " + EOL + - "" + EOL; - stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c719[?]depth=1")) - .willReturn(aResponse() - .withStatus(200) - .withHeader("Content-Type", "text/xml") - .withBody(body))); - - body = - "" + EOL + - " a27ce5a9-29c4-4c22-a017-6615ac73c718" + EOL + - " STMTN5MMSC18" + EOL + - " mmsc-capacity" + EOL + - " SDN-MOBILITY" + EOL + - " vMMSC" + EOL + - " pending-create" + EOL + - " false" + EOL + - " false" + EOL + - " 0000018" + EOL + - " " + EOL + - " " + EOL + - " 973ed047-d251-4fb9-bf1a-65b8949e0a78" + EOL + - " STMTN5MMSC18-MMSC::module-0-0" + EOL + - " 973ed047-d251-4fb9-bf1a-65b8949e0a78" + EOL + - " 1.0" + EOL + - " true" + EOL + - " FILLED-IN-BY-MSO" + EOL + - " pending-create" + EOL + - " 0000078" + EOL + - " " + EOL + - " " + EOL + - " " + EOL + - " " + EOL + - " " + EOL + - "" + EOL; - stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c718[?]depth=1")) - .willReturn(aResponse() - .withStatus(200) - .withHeader("Content-Type", "text/xml") - .withBody(body))); - - body = - "" + EOL + - " a27ce5a9-29c4-4c22-a017-6615ac73c721" + EOL + - " STMTN5MMSC21" + EOL + - " mmsc-capacity" + EOL + - " SDN-MOBILITY" + EOL + - " vMMSC" + EOL + - " pending-create" + EOL + - " false" + EOL + - " false" + EOL + - " 0000021" + EOL + - " " + EOL + - " " + EOL + - " 973ed047-d251-4fb9-bf1a-65b8949e0a73" + EOL + - " STMTN5MMSC21-MMSC::module-0-0" + EOL + - " 973ed047-d251-4fb9-bf1a-65b8949e0a73" + EOL + - " 1.0" + EOL + - " true" + EOL + - " FILLED-IN-BY-MSO" + EOL + - " pending-create" + EOL + - " 0000073" + EOL + - " " + EOL + - " " + EOL + - " " + EOL + - " " + EOL + - " " + EOL + - "" + EOL; - stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c721/vf-modules/vf-module/973ed047-d251-4fb9-bf1a-65b8949e0a73")) - .willReturn(aResponse() - .withStatus(200) - .withHeader("Content-Type", "text/xml") - .withBody(body))); - } - public static void MockAAIDeleteGenericVnf(){ - stubFor(delete(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c721/[?]resource-version=0000021")) - .willReturn(aResponse() - .withStatus(200))); - stubFor(delete(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c718/[?]resource-version=0000018")) - .willReturn(aResponse() - .withStatus(500) - .withHeader("Content-Type", "text/xml") - .withBodyFile("aaiFault.xml"))); - } - - public static void MockAAIDeleteVfModule(){ - stubFor(delete(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c721/vf-modules/vf-module/973ed047-d251-4fb9-bf1a-65b8949e0a73/[?]resource-version=0000073")) - .willReturn(aResponse() - .withStatus(200))); - stubFor(delete(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c720/vf-modules/vf-module/973ed047-d251-4fb9-bf1a-65b8949e0a75/[?]resource-version=0000075")) - .willReturn(aResponse() - .withStatus(200))); - stubFor(delete(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c718/vf-modules/vf-module/973ed047-d251-4fb9-bf1a-65b8949e0a78/[?]resource-version=0000078")) - .willReturn(aResponse() - .withStatus(200))); - stubFor(delete(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c719/vf-modules/vf-module/973ed047-d251-4fb9-bf1a-65b8949e0a77/[?]resource-version=0000077")) - .willReturn(aResponse() - .withStatus(500) - .withHeader("Content-Type", "text/xml") - .withBodyFile("aaiFault.xml"))); - stubFor(get(urlMatching("/aai/v[0-9]+/network/network-policies/network-policy\\?network-policy-fqdn=.*")) - .willReturn(aResponse() - .withStatus(200) - .withHeader("Content-Type", "text/xml") - .withBodyFile("VfModularity/QueryNetworkPolicy_AAIResponse_Success.xml"))); - - stubFor(delete(urlMatching("/aai/v[0-9]+/network/network-policies/network-policy/.*")) - .willReturn(aResponse() - .withStatus(200))); - } -} - +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.bpmn.common; + +import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; +import static com.github.tomakehurst.wiremock.client.WireMock.delete; +import static com.github.tomakehurst.wiremock.client.WireMock.get; +import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; +import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching; + +import java.util.HashMap; +import java.util.Map; + +import org.camunda.bpm.engine.RuntimeService; +import org.camunda.bpm.engine.test.Deployment; +import org.junit.Assert; +import org.junit.Test; +import org.openecomp.mso.bpmn.core.WorkflowException; + +/** + * Unit test for DeleteAAIVfModule.bpmn. + */ +public class DeleteAAIVfModuleTest extends WorkflowTest { + private static final String EOL = "\n"; + + @Test + @Deployment(resources = { + "subprocess/DeleteAAIVfModule.bpmn" + }) + public void TestDeleteGenericVnfSuccess_200() { + // delete the Base Module and Generic Vnf + // vnf-id=a27ce5a9-29c4-4c22-a017-6615ac73c721, vf-module-id=973ed047-d251-4fb9-bf1a-65b8949e0a73 + MockAAIGenericVnfSearch(); + MockAAIDeleteGenericVnf(); + MockAAIDeleteVfModule(); + RuntimeService runtimeService = processEngineRule.getRuntimeService(); + Map variables = new HashMap(); + variables.put("isDebugLogEnabled","true"); + variables.put("DeleteAAIVfModuleRequest"," DELETE_VF_MODULE PORTAL a27ce5a9-29c4-4c22-a017-6615ac73c721 STMTN5MMSC21 973ed047-d251-4fb9-bf1a-65b8949e0a73 STMTN5MMSC21-MMSC::module-0-0 "); + runtimeService.startProcessInstanceByKey("DeleteAAIVfModule", variables); + String response = BPMNUtil.getVariable(processEngineRule, "DeleteAAIVfModule", "DAAIVfMod_deleteGenericVnfResponseCode"); + String responseCode = BPMNUtil.getVariable(processEngineRule, "DeleteAAIVfModule", "DAAIVfMod_deleteGenericVnfResponseCode"); + Assert.assertEquals("200", responseCode); + System.out.println(response); + } + + @Test + @Deployment(resources = { + "subprocess/DeleteAAIVfModule.bpmn" + }) + public void TestDeleteVfModuleSuccess_200() { + // delete Add-on Vf Module for existing Generic Vnf + // vnf-id=a27ce5a9-29c4-4c22-a017-6615ac73c720, vf-module-id=973ed047-d251-4fb9-bf1a-65b8949e0a75 + String request = + "" + EOL + + " " + EOL + + " DELETE_VF_MODULE" + EOL + + " PORTAL" + EOL + + " " + EOL + + " " + EOL + + " a27ce5a9-29c4-4c22-a017-6615ac73c720" + EOL + + " STMTN5MMSC20" + EOL + + " 973ed047-d251-4fb9-bf1a-65b8949e0a75" + EOL + + " STMTN5MMSC20-MMSC::module-1-0" + EOL + + " " + EOL + + " " + EOL + + "" + EOL; + + MockAAIGenericVnfSearch(); + MockAAIDeleteGenericVnf(); + MockAAIDeleteVfModule(); + RuntimeService runtimeService = processEngineRule.getRuntimeService(); + Map variables = new HashMap(); + variables.put("isDebugLogEnabled","true"); + variables.put("DeleteAAIVfModuleRequest",request); + runtimeService.startProcessInstanceByKey("DeleteAAIVfModule", variables); + String response = BPMNUtil.getVariable(processEngineRule, "DeleteAAIVfModule", "DAAIVfMod_deleteVfModuleResponseCode"); + String responseCode = BPMNUtil.getVariable(processEngineRule, "DeleteAAIVfModule", "DAAIVfMod_deleteVfModuleResponseCode"); + Assert.assertEquals("200", responseCode); + System.out.println(response); + } + + @Test + @Deployment(resources = { + "subprocess/DeleteAAIVfModule.bpmn" + }) + public void TestQueryGenericVnfFailure_5000() { + // query Generic Vnf failure (non-404) with A&AI + // vnf-id=a27ce5a9-29c4-4c22-a017-6615ac73c723, vf-module-id=973ed047-d251-4fb9-bf1a-65b8949e0a71 + String request = + "" + EOL + + " " + EOL + + " DELETE_VF_MODULE" + EOL + + " PORTAL" + EOL + + " " + EOL + + " " + EOL + + " a27ce5a9-29c4-4c22-a017-6615ac73c723" + EOL + + " STMTN5MMSC23" + EOL + + " 973ed047-d251-4fb9-bf1a-65b8949e0a71" + EOL + + " STMTN5MMSC20-MMSC::module-1-0" + EOL + + " " + EOL + + " " + EOL + + "" + EOL; + MockAAIGenericVnfSearch(); + MockAAIDeleteGenericVnf(); + MockAAIDeleteVfModule(); + RuntimeService runtimeService = processEngineRule.getRuntimeService(); + Map variables = new HashMap(); + variables.put("isDebugLogEnabled","true"); + variables.put("DeleteAAIVfModuleRequest",request); + runtimeService.startProcessInstanceByKey("DeleteAAIVfModule", variables); + WorkflowException exception = BPMNUtil.getRawVariable(processEngineRule, "DeleteAAIVfModule", "WorkflowException"); + Assert.assertEquals(5000, exception.getErrorCode()); + Assert.assertEquals(true, exception.getErrorMessage().contains("SVC3002")); + System.out.println(exception.getErrorMessage()); + } + + @Test + @Deployment(resources = { + "subprocess/DeleteAAIVfModule.bpmn" + }) + public void TestQueryGenericVnfFailure_1002() { + // attempt to delete Vf Module for Generic Vnf that does not exist (A&AI returns 404) + // vnf-id=a27ce5a9-29c4-4c22-a017-6615ac73c722, vf-module-id=973ed047-d251-4fb9-bf1a-65b8949e0a72 + String request = + "" + EOL + + " " + EOL + + " DELETE_VF_MODULE" + EOL + + " PORTAL" + EOL + + " " + EOL + + " " + EOL + + " a27ce5a9-29c4-4c22-a017-6615ac73c722" + EOL + + " STMTN5MMSC22" + EOL + + " 973ed047-d251-4fb9-bf1a-65b8949e0a72" + EOL + + " STMTN5MMSC22-MMSC::module-1-0" + EOL + + " " + EOL + + " " + EOL + + "" + EOL; + MockAAIGenericVnfSearch(); + MockAAIDeleteGenericVnf(); + MockAAIDeleteVfModule(); + RuntimeService runtimeService = processEngineRule.getRuntimeService(); + Map variables = new HashMap(); + variables.put("isDebugLogEnabled","true"); + variables.put("DeleteAAIVfModuleRequest",request); + runtimeService.startProcessInstanceByKey("DeleteAAIVfModule", variables); + WorkflowException exception = BPMNUtil.getRawVariable(processEngineRule, "DeleteAAIVfModule", "WorkflowException"); + Assert.assertEquals(1002, exception.getErrorCode()); + Assert.assertEquals(true, exception.getErrorMessage().contains("Generic VNF Not Found")); + System.out.println(exception.getErrorMessage()); + } + + @Test + @Deployment(resources = { + "subprocess/DeleteAAIVfModule.bpmn" + }) + public void TestDeleteGenericVnfFailure_5000() { + // A&AI failure (non-200) when attempting to delete a Generic Vnf + // vnf-id=a27ce5a9-29c4-4c22-a017-6615ac73c718, vf-module-id=973ed047-d251-4fb9-bf1a-65b8949e0a78 + String request = + "" + EOL + + " " + EOL + + " DELETE_VF_MODULE" + EOL + + " PORTAL" + EOL + + " " + EOL + + " " + EOL + + " a27ce5a9-29c4-4c22-a017-6615ac73c718" + EOL + + " STMTN5MMSC18" + EOL + + " 973ed047-d251-4fb9-bf1a-65b8949e0a78" + EOL + + " STMTN5MMSC18-MMSC::module-0-0" + EOL + + " " + EOL + + " " + EOL + + "" + EOL; + MockAAIGenericVnfSearch(); + MockAAIDeleteGenericVnf(); + MockAAIDeleteVfModule(); + RuntimeService runtimeService = processEngineRule.getRuntimeService(); + Map variables = new HashMap(); + variables.put("isDebugLogEnabled","true"); + variables.put("DeleteAAIVfModuleRequest",request); + runtimeService.startProcessInstanceByKey("DeleteAAIVfModule", variables); + WorkflowException exception = BPMNUtil.getRawVariable(processEngineRule, "DeleteAAIVfModule", "WorkflowException"); + Assert.assertEquals(5000, exception.getErrorCode()); + Assert.assertEquals(true, exception.getErrorMessage().contains("SVC3002")); + System.out.println(exception.getErrorMessage()); + } + + @Test + @Deployment(resources = { + "subprocess/DeleteAAIVfModule.bpmn" + }) + public void TestDeleteVfModuleFailure_5000() { + // A&AI failure (non-200) when attempting to delete a Vf Module + // vnf-id=a27ce5a9-29c4-4c22-a017-6615ac73c719, vf-module-id=973ed047-d251-4fb9-bf1a-65b8949e0a77 + String request = + "" + EOL + + " " + EOL + + " DELETE_VF_MODULE" + EOL + + " PORTAL" + EOL + + " " + EOL + + " " + EOL + + " a27ce5a9-29c4-4c22-a017-6615ac73c719" + EOL + + " STMTN5MMSC19" + EOL + + " 973ed047-d251-4fb9-bf1a-65b8949e0a77" + EOL + + " STMTN5MMSC19-MMSC::module-1-0" + EOL + + " " + EOL + + " " + EOL + + "" + EOL; + MockAAIGenericVnfSearch(); + MockAAIDeleteGenericVnf(); + MockAAIDeleteVfModule(); + RuntimeService runtimeService = processEngineRule.getRuntimeService(); + Map variables = new HashMap(); + variables.put("isDebugLogEnabled","true"); + variables.put("DeleteAAIVfModuleRequest",request); + runtimeService.startProcessInstanceByKey("DeleteAAIVfModule", variables); + WorkflowException exception = BPMNUtil.getRawVariable(processEngineRule, "DeleteAAIVfModule", "WorkflowException"); + Assert.assertEquals(5000, exception.getErrorCode()); + Assert.assertEquals(true, exception.getErrorMessage().contains("SVC3002")); + System.out.println(exception.getErrorMessage()); + } + + @Test + @Deployment(resources = { + "subprocess/DeleteAAIVfModule.bpmn" + }) + public void TestDeleteVfModuleFailure_1002_1() { + // failure attempting to delete Base Module when not the last Vf Module + // vnf-id=a27ce5a9-29c4-4c22-a017-6615ac73c720, vf-module-id=973ed047-d251-4fb9-bf1a-65b8949e0a74 + String request = + "" + EOL + + " " + EOL + + " DELETE_VF_MODULE" + EOL + + " PORTAL" + EOL + + " " + EOL + + " " + EOL + + " a27ce5a9-29c4-4c22-a017-6615ac73c720" + EOL + + " STMTN5MMSC20" + EOL + + " 973ed047-d251-4fb9-bf1a-65b8949e0a74" + EOL + + " STMTN5MMSC20-MMSC::module-0-0" + EOL + + " " + EOL + + " " + EOL + + "" + EOL; + MockAAIGenericVnfSearch(); + MockAAIDeleteGenericVnf(); + MockAAIDeleteVfModule(); + RuntimeService runtimeService = processEngineRule.getRuntimeService(); + Map variables = new HashMap(); + variables.put("isDebugLogEnabled","true"); + variables.put("DeleteAAIVfModuleRequest",request); + runtimeService.startProcessInstanceByKey("DeleteAAIVfModule", variables); + WorkflowException exception = BPMNUtil.getRawVariable(processEngineRule, "DeleteAAIVfModule", "WorkflowException"); + Assert.assertEquals(1002, exception.getErrorCode()); + Assert.assertEquals(true, exception.getErrorMessage().contains("is Base Module, not Last Module")); + System.out.println(exception.getErrorMessage()); + } + + @Test + @Deployment(resources = { + "subprocess/DeleteAAIVfModule.bpmn" + }) + public void TestDeleteVfModuleFailure_1002_2() { + // failure attempting to delete a Vf Module that does not exist (A&AI returns 404) + // vnf-id=a27ce5a9-29c4-4c22-a017-6615ac73c720, vf-module-id=973ed047-d251-4fb9-bf1a-65b8949e0a76 + MockAAIGenericVnfSearch(); + MockAAIDeleteGenericVnf(); + MockAAIDeleteVfModule(); + RuntimeService runtimeService = processEngineRule.getRuntimeService(); + Map variables = new HashMap(); + variables.put("isDebugLogEnabled","true"); + variables.put("DeleteAAIVfModuleRequest"," DELETE_VF_MODULE PORTAL a27ce5a9-29c4-4c22-a017-6615ac73c720 STMTN5MMSC20 973ed047-d251-4fb9-bf1a-65b8949e0a76 STMTN5MMSC20-MMSC::module-2-0 "); + runtimeService.startProcessInstanceByKey("DeleteAAIVfModule", variables); + WorkflowException exception = BPMNUtil.getRawVariable(processEngineRule, "DeleteAAIVfModule", "WorkflowException"); + Assert.assertEquals(1002, exception.getErrorCode()); + Assert.assertEquals(true, exception.getErrorMessage().contains("does not exist for Generic Vnf Id")); + System.out.println(exception.getErrorMessage()); + } + + // Start of VF Modularization A&AI mocks + + public static void MockAAIGenericVnfSearch(){ + String body; + + // The following stubs are for CreateAAIVfModule and UpdateAAIVfModule + + stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/[?]vnf-name=STMTN5MMSC23&depth=1")) + .willReturn(aResponse() + .withStatus(500) + .withHeader("Content-Type", "text/xml") + .withBodyFile("aaiFault.xml"))); + + stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/[?]vnf-name=STMTN5MMSC22&depth=1")) + .willReturn(aResponse() + .withStatus(404) + .withHeader("Content-Type", "text/xml") + .withBody("Generic VNF Not Found"))); + stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/768073c7-f41f-4822-9323-b75962763d74[?]depth=1")) + .willReturn(aResponse() + .withStatus(404) + .withHeader("Content-Type", "text/xml") + .withBody("Generic VNF Not Found"))); + + body = + "" + EOL + + " a27ce5a9-29c4-4c22-a017-6615ac73c721" + EOL + + " STMTN5MMSC21" + EOL + + " mmsc-capacity" + EOL + + " SDN-MOBILITY" + EOL + + " vMMSC" + EOL + + " pending-create" + EOL + + " false" + EOL + + " false" + EOL + + " 1508691" + EOL + + " " + EOL + + " " + EOL + + " 973ed047-d251-4fb9-bf1a-65b8949e0a73" + EOL + + " STMTN5MMSC21-MMSC::module-0-0" + EOL + + " 973ed047-d251-4fb9-bf1a-65b8949e0a73" + EOL + + " 1.0" + EOL + + " true" + EOL + + " FILLED-IN-BY-MSO" + EOL + + " pending-create" + EOL + + " 1508692" + EOL + + " " + EOL + + " " + EOL + + " " + EOL + + " " + EOL + + " " + EOL + + "" + EOL; + stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/[?]vnf-name=STMTN5MMSC21&depth=1")) + .willReturn(aResponse() + .withStatus(200) + .withHeader("Content-Type", "text/xml") + .withBody(body))); + stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c721[?]depth=1")) + .willReturn(aResponse() + .withStatus(200) + .withHeader("Content-Type", "text/xml") + .withBody(body))); + + body = + "" + EOL + + " 2f6aee38-1e2a-11e6-82d1-ffc7d9ee8aa4" + EOL + + " STMTN5MMSC20" + EOL + + " mmsc-capacity" + EOL + + " SDN-MOBILITY" + EOL + + " vMMSC" + EOL + + " pending-create" + EOL + + " false" + EOL + + " false" + EOL + + " 1508691" + EOL + + " " + EOL + + " " + EOL + + " 973ed047-d251-4fb9-bf1a-65b8949e0a73" + EOL + + " STMTN5MMSC20-MMSC::module-0-0" + EOL + + " 973ed047-d251-4fb9-bf1a-65b8949e0a73" + EOL + + " 1.0" + EOL + + " true" + EOL + + " FILLED-IN-BY-MSO" + EOL + + " pending-create" + EOL + + " 1508692" + EOL + + " " + EOL + + " " + EOL + + " 973ed047-d251-4fb9-bf1a-65b8949e0a74" + EOL + + " STMTN5MMSC20-MMSC::module-1-0" + EOL + + " 973ed047-d251-4fb9-bf1a-65b8949e0a74" + EOL + + " 1.0" + EOL + + " false" + EOL + + " FILLED-IN-BY-MSO" + EOL + + " pending-create" + EOL + + " 1508692" + EOL + + " " + EOL + + " " + EOL + + " " + EOL + + " " + EOL + + " " + EOL + + "" + EOL; + stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/[?]vnf-name=STMTN5MMSC20&depth=1")) + .willReturn(aResponse() + .withStatus(200) + .withHeader("Content-Type", "text/xml") + .withBody(body))); + stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/2f6aee38-1e2a-11e6-82d1-ffc7d9ee8aa4[?]depth=1")) + .willReturn(aResponse() + .withStatus(200) + .withHeader("Content-Type", "text/xml") + .withBody(body))); + + // The following stubs are for DeleteAAIVfModule + + stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c723[?]depth=1")) + .willReturn(aResponse() + .withStatus(500) + .withHeader("Content-Type", "text/xml") + .withBodyFile("aaiFault.xml"))); + + stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c722[?]depth=1")) + .willReturn(aResponse() + .withStatus(404) + .withHeader("Content-Type", "text/xml") + .withBody("Generic VNF Not Found"))); + + body = + "" + EOL + + " a27ce5a9-29c4-4c22-a017-6615ac73c721" + EOL + + " STMTN5MMSC21" + EOL + + " mmsc-capacity" + EOL + + " SDN-MOBILITY" + EOL + + " vMMSC" + EOL + + " pending-create" + EOL + + " false" + EOL + + " false" + EOL + + " 0000021" + EOL + + " " + EOL + + " " + EOL + + " 973ed047-d251-4fb9-bf1a-65b8949e0a73" + EOL + + " STMTN5MMSC21-MMSC::module-0-0" + EOL + + " 973ed047-d251-4fb9-bf1a-65b8949e0a73" + EOL + + " 1.0" + EOL + + " true" + EOL + + " FILLED-IN-BY-MSO" + EOL + + " pending-create" + EOL + + " 0000073" + EOL + + " " + EOL + + " " + EOL + + " " + EOL + + " " + EOL + + " " + EOL + + "" + EOL; + stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c721[?]depth=1")) + .willReturn(aResponse() + .withStatus(200) + .withHeader("Content-Type", "text/xml") + .withBody(body))); + + body = + "" + EOL + + " a27ce5a9-29c4-4c22-a017-6615ac73c720" + EOL + + " STMTN5MMSC20" + EOL + + " mmsc-capacity" + EOL + + " SDN-MOBILITY" + EOL + + " vMMSC" + EOL + + " pending-create" + EOL + + " false" + EOL + + " false" + EOL + + " 0000020" + EOL + + " " + EOL + + " " + EOL + + " 973ed047-d251-4fb9-bf1a-65b8949e0a74" + EOL + + " STMTN5MMSC20-MMSC::module-0-0" + EOL + + " 973ed047-d251-4fb9-bf1a-65b8949e0a74" + EOL + + " 1.0" + EOL + + " true" + EOL + + " FILLED-IN-BY-MSO" + EOL + + " pending-create" + EOL + + " 0000074" + EOL + + " " + EOL + + " " + EOL + + " 973ed047-d251-4fb9-bf1a-65b8949e0a75" + EOL + + " STMTN5MMSC20-MMSC::module-1-0" + EOL + + " 973ed047-d251-4fb9-bf1a-65b8949e0a75" + EOL + + " 1.0" + EOL + + " false" + EOL + + " FILLED-IN-BY-MSO" + EOL + + " pending-create" + EOL + + " 0000075" + EOL + + " " + EOL + + " " + EOL + + " " + EOL + + " " + EOL + + " " + EOL + + "" + EOL; + stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c720[?]depth=1")) + .willReturn(aResponse() + .withStatus(200) + .withHeader("Content-Type", "text/xml") + .withBody(body))); + + body = + "" + EOL + + " a27ce5a9-29c4-4c22-a017-6615ac73c719" + EOL + + " STMTN5MMSC19" + EOL + + " mmsc-capacity" + EOL + + " SDN-MOBILITY" + EOL + + " vMMSC" + EOL + + " pending-create" + EOL + + " false" + EOL + + " false" + EOL + + " 0000019" + EOL + + " " + EOL + + " " + EOL + + " 973ed047-d251-4fb9-bf1a-65b8949e0a76" + EOL + + " STMTN5MMSC19-MMSC::module-0-0" + EOL + + " 973ed047-d251-4fb9-bf1a-65b8949e0a76" + EOL + + " 1.0" + EOL + + " true" + EOL + + " FILLED-IN-BY-MSO" + EOL + + " pending-create" + EOL + + " 0000076" + EOL + + " " + EOL + + " " + EOL + + " 973ed047-d251-4fb9-bf1a-65b8949e0a77" + EOL + + " STMTN5MMSC19-MMSC::module-1-0" + EOL + + " 973ed047-d251-4fb9-bf1a-65b8949e0a77" + EOL + + " 1.0" + EOL + + " false" + EOL + + " FILLED-IN-BY-MSO" + EOL + + " pending-create" + EOL + + " 0000077" + EOL + + " " + EOL + + " " + EOL + + " " + EOL + + " " + EOL + + " " + EOL + + "" + EOL; + stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c719[?]depth=1")) + .willReturn(aResponse() + .withStatus(200) + .withHeader("Content-Type", "text/xml") + .withBody(body))); + + body = + "" + EOL + + " a27ce5a9-29c4-4c22-a017-6615ac73c718" + EOL + + " STMTN5MMSC18" + EOL + + " mmsc-capacity" + EOL + + " SDN-MOBILITY" + EOL + + " vMMSC" + EOL + + " pending-create" + EOL + + " false" + EOL + + " false" + EOL + + " 0000018" + EOL + + " " + EOL + + " " + EOL + + " 973ed047-d251-4fb9-bf1a-65b8949e0a78" + EOL + + " STMTN5MMSC18-MMSC::module-0-0" + EOL + + " 973ed047-d251-4fb9-bf1a-65b8949e0a78" + EOL + + " 1.0" + EOL + + " true" + EOL + + " FILLED-IN-BY-MSO" + EOL + + " pending-create" + EOL + + " 0000078" + EOL + + " " + EOL + + " " + EOL + + " " + EOL + + " " + EOL + + " " + EOL + + "" + EOL; + stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c718[?]depth=1")) + .willReturn(aResponse() + .withStatus(200) + .withHeader("Content-Type", "text/xml") + .withBody(body))); + + body = + "" + EOL + + " a27ce5a9-29c4-4c22-a017-6615ac73c721" + EOL + + " STMTN5MMSC21" + EOL + + " mmsc-capacity" + EOL + + " SDN-MOBILITY" + EOL + + " vMMSC" + EOL + + " pending-create" + EOL + + " false" + EOL + + " false" + EOL + + " 0000021" + EOL + + " " + EOL + + " " + EOL + + " 973ed047-d251-4fb9-bf1a-65b8949e0a73" + EOL + + " STMTN5MMSC21-MMSC::module-0-0" + EOL + + " 973ed047-d251-4fb9-bf1a-65b8949e0a73" + EOL + + " 1.0" + EOL + + " true" + EOL + + " FILLED-IN-BY-MSO" + EOL + + " pending-create" + EOL + + " 0000073" + EOL + + " " + EOL + + " " + EOL + + " " + EOL + + " " + EOL + + " " + EOL + + "" + EOL; + stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c721/vf-modules/vf-module/973ed047-d251-4fb9-bf1a-65b8949e0a73")) + .willReturn(aResponse() + .withStatus(200) + .withHeader("Content-Type", "text/xml") + .withBody(body))); + } + public static void MockAAIDeleteGenericVnf(){ + stubFor(delete(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c721/[?]resource-version=0000021")) + .willReturn(aResponse() + .withStatus(200))); + stubFor(delete(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c718/[?]resource-version=0000018")) + .willReturn(aResponse() + .withStatus(500) + .withHeader("Content-Type", "text/xml") + .withBodyFile("aaiFault.xml"))); + } + + public static void MockAAIDeleteVfModule(){ + stubFor(delete(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c721/vf-modules/vf-module/973ed047-d251-4fb9-bf1a-65b8949e0a73/[?]resource-version=0000073")) + .willReturn(aResponse() + .withStatus(200))); + stubFor(delete(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c720/vf-modules/vf-module/973ed047-d251-4fb9-bf1a-65b8949e0a75/[?]resource-version=0000075")) + .willReturn(aResponse() + .withStatus(200))); + stubFor(delete(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c718/vf-modules/vf-module/973ed047-d251-4fb9-bf1a-65b8949e0a78/[?]resource-version=0000078")) + .willReturn(aResponse() + .withStatus(200))); + stubFor(delete(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c719/vf-modules/vf-module/973ed047-d251-4fb9-bf1a-65b8949e0a77/[?]resource-version=0000077")) + .willReturn(aResponse() + .withStatus(500) + .withHeader("Content-Type", "text/xml") + .withBodyFile("aaiFault.xml"))); + stubFor(get(urlMatching("/aai/v[0-9]+/network/network-policies/network-policy\\?network-policy-fqdn=.*")) + .willReturn(aResponse() + .withStatus(200) + .withHeader("Content-Type", "text/xml") + .withBodyFile("VfModularity/QueryNetworkPolicy_AAIResponse_Success.xml"))); + + stubFor(delete(urlMatching("/aai/v[0-9]+/network/network-policies/network-policy/.*")) + .willReturn(aResponse() + .withStatus(200))); + } +} + diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/FalloutHandlerTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/FalloutHandlerTest.java index 77320751ee..5223bca386 100644 --- a/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/FalloutHandlerTest.java +++ b/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/FalloutHandlerTest.java @@ -1,226 +1,230 @@ -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - MSO - * ================================================================================ - * 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.openecomp.mso.bpmn.common; - -import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; -import static com.github.tomakehurst.wiremock.client.WireMock.post; -import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; -import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; -import static org.openecomp.mso.bpmn.common.BPMNUtil.executeWorkFlow; -import static org.openecomp.mso.bpmn.common.BPMNUtil.waitForWorkflowToFinish; - -import java.util.HashMap; -import java.util.Map; - -import org.camunda.bpm.engine.test.Deployment; -import org.junit.Assert; -import org.junit.Test; -import org.openecomp.mso.bpmn.common.workflow.service.WorkflowResponse; - -/** - * Unit test for FalloutHandler.bpmn. - */ -public class FalloutHandlerTest extends WorkflowTest { - private void setupMocks() { - stubFor(post(urlEqualTo("/dbadapters/RequestsDbAdapter")) - .willReturn(aResponse() - .withStatus(200) - .withHeader("Content-Type", "text/xml") - .withBody("Notified"))); - } - - private void executeFlow(String inputRequestFile) throws InterruptedException { - String method = getClass().getSimpleName() + "." + new Object() { - }.getClass().getEnclosingMethod().getName(); - System.out.println("STARTED TEST: " + method); - - //String changeFeatureActivateRequest = FileUtil.readResourceFile("__files/SDN-ETHERNET-INTERNET/ChangeFeatureActivateV1/" + inputRequestFile); - Map variables = new HashMap(); - variables.put("FalloutHandlerRequest",inputRequestFile); - - WorkflowResponse workflowResponse = executeWorkFlow(processEngineRule, "FalloutHandler", variables); - waitForWorkflowToFinish(processEngineRule, workflowResponse.getProcessInstanceID()); - System.out.println("ENDED TEST: " + method); - } - - @Test - @Deployment(resources = {"subprocess/FalloutHandler.bpmn"}) - public void msoFalloutHandlerWithNotificationurl_200() throws Exception{ - String method = getClass().getSimpleName() + "." + new Object() { - }.getClass().getEnclosingMethod().getName(); - System.out.println("STARTED TEST: " + method); - - //Setup Mocks - setupMocks(); - //Execute Flow - executeFlow(gMsoFalloutHandlerWithNotificationurl()); - //Verify Error - String FH_ResponseCode = BPMNUtil.getVariable(processEngineRule, "FalloutHandler", "FH_ResponseCode"); - Assert.assertEquals("200", FH_ResponseCode); - Assert.assertTrue((boolean) BPMNUtil.getRawVariable(processEngineRule, "FalloutHandler", "FH_SuccessIndicator")); - } - - public String gMsoFalloutHandlerWithNotificationurl() { - //Generated the below XML from ActiveVOS moduler ... Using the generate sample XML feature in ActiveVOS - String xml = "" - + "" - + " " - + " uCPE1020_STUW105_5002" - + " Layer3ServiceActivateRequest" - + " CANCEL" - + " OMX" - + " http://localhost:28090/CCD/StatusNotification" - + " 10205000" - + " 1" - + " " - + " " - + " Some Error Message - Fallout Handler" - + " Some Error Code - Fallout Handler" - + " Some Source System Error Code- Fallout Handler" - + " " - + ""; - - return xml; - - } - - - - - @Test - @Deployment(resources = {"subprocess/FalloutHandler.bpmn"}) - public void msoFalloutHandlerWithNoNotificationurl() throws Exception{ - String method = getClass().getSimpleName() + "." + new Object() { - }.getClass().getEnclosingMethod().getName(); - System.out.println("STARTED TEST: " + method); - //Setup Mocks - setupMocks(); - //Execute Flow - executeFlow(gMsoFalloutHandlerWithNoNotificationurl()); - //Verify Error - String FH_ResponseCode = BPMNUtil.getVariable(processEngineRule, "FalloutHandler", "FH_ResponseCode"); - Assert.assertEquals("200", FH_ResponseCode); - Assert.assertTrue((boolean) BPMNUtil.getRawVariable(processEngineRule, "FalloutHandler", "FH_SuccessIndicator")); - } - - public String gMsoFalloutHandlerWithNoNotificationurl() { - //Generated the below XML from ActiveVOS moduler ... Using the generate sample XML feature in ActiveVOS - String xml = "" - + "" - + " " - + " uCPE1020_STUW105_5002" - + " Layer3ServiceActivateRequest" - + " CANCEL" - + " OMX" - + " " - + " 10205000" - + " 1" - + " " - + " " - + " Some Error Message - Fallout Handler" - + " Some Error Code - Fallout Handler" - + " Some Source System Error Code- Fallout Handler" - + " " - + ""; - - return xml; - } - - @Test - @Deployment(resources = {"subprocess/FalloutHandler.bpmn"}) - public void msoFalloutHandlerWithNotificationurlNoRequestId() throws Exception{ - String method = getClass().getSimpleName() + "." + new Object() { - }.getClass().getEnclosingMethod().getName(); - System.out.println("STARTED TEST: " + method); - //Setup Mocks - setupMocks(); - //Execute Flow - executeFlow(gMsoFalloutHandlerWithNotificationurlNoRequestId()); - //Verify Error - String FH_ResponseCode = BPMNUtil.getVariable(processEngineRule, "FalloutHandler", "FH_ResponseCode"); - Assert.assertEquals("200", FH_ResponseCode); - Assert.assertTrue((boolean) BPMNUtil.getRawVariable(processEngineRule, "FalloutHandler", "FH_SuccessIndicator")); - } - - public String gMsoFalloutHandlerWithNotificationurlNoRequestId() { - //Generated the below XML from ActiveVOS moduler ... Using the generate sample XML feature in ActiveVOS - String xml = "" - + "" - + " " - + " " - + " Layer3ServiceActivateRequest" - + " CANCEL" - + " OMX" - + " www.att.com" - + " 10205000" - + " 1" - + " " - + " " - + " Some Error Message - Fallout Handler" - + " Some Error Code - Fallout Handler" - + " Some Source System Error Code- Fallout Handler" - + " " - + ""; - - return xml; - } - - @Test - @Deployment(resources = {"subprocess/FalloutHandler.bpmn"}) - public void msoFalloutHandlerWithNoNotificationurlNoRequestId() throws Exception{ - String method = getClass().getSimpleName() + "." + new Object() { - }.getClass().getEnclosingMethod().getName(); - System.out.println("STARTED TEST: " + method); - //Setup Mocks - setupMocks(); - //Execute Flow - executeFlow(gMsoFalloutHandlerWithNoNotificationurlNoRequestId()); - //Verify Error - String FH_ResponseCode = BPMNUtil.getVariable(processEngineRule, "FalloutHandler", "FH_ResponseCode"); - Assert.assertEquals("200", FH_ResponseCode); - Assert.assertTrue((boolean) BPMNUtil.getRawVariable(processEngineRule, "FalloutHandler", "FH_SuccessIndicator")); - } - - public String gMsoFalloutHandlerWithNoNotificationurlNoRequestId() { - //Generated the below XML from ActiveVOS moduler ... Using the generate sample XML feature in ActiveVOS - String xml = "" - + "" - + " " - + " " - + " Layer3ServiceActivateRequest" - + " CANCEL" - + " OMX" - + " " - + " 10205000" - + " 1" - + " " - + " " - + " Some Error Message - Fallout Handler" - + " Some Error Code - Fallout Handler" - + " Some Source System Error Code- Fallout Handler" - + " " - + ""; - - return xml; - } - -} - +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.bpmn.common; + +import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; +import static com.github.tomakehurst.wiremock.client.WireMock.post; +import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; +import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; +import static org.openecomp.mso.bpmn.common.BPMNUtil.executeWorkFlow; +import static org.openecomp.mso.bpmn.common.BPMNUtil.waitForWorkflowToFinish; + +import java.util.HashMap; +import java.util.Map; + +import org.camunda.bpm.engine.test.Deployment; +import org.junit.Assert; +import org.junit.Test; +import org.openecomp.mso.bpmn.common.workflow.service.WorkflowResponse; + +/** + * Unit test for FalloutHandler.bpmn. + */ +public class FalloutHandlerTest extends WorkflowTest { + private void setupMocks() { + stubFor(post(urlEqualTo("/dbadapters/RequestsDbAdapter")) + .willReturn(aResponse() + .withStatus(200) + .withHeader("Content-Type", "text/xml") + .withBody("Notified"))); + } + + private void executeFlow(String inputRequestFile) throws InterruptedException { + String method = getClass().getSimpleName() + "." + new Object() { + }.getClass().getEnclosingMethod().getName(); + System.out.println("STARTED TEST: " + method); + + //String changeFeatureActivateRequest = FileUtil.readResourceFile("__files/SDN-ETHERNET-INTERNET/ChangeFeatureActivateV1/" + inputRequestFile); + Map variables = new HashMap(); + variables.put("FalloutHandlerRequest",inputRequestFile); + + WorkflowResponse workflowResponse = executeWorkFlow(processEngineRule, "FalloutHandler", variables); + waitForWorkflowToFinish(processEngineRule, workflowResponse.getProcessInstanceID()); + System.out.println("ENDED TEST: " + method); + } + + @Test + @Deployment(resources = {"subprocess/FalloutHandler.bpmn", + "subprocess/GenericNotificationService.bpmn" + }) + public void msoFalloutHandlerWithNotificationurl_200() throws Exception{ + String method = getClass().getSimpleName() + "." + new Object() { + }.getClass().getEnclosingMethod().getName(); + System.out.println("STARTED TEST: " + method); + + //Setup Mocks + setupMocks(); + //Execute Flow + executeFlow(gMsoFalloutHandlerWithNotificationurl()); + //Verify Error + String FH_ResponseCode = BPMNUtil.getVariable(processEngineRule, "FalloutHandler", "FH_ResponseCode"); + Assert.assertEquals("200", FH_ResponseCode); + Assert.assertTrue((boolean) BPMNUtil.getRawVariable(processEngineRule, "FalloutHandler", "FH_SuccessIndicator")); + } + + public String gMsoFalloutHandlerWithNotificationurl() { + //Generated the below XML from ActiveVOS moduler ... Using the generate sample XML feature in ActiveVOS + String xml = "" + + "" + + " " + + " uCPE1020_STUW105_5002" + + " Layer3ServiceActivateRequest" + + " CANCEL" + + " OMX" + + " http://localhost:28090/CCD/StatusNotification" + + " 10205000" + + " 1" + + " " + + " " + + " Some Error Message - Fallout Handler" + + " Some Error Code - Fallout Handler" + + " Some Source System Error Code- Fallout Handler" + + " " + + ""; + + return xml; + + } + + + + + @Test + @Deployment(resources = {"subprocess/FalloutHandler.bpmn"}) + public void msoFalloutHandlerWithNoNotificationurl() throws Exception{ + String method = getClass().getSimpleName() + "." + new Object() { + }.getClass().getEnclosingMethod().getName(); + System.out.println("STARTED TEST: " + method); + //Setup Mocks + setupMocks(); + //Execute Flow + executeFlow(gMsoFalloutHandlerWithNoNotificationurl()); + //Verify Error + String FH_ResponseCode = BPMNUtil.getVariable(processEngineRule, "FalloutHandler", "FH_ResponseCode"); + Assert.assertEquals("200", FH_ResponseCode); + Assert.assertTrue((boolean) BPMNUtil.getRawVariable(processEngineRule, "FalloutHandler", "FH_SuccessIndicator")); + } + + public String gMsoFalloutHandlerWithNoNotificationurl() { + //Generated the below XML from ActiveVOS moduler ... Using the generate sample XML feature in ActiveVOS + String xml = "" + + "" + + " " + + " uCPE1020_STUW105_5002" + + " Layer3ServiceActivateRequest" + + " CANCEL" + + " OMX" + + " " + + " 10205000" + + " 1" + + " " + + " " + + " Some Error Message - Fallout Handler" + + " Some Error Code - Fallout Handler" + + " Some Source System Error Code- Fallout Handler" + + " " + + ""; + + return xml; + } + + @Test + @Deployment(resources = {"subprocess/FalloutHandler.bpmn", + "subprocess/GenericNotificationService.bpmn" + }) + public void msoFalloutHandlerWithNotificationurlNoRequestId() throws Exception{ + String method = getClass().getSimpleName() + "." + new Object() { + }.getClass().getEnclosingMethod().getName(); + System.out.println("STARTED TEST: " + method); + //Setup Mocks + setupMocks(); + //Execute Flow + executeFlow(gMsoFalloutHandlerWithNotificationurlNoRequestId()); + //Verify Error + String FH_ResponseCode = BPMNUtil.getVariable(processEngineRule, "FalloutHandler", "FH_ResponseCode"); + Assert.assertEquals("200", FH_ResponseCode); + Assert.assertTrue((boolean) BPMNUtil.getRawVariable(processEngineRule, "FalloutHandler", "FH_SuccessIndicator")); + } + + public String gMsoFalloutHandlerWithNotificationurlNoRequestId() { + //Generated the below XML from ActiveVOS moduler ... Using the generate sample XML feature in ActiveVOS + String xml = "" + + "" + + " " + + " " + + " Layer3ServiceActivateRequest" + + " CANCEL" + + " OMX" + + " www.test.com" + + " 10205000" + + " 1" + + " " + + " " + + " Some Error Message - Fallout Handler" + + " Some Error Code - Fallout Handler" + + " Some Source System Error Code- Fallout Handler" + + " " + + ""; + + return xml; + } + + @Test + @Deployment(resources = {"subprocess/FalloutHandler.bpmn"}) + public void msoFalloutHandlerWithNoNotificationurlNoRequestId() throws Exception{ + String method = getClass().getSimpleName() + "." + new Object() { + }.getClass().getEnclosingMethod().getName(); + System.out.println("STARTED TEST: " + method); + //Setup Mocks + setupMocks(); + //Execute Flow + executeFlow(gMsoFalloutHandlerWithNoNotificationurlNoRequestId()); + //Verify Error + String FH_ResponseCode = BPMNUtil.getVariable(processEngineRule, "FalloutHandler", "FH_ResponseCode"); + Assert.assertEquals("200", FH_ResponseCode); + Assert.assertTrue((boolean) BPMNUtil.getRawVariable(processEngineRule, "FalloutHandler", "FH_SuccessIndicator")); + } + + public String gMsoFalloutHandlerWithNoNotificationurlNoRequestId() { + //Generated the below XML from ActiveVOS moduler ... Using the generate sample XML feature in ActiveVOS + String xml = "" + + "" + + " " + + " " + + " Layer3ServiceActivateRequest" + + " CANCEL" + + " OMX" + + " " + + " 10205000" + + " 1" + + " " + + " " + + " Some Error Message - Fallout Handler" + + " Some Error Code - Fallout Handler" + + " Some Source System Error Code- Fallout Handler" + + " " + + ""; + + return xml; + } + +} + diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/PrepareUpdateAAIVfModuleTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/PrepareUpdateAAIVfModuleTest.java index cb5f722a42..6fe6df6e11 100644 --- a/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/PrepareUpdateAAIVfModuleTest.java +++ b/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/PrepareUpdateAAIVfModuleTest.java @@ -1,208 +1,210 @@ -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - MSO - * ================================================================================ - * 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.openecomp.mso.bpmn.common; - -import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockGetGenericVnfByIdWithDepth; -import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockGetGenericVnfById_404; -import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockPutGenericVnf; - -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; - -import org.camunda.bpm.engine.test.Deployment; -import org.junit.Assert; -import org.junit.Test; -import org.openecomp.mso.bpmn.core.WorkflowException; -import org.openecomp.mso.bpmn.mock.FileUtil; - -/** - * Unit tests for PrepareUpdateAAIVfModule.bpmn. - */ -public class PrepareUpdateAAIVfModuleTest extends WorkflowTest { - - /** - * Test the happy path through the flow. - */ - @Test - @Deployment(resources = { - "subprocess/PrepareUpdateAAIVfModule.bpmn" - }) - public void happyPath() throws IOException { - - logStart(); - - String prepareUpdateAAIVfModuleRequest = FileUtil.readResourceFile("__files/VfModularity/PrepareUpdateAAIVfModuleRequest.xml"); - - MockGetGenericVnfByIdWithDepth("skask", 1, "VfModularity/GenericVnf.xml"); - MockPutGenericVnf("/skask/vf-modules/vf-module/supercool", "PCRF", 200); - - String businessKey = UUID.randomUUID().toString(); - Map variables = new HashMap(); - variables.put("mso-request-id", "999-99-9999"); - variables.put("isDebugLogEnabled","true"); - variables.put("PrepareUpdateAAIVfModuleRequest", prepareUpdateAAIVfModuleRequest); - invokeSubProcess("PrepareUpdateAAIVfModule", businessKey, variables); - - Assert.assertTrue(isProcessEnded(businessKey)); - String response = (String) getVariableFromHistory(businessKey, "PUAAIVfMod_updateVfModuleResponse"); - Integer responseCode = (Integer) getVariableFromHistory(businessKey, "PUAAIVfMod_updateVfModuleResponseCode"); - System.out.println("Subflow response code: " + responseCode); - System.out.println("Subflow response: " + response); - Assert.assertEquals(200, responseCode.intValue()); - String heatStackId = (String) getVariableFromHistory(businessKey, "PUAAIVfMod_heatStackId"); - System.out.println("Ouput heat-stack-id:" + heatStackId); - Assert.assertEquals("slowburn", heatStackId); - - logEnd(); - } - - /** - * Test the case where the GET to AAI returns a 404. - */ - @Test - @Deployment(resources = { - "subprocess/PrepareUpdateAAIVfModule.bpmn" - }) - public void badGet() throws IOException { - - logStart(); - - String prepareUpdateAAIVfModuleRequest = FileUtil.readResourceFile("__files/VfModularity/PrepareUpdateAAIVfModuleRequest.xml"); - MockGetGenericVnfById_404("skask[?]depth=1"); - - String businessKey = UUID.randomUUID().toString(); - Map variables = new HashMap(); - variables.put("mso-request-id", "999-99-9999"); - variables.put("isDebugLogEnabled","true"); - variables.put("PrepareUpdateAAIVfModuleRequest", prepareUpdateAAIVfModuleRequest); - invokeSubProcess("PrepareUpdateAAIVfModule", businessKey, variables); - - Assert.assertTrue(isProcessEnded(businessKey)); - String response = (String) getVariableFromHistory(businessKey, "PUAAIVfMod_getVnfResponse"); - Integer responseCode = (Integer) getVariableFromHistory(businessKey, "PUAAIVfMod_getVnfResponseCode"); - WorkflowException workflowException = (WorkflowException) getVariableFromHistory(businessKey, "WorkflowException"); - System.out.println("Subflow response code: " + responseCode); - System.out.println("Subflow response: " + response); - Assert.assertEquals(404, responseCode.intValue()); - Assert.assertNotNull(workflowException); - System.out.println("Subflow WorkflowException error message: " + workflowException.getErrorMessage()); - - logEnd(); - } - - /** - * Test the case where the validation of the VF Module fails. - */ - @Test - @Deployment(resources = { - "subprocess/PrepareUpdateAAIVfModule.bpmn" - }) - public void failValidation1() throws IOException { - - logStart(); - - String prepareUpdateAAIVfModuleRequest = FileUtil.readResourceFile("__files/VfModularity/PrepareUpdateAAIVfModuleRequest.xml").replaceFirst("supercool", "lukewarm"); - - MockGetGenericVnfByIdWithDepth("skask", 1, "VfModularity/GenericVnf.xml"); - - String businessKey = UUID.randomUUID().toString(); - Map variables = new HashMap(); - variables.put("mso-request-id", "999-99-9999"); - variables.put("isDebugLogEnabled","true"); - variables.put("PrepareUpdateAAIVfModuleRequest", prepareUpdateAAIVfModuleRequest); - invokeSubProcess("PrepareUpdateAAIVfModule", businessKey, variables); - - WorkflowException workflowException = (WorkflowException) getVariableFromHistory(businessKey, "WorkflowException"); - Assert.assertNotNull(workflowException); - System.out.println("Subflow WorkflowException error message: " + workflowException.getErrorMessage()); - Assert.assertTrue(workflowException.getErrorMessage().startsWith("VF Module validation error: Orchestration")); - - logEnd(); - } - - /** - * Test the case where the validation of the VF Module fails. - */ - @Test - @Deployment(resources = { - "subprocess/PrepareUpdateAAIVfModule.bpmn" - }) - public void failValidation2() throws IOException { - - logStart(); - - String prepareUpdateAAIVfModuleRequest = FileUtil.readResourceFile("__files/VfModularity/PrepareUpdateAAIVfModuleRequest.xml").replaceFirst("supercool", "notsocool"); - - MockGetGenericVnfByIdWithDepth("skask", 1, "VfModularity/GenericVnf.xml"); - - String businessKey = UUID.randomUUID().toString(); - Map variables = new HashMap(); - variables.put("mso-request-id", "999-99-9999"); - variables.put("isDebugLogEnabled","true"); - variables.put("PrepareUpdateAAIVfModuleRequest", prepareUpdateAAIVfModuleRequest); - invokeSubProcess("PrepareUpdateAAIVfModule", businessKey, variables); - - WorkflowException workflowException = (WorkflowException) getVariableFromHistory(businessKey, "WorkflowException"); - Assert.assertNotNull(workflowException); - System.out.println("Subflow WorkflowException error message: " + workflowException.getErrorMessage()); - Assert.assertTrue(workflowException.getErrorMessage().startsWith("VF Module validation error: VF Module")); - - logEnd(); - } - - /** - * Test the case where the GET to AAI is successful, but the subsequent PUT returns 404. - */ - @Test - @Deployment(resources = { - "subprocess/PrepareUpdateAAIVfModule.bpmn" - }) - public void badPut() throws IOException { - - logStart(); - - String prepareUpdateAAIVfModuleRequest = FileUtil.readResourceFile("__files/VfModularity/PrepareUpdateAAIVfModuleRequest.xml"); - - MockGetGenericVnfByIdWithDepth("skask", 1, "VfModularity/GenericVnf.xml"); - - String businessKey = UUID.randomUUID().toString(); - Map variables = new HashMap(); - variables.put("mso-request-id", "999-99-9999"); - variables.put("isDebugLogEnabled","true"); - variables.put("PrepareUpdateAAIVfModuleRequest", prepareUpdateAAIVfModuleRequest); - invokeSubProcess("PrepareUpdateAAIVfModule", businessKey, variables); - - Assert.assertTrue(isProcessEnded(businessKey)); - String response = (String) getVariableFromHistory(businessKey, "PUAAIVfMod_updateVfModuleResponse"); - Integer responseCode = (Integer) getVariableFromHistory(businessKey, "PUAAIVfMod_updateVfModuleResponseCode"); - WorkflowException workflowException = (WorkflowException) getVariableFromHistory(businessKey, "WorkflowException"); - System.out.println("Subflow response code: " + responseCode); - System.out.println("Subflow response: " + response); - Assert.assertEquals(404, responseCode.intValue()); - Assert.assertNotNull(workflowException); - System.out.println("Subflow WorkflowException error message: " + workflowException.getErrorMessage()); - - logEnd(); - } -} - +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.bpmn.common; + +import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockGetGenericVnfByIdWithDepth; +import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockGetGenericVnfById_404; +import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockPutGenericVnf; +import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockPatchVfModuleId; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +import org.camunda.bpm.engine.test.Deployment; +import org.junit.Assert; +import org.junit.Test; +import org.openecomp.mso.bpmn.core.WorkflowException; +import org.openecomp.mso.bpmn.mock.FileUtil; + +/** + * Unit tests for PrepareUpdateAAIVfModule.bpmn. + */ +public class PrepareUpdateAAIVfModuleTest extends WorkflowTest { + + /** + * Test the happy path through the flow. + */ + @Test + @Deployment(resources = { + "subprocess/PrepareUpdateAAIVfModule.bpmn" + }) + public void happyPath() throws IOException { + + logStart(); + + String prepareUpdateAAIVfModuleRequest = FileUtil.readResourceFile("__files/VfModularity/PrepareUpdateAAIVfModuleRequest.xml"); + + MockGetGenericVnfByIdWithDepth("skask", 1, "VfModularity/GenericVnf.xml"); + MockPutGenericVnf("/skask/vf-modules/vf-module/supercool", "PCRF", 200); + MockPatchVfModuleId("skask", "supercool"); + + String businessKey = UUID.randomUUID().toString(); + Map variables = new HashMap(); + variables.put("mso-request-id", "999-99-9999"); + variables.put("isDebugLogEnabled","true"); + variables.put("PrepareUpdateAAIVfModuleRequest", prepareUpdateAAIVfModuleRequest); + invokeSubProcess("PrepareUpdateAAIVfModule", businessKey, variables); + + Assert.assertTrue(isProcessEnded(businessKey)); + String response = (String) getVariableFromHistory(businessKey, "PUAAIVfMod_updateVfModuleResponse"); + Integer responseCode = (Integer) getVariableFromHistory(businessKey, "PUAAIVfMod_updateVfModuleResponseCode"); + System.out.println("Subflow response code: " + responseCode); + System.out.println("Subflow response: " + response); + Assert.assertEquals(200, responseCode.intValue()); + String heatStackId = (String) getVariableFromHistory(businessKey, "PUAAIVfMod_heatStackId"); + System.out.println("Ouput heat-stack-id:" + heatStackId); + Assert.assertEquals("slowburn", heatStackId); + + logEnd(); + } + + /** + * Test the case where the GET to AAI returns a 404. + */ + @Test + @Deployment(resources = { + "subprocess/PrepareUpdateAAIVfModule.bpmn" + }) + public void badGet() throws IOException { + + logStart(); + + String prepareUpdateAAIVfModuleRequest = FileUtil.readResourceFile("__files/VfModularity/PrepareUpdateAAIVfModuleRequest.xml"); + MockGetGenericVnfById_404("skask[?]depth=1"); + + String businessKey = UUID.randomUUID().toString(); + Map variables = new HashMap(); + variables.put("mso-request-id", "999-99-9999"); + variables.put("isDebugLogEnabled","true"); + variables.put("PrepareUpdateAAIVfModuleRequest", prepareUpdateAAIVfModuleRequest); + invokeSubProcess("PrepareUpdateAAIVfModule", businessKey, variables); + + Assert.assertTrue(isProcessEnded(businessKey)); + String response = (String) getVariableFromHistory(businessKey, "PUAAIVfMod_getVnfResponse"); + Integer responseCode = (Integer) getVariableFromHistory(businessKey, "PUAAIVfMod_getVnfResponseCode"); + WorkflowException workflowException = (WorkflowException) getVariableFromHistory(businessKey, "WorkflowException"); + System.out.println("Subflow response code: " + responseCode); + System.out.println("Subflow response: " + response); + Assert.assertEquals(404, responseCode.intValue()); + Assert.assertNotNull(workflowException); + System.out.println("Subflow WorkflowException error message: " + workflowException.getErrorMessage()); + + logEnd(); + } + + /** + * Test the case where the validation of the VF Module fails. + */ + @Test + @Deployment(resources = { + "subprocess/PrepareUpdateAAIVfModule.bpmn" + }) + public void failValidation1() throws IOException { + + logStart(); + + String prepareUpdateAAIVfModuleRequest = FileUtil.readResourceFile("__files/VfModularity/PrepareUpdateAAIVfModuleRequest.xml").replaceFirst("supercool", "lukewarm"); + + MockGetGenericVnfByIdWithDepth("skask", 1, "VfModularity/GenericVnf.xml"); + + String businessKey = UUID.randomUUID().toString(); + Map variables = new HashMap(); + variables.put("mso-request-id", "999-99-9999"); + variables.put("isDebugLogEnabled","true"); + variables.put("PrepareUpdateAAIVfModuleRequest", prepareUpdateAAIVfModuleRequest); + invokeSubProcess("PrepareUpdateAAIVfModule", businessKey, variables); + + WorkflowException workflowException = (WorkflowException) getVariableFromHistory(businessKey, "WorkflowException"); + Assert.assertNotNull(workflowException); + System.out.println("Subflow WorkflowException error message: " + workflowException.getErrorMessage()); + Assert.assertTrue(workflowException.getErrorMessage().startsWith("VF Module validation error: Orchestration")); + + logEnd(); + } + + /** + * Test the case where the validation of the VF Module fails. + */ + @Test + @Deployment(resources = { + "subprocess/PrepareUpdateAAIVfModule.bpmn" + }) + public void failValidation2() throws IOException { + + logStart(); + + String prepareUpdateAAIVfModuleRequest = FileUtil.readResourceFile("__files/VfModularity/PrepareUpdateAAIVfModuleRequest.xml").replaceFirst("supercool", "notsocool"); + + MockGetGenericVnfByIdWithDepth("skask", 1, "VfModularity/GenericVnf.xml"); + + String businessKey = UUID.randomUUID().toString(); + Map variables = new HashMap(); + variables.put("mso-request-id", "999-99-9999"); + variables.put("isDebugLogEnabled","true"); + variables.put("PrepareUpdateAAIVfModuleRequest", prepareUpdateAAIVfModuleRequest); + invokeSubProcess("PrepareUpdateAAIVfModule", businessKey, variables); + + WorkflowException workflowException = (WorkflowException) getVariableFromHistory(businessKey, "WorkflowException"); + Assert.assertNotNull(workflowException); + System.out.println("Subflow WorkflowException error message: " + workflowException.getErrorMessage()); + Assert.assertTrue(workflowException.getErrorMessage().startsWith("VF Module validation error: VF Module")); + + logEnd(); + } + + /** + * Test the case where the GET to AAI is successful, but the subsequent PUT returns 404. + */ + @Test + @Deployment(resources = { + "subprocess/PrepareUpdateAAIVfModule.bpmn" + }) + public void badPut() throws IOException { + + logStart(); + + String prepareUpdateAAIVfModuleRequest = FileUtil.readResourceFile("__files/VfModularity/PrepareUpdateAAIVfModuleRequest.xml"); + + MockGetGenericVnfByIdWithDepth("skask", 1, "VfModularity/GenericVnf.xml"); + + String businessKey = UUID.randomUUID().toString(); + Map variables = new HashMap(); + variables.put("mso-request-id", "999-99-9999"); + variables.put("isDebugLogEnabled","true"); + variables.put("PrepareUpdateAAIVfModuleRequest", prepareUpdateAAIVfModuleRequest); + invokeSubProcess("PrepareUpdateAAIVfModule", businessKey, variables); + + Assert.assertTrue(isProcessEnded(businessKey)); + String response = (String) getVariableFromHistory(businessKey, "PUAAIVfMod_updateVfModuleResponse"); + Integer responseCode = (Integer) getVariableFromHistory(businessKey, "PUAAIVfMod_updateVfModuleResponseCode"); + WorkflowException workflowException = (WorkflowException) getVariableFromHistory(businessKey, "WorkflowException"); + System.out.println("Subflow response code: " + responseCode); + System.out.println("Subflow response: " + response); + Assert.assertEquals(404, responseCode.intValue()); + Assert.assertNotNull(workflowException); + System.out.println("Subflow WorkflowException error message: " + workflowException.getErrorMessage()); + + logEnd(); + } +} + diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/SDNCAdapterV1Test.java b/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/SDNCAdapterV1Test.java index b0e1dc9afc..846a14f45f 100644 --- a/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/SDNCAdapterV1Test.java +++ b/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/SDNCAdapterV1Test.java @@ -1,389 +1,403 @@ -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - MSO - * ================================================================================ - * 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.openecomp.mso.bpmn.common; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.openecomp.mso.bpmn.mock.StubResponseDatabase.mockUpdateRequestDB; -import static org.openecomp.mso.bpmn.mock.StubResponseSDNCAdapter.mockSDNCAdapter; - -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; - -import javax.ws.rs.core.Response; - -import org.camunda.bpm.engine.MismatchingMessageCorrelationException; -import org.camunda.bpm.engine.impl.cfg.ProcessEngineConfigurationImpl; -import org.camunda.bpm.engine.runtime.Job; -import org.camunda.bpm.engine.test.Deployment; -import org.camunda.bpm.engine.variable.impl.VariableMapImpl; -import org.junit.Assert; -import org.junit.Test; -import org.openecomp.mso.bpmn.common.adapter.sdnc.CallbackHeader; -import org.openecomp.mso.bpmn.common.adapter.sdnc.SDNCAdapterCallbackRequest; -import org.openecomp.mso.bpmn.common.adapter.sdnc.SDNCAdapterResponse; -import org.openecomp.mso.bpmn.common.workflow.service.SDNCAdapterCallbackServiceImpl; -import org.openecomp.mso.bpmn.common.workflow.service.SDNCAdapterCallbackServiceImpl.SDNCAdapterExceptionResponse; -import org.openecomp.mso.bpmn.common.workflow.service.WorkflowResource; -import org.openecomp.mso.bpmn.common.workflow.service.WorkflowResponse; -import org.openecomp.mso.bpmn.mock.FileUtil; - -/** - * Unit test cases for SDNCAdapterV1.bpmn - */ -public class SDNCAdapterV1Test extends WorkflowTest { - - private String sdncAdapterWorkflowRequest; - private String sdncAdapterWorkflowRequestAct; - private String sdncAdapterCallbackRequestData; - private String sdncAdapterCallbackRequestDataNonfinal; - - public SDNCAdapterV1Test() throws IOException { - sdncAdapterWorkflowRequest = FileUtil.readResourceFile("sdncadapterworkflowrequest.xml"); - sdncAdapterWorkflowRequestAct = FileUtil.readResourceFile("sdncadapterworkflowrequest-act.xml"); - sdncAdapterCallbackRequestData = FileUtil.readResourceFile("sdncadaptercallbackrequestdata.text"); - sdncAdapterCallbackRequestDataNonfinal = FileUtil.readResourceFile("sdncadaptercallbackrequestdata-nonfinal.text"); - } - - /** - * End-to-End flow - Unit test for SDNCAdapterV1.bpmn - * - String input & String response - */ - - private WorkflowResponse invokeFlow(String workflowRequest) { - - MapvalueMap = new HashMap(); - valueMap.put("value", workflowRequest); - Map variables = new HashMap(); - variables.put("sdncAdapterWorkflowRequest", valueMap); - - Map valueMap2 = new HashMap(); - valueMap2.put("value", "true"); - variables.put("isDebugLogEnabled", valueMap2); - - VariableMapImpl varMap = new VariableMapImpl(); - varMap.put("variables", variables); - - //System.out.println("Invoking the flow"); - - WorkflowResource workflowResource = new WorkflowResource(); - workflowResource.setProcessEngineServices4junit(processEngineRule); - - Response response = workflowResource.startProcessInstanceByKey("sdncAdapter", varMap); - WorkflowResponse workflowResponse = (WorkflowResponse) response.getEntity(); - - //String pid = workflowResponse.getProcessInstanceID(); - //System.out.println("Back from executing process instance with pid=" + pid); - return workflowResponse; - } - - @Test - @Deployment(resources = {"subprocess/SDNCAdapterV1.bpmn"}) - public void sunnyDay() throws InterruptedException { - - mockSDNCAdapter(200); - - //System.out.println("SDNCAdapter sunny day flow Started!"); - - ProcessExecutionThread thread = new ProcessExecutionThread(sdncAdapterWorkflowRequest); - thread.start(); - waitForExecutionToStart("sdncAdapter", 3); - String pid = getPid(); - - assertProcessInstanceNotFinished(pid); - - System.out.println("Injecting SDNC Adapter asynchronous callback message to continue processing"); - String generatedRequestId = (String) processEngineRule.getRuntimeService().getVariable(pid, "SDNCA_requestId"); - CallbackHeader callbackHeader = new CallbackHeader(); - callbackHeader.setRequestId(generatedRequestId); - callbackHeader.setResponseCode("200"); - callbackHeader.setResponseMessage("OK"); - SDNCAdapterCallbackRequest sdncAdapterCallbackRequest = new SDNCAdapterCallbackRequest(); - sdncAdapterCallbackRequest.setCallbackHeader(callbackHeader); - sdncAdapterCallbackRequest.setRequestData(sdncAdapterCallbackRequestData); - SDNCAdapterCallbackServiceImpl callbackService = new SDNCAdapterCallbackServiceImpl(); - callbackService.setProcessEngineServices4junit(processEngineRule); - SDNCAdapterResponse sdncAdapterResponse = callbackService.sdncAdapterCallback(sdncAdapterCallbackRequest); - //System.out.println("Back from executing process again"); - - assertFalse(sdncAdapterResponse instanceof SDNCAdapterExceptionResponse); - assertProcessInstanceFinished(pid); - - //System.out.println("SDNCAdapter sunny day flow Completed!"); - } - - @Test - @Deployment(resources = {"subprocess/SDNCAdapterV1.bpmn"}) - public void nonFinalWithTimeout() throws InterruptedException { - - mockSDNCAdapter(200); - mockUpdateRequestDB(200, "Database/DBAdapter.xml"); - - //System.out.println("SDNCAdapter interim status processing flow Started!"); - - ProcessExecutionThread thread = new ProcessExecutionThread(sdncAdapterWorkflowRequestAct); - thread.start(); - waitForExecutionToStart("sdncAdapter", 3); - String pid = getPid(); - - assertProcessInstanceNotFinished(pid); - - //System.out.println("Injecting SDNC Adapter asynchronous callback message to continue processing"); - String generatedRequestId = (String) processEngineRule.getRuntimeService().getVariable(pid, "SDNCA_requestId"); - CallbackHeader callbackHeader = new CallbackHeader(); - callbackHeader.setRequestId(generatedRequestId); - callbackHeader.setResponseCode("200"); - callbackHeader.setResponseMessage("OK"); - SDNCAdapterCallbackRequest sdncAdapterCallbackRequest = new SDNCAdapterCallbackRequest(); - sdncAdapterCallbackRequest.setCallbackHeader(callbackHeader); - sdncAdapterCallbackRequest.setRequestData(sdncAdapterCallbackRequestDataNonfinal); - SDNCAdapterCallbackServiceImpl callbackService = new SDNCAdapterCallbackServiceImpl(); - callbackService.setProcessEngineServices4junit(processEngineRule); - SDNCAdapterResponse sdncAdapterResponse = callbackService.sdncAdapterCallback(sdncAdapterCallbackRequest); - //System.out.println("Back from executing process again"); - - assertFalse(sdncAdapterResponse instanceof SDNCAdapterExceptionResponse); - assertProcessInstanceNotFinished(pid); - - checkForTimeout(pid); - - assertEquals(true, (Boolean) (getVariable(pid, "continueListening"))); - - - //System.out.println("SDNCAdapter interim status processing flow Completed!"); - } - - @Test - @Deployment(resources = {"subprocess/SDNCAdapterV1.bpmn"}) - public void nonFinalThenFinal() throws InterruptedException { - - mockSDNCAdapter(200); - mockUpdateRequestDB(200, "Database/DBAdapter.xml"); - - //System.out.println("SDNCAdapter non-final then final processing flow Started!"); - - // Start the flow - ProcessExecutionThread thread = new ProcessExecutionThread(sdncAdapterWorkflowRequestAct); - thread.start(); - waitForExecutionToStart("sdncAdapter", 3); - String pid = getPid(); - - assertProcessInstanceNotFinished(pid); - - // Inject a "non-final" SDNC Adapter asynchronous callback message - //System.out.println("Injecting SDNC Adapter asynchronous callback message to continue processing"); - String generatedRequestId = (String) processEngineRule.getRuntimeService().getVariable(pid, "SDNCA_requestId"); - CallbackHeader callbackHeader = new CallbackHeader(); - callbackHeader.setRequestId(generatedRequestId); - callbackHeader.setResponseCode("200"); - callbackHeader.setResponseMessage("OK"); - SDNCAdapterCallbackRequest sdncAdapterCallbackRequest = new SDNCAdapterCallbackRequest(); - sdncAdapterCallbackRequest.setCallbackHeader(callbackHeader); - sdncAdapterCallbackRequest.setRequestData(sdncAdapterCallbackRequestDataNonfinal); - SDNCAdapterCallbackServiceImpl callbackService = new SDNCAdapterCallbackServiceImpl(); - callbackService.setProcessEngineServices4junit(processEngineRule); - SDNCAdapterResponse sdncAdapterResponse = callbackService.sdncAdapterCallback(sdncAdapterCallbackRequest); - //System.out.println("Back from executing process again"); - - assertFalse(sdncAdapterResponse instanceof SDNCAdapterExceptionResponse); - assertProcessInstanceNotFinished(pid); - assertEquals(true, (Boolean) (getVariable(pid, "continueListening"))); - - // Inject a "final" SDNC Adapter asynchronous callback message - sdncAdapterCallbackRequest.setRequestData(sdncAdapterCallbackRequestData); - sdncAdapterResponse = callbackService.sdncAdapterCallback(sdncAdapterCallbackRequest); - //System.out.println("Back from executing process again"); - - assertFalse(sdncAdapterResponse instanceof SDNCAdapterExceptionResponse); - assertProcessInstanceFinished(pid); - assertEquals(false, (Boolean) (getVariable(pid, "continueListening"))); - - //System.out.println("SDNCAdapter non-final then final processing flow Completed!"); - } - - - - private void waitForExecutionToStart(String processDefintion, int count) throws InterruptedException { - //System.out.println(processEngineRule.getRuntimeService().createExecutionQuery().processDefinitionKey(processDefintion).count()); - while (processEngineRule.getRuntimeService().createExecutionQuery().processDefinitionKey(processDefintion).count() != count) { - Thread.sleep(200); - } - } - - @Test - @Deployment(resources = {"subprocess/SDNCAdapterV1.bpmn"}) - public void badCorrelationIdTest() throws InterruptedException { - - mockSDNCAdapter(200); - - //System.out.println("SDNCAdapter bad RequestId test Started!"); - - ProcessExecutionThread thread = new ProcessExecutionThread(sdncAdapterWorkflowRequest); - thread.start(); - waitForExecutionToStart("sdncAdapter", 3); - String pid = getPid(); - assertProcessInstanceNotFinished(pid); - - //System.out.println("Injecting SDNC Adapter asynchronous callback message to continue processing"); - String badRequestId = "This is not the RequestId that was used"; - CallbackHeader callbackHeader = new CallbackHeader(); - callbackHeader.setRequestId(badRequestId); - callbackHeader.setResponseCode("200"); - callbackHeader.setResponseMessage("OK"); - SDNCAdapterCallbackRequest sdncAdapterCallbackRequest = new SDNCAdapterCallbackRequest(); - sdncAdapterCallbackRequest.setCallbackHeader(callbackHeader); - sdncAdapterCallbackRequest.setRequestData(sdncAdapterCallbackRequestData); - SDNCAdapterCallbackServiceImpl callbackService = new SDNCAdapterCallbackServiceImpl(); - callbackService.setProcessEngineServices4junit(processEngineRule); - SDNCAdapterResponse sdncAdapterResponse = callbackService.sdncAdapterCallback(sdncAdapterCallbackRequest); - //System.out.println("Back from executing process again"); - - assertTrue(sdncAdapterResponse instanceof SDNCAdapterExceptionResponse); - assertTrue(((SDNCAdapterExceptionResponse) sdncAdapterResponse).getException() instanceof MismatchingMessageCorrelationException); - assertProcessInstanceNotFinished(pid); - - //System.out.println("SDNCAdapter bad RequestId test Completed!"); - } - - @Test - @Deployment(resources = {"subprocess/SDNCAdapterV1.bpmn"}) - public void badSynchronousResponse() throws IOException, InterruptedException { - - mockSDNCAdapter(404); - - //System.out.println("SDNCAdapter bad synchronous response flow Started!"); - - ProcessExecutionThread thread = new ProcessExecutionThread(sdncAdapterWorkflowRequest); - thread.start(); - while (thread.isAlive()) { - Thread.sleep(200); - } - WorkflowResponse response = thread.workflowResponse; - Assert.assertNotNull(response); - Assert.assertEquals("404 error", response.getMessageCode(),7000); -// assertProcessInstanceFinished(response.getProcessInstanceID()); - //System.out.println("SDNCAdapter bad synchronous response flow Completed!"); - } - - @Test - @Deployment(resources = {"subprocess/SDNCAdapterV1.bpmn"}) - public void sdncNotFound() throws IOException, InterruptedException { - mockSDNCAdapter(200); - mockSDNCAdapter("/sdncAdapterMock/404", 400, "sdncCallbackErrorResponse.xml"); - - ProcessExecutionThread thread = new ProcessExecutionThread(sdncAdapterWorkflowRequest); - thread.start(); - waitForExecutionToStart("sdncAdapter", 3); - String pid = getPid(); - - //System.out.println("Injecting SDNC Adapter asynchronous callback message to continue processing"); - String generatedRequestId = (String) processEngineRule.getRuntimeService().getVariable(pid, "SDNCA_requestId"); - CallbackHeader callbackHeader = new CallbackHeader(); - callbackHeader.setRequestId(generatedRequestId); - callbackHeader.setResponseCode("404"); - callbackHeader.setResponseMessage("Error processing request to SDNC. Not Found. https://sdncodl.it.us.aic.cip.att.com:8443/restconf/config/L3SDN-API:services/layer3-service-list/AS%2FVLXM%2F000199%2F%2FSB_INTERNET. SDNC Returned-[error-type:application, error-tag:data-missing, error-message:Request could not be completed because the relevant data model content does not exist.]"); - SDNCAdapterCallbackRequest sdncAdapterCallbackRequest = new SDNCAdapterCallbackRequest(); - sdncAdapterCallbackRequest.setCallbackHeader(callbackHeader); - SDNCAdapterCallbackServiceImpl callbackService = new SDNCAdapterCallbackServiceImpl(); - callbackService.setProcessEngineServices4junit(processEngineRule); - SDNCAdapterResponse sdncAdapterResponse = callbackService.sdncAdapterCallback(sdncAdapterCallbackRequest); - //System.out.println("Back from executing process again"); - - assertProcessInstanceFinished(pid); - assertNotNull(sdncAdapterResponse); - //TODO query history to see SDNCA_ResponseCode, SDNCA_ErrorResponse - //System.out.println("SDNCAdapter SDNC Notfound test Completed!"); - } - - @Test - @Deployment(resources = {"subprocess/SDNCAdapterV1.bpmn"}) - public void asynchronousMessageTimeout() throws IOException, InterruptedException { - mockSDNCAdapter(200); - //System.out.println("SDNCAdapter asynchronous message timeout flow Started!"); - ProcessExecutionThread thread = new ProcessExecutionThread(sdncAdapterWorkflowRequest); - thread.start(); - waitForExecutionToStart("sdncAdapter", 3); - checkForTimeout(getPid()); - } - - private void checkForTimeout(String pid) throws InterruptedException { - - assertProcessInstanceNotFinished(pid); - - ProcessEngineConfigurationImpl processEngineConfiguration = - (ProcessEngineConfigurationImpl) processEngineRule.getProcessEngine().getProcessEngineConfiguration(); - assertTrue(processEngineConfiguration.getJobExecutor().isActive()); - - Job timerJob = processEngineRule.getManagementService().createJobQuery().processInstanceId(pid).singleResult(); - assertNotNull(timerJob); - - processEngineRule.getManagementService().executeJob(timerJob.getId()); - - assertProcessInstanceFinished(pid); - - //System.out.println("SDNCAdapter asynchronous message timeout flow Completed!"); - } - - class ProcessExecutionThread extends Thread { - - private String workflowRequest; - private WorkflowResponse workflowResponse; - - public ProcessExecutionThread(String workflowRequest) { - this.workflowRequest = workflowRequest; - } - - public void run() { - workflowResponse = invokeFlow(workflowRequest); - workflowResponse.getProcessInstanceID(); - } - } - - private String getPid() { - return processEngineRule.getHistoryService().createHistoricProcessInstanceQuery().list().get(0).getId(); - } - - private Object getVariable(String pid, String variableName) { - try { - return - processEngineRule - .getHistoryService() - .createHistoricVariableInstanceQuery() - .processInstanceId(pid).variableName(variableName) - .singleResult() - .getValue(); - } catch(Exception ex) { - return null; - } - } - - private void assertProcessInstanceFinished(String pid) { - assertEquals(1, processEngineRule.getHistoryService().createHistoricProcessInstanceQuery().processInstanceId(pid).finished().count()); - } - - private void assertProcessInstanceNotFinished(String pid) { - assertEquals(0, processEngineRule.getHistoryService().createHistoricProcessInstanceQuery().processInstanceId(pid).finished().count()); - } - -} +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.bpmn.common; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.openecomp.mso.bpmn.mock.StubResponseDatabase.mockUpdateRequestDB; +import static org.openecomp.mso.bpmn.mock.StubResponseSDNCAdapter.mockSDNCAdapter; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +import javax.ws.rs.core.Response; + +import org.camunda.bpm.engine.MismatchingMessageCorrelationException; +import org.camunda.bpm.engine.impl.cfg.ProcessEngineConfigurationImpl; +import org.camunda.bpm.engine.runtime.Job; +import org.camunda.bpm.engine.test.Deployment; +import org.camunda.bpm.engine.variable.impl.VariableMapImpl; +import org.junit.Assert; +import org.junit.Test; +import org.openecomp.mso.bpmn.common.adapter.sdnc.CallbackHeader; +import org.openecomp.mso.bpmn.common.adapter.sdnc.SDNCAdapterCallbackRequest; +import org.openecomp.mso.bpmn.common.adapter.sdnc.SDNCAdapterResponse; +import org.openecomp.mso.bpmn.common.workflow.service.SDNCAdapterCallbackServiceImpl; +import org.openecomp.mso.bpmn.common.workflow.service.SDNCAdapterCallbackServiceImpl.SDNCAdapterExceptionResponse; +import org.openecomp.mso.bpmn.common.workflow.service.WorkflowResource; +import org.openecomp.mso.bpmn.common.workflow.service.WorkflowResponse; +import org.openecomp.mso.bpmn.mock.FileUtil; + +/** + * Unit test cases for SDNCAdapterV1.bpmn + */ +public class SDNCAdapterV1Test extends WorkflowTest { + + private String sdncAdapterWorkflowRequest; + private String sdncAdapterWorkflowRequestAct; + private String sdncAdapterCallbackRequestData; + private String sdncAdapterCallbackRequestDataNonfinal; + + public SDNCAdapterV1Test() throws IOException { + sdncAdapterWorkflowRequest = FileUtil.readResourceFile("sdncadapterworkflowrequest.xml"); + sdncAdapterWorkflowRequestAct = FileUtil.readResourceFile("sdncadapterworkflowrequest-act.xml"); + sdncAdapterCallbackRequestData = FileUtil.readResourceFile("sdncadaptercallbackrequestdata.text"); + sdncAdapterCallbackRequestDataNonfinal = FileUtil.readResourceFile("sdncadaptercallbackrequestdata-nonfinal.text"); + } + + /** + * End-to-End flow - Unit test for SDNCAdapterV1.bpmn + * - String input & String response + */ + + private WorkflowResponse invokeFlow(String workflowRequest) { + + MapvalueMap = new HashMap(); + valueMap.put("value", workflowRequest); + Map variables = new HashMap(); + variables.put("sdncAdapterWorkflowRequest", valueMap); + + Map valueMap2 = new HashMap(); + valueMap2.put("value", "true"); + variables.put("isDebugLogEnabled", valueMap2); + + VariableMapImpl varMap = new VariableMapImpl(); + varMap.put("variables", variables); + + //System.out.println("Invoking the flow"); + + WorkflowResource workflowResource = new WorkflowResource(); + workflowResource.setProcessEngineServices4junit(processEngineRule); + + Response response = workflowResource.startProcessInstanceByKey("sdncAdapter", varMap); + WorkflowResponse workflowResponse = (WorkflowResponse) response.getEntity(); + + //String pid = workflowResponse.getProcessInstanceID(); + //System.out.println("Back from executing process instance with pid=" + pid); + return workflowResponse; + } + + @Test + @Deployment(resources = {"subprocess/SDNCAdapterV1.bpmn", + "subprocess/GenericNotificationService.bpmn" + }) + public void sunnyDay() throws InterruptedException { + + mockSDNCAdapter(200); + + //System.out.println("SDNCAdapter sunny day flow Started!"); + + ProcessExecutionThread thread = new ProcessExecutionThread(sdncAdapterWorkflowRequest); + thread.start(); + waitForExecutionToStart("sdncAdapter", 3); + String pid = getPid(); + + assertProcessInstanceNotFinished(pid); + + System.out.println("Injecting SDNC Adapter asynchronous callback message to continue processing"); + String generatedRequestId = (String) processEngineRule.getRuntimeService().getVariable(pid, "SDNCA_requestId"); + CallbackHeader callbackHeader = new CallbackHeader(); + callbackHeader.setRequestId(generatedRequestId); + callbackHeader.setResponseCode("200"); + callbackHeader.setResponseMessage("OK"); + SDNCAdapterCallbackRequest sdncAdapterCallbackRequest = new SDNCAdapterCallbackRequest(); + sdncAdapterCallbackRequest.setCallbackHeader(callbackHeader); + sdncAdapterCallbackRequest.setRequestData(sdncAdapterCallbackRequestData); + SDNCAdapterCallbackServiceImpl callbackService = new SDNCAdapterCallbackServiceImpl(); + callbackService.setProcessEngineServices4junit(processEngineRule); + SDNCAdapterResponse sdncAdapterResponse = callbackService.sdncAdapterCallback(sdncAdapterCallbackRequest); + //System.out.println("Back from executing process again"); + + assertFalse(sdncAdapterResponse instanceof SDNCAdapterExceptionResponse); + assertProcessInstanceFinished(pid); + + //System.out.println("SDNCAdapter sunny day flow Completed!"); + } + + @Test + @Deployment(resources = {"subprocess/SDNCAdapterV1.bpmn", + "subprocess/GenericNotificationService.bpmn" + }) + public void nonFinalWithTimeout() throws InterruptedException { + + mockSDNCAdapter(200); + mockUpdateRequestDB(200, "Database/DBAdapter.xml"); + + //System.out.println("SDNCAdapter interim status processing flow Started!"); + + ProcessExecutionThread thread = new ProcessExecutionThread(sdncAdapterWorkflowRequestAct); + thread.start(); + waitForExecutionToStart("sdncAdapter", 3); + String pid = getPid(); + + assertProcessInstanceNotFinished(pid); + + //System.out.println("Injecting SDNC Adapter asynchronous callback message to continue processing"); + String generatedRequestId = (String) processEngineRule.getRuntimeService().getVariable(pid, "SDNCA_requestId"); + CallbackHeader callbackHeader = new CallbackHeader(); + callbackHeader.setRequestId(generatedRequestId); + callbackHeader.setResponseCode("200"); + callbackHeader.setResponseMessage("OK"); + SDNCAdapterCallbackRequest sdncAdapterCallbackRequest = new SDNCAdapterCallbackRequest(); + sdncAdapterCallbackRequest.setCallbackHeader(callbackHeader); + sdncAdapterCallbackRequest.setRequestData(sdncAdapterCallbackRequestDataNonfinal); + SDNCAdapterCallbackServiceImpl callbackService = new SDNCAdapterCallbackServiceImpl(); + callbackService.setProcessEngineServices4junit(processEngineRule); + SDNCAdapterResponse sdncAdapterResponse = callbackService.sdncAdapterCallback(sdncAdapterCallbackRequest); + //System.out.println("Back from executing process again"); + + assertFalse(sdncAdapterResponse instanceof SDNCAdapterExceptionResponse); + assertProcessInstanceNotFinished(pid); + + checkForTimeout(pid); + + assertEquals(true, (Boolean) (getVariable(pid, "continueListening"))); + + + //System.out.println("SDNCAdapter interim status processing flow Completed!"); + } + + @Test + @Deployment(resources = {"subprocess/SDNCAdapterV1.bpmn", + "subprocess/GenericNotificationService.bpmn" + }) + public void nonFinalThenFinal() throws InterruptedException { + + mockSDNCAdapter(200); + mockUpdateRequestDB(200, "Database/DBAdapter.xml"); + + //System.out.println("SDNCAdapter non-final then final processing flow Started!"); + + // Start the flow + ProcessExecutionThread thread = new ProcessExecutionThread(sdncAdapterWorkflowRequestAct); + thread.start(); + waitForExecutionToStart("sdncAdapter", 3); + String pid = getPid(); + + assertProcessInstanceNotFinished(pid); + + // Inject a "non-final" SDNC Adapter asynchronous callback message + //System.out.println("Injecting SDNC Adapter asynchronous callback message to continue processing"); + String generatedRequestId = (String) processEngineRule.getRuntimeService().getVariable(pid, "SDNCA_requestId"); + CallbackHeader callbackHeader = new CallbackHeader(); + callbackHeader.setRequestId(generatedRequestId); + callbackHeader.setResponseCode("200"); + callbackHeader.setResponseMessage("OK"); + SDNCAdapterCallbackRequest sdncAdapterCallbackRequest = new SDNCAdapterCallbackRequest(); + sdncAdapterCallbackRequest.setCallbackHeader(callbackHeader); + sdncAdapterCallbackRequest.setRequestData(sdncAdapterCallbackRequestDataNonfinal); + SDNCAdapterCallbackServiceImpl callbackService = new SDNCAdapterCallbackServiceImpl(); + callbackService.setProcessEngineServices4junit(processEngineRule); + SDNCAdapterResponse sdncAdapterResponse = callbackService.sdncAdapterCallback(sdncAdapterCallbackRequest); + //System.out.println("Back from executing process again"); + + assertFalse(sdncAdapterResponse instanceof SDNCAdapterExceptionResponse); + assertProcessInstanceNotFinished(pid); + assertEquals(true, (Boolean) (getVariable(pid, "continueListening"))); + + // Inject a "final" SDNC Adapter asynchronous callback message + sdncAdapterCallbackRequest.setRequestData(sdncAdapterCallbackRequestData); + sdncAdapterResponse = callbackService.sdncAdapterCallback(sdncAdapterCallbackRequest); + //System.out.println("Back from executing process again"); + + assertFalse(sdncAdapterResponse instanceof SDNCAdapterExceptionResponse); + assertProcessInstanceFinished(pid); + assertEquals(false, (Boolean) (getVariable(pid, "continueListening"))); + + //System.out.println("SDNCAdapter non-final then final processing flow Completed!"); + } + + + + private void waitForExecutionToStart(String processDefintion, int count) throws InterruptedException { + //System.out.println(processEngineRule.getRuntimeService().createExecutionQuery().processDefinitionKey(processDefintion).count()); + while (processEngineRule.getRuntimeService().createExecutionQuery().processDefinitionKey(processDefintion).count() != count) { + Thread.sleep(200); + } + } + + @Test + @Deployment(resources = {"subprocess/SDNCAdapterV1.bpmn", + "subprocess/GenericNotificationService.bpmn" + }) + public void badCorrelationIdTest() throws InterruptedException { + + mockSDNCAdapter(200); + + //System.out.println("SDNCAdapter bad RequestId test Started!"); + + ProcessExecutionThread thread = new ProcessExecutionThread(sdncAdapterWorkflowRequest); + thread.start(); + waitForExecutionToStart("sdncAdapter", 3); + String pid = getPid(); + assertProcessInstanceNotFinished(pid); + + //System.out.println("Injecting SDNC Adapter asynchronous callback message to continue processing"); + String badRequestId = "This is not the RequestId that was used"; + CallbackHeader callbackHeader = new CallbackHeader(); + callbackHeader.setRequestId(badRequestId); + callbackHeader.setResponseCode("200"); + callbackHeader.setResponseMessage("OK"); + SDNCAdapterCallbackRequest sdncAdapterCallbackRequest = new SDNCAdapterCallbackRequest(); + sdncAdapterCallbackRequest.setCallbackHeader(callbackHeader); + sdncAdapterCallbackRequest.setRequestData(sdncAdapterCallbackRequestData); + SDNCAdapterCallbackServiceImpl callbackService = new SDNCAdapterCallbackServiceImpl(); + callbackService.setProcessEngineServices4junit(processEngineRule); + SDNCAdapterResponse sdncAdapterResponse = callbackService.sdncAdapterCallback(sdncAdapterCallbackRequest); + //System.out.println("Back from executing process again"); + + assertTrue(sdncAdapterResponse instanceof SDNCAdapterExceptionResponse); + assertTrue(((SDNCAdapterExceptionResponse) sdncAdapterResponse).getException() instanceof IllegalStateException); + assertProcessInstanceNotFinished(pid); + + //System.out.println("SDNCAdapter bad RequestId test Completed!"); + } + + @Test + @Deployment(resources = {"subprocess/SDNCAdapterV1.bpmn", + "subprocess/GenericNotificationService.bpmn" + }) + public void badSynchronousResponse() throws IOException, InterruptedException { + + mockSDNCAdapter(404); + + //System.out.println("SDNCAdapter bad synchronous response flow Started!"); + + ProcessExecutionThread thread = new ProcessExecutionThread(sdncAdapterWorkflowRequest); + thread.start(); + while (thread.isAlive()) { + Thread.sleep(200); + } + WorkflowResponse response = thread.workflowResponse; + Assert.assertNotNull(response); + Assert.assertEquals("404 error", response.getMessageCode(),7000); +// assertProcessInstanceFinished(response.getProcessInstanceID()); + //System.out.println("SDNCAdapter bad synchronous response flow Completed!"); + } + + @Test + @Deployment(resources = {"subprocess/SDNCAdapterV1.bpmn", + "subprocess/GenericNotificationService.bpmn" + }) + public void sdncNotFound() throws IOException, InterruptedException { + mockSDNCAdapter(200); + mockSDNCAdapter("/sdncAdapterMock/404", 400, "sdncCallbackErrorResponse.xml"); + + ProcessExecutionThread thread = new ProcessExecutionThread(sdncAdapterWorkflowRequest); + thread.start(); + waitForExecutionToStart("sdncAdapter", 3); + String pid = getPid(); + + //System.out.println("Injecting SDNC Adapter asynchronous callback message to continue processing"); + String generatedRequestId = (String) processEngineRule.getRuntimeService().getVariable(pid, "SDNCA_requestId"); + CallbackHeader callbackHeader = new CallbackHeader(); + callbackHeader.setRequestId(generatedRequestId); + callbackHeader.setResponseCode("404"); + callbackHeader.setResponseMessage("Error processing request to SDNC. Not Found. https://sdncodl.it.us.aic.cip.com:8443/restconf/config/L3SDN-API:services/layer3-service-list/AS%2FVLXM%2F000199%2F%2FSB_INTERNET. SDNC Returned-[error-type:application, error-tag:data-missing, error-message:Request could not be completed because the relevant data model content does not exist.]"); + SDNCAdapterCallbackRequest sdncAdapterCallbackRequest = new SDNCAdapterCallbackRequest(); + sdncAdapterCallbackRequest.setCallbackHeader(callbackHeader); + SDNCAdapterCallbackServiceImpl callbackService = new SDNCAdapterCallbackServiceImpl(); + callbackService.setProcessEngineServices4junit(processEngineRule); + SDNCAdapterResponse sdncAdapterResponse = callbackService.sdncAdapterCallback(sdncAdapterCallbackRequest); + //System.out.println("Back from executing process again"); + + assertProcessInstanceFinished(pid); + assertNotNull(sdncAdapterResponse); + //TODO query history to see SDNCA_ResponseCode, SDNCA_ErrorResponse + //System.out.println("SDNCAdapter SDNC Notfound test Completed!"); + } + + @Test + @Deployment(resources = {"subprocess/SDNCAdapterV1.bpmn", + "subprocess/GenericNotificationService.bpmn" + }) + public void asynchronousMessageTimeout() throws IOException, InterruptedException { + mockSDNCAdapter(200); + //System.out.println("SDNCAdapter asynchronous message timeout flow Started!"); + ProcessExecutionThread thread = new ProcessExecutionThread(sdncAdapterWorkflowRequest); + thread.start(); + waitForExecutionToStart("sdncAdapter", 3); + checkForTimeout(getPid()); + } + + private void checkForTimeout(String pid) throws InterruptedException { + + assertProcessInstanceNotFinished(pid); + + ProcessEngineConfigurationImpl processEngineConfiguration = + (ProcessEngineConfigurationImpl) processEngineRule.getProcessEngine().getProcessEngineConfiguration(); + assertTrue(processEngineConfiguration.getJobExecutor().isActive()); + + Job timerJob = processEngineRule.getManagementService().createJobQuery().processInstanceId(pid).singleResult(); + assertNotNull(timerJob); + + processEngineRule.getManagementService().executeJob(timerJob.getId()); + + assertProcessInstanceFinished(pid); + + //System.out.println("SDNCAdapter asynchronous message timeout flow Completed!"); + } + + class ProcessExecutionThread extends Thread { + + private String workflowRequest; + private WorkflowResponse workflowResponse; + + public ProcessExecutionThread(String workflowRequest) { + this.workflowRequest = workflowRequest; + } + + public void run() { + workflowResponse = invokeFlow(workflowRequest); + workflowResponse.getProcessInstanceID(); + } + } + + private String getPid() { + return processEngineRule.getHistoryService().createHistoricProcessInstanceQuery().list().get(0).getId(); + } + + private Object getVariable(String pid, String variableName) { + try { + return + processEngineRule + .getHistoryService() + .createHistoricVariableInstanceQuery() + .processInstanceId(pid).variableName(variableName) + .singleResult() + .getValue(); + } catch(Exception ex) { + return null; + } + } + + private void assertProcessInstanceFinished(String pid) { + assertEquals(1, processEngineRule.getHistoryService().createHistoricProcessInstanceQuery().processInstanceId(pid).finished().count()); + } + + private void assertProcessInstanceNotFinished(String pid) { + assertEquals(0, processEngineRule.getHistoryService().createHistoricProcessInstanceQuery().processInstanceId(pid).finished().count()); + } + +} diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/UpdateAAIGenericVnfTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/UpdateAAIGenericVnfTest.java index 4ae76206cc..18fb5acbce 100644 --- a/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/UpdateAAIGenericVnfTest.java +++ b/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/UpdateAAIGenericVnfTest.java @@ -1,171 +1,173 @@ -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - MSO - * ================================================================================ - * 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.openecomp.mso.bpmn.common; - -import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockGetGenericVnfByIdWithDepth; -import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockGetGenericVnfById_404; -import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockPutGenericVnf; -import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockPutGenericVnf_Bad; - -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; - -import org.camunda.bpm.engine.test.Deployment; -import org.junit.Assert; -import org.junit.Test; -import org.openecomp.mso.bpmn.core.WorkflowException; -import org.openecomp.mso.bpmn.mock.FileUtil; - -/** - * Unit tests for UpdateAAIGenericVnf bpmn. - */ -public class UpdateAAIGenericVnfTest extends WorkflowTest { - - /** - * Test the happy path through the flow. - */ - @Test - @Deployment(resources = { - "subprocess/UpdateAAIGenericVnf.bpmn" - }) - public void happyPath() throws IOException { - logStart(); - - String updateAAIGenericVnfRequest = FileUtil.readResourceFile("__files/VfModularity/UpdateAAIGenericVnfRequest.xml"); - MockGetGenericVnfByIdWithDepth("skask", 1, "VfModularity/GenericVnf.xml"); - MockPutGenericVnf("/skask", 200); - - String businessKey = UUID.randomUUID().toString(); - Map variables = new HashMap(); - variables.put("mso-request-id", "999-99-9999"); - variables.put("isDebugLogEnabled","true"); - variables.put("UpdateAAIGenericVnfRequest", updateAAIGenericVnfRequest); - invokeSubProcess("UpdateAAIGenericVnf", businessKey, variables); - - Assert.assertTrue(isProcessEnded(businessKey)); - String response = (String) getVariableFromHistory(businessKey, "UAAIGenVnf_updateGenericVnfResponse"); - Integer responseCode = (Integer) getVariableFromHistory(businessKey, "UAAIGenVnf_updateGenericVnfResponseCode"); - System.out.println("Subflow response code: " + responseCode); - System.out.println("Subflow response: " + response); - Assert.assertEquals(200, responseCode.intValue()); - - logEnd(); - } - - /** - * Test the happy path through the flow. - */ - @Test - @Deployment(resources = { - "subprocess/UpdateAAIGenericVnf.bpmn" - }) - public void personaMismatch() throws IOException { - - logStart(); - - String updateAAIGenericVnfRequest = FileUtil.readResourceFile("__files/VfModularity/UpdateAAIGenericVnfRequest.xml"); - updateAAIGenericVnfRequest = updateAAIGenericVnfRequest.replaceFirst("introvert", "extrovert"); - - MockGetGenericVnfByIdWithDepth("skask", 1, "VfModularity/GenericVnf.xml"); - - String businessKey = UUID.randomUUID().toString(); - Map variables = new HashMap(); - variables.put("mso-request-id", "999-99-9999"); - variables.put("isDebugLogEnabled","true"); - variables.put("UpdateAAIGenericVnfRequest", updateAAIGenericVnfRequest); - invokeSubProcess("UpdateAAIGenericVnf", businessKey, variables); - - Assert.assertTrue(isProcessEnded(businessKey)); - WorkflowException workflowException = (WorkflowException) getVariableFromHistory(businessKey, "WorkflowException"); - System.out.println("Workflow Exception: " + workflowException); - Assert.assertNotNull(workflowException); - - logEnd(); - } - - /** - * Test the case where the GET to AAI returns a 404. - */ - @Test - @Deployment(resources = { - "subprocess/UpdateAAIGenericVnf.bpmn" - }) - public void badGet() throws IOException { - - logStart(); - - String updateAAIGenericVnfRequest = FileUtil.readResourceFile("__files/VfModularity/UpdateAAIGenericVnfRequest.xml"); - - MockGetGenericVnfById_404("skask[?]depth=1"); - - String businessKey = UUID.randomUUID().toString(); - Map variables = new HashMap(); - variables.put("mso-request-id", "999-99-9999"); - variables.put("isDebugLogEnabled","true"); - variables.put("UpdateAAIGenericVnfRequest", updateAAIGenericVnfRequest); - invokeSubProcess("UpdateAAIGenericVnf", businessKey, variables); - - Assert.assertTrue(isProcessEnded(businessKey)); - String response = (String) getVariableFromHistory(businessKey, "UAAIGenVnf_getGenericVnfResponse"); - Integer responseCode = (Integer) getVariableFromHistory(businessKey, "UAAIGenVnf_getGenericVnfResponseCode"); - System.out.println("Subflow response code: " + responseCode); - System.out.println("Subflow response: " + response); - Assert.assertEquals(404, responseCode.intValue()); - - logEnd(); - } - - /** - * Test the case where the GET to AAI is successful, but he subsequent PUT returns 404. - */ - @Test - @Deployment(resources = { - "subprocess/UpdateAAIGenericVnf.bpmn" - }) - public void badPut() throws IOException { - - logStart(); - - String updateAAIGenericVnfRequest = FileUtil.readResourceFile("__files/VfModularity/UpdateAAIGenericVnfRequest.xml"); - - MockGetGenericVnfByIdWithDepth("skask", 1, "VfModularity/GenericVnf.xml"); - MockPutGenericVnf_Bad("skask", 404); - - String businessKey = UUID.randomUUID().toString(); - Map variables = new HashMap(); - variables.put("mso-request-id", "999-99-9999"); - variables.put("isDebugLogEnabled","true"); - variables.put("UpdateAAIGenericVnfRequest", updateAAIGenericVnfRequest); - invokeSubProcess("UpdateAAIGenericVnf", businessKey, variables); - - Assert.assertTrue(isProcessEnded(businessKey)); - String response = (String) getVariableFromHistory(businessKey, "UAAIGenVnf_updateGenericVnfResponse"); - Integer responseCode = (Integer) getVariableFromHistory(businessKey, "UAAIGenVnf_updateGenericVnfResponseCode"); - System.out.println("Subflow response code: " + responseCode); - System.out.println("Subflow response: " + response); - Assert.assertEquals(404, responseCode.intValue()); - - logEnd(); - } -} - +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.bpmn.common; + +import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockGetGenericVnfByIdWithDepth; +import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockGetGenericVnfById_404; +import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockPutGenericVnf; +import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockPutGenericVnf_Bad; +import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockPatchGenericVnf; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +import org.camunda.bpm.engine.test.Deployment; +import org.junit.Assert; +import org.junit.Test; +import org.openecomp.mso.bpmn.core.WorkflowException; +import org.openecomp.mso.bpmn.mock.FileUtil; + +/** + * Unit tests for UpdateAAIGenericVnf bpmn. + */ +public class UpdateAAIGenericVnfTest extends WorkflowTest { + + /** + * Test the happy path through the flow. + */ + @Test + @Deployment(resources = { + "subprocess/UpdateAAIGenericVnf.bpmn" + }) + public void happyPath() throws IOException { + logStart(); + + String updateAAIGenericVnfRequest = FileUtil.readResourceFile("__files/VfModularity/UpdateAAIGenericVnfRequest.xml"); + MockGetGenericVnfByIdWithDepth("skask", 1, "VfModularity/GenericVnf.xml"); + MockPutGenericVnf("/skask", 200); + MockPatchGenericVnf("skask"); + + String businessKey = UUID.randomUUID().toString(); + Map variables = new HashMap(); + variables.put("mso-request-id", "999-99-9999"); + variables.put("isDebugLogEnabled","true"); + variables.put("UpdateAAIGenericVnfRequest", updateAAIGenericVnfRequest); + invokeSubProcess("UpdateAAIGenericVnf", businessKey, variables); + + Assert.assertTrue(isProcessEnded(businessKey)); + String response = (String) getVariableFromHistory(businessKey, "UAAIGenVnf_updateGenericVnfResponse"); + Integer responseCode = (Integer) getVariableFromHistory(businessKey, "UAAIGenVnf_updateGenericVnfResponseCode"); + System.out.println("Subflow response code: " + responseCode); + System.out.println("Subflow response: " + response); + Assert.assertEquals(200, responseCode.intValue()); + + logEnd(); + } + + /** + * Test the happy path through the flow. + */ + @Test + @Deployment(resources = { + "subprocess/UpdateAAIGenericVnf.bpmn" + }) + public void personaMismatch() throws IOException { + + logStart(); + + String updateAAIGenericVnfRequest = FileUtil.readResourceFile("__files/VfModularity/UpdateAAIGenericVnfRequest.xml"); + updateAAIGenericVnfRequest = updateAAIGenericVnfRequest.replaceFirst("introvert", "extrovert"); + + MockGetGenericVnfByIdWithDepth("skask", 1, "VfModularity/GenericVnf.xml"); + + String businessKey = UUID.randomUUID().toString(); + Map variables = new HashMap(); + variables.put("mso-request-id", "999-99-9999"); + variables.put("isDebugLogEnabled","true"); + variables.put("UpdateAAIGenericVnfRequest", updateAAIGenericVnfRequest); + invokeSubProcess("UpdateAAIGenericVnf", businessKey, variables); + + Assert.assertTrue(isProcessEnded(businessKey)); + WorkflowException workflowException = (WorkflowException) getVariableFromHistory(businessKey, "WorkflowException"); + System.out.println("Workflow Exception: " + workflowException); + Assert.assertNotNull(workflowException); + + logEnd(); + } + + /** + * Test the case where the GET to AAI returns a 404. + */ + @Test + @Deployment(resources = { + "subprocess/UpdateAAIGenericVnf.bpmn" + }) + public void badGet() throws IOException { + + logStart(); + + String updateAAIGenericVnfRequest = FileUtil.readResourceFile("__files/VfModularity/UpdateAAIGenericVnfRequest.xml"); + + MockGetGenericVnfById_404("skask[?]depth=1"); + + String businessKey = UUID.randomUUID().toString(); + Map variables = new HashMap(); + variables.put("mso-request-id", "999-99-9999"); + variables.put("isDebugLogEnabled","true"); + variables.put("UpdateAAIGenericVnfRequest", updateAAIGenericVnfRequest); + invokeSubProcess("UpdateAAIGenericVnf", businessKey, variables); + + Assert.assertTrue(isProcessEnded(businessKey)); + String response = (String) getVariableFromHistory(businessKey, "UAAIGenVnf_getGenericVnfResponse"); + Integer responseCode = (Integer) getVariableFromHistory(businessKey, "UAAIGenVnf_getGenericVnfResponseCode"); + System.out.println("Subflow response code: " + responseCode); + System.out.println("Subflow response: " + response); + Assert.assertEquals(404, responseCode.intValue()); + + logEnd(); + } + + /** + * Test the case where the GET to AAI is successful, but he subsequent PUT returns 404. + */ + @Test + @Deployment(resources = { + "subprocess/UpdateAAIGenericVnf.bpmn" + }) + public void badPut() throws IOException { + + logStart(); + + String updateAAIGenericVnfRequest = FileUtil.readResourceFile("__files/VfModularity/UpdateAAIGenericVnfRequest.xml"); + + MockGetGenericVnfByIdWithDepth("skask", 1, "VfModularity/GenericVnf.xml"); + MockPutGenericVnf_Bad("skask", 404); + + String businessKey = UUID.randomUUID().toString(); + Map variables = new HashMap(); + variables.put("mso-request-id", "999-99-9999"); + variables.put("isDebugLogEnabled","true"); + variables.put("UpdateAAIGenericVnfRequest", updateAAIGenericVnfRequest); + invokeSubProcess("UpdateAAIGenericVnf", businessKey, variables); + + Assert.assertTrue(isProcessEnded(businessKey)); + String response = (String) getVariableFromHistory(businessKey, "UAAIGenVnf_updateGenericVnfResponse"); + Integer responseCode = (Integer) getVariableFromHistory(businessKey, "UAAIGenVnf_updateGenericVnfResponseCode"); + System.out.println("Subflow response code: " + responseCode); + System.out.println("Subflow response: " + response); + Assert.assertEquals(404, responseCode.intValue()); + + logEnd(); + } +} + diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/UpdateAAIVfModuleTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/UpdateAAIVfModuleTest.java index 8691ae8e61..035f097be2 100644 --- a/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/UpdateAAIVfModuleTest.java +++ b/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/UpdateAAIVfModuleTest.java @@ -1,137 +1,139 @@ -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - MSO - * ================================================================================ - * 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.openecomp.mso.bpmn.common; - -import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockGetGenericVnfById; -import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockGetGenericVnfByIdWithPriority; -import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockGetGenericVnfById_404; -import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockPutGenericVnf; - -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; - -import org.camunda.bpm.engine.test.Deployment; -import org.junit.Assert; -import org.junit.Test; -import org.openecomp.mso.bpmn.mock.FileUtil; - -/** - * Unit tests for UpdateAAIVfModuleTest.bpmn. - */ -public class UpdateAAIVfModuleTest extends WorkflowTest { - - /** - * Test the happy path through the flow. - */ - @Test - @Deployment(resources = { - "subprocess/UpdateAAIVfModule.bpmn" - }) - public void happyPath() throws IOException { - logStart(); - - String updateAAIVfModuleRequest = FileUtil.readResourceFile("__files/VfModularity/UpdateAAIVfModuleRequest.xml"); - MockGetGenericVnfByIdWithPriority("/skask/vf-modules/vf-module/supercool", 200, "VfModularity/VfModule-supercool.xml"); - MockPutGenericVnf("/skask/vf-modules/vf-module/supercool", "PCRF", 200); - - String businessKey = UUID.randomUUID().toString(); - Map variables = new HashMap(); - variables.put("mso-request-id", "999-99-9999"); - variables.put("isDebugLogEnabled","true"); - variables.put("UpdateAAIVfModuleRequest", updateAAIVfModuleRequest); - invokeSubProcess("UpdateAAIVfModule", businessKey, variables); - - Assert.assertTrue(isProcessEnded(businessKey)); - String response = (String) getVariableFromHistory(businessKey, "UAAIVfMod_updateVfModuleResponse"); - Integer responseCode = (Integer) getVariableFromHistory(businessKey, "UAAIVfMod_updateVfModuleResponseCode"); - System.out.println("Subflow response code: " + responseCode); - System.out.println("Subflow response: " + response); - Assert.assertEquals(200, responseCode.intValue()); - - logEnd(); - } - - /** - * Test the case where the GET to AAI returns a 404. - */ - @Test - @Deployment(resources = { - "subprocess/UpdateAAIVfModule.bpmn" - }) - public void badGet() throws IOException { - - logStart(); - - String updateAAIVfModuleRequest = FileUtil.readResourceFile("__files/VfModularity/UpdateAAIVfModuleRequest.xml"); - MockGetGenericVnfById("/skask/vf-modules/vf-module/.*", "VfModularity/VfModule-supercool.xml", 404); - - String businessKey = UUID.randomUUID().toString(); - Map variables = new HashMap(); - variables.put("mso-request-id", "999-99-9999"); - variables.put("isDebugLogEnabled","true"); - variables.put("UpdateAAIVfModuleRequest", updateAAIVfModuleRequest); - invokeSubProcess("UpdateAAIVfModule", businessKey, variables); - - Assert.assertTrue(isProcessEnded(businessKey)); - String response = (String) getVariableFromHistory(businessKey, "UAAIVfMod_getVfModuleResponse"); - Integer responseCode = (Integer) getVariableFromHistory(businessKey, "UAAIVfMod_getVfModuleResponseCode"); - System.out.println("Subflow response code: " + responseCode); - System.out.println("Subflow response: " + response); - Assert.assertEquals(404, responseCode.intValue()); - - logEnd(); - } - - /** - * Test the case where the GET to AAI is successful, but he subsequent PUT returns 404. - */ - @Test - @Deployment(resources = { - "subprocess/UpdateAAIVfModule.bpmn" - }) - public void badPut() throws IOException { - - logStart(); - - String updateAAIVfModuleRequest = FileUtil.readResourceFile("__files/VfModularity/UpdateAAIVfModuleRequest.xml"); - MockGetGenericVnfById_404("/skask/vf-modules/vf-module/supercool"); - MockGetGenericVnfById("/skask/vf-modules/vf-module/supercool", "VfModularity/VfModule-supercool.xml", 200); - - String businessKey = UUID.randomUUID().toString(); - Map variables = new HashMap(); - variables.put("mso-request-id", "999-99-9999"); - variables.put("isDebugLogEnabled","true"); - variables.put("UpdateAAIVfModuleRequest", updateAAIVfModuleRequest); - invokeSubProcess("UpdateAAIVfModule", businessKey, variables); - - Assert.assertTrue(isProcessEnded(businessKey)); - String response = (String) getVariableFromHistory(businessKey, "UAAIVfMod_updateVfModuleResponse"); - Integer responseCode = (Integer) getVariableFromHistory(businessKey, "UAAIVfMod_updateVfModuleResponseCode"); - System.out.println("Subflow response code: " + responseCode); - System.out.println("Subflow response: " + response); - Assert.assertEquals(404, responseCode.intValue()); - - logEnd(); - } -} - +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.bpmn.common; + +import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockGetGenericVnfById; +import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockGetGenericVnfByIdWithPriority; +import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockGetGenericVnfById_404; +import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockPutGenericVnf; +import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockPatchVfModuleId; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +import org.camunda.bpm.engine.test.Deployment; +import org.junit.Assert; +import org.junit.Test; +import org.openecomp.mso.bpmn.mock.FileUtil; + +/** + * Unit tests for UpdateAAIVfModuleTest.bpmn. + */ +public class UpdateAAIVfModuleTest extends WorkflowTest { + + /** + * Test the happy path through the flow. + */ + @Test + @Deployment(resources = { + "subprocess/UpdateAAIVfModule.bpmn" + }) + public void happyPath() throws IOException { + logStart(); + + String updateAAIVfModuleRequest = FileUtil.readResourceFile("__files/VfModularity/UpdateAAIVfModuleRequest.xml"); + MockGetGenericVnfByIdWithPriority("/skask/vf-modules/vf-module/supercool", 200, "VfModularity/VfModule-supercool.xml"); + MockPutGenericVnf("/skask/vf-modules/vf-module/supercool", "PCRF", 200); + MockPatchVfModuleId("skask", "supercool"); + + String businessKey = UUID.randomUUID().toString(); + Map variables = new HashMap(); + variables.put("mso-request-id", "999-99-9999"); + variables.put("isDebugLogEnabled","true"); + variables.put("UpdateAAIVfModuleRequest", updateAAIVfModuleRequest); + invokeSubProcess("UpdateAAIVfModule", businessKey, variables); + + Assert.assertTrue(isProcessEnded(businessKey)); + String response = (String) getVariableFromHistory(businessKey, "UAAIVfMod_updateVfModuleResponse"); + Integer responseCode = (Integer) getVariableFromHistory(businessKey, "UAAIVfMod_updateVfModuleResponseCode"); + System.out.println("Subflow response code: " + responseCode); + System.out.println("Subflow response: " + response); + Assert.assertEquals(200, responseCode.intValue()); + + logEnd(); + } + + /** + * Test the case where the GET to AAI returns a 404. + */ + @Test + @Deployment(resources = { + "subprocess/UpdateAAIVfModule.bpmn" + }) + public void badGet() throws IOException { + + logStart(); + + String updateAAIVfModuleRequest = FileUtil.readResourceFile("__files/VfModularity/UpdateAAIVfModuleRequest.xml"); + MockGetGenericVnfById("/skask/vf-modules/vf-module/.*", "VfModularity/VfModule-supercool.xml", 404); + + String businessKey = UUID.randomUUID().toString(); + Map variables = new HashMap(); + variables.put("mso-request-id", "999-99-9999"); + variables.put("isDebugLogEnabled","true"); + variables.put("UpdateAAIVfModuleRequest", updateAAIVfModuleRequest); + invokeSubProcess("UpdateAAIVfModule", businessKey, variables); + + Assert.assertTrue(isProcessEnded(businessKey)); + String response = (String) getVariableFromHistory(businessKey, "UAAIVfMod_getVfModuleResponse"); + Integer responseCode = (Integer) getVariableFromHistory(businessKey, "UAAIVfMod_getVfModuleResponseCode"); + System.out.println("Subflow response code: " + responseCode); + System.out.println("Subflow response: " + response); + Assert.assertEquals(404, responseCode.intValue()); + + logEnd(); + } + + /** + * Test the case where the GET to AAI is successful, but he subsequent PUT returns 404. + */ + @Test + @Deployment(resources = { + "subprocess/UpdateAAIVfModule.bpmn" + }) + public void badPut() throws IOException { + + logStart(); + + String updateAAIVfModuleRequest = FileUtil.readResourceFile("__files/VfModularity/UpdateAAIVfModuleRequest.xml"); + MockGetGenericVnfById_404("/skask/vf-modules/vf-module/supercool"); + MockGetGenericVnfById("/skask/vf-modules/vf-module/supercool", "VfModularity/VfModule-supercool.xml", 200); + + String businessKey = UUID.randomUUID().toString(); + Map variables = new HashMap(); + variables.put("mso-request-id", "999-99-9999"); + variables.put("isDebugLogEnabled","true"); + variables.put("UpdateAAIVfModuleRequest", updateAAIVfModuleRequest); + invokeSubProcess("UpdateAAIVfModule", businessKey, variables); + + Assert.assertTrue(isProcessEnded(businessKey)); + String response = (String) getVariableFromHistory(businessKey, "UAAIVfMod_updateVfModuleResponse"); + Integer responseCode = (Integer) getVariableFromHistory(businessKey, "UAAIVfMod_updateVfModuleResponseCode"); + System.out.println("Subflow response code: " + responseCode); + System.out.println("Subflow response: " + response); + Assert.assertEquals(404, responseCode.intValue()); + + logEnd(); + } +} + diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/WorkflowTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/WorkflowTest.java index c47521384b..46bbb72e56 100644 --- a/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/WorkflowTest.java +++ b/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/WorkflowTest.java @@ -1,1796 +1,1796 @@ -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - MSO - * ================================================================================ - * 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.openecomp.mso.bpmn.common; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; - -import java.io.IOException; -import java.io.StringReader; -import java.lang.management.ManagementFactory; -import java.lang.management.RuntimeMXBean; -import java.lang.reflect.Field; -import java.lang.reflect.Modifier; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.UUID; - -import javax.ws.rs.core.Response; -import javax.xml.bind.JAXBException; -import javax.xml.namespace.NamespaceContext; -import javax.xml.namespace.QName; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.xpath.XPath; -import javax.xml.xpath.XPathConstants; -import javax.xml.xpath.XPathExpression; -import javax.xml.xpath.XPathExpressionException; -import javax.xml.xpath.XPathFactory; - -import org.camunda.bpm.engine.RuntimeService; -import org.camunda.bpm.engine.history.HistoricProcessInstance; -import org.camunda.bpm.engine.history.HistoricVariableInstance; -import org.camunda.bpm.engine.runtime.ProcessInstance; -import org.camunda.bpm.engine.test.ProcessEngineRule; -import org.camunda.bpm.engine.variable.impl.VariableMapImpl; -import org.custommonkey.xmlunit.DetailedDiff; -import org.custommonkey.xmlunit.XMLUnit; -import org.jboss.resteasy.spi.AsynchronousResponse; -import org.junit.Before; -import org.junit.Rule; -import org.openecomp.mso.bpmn.common.adapter.sdnc.CallbackHeader; -import org.openecomp.mso.bpmn.common.adapter.sdnc.SDNCAdapterCallbackRequest; -import org.openecomp.mso.bpmn.common.adapter.sdnc.SDNCAdapterResponse; -import org.openecomp.mso.bpmn.common.adapter.vnf.CreateVnfNotification; -import org.openecomp.mso.bpmn.common.adapter.vnf.DeleteVnfNotification; -import org.openecomp.mso.bpmn.common.adapter.vnf.MsoExceptionCategory; -import org.openecomp.mso.bpmn.common.adapter.vnf.MsoRequest; -import org.openecomp.mso.bpmn.common.adapter.vnf.UpdateVnfNotification; -import org.openecomp.mso.bpmn.common.adapter.vnf.VnfRollback; -import org.openecomp.mso.bpmn.common.workflow.service.SDNCAdapterCallbackServiceImpl; -import org.openecomp.mso.bpmn.common.workflow.service.VnfAdapterNotifyServiceImpl; -import org.openecomp.mso.bpmn.common.workflow.service.WorkflowAsyncCommonResource; -import org.openecomp.mso.bpmn.common.workflow.service.WorkflowMessageResource; -import org.openecomp.mso.bpmn.common.workflow.service.WorkflowResponse; -import org.openecomp.mso.bpmn.core.CamundaDBSetup; -import org.openecomp.mso.bpmn.core.PropertyConfigurationSetup; -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.xml.sax.SAXException; - -import com.github.tomakehurst.wiremock.core.WireMockConfiguration; -import com.github.tomakehurst.wiremock.extension.ResponseTransformer; -import com.github.tomakehurst.wiremock.junit.WireMockRule; - - - -/** - * A base class for Workflow tests. - *

- * WireMock response transformers may be specified by declaring public - * static fields with the @WorkflowTestTransformer annotation. For example: - *

- *     @WorkflowTestTransformer
- *     public static final ResponseTransformer sdncAdapterMockTransformer =
- *         new SDNCAdapterMockTransformer();
- * 
- */ -public class WorkflowTest { - @Rule - public final ProcessEngineRule processEngineRule = new ProcessEngineRule(); - - @Rule - public final WireMockRule wireMockRule; - - /** - * Constructor. - */ - public WorkflowTest() throws RuntimeException { - // Process WorkflowTestTransformer annotations - List transformerList = new ArrayList(); - - for (Field field : getClass().getFields()) { - WorkflowTestTransformer annotation = (WorkflowTestTransformer) - field.getAnnotation(WorkflowTestTransformer.class); - - if (annotation == null) { - continue; - } - - if (!Modifier.isStatic(field.getModifiers())) { - throw new RuntimeException(field.getDeclaringClass().getName() - + "#" + field.getName() + " has a @WorkflowTestTransformer " - + " annotation but it is not declared static"); - } - - ResponseTransformer transformer; - - try { - transformer = (ResponseTransformer) field.get(null); - } catch (IllegalAccessException e) { - throw new RuntimeException(field.getDeclaringClass().getName() - + "#" + field.getName() + " is not accessible", e); - } catch (ClassCastException e) { - throw new RuntimeException(field.getDeclaringClass().getName() - + "#" + field.getName() + " is not a ResponseTransformer", e); - } - - if (transformer == null) { - continue; - } - - transformerList.add(transformer); - } - - ResponseTransformer[] transformerArray = - transformerList.toArray(new ResponseTransformer[transformerList.size()]); - - wireMockRule = new WireMockRule(WireMockConfiguration.wireMockConfig() - .port(28090).extensions(transformerArray)); - } - - @Before - public void testSetup() throws Exception { - CamundaDBSetup.configure(); - PropertyConfigurationSetup.init(); - } - - /** - * The current request ID. Normally set when an "invoke" method is called. - */ - protected volatile String msoRequestId = null; - - /** - * The current service instance ID. Normally set when an "invoke" method - * is called. - */ - protected volatile String msoServiceInstanceId = null; - - /** - * Logs a test start method. - */ - protected void logStart() { - StackTraceElement[] st = Thread.currentThread().getStackTrace(); - String method = st[2].getMethodName(); - System.out.println("STARTED TEST: " + method); - } - - /** - * Logs a test end method. - */ - protected void logEnd() { - StackTraceElement[] st = Thread.currentThread().getStackTrace(); - String method = st[2].getMethodName(); - System.out.println("ENDED TEST: " + method); - } - - /** - * Invokes a subprocess. - * @param processKey the process key - * @param businessKey a unique key that will identify the process instance - * @param injectedVariables variables to inject into the process - */ - protected void invokeSubProcess(String processKey, String businessKey, - Map injectedVariables) { - RuntimeMXBean runtimeMxBean = ManagementFactory.getRuntimeMXBean(); - List arguments = runtimeMxBean.getInputArguments(); - System.out.println("JVM args = " + arguments); - - msoRequestId = (String) injectedVariables.get("mso-request-id"); - - if (msoRequestId == null) { - String msg = "mso-request-id variable was not provided"; - System.out.println(msg); - fail(msg); - } - - // Note: some scenarios don't have a service-instance-id, may be null - msoServiceInstanceId = (String) injectedVariables.get("mso-service-instance-id"); - - RuntimeService runtimeService = processEngineRule.getRuntimeService(); - runtimeService.startProcessInstanceByKey(processKey, businessKey, injectedVariables); - } - - /** - * Invokes an asynchronous process. - * Errors are handled with junit assertions and will cause the test to fail. - * @param processKey the process key - * @param schemaVersion the API schema version, e.g. "v1" - * @param businessKey a unique key that will identify the process instance - * @param request the request - * @return a TestAsyncResponse object associated with the test - */ - protected TestAsyncResponse invokeAsyncProcess(String processKey, - String schemaVersion, String businessKey, String request) { - return invokeAsyncProcess(processKey, schemaVersion, businessKey, request, null); - } - - /** - * Invokes an asynchronous process. - * Errors are handled with junit assertions and will cause the test to fail. - * @param processKey the process key - * @param schemaVersion the API schema version, e.g. "v1" - * @param businessKey a unique key that will identify the process instance - * @param request the request - * @param injectedVariables optional variables to inject into the process - * @return a TestAsyncResponse object associated with the test - */ - public TestAsyncResponse invokeAsyncProcess(String processKey, - String schemaVersion, String businessKey, String request, - Map injectedVariables) { - - RuntimeMXBean runtimeMxBean = ManagementFactory.getRuntimeMXBean(); - List arguments = runtimeMxBean.getInputArguments(); - System.out.println("JVM args = " + arguments); - - Map variables = createVariables(schemaVersion, businessKey, - request, injectedVariables, false); - VariableMapImpl variableMapImpl = createVariableMapImpl(variables); - - System.out.println("Sending " + request + " to " + processKey + " process"); - WorkflowAsyncCommonResource workflowResource = new WorkflowAsyncCommonResource(); - workflowResource.setProcessEngineServices4junit(processEngineRule); - - TestAsyncResponse asyncResponse = new TestAsyncResponse(); - workflowResource.startProcessInstanceByKey(asyncResponse, processKey, variableMapImpl); - return asyncResponse; - } - - /** - * Invokes an asynchronous process. - * Errors are handled with junit assertions and will cause the test to fail. - * @param processKey the process key - * @param schemaVersion the API schema version, e.g. "v1" - * @param businessKey a unique key that will identify the process instance - * @param request the request - * @param injectedVariables optional variables to inject into the process - * @param serviceInstantiationModel indicates whether this method is being - * invoked for a flow that is designed using the service instantiation model - * @return a TestAsyncResponse object associated with the test - */ - protected TestAsyncResponse invokeAsyncProcess(String processKey, - String schemaVersion, String businessKey, String request, - Map injectedVariables, boolean serviceInstantiationModel) { - - RuntimeMXBean runtimeMxBean = ManagementFactory.getRuntimeMXBean(); - List arguments = runtimeMxBean.getInputArguments(); - System.out.println("JVM args = " + arguments); - - Map variables = createVariables(schemaVersion, businessKey, - request, injectedVariables, serviceInstantiationModel); - VariableMapImpl variableMapImpl = createVariableMapImpl(variables); - - System.out.println("Sending " + request + " to " + processKey + " process"); - WorkflowAsyncCommonResource workflowResource = new WorkflowAsyncCommonResource(); - workflowResource.setProcessEngineServices4junit(processEngineRule); - - TestAsyncResponse asyncResponse = new TestAsyncResponse(); - workflowResource.startProcessInstanceByKey(asyncResponse, processKey, variableMapImpl); - return asyncResponse; - } - - /** - * Private helper method that creates a variable map for a request. - * Errors are handled with junit assertions and will cause the test to fail. - * @param schemaVersion the API schema version, e.g. "v1" - * @param businessKey a unique key that will identify the process instance - * @param request the request - * @param injectedVariables optional variables to inject into the process - * @param serviceInstantiationModel indicates whether this method is being - * invoked for a flow that is designed using the service instantiation model - * @return a variable map - */ - private Map createVariables(String schemaVersion, - String businessKey, String request, Map injectedVariables, - boolean serviceInstantiationModel) { - - Map variables = new HashMap(); - - // These variables may be overridded by injected variables. - variables.put("mso-service-request-timeout", "180"); - variables.put("isDebugLogEnabled", "true"); - - // These variables may not be overridded by injected variables. - String[] notAllowed = new String[] { - "mso-schema-version", - "mso-business-key", - "bpmnRequest", - "mso-request-id", - "mso-service-instance-id" - }; - - if (injectedVariables != null) { - for (String key : injectedVariables.keySet()) { - for (String var : notAllowed) { - if (var.equals(key)) { - String msg = "Cannot specify " + var + " in injected variables"; - System.out.println(msg); - fail(msg); - } - } - - variables.put(key, injectedVariables.get(key)); - } - } - - variables.put("mso-schema-version", schemaVersion); - variables.put("mso-business-key", businessKey); - variables.put("bpmnRequest", request); - - if (serviceInstantiationModel) { - - /* - * The request ID and the service instance ID are generated for flows - * that follow the service instantiation model unless "requestId" and - * "serviceInstanceId" are injected variables. - */ - - try { - msoRequestId = (String) injectedVariables.get("requestId"); - variables.put("mso-request-id", msoRequestId); - msoServiceInstanceId = (String) injectedVariables.get("serviceInstanceId"); - variables.put("mso-service-instance-id", msoServiceInstanceId); - } - catch(Exception e) { - } - if (msoRequestId == null || msoRequestId.trim().equals("")) { - System.out.println("No requestId element in injectedVariables"); - variables.put("mso-request-id", UUID.randomUUID().toString()); - } - if (msoServiceInstanceId == null || msoServiceInstanceId.trim().equals("")) { - System.out.println("No seviceInstanceId element in injectedVariables"); - variables.put("mso-service-instance-id", UUID.randomUUID().toString()); - } - - } else { - msoRequestId = getXMLTextElement(request, "request-id"); - - if (msoRequestId == null) { - //check in injected variables - try { - msoRequestId = (String) injectedVariables.get("requestId"); - } - catch(Exception e) { - } - if (msoRequestId == null || msoRequestId.trim().equals("")) { - String msg = "No request-id element in " + request; - System.out.println(msg); - fail(msg); - } - } - - variables.put("mso-request-id", msoRequestId); - - // Note: some request types don't have a service-instance-id - msoServiceInstanceId = getXMLTextElement(request, "service-instance-id"); - - if (msoServiceInstanceId != null) { - variables.put("mso-service-instance-id", msoServiceInstanceId); - } - } - - return variables; - } - - /** - * Private helper method that creates a camunda VariableMapImpl from a simple - * variable map. - * @param variables the simple variable map - * @return a VariableMap - */ - private VariableMapImpl createVariableMapImpl(Map variables) { - Map wrappedVariables = new HashMap(); - - for (String key : variables.keySet()) { - Object value = variables.get(key); - wrappedVariables.put(key, wrapVariableValue(value)); - } - - VariableMapImpl variableMapImpl = new VariableMapImpl(); - variableMapImpl.put("variables", wrappedVariables); - return variableMapImpl; - } - - /** - * Private helper method that wraps a variable value for inclusion in a - * camunda VariableMapImpl. - * @param value the variable value - * @return the wrapped variable - */ - private Map wrapVariableValue(Object value) { - HashMap valueMap = new HashMap(); - valueMap.put("value", value); - return valueMap; - } - - /** - * Receives a response from an asynchronous process. - * Errors are handled with junit assertions and will cause the test to fail. - * @param businessKey the process business key - * @param asyncResponse the TestAsyncResponse object associated with the test - * @param timeout the timeout in milliseconds - * @return the WorkflowResponse - */ - public WorkflowResponse receiveResponse(String businessKey, - TestAsyncResponse asyncResponse, long timeout) { - System.out.println("Waiting " + timeout + "ms for process with business key " + businessKey - + " to send a response"); - - long now = System.currentTimeMillis() + timeout; - long endTime = now + timeout; - - while (now <= endTime) { - Response response = asyncResponse.getResponse(); - - if (response != null) { - System.out.println("Received a response from process with business key " + businessKey); - - Object entity = response.getEntity(); - - if (!(entity instanceof WorkflowResponse)) { - String msg = "Response entity is " + - (entity == null ? "null" : entity.getClass().getName()) + - ", expected WorkflowResponse"; - System.out.println(msg); - fail(msg); - return null; // unreachable - } - - return (WorkflowResponse) entity; - } - - try { - Thread.sleep(200); - } catch (InterruptedException e) { - String msg = "Interrupted waiting for a response from process with business key " + - businessKey; - System.out.println(msg); - fail(msg); - return null; // unreachable - } - - now = System.currentTimeMillis(); - } - - String msg = "No response received from process with business key " + businessKey + - " within " + timeout + "ms"; - System.out.println(msg); - fail("Process with business key " + businessKey + " did not end within 10000ms"); - return null; // unreachable - } - - /** - * Runs a program to inject SDNC callback data into the test environment. - * A program is essentially just a list of keys that identify callback data - * to be injected, in sequence. An example program: - *
-	 *     reserve, assign, delete:ERR
-	 * 
- * Errors are handled with junit assertions and will cause the test to fail. - * @param callbacks an object containing callback data for the program - * @param program the program to execute - */ - protected void injectSDNCRestCallbacks(CallbackSet callbacks, String program) { - - String[] cmds = program.replaceAll("\\s+", "").split(","); - - for (String cmd : cmds) { - String action = cmd; - String modifier = "STD"; - - if (cmd.contains(":")) { - String[] parts = cmd.split(":"); - action = parts[0]; - modifier = parts[1]; - } - - String content = null; - - if ("STD".equals(modifier)) { - content = callbacks.get(action); - - if (content == null) { - String msg = "No callback defined for '" + action + "' SDNC request"; - System.out.println(msg); - fail(msg); - } - } else if ("ERR".equals(modifier)) { - content = "{\"SDNCServiceError\":{\"sdncRequestId\":\"((REQUEST-ID))\",\"responseCode\":\"500\",\"responseMessage\":\"SIMULATED ERROR FROM SDNC ADAPTER\",\"ackFinalIndicator\":\"Y\"}}"; - } else { - String msg = "Invalid SDNC program modifier: '" + modifier + "'"; - System.out.println(msg); - fail(msg); - } - - if (!injectSDNCRestCallback(content, 10000)) { - fail("Failed to inject SDNC '" + action + "' callback"); - } - - try { - Thread.sleep(1000); - } catch (InterruptedException e) { - fail("Interrupted after injection of SDNC '" + action + "' callback"); - } - } - } - - /** - * Runs a program to inject SDNC events into the test environment. - * A program is essentially just a list of keys that identify event data - * to be injected, in sequence. An example program: - *
-	 *     event1, event2
-	 * 
- * Errors are handled with junit assertions and will cause the test to fail. - * Defaults the Event Type to "SDNCAEvent" for backward compatibility. - * @param callbacks an object containing event data for the program - * @param program the program to execute - */ - protected void injectSDNCEvents(CallbackSet callbacks, String program) { - injectSDNCEvents(callbacks, program, "SDNCAEvent"); - } - - /** - * Runs a program to inject SDNC events into the test environment. - * A program is essentially just a list of keys that identify event data - * to be injected, in sequence. An example program: - *
-	 *     event1, event2
-	 * 
- * Errors are handled with junit assertions and will cause the test to fail. - * @param callbacks an object containing event data for the program - * @param program the program to execute - * @param eventType (i.e. "SDNCAEvent", "SNIROResponse", etc.) - */ - protected void injectSDNCEvents(CallbackSet callbacks, String program, String eventType) { - - String[] cmds = program.replaceAll("\\s+", "").split(","); - - for (String cmd : cmds) { - String action = cmd; - String modifier = "STD"; - - if (cmd.contains(":")) { - String[] parts = cmd.split(":"); - action = parts[0]; - modifier = parts[1]; - } - - String content = null; - - if ("STD".equals(modifier)) { - content = callbacks.get(action); - - if (content == null) { - String msg = "No SDNC event callback defined for '" + action + "'"; - System.out.println(msg); - fail(msg); - } - } else { - String msg = "Invalid SDNC program modifier: '" + modifier + "'"; - System.out.println(msg); - fail(msg); - } - - if (!injectWorkflowMessage(eventType, content, 10000)) { - fail("Failed to inject SDNC '" + action + "' event"); - } - - try { - Thread.sleep(1000); - } catch (InterruptedException e) { - fail("Interrupted after injection of SDNC '" + action + "' event"); - } - } - } - - /** - * Runs a program to inject SDNC callback data into the test environment. - * A program is essentially just a list of keys that identify callback data - * to be injected, in sequence. An example program: - *
-	 *     reserve, assign, delete:ERR
-	 * 
- * Errors are handled with junit assertions and will cause the test to fail. - * @param callbacks an object containing callback data for the program - * @param program the program to execute - */ - public void injectSDNCCallbacks(CallbackSet callbacks, String program) { - - String[] cmds = program.replaceAll("\\s+", "").split(","); - - for (String cmd : cmds) { - String action = cmd; - String modifier = "STD"; - - if (cmd.contains(":")) { - String[] parts = cmd.split(":"); - action = parts[0]; - modifier = parts[1]; - } - - String content = null; - int respCode = 200; - String respMsg = "OK"; - - if ("STD".equals(modifier)) { - content = callbacks.get(action); - - if (content == null) { - String msg = "No callback defined for '" + action + "' SDNC request"; - System.out.println(msg); - fail(msg); - } - - respCode = 200; - respMsg = "OK"; - } else if ("ERR".equals(modifier)) { - content = "((REQUEST-ID))500SIMULATED ERROR FROM SDNC ADAPTER"; - respCode = 500; - respMsg = "SERVER ERROR"; - } else { - String msg = "Invalid SDNC program modifier: '" + modifier + "'"; - System.out.println(msg); - fail(msg); - } - - if (!injectSDNCCallback(respCode, respMsg, content, 10000)) { - fail("Failed to inject SDNC '" + action + "' callback"); - } - - try { - Thread.sleep(1000); - } catch (InterruptedException e) { - fail("Interrupted after injection of SDNC '" + action + "' callback"); - } - } - } - - /** - * Runs a program to inject VNF adapter REST callback data into the test environment. - * A program is essentially just a list of keys that identify callback data - * to be injected, in sequence. An example program: - *
-	 *     create, rollback
-	 * 
- * Errors are handled with junit assertions and will cause the test to fail. - * @param callbacks an object containing callback data for the program - * @param program the program to execute - */ - public void injectVNFRestCallbacks(CallbackSet callbacks, String program) { - - String[] cmds = program.replaceAll("\\s+", "").split(","); - - for (String cmd : cmds) { - String action = cmd; - String modifier = "STD"; - - if (cmd.contains(":")) { - String[] parts = cmd.split(":"); - action = parts[0]; - modifier = parts[1]; - } - - String content = null; - - if ("STD".equals(modifier)) { - content = callbacks.get(action); - - if (content == null) { - String msg = "No callback defined for '" + action + "' VNF REST request"; - System.out.println(msg); - fail(msg); - } - } else if ("ERR".equals(modifier)) { - content = "SIMULATED ERROR FROM VNF ADAPTER"; - } else { - String msg = "Invalid VNF REST program modifier: '" + modifier + "'"; - System.out.println(msg); - fail(msg); - } - - if (!injectVnfAdapterRestCallback(content, 10000)) { - fail("Failed to inject VNF REST '" + action + "' callback"); - } - - try { - Thread.sleep(1000); - } catch (InterruptedException e) { - fail("Interrupted after injection of VNF REST '" + action + "' callback"); - } - } - } - - /** - * Runs a program to inject VNF callback data into the test environment. - * A program is essentially just a list of keys that identify callback data - * to be injected, in sequence. An example program: - *
-	 *     createVnf, deleteVnf
-	 * 
- * Errors are handled with junit assertions and will cause the test to fail. - * @param callbacks an object containing callback data for the program - * @param program the program to execute - */ - protected void injectVNFCallbacks(CallbackSet callbacks, String program) { - - String[] cmds = program.replaceAll("\\s+", "").split(","); - - for (String cmd : cmds) { - String action = cmd; - String modifier = "STD"; - - if (cmd.contains(":")) { - String[] parts = cmd.split(":"); - action = parts[0]; - modifier = parts[1]; - } - - String content = null; - - if ("STD".equals(modifier)) { - content = callbacks.get(action); - - if (content == null) { - String msg = "No callback defined for '" + action + "' VNF request"; - System.out.println(msg); - fail(msg); - } - - } else if ("ERR".equals(modifier)) { - String msg = "Currently unsupported VNF program modifier: '" + modifier + "'"; - System.out.println(msg); - fail(msg); - } else { - String msg = "Invalid VNF program modifier: '" + modifier + "'"; - System.out.println(msg); - fail(msg); - } - - boolean injected = false; - - if (content.contains("createVnfNotification")) { - injected = injectCreateVNFCallback(content, 10000); - } else if (content.contains("deleteVnfNotification")) { - injected = injectDeleteVNFCallback(content, 10000); - } else if (content.contains("updateVnfNotification")) { - injected = injectUpdateVNFCallback(content, 10000); - } - - if (!injected) { - String msg = "Failed to inject VNF '" + action + "' callback"; - System.out.println(msg); - fail(msg); - } - - try { - Thread.sleep(1000); - } catch (InterruptedException e) { - fail("Interrupted after injection of VNF '" + action + "' callback"); - } - } - } - - /** - * Waits for the number of running processes with the specified process - * definition key to equal a particular count. - * @param processKey the process definition key - * @param count the desired count - * @param timeout the timeout in milliseconds - */ - public void waitForRunningProcessCount(String processKey, int count, long timeout) { - System.out.println("Waiting " + timeout + "ms for there to be " + count + " " - + processKey + " instances"); - - long now = System.currentTimeMillis() + timeout; - long endTime = now + timeout; - int last = -1; - - while (now <= endTime) { - int actual = processEngineRule.getRuntimeService() - .createProcessInstanceQuery() - .processDefinitionKey(processKey) - .list().size(); - - if (actual != last) { - System.out.println("There are now " + actual + " " - + processKey + " instances"); - last = actual; - } - - if (actual == count) { - return; - } - - try { - Thread.sleep(200); - } catch (InterruptedException e) { - String msg = "Interrupted waiting for there to be " + count + " " - + processKey + " instances"; - System.out.println(msg); - fail(msg); - } - - now = System.currentTimeMillis(); - } - - String msg = "Timed out waiting for there to be " + count + " " - + processKey + " instances"; - System.out.println(msg); - fail(msg); - } - - /** - * Waits for the specified process variable to be set. - * @param processKey the process definition key - * @param variable the variable name - * @param timeout the timeout in milliseconds - * @return the variable value, or null if it cannot be obtained - * in the specified time - */ - protected Object getProcessVariable(String processKey, String variable, - long timeout) { - - System.out.println("Waiting " + timeout + "ms for " - + processKey + "." + variable + " to be set"); - - long now = System.currentTimeMillis() + timeout; - long endTime = now + timeout; - - ProcessInstance processInstance = null; - Object value = null; - - while (value == null) { - if (now > endTime) { - if (processInstance == null) { - System.out.println("Timed out waiting for " - + processKey + " to start"); - } else { - System.out.println("Timed out waiting for " - + processKey + "[" + processInstance.getId() - + "]." + variable + " to be set"); - } - - return null; - } - - if (processInstance == null) { - processInstance = processEngineRule.getRuntimeService() - .createProcessInstanceQuery() - .processDefinitionKey(processKey) - .singleResult(); - } - - if (processInstance != null) { - value = processEngineRule.getRuntimeService() - .getVariable(processInstance.getId(), variable); - } - - try { - Thread.sleep(200); - } catch (InterruptedException e) { - System.out.println("Interrupted waiting for " - + processKey + "." + variable + " to be set"); - return null; - } - - now = System.currentTimeMillis(); - } - - System.out.println(processKey + "[" - + processInstance.getId() + "]." + variable + "=" - + value); - - return value; - } - - /** - * Injects a single SDNC adapter callback request. The specified callback data - * may contain the placeholder string ((REQUEST-ID)) which is replaced with - * the actual SDNC request ID. Note: this is not the requestId in the original - * MSO request. - * @param content the content of the callback - * @param timeout the timeout in milliseconds - * @return true if the callback could be injected, false otherwise - */ - protected boolean injectSDNCRestCallback(String content, long timeout) { - String sdncRequestId = (String) getProcessVariable("SDNCAdapterRestV1", - "SDNCAResponse_CORRELATOR", timeout); - - if (sdncRequestId == null) { - return false; - } - - content = content.replace("((REQUEST-ID))", sdncRequestId); - // Deprecated usage. All test code should switch to the (( ... )) syntax. - content = content.replace("{{REQUEST-ID}}", sdncRequestId); - - System.out.println("Injecting SDNC adapter callback"); - WorkflowMessageResource workflowMessageResource = new WorkflowMessageResource(); - workflowMessageResource.setProcessEngineServices4junit(processEngineRule); - Response response = workflowMessageResource.deliver("SDNCAResponse", sdncRequestId, content); - System.out.println("Workflow response to SDNC adapter callback: " + response); - return true; - } - - /** - * Injects a single SDNC adapter callback request. The specified callback data - * may contain the placeholder string ((REQUEST-ID)) which is replaced with - * the actual SDNC request ID. Note: this is not the requestId in the original - * MSO request. - * @param content the content of the callback - * @param respCode the response code (normally 200) - * @param respMsg the response message (normally "OK") - * @param timeout the timeout in milliseconds - * @return true if the callback could be injected, false otherwise - */ - protected boolean injectSDNCCallback(int respCode, String respMsg, - String content, long timeout) { - - String sdncRequestId = (String) getProcessVariable("sdncAdapter", - "SDNCA_requestId", timeout); - - if (sdncRequestId == null) { - return false; - } - - content = content.replace("((REQUEST-ID))", sdncRequestId); - // Deprecated usage. All test code should switch to the (( ... )) syntax. - content = content.replace("{{REQUEST-ID}}", sdncRequestId); - - System.out.println("Injecting SDNC adapter callback"); - CallbackHeader callbackHeader = new CallbackHeader(); - callbackHeader.setRequestId(sdncRequestId); - callbackHeader.setResponseCode(String.valueOf(respCode)); - callbackHeader.setResponseMessage(respMsg); - SDNCAdapterCallbackRequest sdncAdapterCallbackRequest = new SDNCAdapterCallbackRequest(); - sdncAdapterCallbackRequest.setCallbackHeader(callbackHeader); - sdncAdapterCallbackRequest.setRequestData(content); - SDNCAdapterCallbackServiceImpl callbackService = new SDNCAdapterCallbackServiceImpl(); - callbackService.setProcessEngineServices4junit(processEngineRule); - SDNCAdapterResponse sdncAdapterResponse = callbackService.sdncAdapterCallback(sdncAdapterCallbackRequest); - System.out.println("Workflow response to SDNC adapter callback: " + sdncAdapterResponse); - - return true; - } - - /** - * Injects a single VNF adapter callback request. The specified callback data - * may contain the placeholder string ((MESSAGE-ID)) which is replaced with - * the actual message ID. Note: this is not the requestId in the original - * MSO request. - * @param content the content of the callback - * @param timeout the timeout in milliseconds - * @return true if the callback could be injected, false otherwise - */ - protected boolean injectVnfAdapterRestCallback(String content, long timeout) { - String messageId = (String) getProcessVariable("vnfAdapterRestV1", - "VNFAResponse_CORRELATOR", timeout); - - if (messageId == null) { - return false; - } - - content = content.replace("((MESSAGE-ID))", messageId); - // Deprecated usage. All test code should switch to the (( ... )) syntax. - content = content.replace("{{MESSAGE-ID}}", messageId); - - System.out.println("Injecting VNF adapter callback"); - WorkflowMessageResource workflowMessageResource = new WorkflowMessageResource(); - workflowMessageResource.setProcessEngineServices4junit(processEngineRule); - Response response = workflowMessageResource.deliver("VNFAResponse", messageId, content); - System.out.println("Workflow response to VNF adapter callback: " + response); - return true; - } - - /** - * Injects a Create VNF adapter callback request. The specified callback data - * may contain the placeholder string ((MESSAGE-ID)) which is replaced with - * the actual message ID. It may also contain the placeholder string - * ((REQUEST-ID)) which is replaced request ID of the original MSO request. - * @param content the content of the callback - * @param timeout the timeout in milliseconds - * @return true if the callback could be injected, false otherwise - * @throws JAXBException if the content does not adhere to the schema - */ - protected boolean injectCreateVNFCallback(String content, long timeout) { - - String messageId = (String) getProcessVariable("vnfAdapterCreateV1", - "VNFC_messageId", timeout); - - if (messageId == null) { - return false; - } - - content = content.replace("((MESSAGE-ID))", messageId); - // Deprecated usage. All test code should switch to the (( ... )) syntax. - content = content.replace("{{MESSAGE-ID}}", messageId); - - if(content.contains("((REQUEST-ID))")){ - content = content.replace("((REQUEST-ID))", msoRequestId); - // Deprecated usage. All test code should switch to the (( ... )) syntax. - content = content.replace("{{REQUEST-ID}}", msoRequestId); - } - - System.out.println("Injecting VNF adapter callback"); - - // Is it possible to unmarshal this with JAXB? I couldn't. - - CreateVnfNotification createVnfNotification = new CreateVnfNotification(); - XPathTool xpathTool = new VnfNotifyXPathTool(); - xpathTool.setXML(content); - - try { - String completed = xpathTool.evaluate( - "/tns:createVnfNotification/tns:completed/text()"); - createVnfNotification.setCompleted("true".equals(completed)); - - String vnfId = xpathTool.evaluate( - "/tns:createVnfNotification/tns:vnfId/text()"); - createVnfNotification.setVnfId(vnfId); - - NodeList entries = (NodeList) xpathTool.evaluate( - "/tns:createVnfNotification/tns:outputs/tns:entry", - XPathConstants.NODESET); - - CreateVnfNotificationOutputs outputs = new CreateVnfNotificationOutputs(); - - for (int i = 0; i < entries.getLength(); i++) { - Node node = entries.item(i); - - if (node.getNodeType() == Node.ELEMENT_NODE) { - Element entry = (Element) node; - String key = entry.getElementsByTagNameNS("*", "key").item(0).getTextContent(); - String value = entry.getElementsByTagNameNS("*", "value").item(0).getTextContent(); - outputs.add(key, value); - } - } - - createVnfNotification.setOutputs(outputs); - - VnfRollback rollback = new VnfRollback(); - - String cloudSiteId = xpathTool.evaluate( - "/tns:createVnfNotification/tns:rollback/tns:cloudSiteId/text()"); - rollback.setCloudSiteId(cloudSiteId); - - String requestId = xpathTool.evaluate( - "/tns:createVnfNotification/tns:rollback/tns:msoRequest/tns:requestId/text()"); - String serviceInstanceId = xpathTool.evaluate( - "/tns:createVnfNotification/tns:rollback/tns:msoRequest/tns:serviceInstanceId/text()"); - - if (requestId != null || serviceInstanceId != null) { - MsoRequest msoRequest = new MsoRequest(); - msoRequest.setRequestId(requestId); - msoRequest.setServiceInstanceId(serviceInstanceId); - rollback.setMsoRequest(msoRequest); - } - - String tenantCreated = xpathTool.evaluate( - "/tns:createVnfNotification/tns:rollback/tns:tenantCreated/text()"); - rollback.setTenantCreated("true".equals(tenantCreated)); - - String tenantId = xpathTool.evaluate( - "/tns:createVnfNotification/tns:rollback/tns:tenantId/text()"); - rollback.setTenantId(tenantId); - - String vnfCreated = xpathTool.evaluate( - "/tns:createVnfNotification/tns:rollback/tns:vnfCreated/text()"); - rollback.setVnfCreated("true".equals(vnfCreated)); - - String rollbackVnfId = xpathTool.evaluate( - "/tns:createVnfNotification/tns:rollback/tns:vnfId/text()"); - rollback.setVnfId(rollbackVnfId); - - createVnfNotification.setRollback(rollback); - - } catch (Exception e) { - System.out.println("Failed to unmarshal VNF callback content:"); - System.out.println(content); - return false; - } - - VnfAdapterNotifyServiceImpl notifyService = new VnfAdapterNotifyServiceImpl(); - notifyService.setProcessEngineServices4junit(processEngineRule); - - notifyService.createVnfNotification( - messageId, - createVnfNotification.isCompleted(), - createVnfNotification.getException(), - createVnfNotification.getErrorMessage(), - createVnfNotification.getVnfId(), - createVnfNotification.getOutputs(), - createVnfNotification.getRollback()); - - return true; - } - - /** - * Injects a Delete VNF adapter callback request. The specified callback data - * may contain the placeholder string ((MESSAGE-ID)) which is replaced with - * the actual message ID. It may also contain the placeholder string - * ((REQUEST-ID)) which is replaced request ID of the original MSO request. - * @param content the content of the callback - * @param timeout the timeout in milliseconds - * @return true if the callback could be injected, false otherwise - * @throws JAXBException if the content does not adhere to the schema - */ - protected boolean injectDeleteVNFCallback(String content, long timeout) { - - String messageId = (String) getProcessVariable("vnfAdapterDeleteV1", - "VNFDEL_uuid", timeout); - - if (messageId == null) { - return false; - } - - content = content.replace("((MESSAGE-ID))", messageId); - // Deprecated usage. All test code should switch to the (( ... )) syntax. - content = content.replace("{{MESSAGE-ID}}", messageId); - - System.out.println("Injecting VNF adapter delete callback"); - - // Is it possible to unmarshal this with JAXB? I couldn't. - - DeleteVnfNotification deleteVnfNotification = new DeleteVnfNotification(); - XPathTool xpathTool = new VnfNotifyXPathTool(); - xpathTool.setXML(content); - - try { - String completed = xpathTool.evaluate( - "/tns:deleteVnfNotification/tns:completed/text()"); - deleteVnfNotification.setCompleted("true".equals(completed)); - // if notification failure, set the exception and error message - if (deleteVnfNotification.isCompleted() == false) { - deleteVnfNotification.setException(MsoExceptionCategory.INTERNAL); - deleteVnfNotification.setErrorMessage(xpathTool.evaluate( - "/tns:deleteVnfNotification/tns:errorMessage/text()")) ; - } - - } catch (Exception e) { - System.out.println("Failed to unmarshal VNF Delete callback content:"); - System.out.println(content); - return false; - } - - VnfAdapterNotifyServiceImpl notifyService = new VnfAdapterNotifyServiceImpl(); - notifyService.setProcessEngineServices4junit(processEngineRule); - - notifyService.deleteVnfNotification( - messageId, - deleteVnfNotification.isCompleted(), - deleteVnfNotification.getException(), - deleteVnfNotification.getErrorMessage()); - - return true; - } - - /** - * Injects a Update VNF adapter callback request. The specified callback data - * may contain the placeholder string ((MESSAGE-ID)) which is replaced with - * the actual message ID. It may also contain the placeholder string - * ((REQUEST-ID)) which is replaced request ID of the original MSO request. - * @param content the content of the callback - * @param timeout the timeout in milliseconds - * @return true if the callback could be injected, false otherwise - * @throws JAXBException if the content does not adhere to the schema - */ - protected boolean injectUpdateVNFCallback(String content, long timeout) { - - String messageId = (String) getProcessVariable("vnfAdapterUpdate", - "VNFU_messageId", timeout); - - if (messageId == null) { - return false; - } - - content = content.replace("((MESSAGE-ID))", messageId); - // Deprecated usage. All test code should switch to the (( ... )) syntax. - content = content.replace("{{MESSAGE-ID}}", messageId); - - content = content.replace("((REQUEST-ID))", msoRequestId); - // Deprecated usage. All test code should switch to the (( ... )) syntax. - content = content.replace("{{REQUEST-ID}}", msoRequestId); - - System.out.println("Injecting VNF adapter callback"); - - // Is it possible to unmarshal this with JAXB? I couldn't. - - UpdateVnfNotification updateVnfNotification = new UpdateVnfNotification(); - XPathTool xpathTool = new VnfNotifyXPathTool(); - xpathTool.setXML(content); - - try { - String completed = xpathTool.evaluate( - "/tns:updateVnfNotification/tns:completed/text()"); - updateVnfNotification.setCompleted("true".equals(completed)); - - NodeList entries = (NodeList) xpathTool.evaluate( - "/tns:updateVnfNotification/tns:outputs/tns:entry", - XPathConstants.NODESET); - - UpdateVnfNotificationOutputs outputs = new UpdateVnfNotificationOutputs(); - - for (int i = 0; i < entries.getLength(); i++) { - Node node = entries.item(i); - - if (node.getNodeType() == Node.ELEMENT_NODE) { - Element entry = (Element) node; - String key = entry.getElementsByTagNameNS("*", "key").item(0).getTextContent(); - String value = entry.getElementsByTagNameNS("*", "value").item(0).getTextContent(); - outputs.add(key, value); - } - } - - updateVnfNotification.setOutputs(outputs); - - VnfRollback rollback = new VnfRollback(); - - String cloudSiteId = xpathTool.evaluate( - "/tns:updateVnfNotification/tns:rollback/tns:cloudSiteId/text()"); - rollback.setCloudSiteId(cloudSiteId); - - String requestId = xpathTool.evaluate( - "/tns:updateVnfNotification/tns:rollback/tns:msoRequest/tns:requestId/text()"); - String serviceInstanceId = xpathTool.evaluate( - "/tns:updateVnfNotification/tns:rollback/tns:msoRequest/tns:serviceInstanceId/text()"); - - if (requestId != null || serviceInstanceId != null) { - MsoRequest msoRequest = new MsoRequest(); - msoRequest.setRequestId(requestId); - msoRequest.setServiceInstanceId(serviceInstanceId); - rollback.setMsoRequest(msoRequest); - } - - String tenantCreated = xpathTool.evaluate( - "/tns:updateVnfNotification/tns:rollback/tns:tenantCreated/text()"); - rollback.setTenantCreated("true".equals(tenantCreated)); - - String tenantId = xpathTool.evaluate( - "/tns:updateVnfNotification/tns:rollback/tns:tenantId/text()"); - rollback.setTenantId(tenantId); - - String vnfCreated = xpathTool.evaluate( - "/tns:updateVnfNotification/tns:rollback/tns:vnfCreated/text()"); - rollback.setVnfCreated("true".equals(vnfCreated)); - - String rollbackVnfId = xpathTool.evaluate( - "/tns:updateVnfNotification/tns:rollback/tns:vnfId/text()"); - rollback.setVnfId(rollbackVnfId); - - updateVnfNotification.setRollback(rollback); - - } catch (Exception e) { - System.out.println("Failed to unmarshal VNF callback content:"); - System.out.println(content); - return false; - } - - VnfAdapterNotifyServiceImpl notifyService = new VnfAdapterNotifyServiceImpl(); - notifyService.setProcessEngineServices4junit(processEngineRule); - - notifyService.updateVnfNotification( - messageId, - updateVnfNotification.isCompleted(), - updateVnfNotification.getException(), - updateVnfNotification.getErrorMessage(), - updateVnfNotification.getOutputs(), - updateVnfNotification.getRollback()); - - return true; - } - - /** - * Injects a workflow message. The specified callback data may contain the - * placeholder string ((CORRELATOR)) which is replaced with the actual - * correlator value. - * @param content the message type - * @param content the message content - * @param timeout the timeout in milliseconds - * @return true if the event could be injected, false otherwise - */ - protected boolean injectWorkflowMessage(String messageType, String content, long timeout) { - String correlator = (String) getProcessVariable("ReceiveWorkflowMessage", - messageType + "_CORRELATOR", timeout); - - if (correlator == null) { - return false; - } - - content = content.replace("((CORRELATOR))", correlator); - - System.out.println("Injecting " + messageType + " message"); - WorkflowMessageResource workflowMessageResource = new WorkflowMessageResource(); - workflowMessageResource.setProcessEngineServices4junit(processEngineRule); - Response response = workflowMessageResource.deliver(messageType, correlator, content); - System.out.println("Workflow response to " + messageType + " message: " + response); - return true; - } - - /** - * Wait for the process to end. - * @param businessKey the process business key - * @param timeout the amount of time to wait, in milliseconds - */ - public void waitForProcessEnd(String businessKey, long timeout) { - System.out.println("Waiting " + timeout + "ms for process with business key " + - businessKey + " to end"); - - long now = System.currentTimeMillis() + timeout; - long endTime = now + timeout; - - while (now <= endTime) { - if (isProcessEnded(businessKey)) { - System.out.println("Process with business key " + businessKey + " has ended"); - return; - } - - try { - Thread.sleep(200); - } catch (InterruptedException e) { - String msg = "Interrupted waiting for process with business key " + - businessKey + " to end"; - System.out.println(msg); - fail(msg); - } - - now = System.currentTimeMillis(); - } - - String msg = "Process with business key " + businessKey + - " did not end within " + timeout + "ms"; - System.out.println(msg); - fail(msg); - } - - /** - * Verifies that the specified historic process variable has the specified value. - * If the variable does not have the specified value, the test is failed. - * @param businessKey the process business key - * @param variable the variable name - * @param value the expected variable value - */ - public void checkVariable(String businessKey, String variable, Object value) { - if (!isProcessEnded(businessKey)) { - fail("Cannot get historic variable " + variable + " because process with business key " + - businessKey + " has not ended"); - } - - Object variableValue = getVariableFromHistory(businessKey, variable); - assertEquals(value, variableValue); - } - - /** - * Checks to see if the specified process is ended. - * @param businessKey the process business Key - * @return true if the process is ended - */ - protected boolean isProcessEnded(String businessKey) { - HistoricProcessInstance processInstance = processEngineRule.getHistoryService() - .createHistoricProcessInstanceQuery().processInstanceBusinessKey(businessKey).singleResult(); - return processInstance != null && processInstance.getEndTime() != null; - } - - /** - * Gets a variable value from a historical process instance. - * @param businessKey the process business key - * @param variableName the variable name - * @return the variable value, or null if the variable could not be - * obtained - */ - public Object getVariableFromHistory(String businessKey, String variableName) { - try { - HistoricProcessInstance processInstance = processEngineRule.getHistoryService() - .createHistoricProcessInstanceQuery().processInstanceBusinessKey(businessKey).singleResult(); - - if (processInstance == null) { - return null; - } - - HistoricVariableInstance v = processEngineRule.getHistoryService() - .createHistoricVariableInstanceQuery().processInstanceId(processInstance.getId()) - .variableName(variableName).singleResult(); - return v == null ? null : v.getValue(); - } catch (Exception e) { - System.out.println("Error retrieving variable " + variableName + - " from historical process with business key " + businessKey + ": " + e); - return null; - } - } - - /** - * Gets the value of a subflow variable from the specified subflow's - * historical process instance. - * - * @param subflowName - the name of the subflow that contains the variable - * @param variableName the variable name - * - * @return the variable value, or null if the variable could not be obtained - * - */ - protected Object getVariableFromSubflowHistory(String subflowName, String variableName) { - try { - List processInstanceList = processEngineRule.getHistoryService() - .createHistoricProcessInstanceQuery().processDefinitionName(subflowName).list(); - - Collections.sort(processInstanceList, new Comparator() { - public int compare(HistoricProcessInstance m1, HistoricProcessInstance m2) { - return m1.getStartTime().compareTo(m2.getStartTime()); - } - }); - - HistoricProcessInstance processInstance = processInstanceList.get(0); - - if (processInstanceList == null) { - return null; - } - - HistoricVariableInstance v = processEngineRule.getHistoryService() - .createHistoricVariableInstanceQuery().processInstanceId(processInstance.getId()) - .variableName(variableName).singleResult(); - return v == null ? null : v.getValue(); - } catch (Exception e) { - System.out.println("Error retrieving variable " + variableName + - " from sub flow: " + subflowName + ", Exception is: " + e); - return null; - } - } - - /** - * Gets the value of a subflow variable from the subflow's - * historical process x instance. - * - * @param subflowName - the name of the subflow that contains the variable - * @param variableName the variable name - * @param subflowInstanceIndex - the instance of the subflow (use when same subflow is called more than once from mainflow) - * - * @return the variable value, or null if the variable could not be obtained - */ - protected Object getVariableFromSubflowHistory(int subflowInstanceIndex, String subflowName, String variableName) { - try { - List processInstanceList = processEngineRule.getHistoryService() - .createHistoricProcessInstanceQuery().processDefinitionName(subflowName).list(); - - Collections.sort(processInstanceList, new Comparator() { - public int compare(HistoricProcessInstance m1, HistoricProcessInstance m2) { - return m1.getStartTime().compareTo(m2.getStartTime()); - } - }); - - HistoricProcessInstance processInstance = processInstanceList.get(subflowInstanceIndex); - - if (processInstanceList == null) { - return null; - } - - HistoricVariableInstance v = processEngineRule.getHistoryService() - .createHistoricVariableInstanceQuery().processInstanceId(processInstance.getId()) - .variableName(variableName).singleResult(); - return v == null ? null : v.getValue(); - } catch (Exception e) { - System.out.println("Error retrieving variable " + variableName + - " from " + subflowInstanceIndex + " instance index of sub flow: " + subflowName + ", Exception is: " + e); - return null; - } - } - - - /** - * Extracts text from an XML element. This method is not namespace aware - * (namespaces are ignored). The first matching element is selected. - * @param xml the XML document or fragment - * @param tag the desired element, e.g. "" - * @return the element text, or null if the element was not found - */ - protected String getXMLTextElement(String xml, String tag) { - xml = removeXMLNamespaces(xml); - - if (!tag.startsWith("<")) { - tag = "<" + tag + ">"; - } - - int start = xml.indexOf(tag); - - if (start == -1) { - return null; - } - - int end = xml.indexOf('<', start + tag.length()); - - if (end == -1) { - return null; - } - - return xml.substring(start + tag.length(), end); - } - - /** - * Removes namespace definitions and prefixes from XML, if any. - */ - private String removeXMLNamespaces(String xml) { - // remove xmlns declaration - xml = xml.replaceAll("xmlns.*?(\"|\').*?(\"|\')", ""); - - // remove opening tag prefix - xml = xml.replaceAll("(<)(\\w+:)(.*?>)", "$1$3"); - - // remove closing tags prefix - xml = xml.replaceAll("()", "$1$3"); - - // remove extra spaces left when xmlns declarations are removed - xml = xml.replaceAll("\\s+>", ">"); - - return xml; - } - - /** - * Asserts that two XML documents are semantically equivalent. Differences - * in whitespace or in namespace usage do not affect the comparison. - * @param expected the expected XML - * @param actual the XML to test - * @throws SAXException - * @throws IOException - */ - public static void assertXMLEquals(String expected, String actual) - throws SAXException, IOException { - XMLUnit.setIgnoreWhitespace(true); - XMLUnit.setIgnoreAttributeOrder(true); - DetailedDiff diff = new DetailedDiff(XMLUnit.compareXML(expected, actual)); - List allDifferences = diff.getAllDifferences(); - assertEquals("Differences found: " + diff.toString(), 0, allDifferences.size()); - } - - /** - * A test implementation of AsynchronousResponse. - */ - public class TestAsyncResponse implements AsynchronousResponse { - Response response = null; - - /** - * {@inheritDoc} - */ - @Override - public synchronized void setResponse(Response response) { - this.response = response; - } - - /** - * Gets the response. - * @return the response, or null if none has been produced yet - */ - public synchronized Response getResponse() { - return response; - } - } - - /** - * An object that contains callback data for a "program". - */ - public class CallbackSet { - private final Map map = new HashMap(); - - /** - * Add callback data to the set. - * @param action the action with which the data is associated - * @param content the callback data - */ - public void put(String action, String content) { - map.put(action, content); - } - - /** - * Retrieve callback data from the set. - * @param action the action with which the data is associated - * @return the callback data, or null if there is none for the specified operation - */ - public String get(String action) { - return map.get(action); - } - } - - /** - * A tool for evaluating XPath expressions. - */ - protected class XPathTool { - private final DocumentBuilderFactory factory; - private final SimpleNamespaceContext context = new SimpleNamespaceContext(); - private final XPath xpath = XPathFactory.newInstance().newXPath(); - private String xml = null; - private Document doc = null; - - /** - * Constructor. - */ - public XPathTool() { - factory = DocumentBuilderFactory.newInstance(); - factory.setNamespaceAware(true); - xpath.setNamespaceContext(context); - } - - /** - * Adds a namespace. - * @param prefix the namespace prefix - * @param uri the namespace uri - */ - public synchronized void addNamespace(String prefix, String uri) { - context.add(prefix, uri); - } - - /** - * Sets the XML content to be operated on. - * @param xml the XML content - */ - public synchronized void setXML(String xml) { - this.xml = xml; - this.doc = null; - } - - /** - * Returns the document object. - * @return the document object, or null if XML has not been set - * @throws SAXException - * @throws IOException - * @throws ParserConfigurationException - */ - public synchronized Document getDocument() - throws ParserConfigurationException, IOException, SAXException { - if (xml == null) { - return null; - } - - buildDocument(); - return doc; - } - - /** - * Evaluates the specified XPath expression and returns a string result. - * This method throws exceptions on error. - * @param expression the expression - * @return the result object - * @throws ParserConfigurationException - * @throws IOException - * @throws SAXException - * @throws XPathExpressionException on error - */ - public synchronized String evaluate(String expression) - throws ParserConfigurationException, SAXException, - IOException, XPathExpressionException { - return (String) evaluate(expression, XPathConstants.STRING); - } - - /** - * Evaluates the specified XPath expression. - * This method throws exceptions on error. - * @param expression the expression - * @param returnType the return type - * @return the result object - * @throws ParserConfigurationException - * @throws IOException - * @throws SAXException - * @throws XPathExpressionException on error - */ - public synchronized Object evaluate(String expression, QName returnType) - throws ParserConfigurationException, SAXException, - IOException, XPathExpressionException { - - buildDocument(); - XPathExpression expr = xpath.compile(expression); - return expr.evaluate(doc, returnType); - } - - /** - * Private helper method that builds the document object. - * Assumes the calling method is synchronized. - * @throws ParserConfigurationException - * @throws IOException - * @throws SAXException - */ - private void buildDocument() throws ParserConfigurationException, - IOException, SAXException { - if (doc == null) { - if (xml == null) { - throw new IOException("XML input is null"); - } - - DocumentBuilder builder = factory.newDocumentBuilder(); - InputSource source = new InputSource(new StringReader(xml)); - doc = builder.parse(source); - } - } - } - - /** - * A NamespaceContext class based on a Map. - */ - private class SimpleNamespaceContext implements NamespaceContext { - private Map prefixMap = new HashMap(); - private Map uriMap = new HashMap(); - - public synchronized void add(String prefix, String uri) { - prefixMap.put(prefix, uri); - uriMap.put(uri, prefix); - } - - @Override - public synchronized String getNamespaceURI(String prefix) { - return prefixMap.get(prefix); - } - - @Override - public Iterator getPrefixes(String uri) { - List list = new ArrayList(); - String prefix = uriMap.get(uri); - if (prefix != null) { - list.add(prefix); - } - return list.iterator(); - } - - @Override - public String getPrefix(String uri) { - return uriMap.get(uri); - } - } - - /** - * A VnfNotify XPathTool. - */ - protected class VnfNotifyXPathTool extends XPathTool { - public VnfNotifyXPathTool() { - addNamespace("tns", "http://org.openecomp.mso/vnfNotify"); - } - } - - /** - * Helper class to make it easier to create this type. - */ - private static class CreateVnfNotificationOutputs - extends org.openecomp.mso.bpmn.common.adapter.vnf.CreateVnfNotification.Outputs { - public void add(String key, String value) { - Entry entry = new Entry(); - entry.setKey(key); - entry.setValue(value); - getEntry().add(entry); - } - } - - /** - * Helper class to make it easier to create this type. - */ - private static class UpdateVnfNotificationOutputs - extends org.openecomp.mso.bpmn.common.adapter.vnf.UpdateVnfNotification.Outputs { - public void add(String key, String value) { - Entry entry = new Entry(); - entry.setKey(key); - entry.setValue(value); - getEntry().add(entry); - } - } -} +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.bpmn.common; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + +import java.io.IOException; +import java.io.StringReader; +import java.lang.management.ManagementFactory; +import java.lang.management.RuntimeMXBean; +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import javax.ws.rs.core.Response; +import javax.xml.bind.JAXBException; +import javax.xml.namespace.NamespaceContext; +import javax.xml.namespace.QName; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.xpath.XPath; +import javax.xml.xpath.XPathConstants; +import javax.xml.xpath.XPathExpression; +import javax.xml.xpath.XPathExpressionException; +import javax.xml.xpath.XPathFactory; + +import org.camunda.bpm.engine.RuntimeService; +import org.camunda.bpm.engine.history.HistoricProcessInstance; +import org.camunda.bpm.engine.history.HistoricVariableInstance; +import org.camunda.bpm.engine.runtime.ProcessInstance; +import org.camunda.bpm.engine.test.ProcessEngineRule; +import org.camunda.bpm.engine.variable.impl.VariableMapImpl; +import org.custommonkey.xmlunit.DetailedDiff; +import org.custommonkey.xmlunit.XMLUnit; +import org.jboss.resteasy.spi.AsynchronousResponse; +import org.junit.Before; +import org.junit.Rule; +import org.openecomp.mso.bpmn.common.adapter.sdnc.CallbackHeader; +import org.openecomp.mso.bpmn.common.adapter.sdnc.SDNCAdapterCallbackRequest; +import org.openecomp.mso.bpmn.common.adapter.sdnc.SDNCAdapterResponse; +import org.openecomp.mso.bpmn.common.adapter.vnf.CreateVnfNotification; +import org.openecomp.mso.bpmn.common.adapter.vnf.DeleteVnfNotification; +import org.openecomp.mso.bpmn.common.adapter.vnf.MsoExceptionCategory; +import org.openecomp.mso.bpmn.common.adapter.vnf.MsoRequest; +import org.openecomp.mso.bpmn.common.adapter.vnf.UpdateVnfNotification; +import org.openecomp.mso.bpmn.common.adapter.vnf.VnfRollback; +import org.openecomp.mso.bpmn.common.workflow.service.SDNCAdapterCallbackServiceImpl; +import org.openecomp.mso.bpmn.common.workflow.service.VnfAdapterNotifyServiceImpl; +import org.openecomp.mso.bpmn.common.workflow.service.WorkflowAsyncCommonResource; +import org.openecomp.mso.bpmn.common.workflow.service.WorkflowMessageResource; +import org.openecomp.mso.bpmn.common.workflow.service.WorkflowResponse; +import org.openecomp.mso.bpmn.core.CamundaDBSetup; +import org.openecomp.mso.bpmn.core.PropertyConfigurationSetup; +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.xml.sax.SAXException; + +import com.github.tomakehurst.wiremock.core.WireMockConfiguration; +import com.github.tomakehurst.wiremock.extension.ResponseTransformer; +import com.github.tomakehurst.wiremock.junit.WireMockRule; + + + +/** + * A base class for Workflow tests. + *

+ * WireMock response transformers may be specified by declaring public + * static fields with the @WorkflowTestTransformer annotation. For example: + *

+ *     @WorkflowTestTransformer
+ *     public static final ResponseTransformer sdncAdapterMockTransformer =
+ *         new SDNCAdapterMockTransformer();
+ * 
+ */ +public class WorkflowTest { + @Rule + public final ProcessEngineRule processEngineRule = new ProcessEngineRule(); + + @Rule + public final WireMockRule wireMockRule; + + /** + * Constructor. + */ + public WorkflowTest() throws RuntimeException { + // Process WorkflowTestTransformer annotations + List transformerList = new ArrayList(); + + for (Field field : getClass().getFields()) { + WorkflowTestTransformer annotation = (WorkflowTestTransformer) + field.getAnnotation(WorkflowTestTransformer.class); + + if (annotation == null) { + continue; + } + + if (!Modifier.isStatic(field.getModifiers())) { + throw new RuntimeException(field.getDeclaringClass().getName() + + "#" + field.getName() + " has a @WorkflowTestTransformer " + + " annotation but it is not declared static"); + } + + ResponseTransformer transformer; + + try { + transformer = (ResponseTransformer) field.get(null); + } catch (IllegalAccessException e) { + throw new RuntimeException(field.getDeclaringClass().getName() + + "#" + field.getName() + " is not accessible", e); + } catch (ClassCastException e) { + throw new RuntimeException(field.getDeclaringClass().getName() + + "#" + field.getName() + " is not a ResponseTransformer", e); + } + + if (transformer == null) { + continue; + } + + transformerList.add(transformer); + } + + ResponseTransformer[] transformerArray = + transformerList.toArray(new ResponseTransformer[transformerList.size()]); + + wireMockRule = new WireMockRule(WireMockConfiguration.wireMockConfig() + .port(28090).extensions(transformerArray)); + } + + @Before + public void testSetup() throws Exception { + CamundaDBSetup.configure(); + PropertyConfigurationSetup.init(); + } + + /** + * The current request ID. Normally set when an "invoke" method is called. + */ + protected volatile String msoRequestId = null; + + /** + * The current service instance ID. Normally set when an "invoke" method + * is called. + */ + protected volatile String msoServiceInstanceId = null; + + /** + * Logs a test start method. + */ + protected void logStart() { + StackTraceElement[] st = Thread.currentThread().getStackTrace(); + String method = st[2].getMethodName(); + System.out.println("STARTED TEST: " + method); + } + + /** + * Logs a test end method. + */ + protected void logEnd() { + StackTraceElement[] st = Thread.currentThread().getStackTrace(); + String method = st[2].getMethodName(); + System.out.println("ENDED TEST: " + method); + } + + /** + * Invokes a subprocess. + * @param processKey the process key + * @param businessKey a unique key that will identify the process instance + * @param injectedVariables variables to inject into the process + */ + protected void invokeSubProcess(String processKey, String businessKey, + Map injectedVariables) { + RuntimeMXBean runtimeMxBean = ManagementFactory.getRuntimeMXBean(); + List arguments = runtimeMxBean.getInputArguments(); + System.out.println("JVM args = " + arguments); + + msoRequestId = (String) injectedVariables.get("mso-request-id"); + + if (msoRequestId == null) { + String msg = "mso-request-id variable was not provided"; + System.out.println(msg); + fail(msg); + } + + // Note: some scenarios don't have a service-instance-id, may be null + msoServiceInstanceId = (String) injectedVariables.get("mso-service-instance-id"); + + RuntimeService runtimeService = processEngineRule.getRuntimeService(); + runtimeService.startProcessInstanceByKey(processKey, businessKey, injectedVariables); + } + + /** + * Invokes an asynchronous process. + * Errors are handled with junit assertions and will cause the test to fail. + * @param processKey the process key + * @param schemaVersion the API schema version, e.g. "v1" + * @param businessKey a unique key that will identify the process instance + * @param request the request + * @return a TestAsyncResponse object associated with the test + */ + protected TestAsyncResponse invokeAsyncProcess(String processKey, + String schemaVersion, String businessKey, String request) { + return invokeAsyncProcess(processKey, schemaVersion, businessKey, request, null); + } + + /** + * Invokes an asynchronous process. + * Errors are handled with junit assertions and will cause the test to fail. + * @param processKey the process key + * @param schemaVersion the API schema version, e.g. "v1" + * @param businessKey a unique key that will identify the process instance + * @param request the request + * @param injectedVariables optional variables to inject into the process + * @return a TestAsyncResponse object associated with the test + */ + public TestAsyncResponse invokeAsyncProcess(String processKey, + String schemaVersion, String businessKey, String request, + Map injectedVariables) { + + RuntimeMXBean runtimeMxBean = ManagementFactory.getRuntimeMXBean(); + List arguments = runtimeMxBean.getInputArguments(); + System.out.println("JVM args = " + arguments); + + Map variables = createVariables(schemaVersion, businessKey, + request, injectedVariables, false); + VariableMapImpl variableMapImpl = createVariableMapImpl(variables); + + System.out.println("Sending " + request + " to " + processKey + " process"); + WorkflowAsyncCommonResource workflowResource = new WorkflowAsyncCommonResource(); + workflowResource.setProcessEngineServices4junit(processEngineRule); + + TestAsyncResponse asyncResponse = new TestAsyncResponse(); + workflowResource.startProcessInstanceByKey(asyncResponse, processKey, variableMapImpl); + return asyncResponse; + } + + /** + * Invokes an asynchronous process. + * Errors are handled with junit assertions and will cause the test to fail. + * @param processKey the process key + * @param schemaVersion the API schema version, e.g. "v1" + * @param businessKey a unique key that will identify the process instance + * @param request the request + * @param injectedVariables optional variables to inject into the process + * @param serviceInstantiationModel indicates whether this method is being + * invoked for a flow that is designed using the service instantiation model + * @return a TestAsyncResponse object associated with the test + */ + protected TestAsyncResponse invokeAsyncProcess(String processKey, + String schemaVersion, String businessKey, String request, + Map injectedVariables, boolean serviceInstantiationModel) { + + RuntimeMXBean runtimeMxBean = ManagementFactory.getRuntimeMXBean(); + List arguments = runtimeMxBean.getInputArguments(); + System.out.println("JVM args = " + arguments); + + Map variables = createVariables(schemaVersion, businessKey, + request, injectedVariables, serviceInstantiationModel); + VariableMapImpl variableMapImpl = createVariableMapImpl(variables); + + System.out.println("Sending " + request + " to " + processKey + " process"); + WorkflowAsyncCommonResource workflowResource = new WorkflowAsyncCommonResource(); + workflowResource.setProcessEngineServices4junit(processEngineRule); + + TestAsyncResponse asyncResponse = new TestAsyncResponse(); + workflowResource.startProcessInstanceByKey(asyncResponse, processKey, variableMapImpl); + return asyncResponse; + } + + /** + * Private helper method that creates a variable map for a request. + * Errors are handled with junit assertions and will cause the test to fail. + * @param schemaVersion the API schema version, e.g. "v1" + * @param businessKey a unique key that will identify the process instance + * @param request the request + * @param injectedVariables optional variables to inject into the process + * @param serviceInstantiationModel indicates whether this method is being + * invoked for a flow that is designed using the service instantiation model + * @return a variable map + */ + private Map createVariables(String schemaVersion, + String businessKey, String request, Map injectedVariables, + boolean serviceInstantiationModel) { + + Map variables = new HashMap(); + + // These variables may be overridded by injected variables. + variables.put("mso-service-request-timeout", "180"); + variables.put("isDebugLogEnabled", "true"); + + // These variables may not be overridded by injected variables. + String[] notAllowed = new String[] { + "mso-schema-version", + "mso-business-key", + "bpmnRequest", + "mso-request-id", + "mso-service-instance-id" + }; + + if (injectedVariables != null) { + for (String key : injectedVariables.keySet()) { + for (String var : notAllowed) { + if (var.equals(key)) { + String msg = "Cannot specify " + var + " in injected variables"; + System.out.println(msg); + fail(msg); + } + } + + variables.put(key, injectedVariables.get(key)); + } + } + + variables.put("mso-schema-version", schemaVersion); + variables.put("mso-business-key", businessKey); + variables.put("bpmnRequest", request); + + if (serviceInstantiationModel) { + + /* + * The request ID and the service instance ID are generated for flows + * that follow the service instantiation model unless "requestId" and + * "serviceInstanceId" are injected variables. + */ + + try { + msoRequestId = (String) injectedVariables.get("requestId"); + variables.put("mso-request-id", msoRequestId); + msoServiceInstanceId = (String) injectedVariables.get("serviceInstanceId"); + variables.put("mso-service-instance-id", msoServiceInstanceId); + } + catch(Exception e) { + } + if (msoRequestId == null || msoRequestId.trim().equals("")) { + System.out.println("No requestId element in injectedVariables"); + variables.put("mso-request-id", UUID.randomUUID().toString()); + } + if (msoServiceInstanceId == null || msoServiceInstanceId.trim().equals("")) { + System.out.println("No seviceInstanceId element in injectedVariables"); + variables.put("mso-service-instance-id", UUID.randomUUID().toString()); + } + + } else { + msoRequestId = getXMLTextElement(request, "request-id"); + + if (msoRequestId == null) { + //check in injected variables + try { + msoRequestId = (String) injectedVariables.get("requestId"); + } + catch(Exception e) { + } + if (msoRequestId == null || msoRequestId.trim().equals("")) { + String msg = "No request-id element in " + request; + System.out.println(msg); + fail(msg); + } + } + + variables.put("mso-request-id", msoRequestId); + + // Note: some request types don't have a service-instance-id + msoServiceInstanceId = getXMLTextElement(request, "service-instance-id"); + + if (msoServiceInstanceId != null) { + variables.put("mso-service-instance-id", msoServiceInstanceId); + } + } + + return variables; + } + + /** + * Private helper method that creates a camunda VariableMapImpl from a simple + * variable map. + * @param variables the simple variable map + * @return a VariableMap + */ + private VariableMapImpl createVariableMapImpl(Map variables) { + Map wrappedVariables = new HashMap(); + + for (String key : variables.keySet()) { + Object value = variables.get(key); + wrappedVariables.put(key, wrapVariableValue(value)); + } + + VariableMapImpl variableMapImpl = new VariableMapImpl(); + variableMapImpl.put("variables", wrappedVariables); + return variableMapImpl; + } + + /** + * Private helper method that wraps a variable value for inclusion in a + * camunda VariableMapImpl. + * @param value the variable value + * @return the wrapped variable + */ + private Map wrapVariableValue(Object value) { + HashMap valueMap = new HashMap(); + valueMap.put("value", value); + return valueMap; + } + + /** + * Receives a response from an asynchronous process. + * Errors are handled with junit assertions and will cause the test to fail. + * @param businessKey the process business key + * @param asyncResponse the TestAsyncResponse object associated with the test + * @param timeout the timeout in milliseconds + * @return the WorkflowResponse + */ + public WorkflowResponse receiveResponse(String businessKey, + TestAsyncResponse asyncResponse, long timeout) { + System.out.println("Waiting " + timeout + "ms for process with business key " + businessKey + + " to send a response"); + + long now = System.currentTimeMillis() + timeout; + long endTime = now + timeout; + + while (now <= endTime) { + Response response = asyncResponse.getResponse(); + + if (response != null) { + System.out.println("Received a response from process with business key " + businessKey); + + Object entity = response.getEntity(); + + if (!(entity instanceof WorkflowResponse)) { + String msg = "Response entity is " + + (entity == null ? "null" : entity.getClass().getName()) + + ", expected WorkflowResponse"; + System.out.println(msg); + fail(msg); + return null; // unreachable + } + + return (WorkflowResponse) entity; + } + + try { + Thread.sleep(200); + } catch (InterruptedException e) { + String msg = "Interrupted waiting for a response from process with business key " + + businessKey; + System.out.println(msg); + fail(msg); + return null; // unreachable + } + + now = System.currentTimeMillis(); + } + + String msg = "No response received from process with business key " + businessKey + + " within " + timeout + "ms"; + System.out.println(msg); + fail("Process with business key " + businessKey + " did not end within 10000ms"); + return null; // unreachable + } + + /** + * Runs a program to inject SDNC callback data into the test environment. + * A program is essentially just a list of keys that identify callback data + * to be injected, in sequence. An example program: + *
+	 *     reserve, assign, delete:ERR
+	 * 
+ * Errors are handled with junit assertions and will cause the test to fail. + * @param callbacks an object containing callback data for the program + * @param program the program to execute + */ + protected void injectSDNCRestCallbacks(CallbackSet callbacks, String program) { + + String[] cmds = program.replaceAll("\\s+", "").split(","); + + for (String cmd : cmds) { + String action = cmd; + String modifier = "STD"; + + if (cmd.contains(":")) { + String[] parts = cmd.split(":"); + action = parts[0]; + modifier = parts[1]; + } + + String content = null; + + if ("STD".equals(modifier)) { + content = callbacks.get(action); + + if (content == null) { + String msg = "No callback defined for '" + action + "' SDNC request"; + System.out.println(msg); + fail(msg); + } + } else if ("ERR".equals(modifier)) { + content = "{\"SDNCServiceError\":{\"sdncRequestId\":\"((REQUEST-ID))\",\"responseCode\":\"500\",\"responseMessage\":\"SIMULATED ERROR FROM SDNC ADAPTER\",\"ackFinalIndicator\":\"Y\"}}"; + } else { + String msg = "Invalid SDNC program modifier: '" + modifier + "'"; + System.out.println(msg); + fail(msg); + } + + if (!injectSDNCRestCallback(content, 10000)) { + fail("Failed to inject SDNC '" + action + "' callback"); + } + + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + fail("Interrupted after injection of SDNC '" + action + "' callback"); + } + } + } + + /** + * Runs a program to inject SDNC events into the test environment. + * A program is essentially just a list of keys that identify event data + * to be injected, in sequence. An example program: + *
+	 *     event1, event2
+	 * 
+ * Errors are handled with junit assertions and will cause the test to fail. + * Defaults the Event Type to "SDNCAEvent" for backward compatibility. + * @param callbacks an object containing event data for the program + * @param program the program to execute + */ + protected void injectSDNCEvents(CallbackSet callbacks, String program) { + injectSDNCEvents(callbacks, program, "SDNCAEvent"); + } + + /** + * Runs a program to inject SDNC events into the test environment. + * A program is essentially just a list of keys that identify event data + * to be injected, in sequence. An example program: + *
+	 *     event1, event2
+	 * 
+ * Errors are handled with junit assertions and will cause the test to fail. + * @param callbacks an object containing event data for the program + * @param program the program to execute + * @param eventType (i.e. "SDNCAEvent", "SNIROResponse", etc.) + */ + protected void injectSDNCEvents(CallbackSet callbacks, String program, String eventType) { + + String[] cmds = program.replaceAll("\\s+", "").split(","); + + for (String cmd : cmds) { + String action = cmd; + String modifier = "STD"; + + if (cmd.contains(":")) { + String[] parts = cmd.split(":"); + action = parts[0]; + modifier = parts[1]; + } + + String content = null; + + if ("STD".equals(modifier)) { + content = callbacks.get(action); + + if (content == null) { + String msg = "No SDNC event callback defined for '" + action + "'"; + System.out.println(msg); + fail(msg); + } + } else { + String msg = "Invalid SDNC program modifier: '" + modifier + "'"; + System.out.println(msg); + fail(msg); + } + + if (!injectWorkflowMessage(eventType, content, 10000)) { + fail("Failed to inject SDNC '" + action + "' event"); + } + + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + fail("Interrupted after injection of SDNC '" + action + "' event"); + } + } + } + + /** + * Runs a program to inject SDNC callback data into the test environment. + * A program is essentially just a list of keys that identify callback data + * to be injected, in sequence. An example program: + *
+	 *     reserve, assign, delete:ERR
+	 * 
+ * Errors are handled with junit assertions and will cause the test to fail. + * @param callbacks an object containing callback data for the program + * @param program the program to execute + */ + public void injectSDNCCallbacks(CallbackSet callbacks, String program) { + + String[] cmds = program.replaceAll("\\s+", "").split(","); + + for (String cmd : cmds) { + String action = cmd; + String modifier = "STD"; + + if (cmd.contains(":")) { + String[] parts = cmd.split(":"); + action = parts[0]; + modifier = parts[1]; + } + + String content = null; + int respCode = 200; + String respMsg = "OK"; + + if ("STD".equals(modifier)) { + content = callbacks.get(action); + + if (content == null) { + String msg = "No callback defined for '" + action + "' SDNC request"; + System.out.println(msg); + fail(msg); + } + + respCode = 200; + respMsg = "OK"; + } else if ("ERR".equals(modifier)) { + content = "((REQUEST-ID))500SIMULATED ERROR FROM SDNC ADAPTER"; + respCode = 500; + respMsg = "SERVER ERROR"; + } else { + String msg = "Invalid SDNC program modifier: '" + modifier + "'"; + System.out.println(msg); + fail(msg); + } + + if (!injectSDNCCallback(respCode, respMsg, content, 10000)) { + fail("Failed to inject SDNC '" + action + "' callback"); + } + + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + fail("Interrupted after injection of SDNC '" + action + "' callback"); + } + } + } + + /** + * Runs a program to inject VNF adapter REST callback data into the test environment. + * A program is essentially just a list of keys that identify callback data + * to be injected, in sequence. An example program: + *
+	 *     create, rollback
+	 * 
+ * Errors are handled with junit assertions and will cause the test to fail. + * @param callbacks an object containing callback data for the program + * @param program the program to execute + */ + public void injectVNFRestCallbacks(CallbackSet callbacks, String program) { + + String[] cmds = program.replaceAll("\\s+", "").split(","); + + for (String cmd : cmds) { + String action = cmd; + String modifier = "STD"; + + if (cmd.contains(":")) { + String[] parts = cmd.split(":"); + action = parts[0]; + modifier = parts[1]; + } + + String content = null; + + if ("STD".equals(modifier)) { + content = callbacks.get(action); + + if (content == null) { + String msg = "No callback defined for '" + action + "' VNF REST request"; + System.out.println(msg); + fail(msg); + } + } else if ("ERR".equals(modifier)) { + content = "SIMULATED ERROR FROM VNF ADAPTER"; + } else { + String msg = "Invalid VNF REST program modifier: '" + modifier + "'"; + System.out.println(msg); + fail(msg); + } + + if (!injectVnfAdapterRestCallback(content, 10000)) { + fail("Failed to inject VNF REST '" + action + "' callback"); + } + + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + fail("Interrupted after injection of VNF REST '" + action + "' callback"); + } + } + } + + /** + * Runs a program to inject VNF callback data into the test environment. + * A program is essentially just a list of keys that identify callback data + * to be injected, in sequence. An example program: + *
+	 *     createVnf, deleteVnf
+	 * 
+ * Errors are handled with junit assertions and will cause the test to fail. + * @param callbacks an object containing callback data for the program + * @param program the program to execute + */ + protected void injectVNFCallbacks(CallbackSet callbacks, String program) { + + String[] cmds = program.replaceAll("\\s+", "").split(","); + + for (String cmd : cmds) { + String action = cmd; + String modifier = "STD"; + + if (cmd.contains(":")) { + String[] parts = cmd.split(":"); + action = parts[0]; + modifier = parts[1]; + } + + String content = null; + + if ("STD".equals(modifier)) { + content = callbacks.get(action); + + if (content == null) { + String msg = "No callback defined for '" + action + "' VNF request"; + System.out.println(msg); + fail(msg); + } + + } else if ("ERR".equals(modifier)) { + String msg = "Currently unsupported VNF program modifier: '" + modifier + "'"; + System.out.println(msg); + fail(msg); + } else { + String msg = "Invalid VNF program modifier: '" + modifier + "'"; + System.out.println(msg); + fail(msg); + } + + boolean injected = false; + + if (content.contains("createVnfNotification")) { + injected = injectCreateVNFCallback(content, 10000); + } else if (content.contains("deleteVnfNotification")) { + injected = injectDeleteVNFCallback(content, 10000); + } else if (content.contains("updateVnfNotification")) { + injected = injectUpdateVNFCallback(content, 10000); + } + + if (!injected) { + String msg = "Failed to inject VNF '" + action + "' callback"; + System.out.println(msg); + fail(msg); + } + + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + fail("Interrupted after injection of VNF '" + action + "' callback"); + } + } + } + + /** + * Waits for the number of running processes with the specified process + * definition key to equal a particular count. + * @param processKey the process definition key + * @param count the desired count + * @param timeout the timeout in milliseconds + */ + public void waitForRunningProcessCount(String processKey, int count, long timeout) { + System.out.println("Waiting " + timeout + "ms for there to be " + count + " " + + processKey + " instances"); + + long now = System.currentTimeMillis() + timeout; + long endTime = now + timeout; + int last = -1; + + while (now <= endTime) { + int actual = processEngineRule.getRuntimeService() + .createProcessInstanceQuery() + .processDefinitionKey(processKey) + .list().size(); + + if (actual != last) { + System.out.println("There are now " + actual + " " + + processKey + " instances"); + last = actual; + } + + if (actual == count) { + return; + } + + try { + Thread.sleep(200); + } catch (InterruptedException e) { + String msg = "Interrupted waiting for there to be " + count + " " + + processKey + " instances"; + System.out.println(msg); + fail(msg); + } + + now = System.currentTimeMillis(); + } + + String msg = "Timed out waiting for there to be " + count + " " + + processKey + " instances"; + System.out.println(msg); + fail(msg); + } + + /** + * Waits for the specified process variable to be set. + * @param processKey the process definition key + * @param variable the variable name + * @param timeout the timeout in milliseconds + * @return the variable value, or null if it cannot be obtained + * in the specified time + */ + protected Object getProcessVariable(String processKey, String variable, + long timeout) { + + System.out.println("Waiting " + timeout + "ms for " + + processKey + "." + variable + " to be set"); + + long now = System.currentTimeMillis() + timeout; + long endTime = now + timeout; + + ProcessInstance processInstance = null; + Object value = null; + + while (value == null) { + if (now > endTime) { + if (processInstance == null) { + System.out.println("Timed out waiting for " + + processKey + " to start"); + } else { + System.out.println("Timed out waiting for " + + processKey + "[" + processInstance.getId() + + "]." + variable + " to be set"); + } + + return null; + } + + if (processInstance == null) { + processInstance = processEngineRule.getRuntimeService() + .createProcessInstanceQuery() + .processDefinitionKey(processKey) + .singleResult(); + } + + if (processInstance != null) { + value = processEngineRule.getRuntimeService() + .getVariable(processInstance.getId(), variable); + } + + try { + Thread.sleep(200); + } catch (InterruptedException e) { + System.out.println("Interrupted waiting for " + + processKey + "." + variable + " to be set"); + return null; + } + + now = System.currentTimeMillis(); + } + + System.out.println(processKey + "[" + + processInstance.getId() + "]." + variable + "=" + + value); + + return value; + } + + /** + * Injects a single SDNC adapter callback request. The specified callback data + * may contain the placeholder string ((REQUEST-ID)) which is replaced with + * the actual SDNC request ID. Note: this is not the requestId in the original + * MSO request. + * @param content the content of the callback + * @param timeout the timeout in milliseconds + * @return true if the callback could be injected, false otherwise + */ + protected boolean injectSDNCRestCallback(String content, long timeout) { + String sdncRequestId = (String) getProcessVariable("SDNCAdapterRestV1", + "SDNCAResponse_CORRELATOR", timeout); + + if (sdncRequestId == null) { + return false; + } + + content = content.replace("((REQUEST-ID))", sdncRequestId); + // Deprecated usage. All test code should switch to the (( ... )) syntax. + content = content.replace("{{REQUEST-ID}}", sdncRequestId); + + System.out.println("Injecting SDNC adapter callback"); + WorkflowMessageResource workflowMessageResource = new WorkflowMessageResource(); + workflowMessageResource.setProcessEngineServices4junit(processEngineRule); + Response response = workflowMessageResource.deliver("SDNCAResponse", sdncRequestId, content); + System.out.println("Workflow response to SDNC adapter callback: " + response); + return true; + } + + /** + * Injects a single SDNC adapter callback request. The specified callback data + * may contain the placeholder string ((REQUEST-ID)) which is replaced with + * the actual SDNC request ID. Note: this is not the requestId in the original + * MSO request. + * @param content the content of the callback + * @param respCode the response code (normally 200) + * @param respMsg the response message (normally "OK") + * @param timeout the timeout in milliseconds + * @return true if the callback could be injected, false otherwise + */ + protected boolean injectSDNCCallback(int respCode, String respMsg, + String content, long timeout) { + + String sdncRequestId = (String) getProcessVariable("sdncAdapter", + "SDNCA_requestId", timeout); + + if (sdncRequestId == null) { + return false; + } + + content = content.replace("((REQUEST-ID))", sdncRequestId); + // Deprecated usage. All test code should switch to the (( ... )) syntax. + content = content.replace("{{REQUEST-ID}}", sdncRequestId); + + System.out.println("Injecting SDNC adapter callback"); + CallbackHeader callbackHeader = new CallbackHeader(); + callbackHeader.setRequestId(sdncRequestId); + callbackHeader.setResponseCode(String.valueOf(respCode)); + callbackHeader.setResponseMessage(respMsg); + SDNCAdapterCallbackRequest sdncAdapterCallbackRequest = new SDNCAdapterCallbackRequest(); + sdncAdapterCallbackRequest.setCallbackHeader(callbackHeader); + sdncAdapterCallbackRequest.setRequestData(content); + SDNCAdapterCallbackServiceImpl callbackService = new SDNCAdapterCallbackServiceImpl(); + callbackService.setProcessEngineServices4junit(processEngineRule); + SDNCAdapterResponse sdncAdapterResponse = callbackService.sdncAdapterCallback(sdncAdapterCallbackRequest); + System.out.println("Workflow response to SDNC adapter callback: " + sdncAdapterResponse); + + return true; + } + + /** + * Injects a single VNF adapter callback request. The specified callback data + * may contain the placeholder string ((MESSAGE-ID)) which is replaced with + * the actual message ID. Note: this is not the requestId in the original + * MSO request. + * @param content the content of the callback + * @param timeout the timeout in milliseconds + * @return true if the callback could be injected, false otherwise + */ + protected boolean injectVnfAdapterRestCallback(String content, long timeout) { + String messageId = (String) getProcessVariable("vnfAdapterRestV1", + "VNFAResponse_CORRELATOR", timeout); + + if (messageId == null) { + return false; + } + + content = content.replace("((MESSAGE-ID))", messageId); + // Deprecated usage. All test code should switch to the (( ... )) syntax. + content = content.replace("{{MESSAGE-ID}}", messageId); + + System.out.println("Injecting VNF adapter callback"); + WorkflowMessageResource workflowMessageResource = new WorkflowMessageResource(); + workflowMessageResource.setProcessEngineServices4junit(processEngineRule); + Response response = workflowMessageResource.deliver("VNFAResponse", messageId, content); + System.out.println("Workflow response to VNF adapter callback: " + response); + return true; + } + + /** + * Injects a Create VNF adapter callback request. The specified callback data + * may contain the placeholder string ((MESSAGE-ID)) which is replaced with + * the actual message ID. It may also contain the placeholder string + * ((REQUEST-ID)) which is replaced request ID of the original MSO request. + * @param content the content of the callback + * @param timeout the timeout in milliseconds + * @return true if the callback could be injected, false otherwise + * @throws JAXBException if the content does not adhere to the schema + */ + protected boolean injectCreateVNFCallback(String content, long timeout) { + + String messageId = (String) getProcessVariable("vnfAdapterCreateV1", + "VNFC_messageId", timeout); + + if (messageId == null) { + return false; + } + + content = content.replace("((MESSAGE-ID))", messageId); + // Deprecated usage. All test code should switch to the (( ... )) syntax. + content = content.replace("{{MESSAGE-ID}}", messageId); + + if(content.contains("((REQUEST-ID))")){ + content = content.replace("((REQUEST-ID))", msoRequestId); + // Deprecated usage. All test code should switch to the (( ... )) syntax. + content = content.replace("{{REQUEST-ID}}", msoRequestId); + } + + System.out.println("Injecting VNF adapter callback"); + + // Is it possible to unmarshal this with JAXB? I couldn't. + + CreateVnfNotification createVnfNotification = new CreateVnfNotification(); + XPathTool xpathTool = new VnfNotifyXPathTool(); + xpathTool.setXML(content); + + try { + String completed = xpathTool.evaluate( + "/tns:createVnfNotification/tns:completed/text()"); + createVnfNotification.setCompleted("true".equals(completed)); + + String vnfId = xpathTool.evaluate( + "/tns:createVnfNotification/tns:vnfId/text()"); + createVnfNotification.setVnfId(vnfId); + + NodeList entries = (NodeList) xpathTool.evaluate( + "/tns:createVnfNotification/tns:outputs/tns:entry", + XPathConstants.NODESET); + + CreateVnfNotificationOutputs outputs = new CreateVnfNotificationOutputs(); + + for (int i = 0; i < entries.getLength(); i++) { + Node node = entries.item(i); + + if (node.getNodeType() == Node.ELEMENT_NODE) { + Element entry = (Element) node; + String key = entry.getElementsByTagNameNS("*", "key").item(0).getTextContent(); + String value = entry.getElementsByTagNameNS("*", "value").item(0).getTextContent(); + outputs.add(key, value); + } + } + + createVnfNotification.setOutputs(outputs); + + VnfRollback rollback = new VnfRollback(); + + String cloudSiteId = xpathTool.evaluate( + "/tns:createVnfNotification/tns:rollback/tns:cloudSiteId/text()"); + rollback.setCloudSiteId(cloudSiteId); + + String requestId = xpathTool.evaluate( + "/tns:createVnfNotification/tns:rollback/tns:msoRequest/tns:requestId/text()"); + String serviceInstanceId = xpathTool.evaluate( + "/tns:createVnfNotification/tns:rollback/tns:msoRequest/tns:serviceInstanceId/text()"); + + if (requestId != null || serviceInstanceId != null) { + MsoRequest msoRequest = new MsoRequest(); + msoRequest.setRequestId(requestId); + msoRequest.setServiceInstanceId(serviceInstanceId); + rollback.setMsoRequest(msoRequest); + } + + String tenantCreated = xpathTool.evaluate( + "/tns:createVnfNotification/tns:rollback/tns:tenantCreated/text()"); + rollback.setTenantCreated("true".equals(tenantCreated)); + + String tenantId = xpathTool.evaluate( + "/tns:createVnfNotification/tns:rollback/tns:tenantId/text()"); + rollback.setTenantId(tenantId); + + String vnfCreated = xpathTool.evaluate( + "/tns:createVnfNotification/tns:rollback/tns:vnfCreated/text()"); + rollback.setVnfCreated("true".equals(vnfCreated)); + + String rollbackVnfId = xpathTool.evaluate( + "/tns:createVnfNotification/tns:rollback/tns:vnfId/text()"); + rollback.setVnfId(rollbackVnfId); + + createVnfNotification.setRollback(rollback); + + } catch (Exception e) { + System.out.println("Failed to unmarshal VNF callback content:"); + System.out.println(content); + return false; + } + + VnfAdapterNotifyServiceImpl notifyService = new VnfAdapterNotifyServiceImpl(); + notifyService.setProcessEngineServices4junit(processEngineRule); + + notifyService.createVnfNotification( + messageId, + createVnfNotification.isCompleted(), + createVnfNotification.getException(), + createVnfNotification.getErrorMessage(), + createVnfNotification.getVnfId(), + createVnfNotification.getOutputs(), + createVnfNotification.getRollback()); + + return true; + } + + /** + * Injects a Delete VNF adapter callback request. The specified callback data + * may contain the placeholder string ((MESSAGE-ID)) which is replaced with + * the actual message ID. It may also contain the placeholder string + * ((REQUEST-ID)) which is replaced request ID of the original MSO request. + * @param content the content of the callback + * @param timeout the timeout in milliseconds + * @return true if the callback could be injected, false otherwise + * @throws JAXBException if the content does not adhere to the schema + */ + protected boolean injectDeleteVNFCallback(String content, long timeout) { + + String messageId = (String) getProcessVariable("vnfAdapterDeleteV1", + "VNFDEL_uuid", timeout); + + if (messageId == null) { + return false; + } + + content = content.replace("((MESSAGE-ID))", messageId); + // Deprecated usage. All test code should switch to the (( ... )) syntax. + content = content.replace("{{MESSAGE-ID}}", messageId); + + System.out.println("Injecting VNF adapter delete callback"); + + // Is it possible to unmarshal this with JAXB? I couldn't. + + DeleteVnfNotification deleteVnfNotification = new DeleteVnfNotification(); + XPathTool xpathTool = new VnfNotifyXPathTool(); + xpathTool.setXML(content); + + try { + String completed = xpathTool.evaluate( + "/tns:deleteVnfNotification/tns:completed/text()"); + deleteVnfNotification.setCompleted("true".equals(completed)); + // if notification failure, set the exception and error message + if (deleteVnfNotification.isCompleted() == false) { + deleteVnfNotification.setException(MsoExceptionCategory.INTERNAL); + deleteVnfNotification.setErrorMessage(xpathTool.evaluate( + "/tns:deleteVnfNotification/tns:errorMessage/text()")) ; + } + + } catch (Exception e) { + System.out.println("Failed to unmarshal VNF Delete callback content:"); + System.out.println(content); + return false; + } + + VnfAdapterNotifyServiceImpl notifyService = new VnfAdapterNotifyServiceImpl(); + notifyService.setProcessEngineServices4junit(processEngineRule); + + notifyService.deleteVnfNotification( + messageId, + deleteVnfNotification.isCompleted(), + deleteVnfNotification.getException(), + deleteVnfNotification.getErrorMessage()); + + return true; + } + + /** + * Injects a Update VNF adapter callback request. The specified callback data + * may contain the placeholder string ((MESSAGE-ID)) which is replaced with + * the actual message ID. It may also contain the placeholder string + * ((REQUEST-ID)) which is replaced request ID of the original MSO request. + * @param content the content of the callback + * @param timeout the timeout in milliseconds + * @return true if the callback could be injected, false otherwise + * @throws JAXBException if the content does not adhere to the schema + */ + protected boolean injectUpdateVNFCallback(String content, long timeout) { + + String messageId = (String) getProcessVariable("vnfAdapterUpdate", + "VNFU_messageId", timeout); + + if (messageId == null) { + return false; + } + + content = content.replace("((MESSAGE-ID))", messageId); + // Deprecated usage. All test code should switch to the (( ... )) syntax. + content = content.replace("{{MESSAGE-ID}}", messageId); + + content = content.replace("((REQUEST-ID))", msoRequestId); + // Deprecated usage. All test code should switch to the (( ... )) syntax. + content = content.replace("{{REQUEST-ID}}", msoRequestId); + + System.out.println("Injecting VNF adapter callback"); + + // Is it possible to unmarshal this with JAXB? I couldn't. + + UpdateVnfNotification updateVnfNotification = new UpdateVnfNotification(); + XPathTool xpathTool = new VnfNotifyXPathTool(); + xpathTool.setXML(content); + + try { + String completed = xpathTool.evaluate( + "/tns:updateVnfNotification/tns:completed/text()"); + updateVnfNotification.setCompleted("true".equals(completed)); + + NodeList entries = (NodeList) xpathTool.evaluate( + "/tns:updateVnfNotification/tns:outputs/tns:entry", + XPathConstants.NODESET); + + UpdateVnfNotificationOutputs outputs = new UpdateVnfNotificationOutputs(); + + for (int i = 0; i < entries.getLength(); i++) { + Node node = entries.item(i); + + if (node.getNodeType() == Node.ELEMENT_NODE) { + Element entry = (Element) node; + String key = entry.getElementsByTagNameNS("*", "key").item(0).getTextContent(); + String value = entry.getElementsByTagNameNS("*", "value").item(0).getTextContent(); + outputs.add(key, value); + } + } + + updateVnfNotification.setOutputs(outputs); + + VnfRollback rollback = new VnfRollback(); + + String cloudSiteId = xpathTool.evaluate( + "/tns:updateVnfNotification/tns:rollback/tns:cloudSiteId/text()"); + rollback.setCloudSiteId(cloudSiteId); + + String requestId = xpathTool.evaluate( + "/tns:updateVnfNotification/tns:rollback/tns:msoRequest/tns:requestId/text()"); + String serviceInstanceId = xpathTool.evaluate( + "/tns:updateVnfNotification/tns:rollback/tns:msoRequest/tns:serviceInstanceId/text()"); + + if (requestId != null || serviceInstanceId != null) { + MsoRequest msoRequest = new MsoRequest(); + msoRequest.setRequestId(requestId); + msoRequest.setServiceInstanceId(serviceInstanceId); + rollback.setMsoRequest(msoRequest); + } + + String tenantCreated = xpathTool.evaluate( + "/tns:updateVnfNotification/tns:rollback/tns:tenantCreated/text()"); + rollback.setTenantCreated("true".equals(tenantCreated)); + + String tenantId = xpathTool.evaluate( + "/tns:updateVnfNotification/tns:rollback/tns:tenantId/text()"); + rollback.setTenantId(tenantId); + + String vnfCreated = xpathTool.evaluate( + "/tns:updateVnfNotification/tns:rollback/tns:vnfCreated/text()"); + rollback.setVnfCreated("true".equals(vnfCreated)); + + String rollbackVnfId = xpathTool.evaluate( + "/tns:updateVnfNotification/tns:rollback/tns:vnfId/text()"); + rollback.setVnfId(rollbackVnfId); + + updateVnfNotification.setRollback(rollback); + + } catch (Exception e) { + System.out.println("Failed to unmarshal VNF callback content:"); + System.out.println(content); + return false; + } + + VnfAdapterNotifyServiceImpl notifyService = new VnfAdapterNotifyServiceImpl(); + notifyService.setProcessEngineServices4junit(processEngineRule); + + notifyService.updateVnfNotification( + messageId, + updateVnfNotification.isCompleted(), + updateVnfNotification.getException(), + updateVnfNotification.getErrorMessage(), + updateVnfNotification.getOutputs(), + updateVnfNotification.getRollback()); + + return true; + } + + /** + * Injects a workflow message. The specified callback data may contain the + * placeholder string ((CORRELATOR)) which is replaced with the actual + * correlator value. + * @param content the message type + * @param content the message content + * @param timeout the timeout in milliseconds + * @return true if the event could be injected, false otherwise + */ + protected boolean injectWorkflowMessage(String messageType, String content, long timeout) { + String correlator = (String) getProcessVariable("ReceiveWorkflowMessage", + messageType + "_CORRELATOR", timeout); + + if (correlator == null) { + return false; + } + + content = content.replace("((CORRELATOR))", correlator); + + System.out.println("Injecting " + messageType + " message"); + WorkflowMessageResource workflowMessageResource = new WorkflowMessageResource(); + workflowMessageResource.setProcessEngineServices4junit(processEngineRule); + Response response = workflowMessageResource.deliver(messageType, correlator, content); + System.out.println("Workflow response to " + messageType + " message: " + response); + return true; + } + + /** + * Wait for the process to end. + * @param businessKey the process business key + * @param timeout the amount of time to wait, in milliseconds + */ + public void waitForProcessEnd(String businessKey, long timeout) { + System.out.println("Waiting " + timeout + "ms for process with business key " + + businessKey + " to end"); + + long now = System.currentTimeMillis() + timeout; + long endTime = now + timeout; + + while (now <= endTime) { + if (isProcessEnded(businessKey)) { + System.out.println("Process with business key " + businessKey + " has ended"); + return; + } + + try { + Thread.sleep(200); + } catch (InterruptedException e) { + String msg = "Interrupted waiting for process with business key " + + businessKey + " to end"; + System.out.println(msg); + fail(msg); + } + + now = System.currentTimeMillis(); + } + + String msg = "Process with business key " + businessKey + + " did not end within " + timeout + "ms"; + System.out.println(msg); + fail(msg); + } + + /** + * Verifies that the specified historic process variable has the specified value. + * If the variable does not have the specified value, the test is failed. + * @param businessKey the process business key + * @param variable the variable name + * @param value the expected variable value + */ + public void checkVariable(String businessKey, String variable, Object value) { + if (!isProcessEnded(businessKey)) { + fail("Cannot get historic variable " + variable + " because process with business key " + + businessKey + " has not ended"); + } + + Object variableValue = getVariableFromHistory(businessKey, variable); + assertEquals(value, variableValue); + } + + /** + * Checks to see if the specified process is ended. + * @param businessKey the process business Key + * @return true if the process is ended + */ + protected boolean isProcessEnded(String businessKey) { + HistoricProcessInstance processInstance = processEngineRule.getHistoryService() + .createHistoricProcessInstanceQuery().processInstanceBusinessKey(businessKey).singleResult(); + return processInstance != null && processInstance.getEndTime() != null; + } + + /** + * Gets a variable value from a historical process instance. + * @param businessKey the process business key + * @param variableName the variable name + * @return the variable value, or null if the variable could not be + * obtained + */ + public Object getVariableFromHistory(String businessKey, String variableName) { + try { + HistoricProcessInstance processInstance = processEngineRule.getHistoryService() + .createHistoricProcessInstanceQuery().processInstanceBusinessKey(businessKey).singleResult(); + + if (processInstance == null) { + return null; + } + + HistoricVariableInstance v = processEngineRule.getHistoryService() + .createHistoricVariableInstanceQuery().processInstanceId(processInstance.getId()) + .variableName(variableName).singleResult(); + return v == null ? null : v.getValue(); + } catch (Exception e) { + System.out.println("Error retrieving variable " + variableName + + " from historical process with business key " + businessKey + ": " + e); + return null; + } + } + + /** + * Gets the value of a subflow variable from the specified subflow's + * historical process instance. + * + * @param subflowName - the name of the subflow that contains the variable + * @param variableName the variable name + * + * @return the variable value, or null if the variable could not be obtained + * + */ + protected Object getVariableFromSubflowHistory(String subflowName, String variableName) { + try { + List processInstanceList = processEngineRule.getHistoryService() + .createHistoricProcessInstanceQuery().processDefinitionName(subflowName).list(); + + Collections.sort(processInstanceList, new Comparator() { + public int compare(HistoricProcessInstance m1, HistoricProcessInstance m2) { + return m1.getStartTime().compareTo(m2.getStartTime()); + } + }); + + HistoricProcessInstance processInstance = processInstanceList.get(0); + + if (processInstanceList == null) { + return null; + } + + HistoricVariableInstance v = processEngineRule.getHistoryService() + .createHistoricVariableInstanceQuery().processInstanceId(processInstance.getId()) + .variableName(variableName).singleResult(); + return v == null ? null : v.getValue(); + } catch (Exception e) { + System.out.println("Error retrieving variable " + variableName + + " from sub flow: " + subflowName + ", Exception is: " + e); + return null; + } + } + + /** + * Gets the value of a subflow variable from the subflow's + * historical process x instance. + * + * @param subflowName - the name of the subflow that contains the variable + * @param variableName the variable name + * @param subflowInstanceIndex - the instance of the subflow (use when same subflow is called more than once from mainflow) + * + * @return the variable value, or null if the variable could not be obtained + */ + protected Object getVariableFromSubflowHistory(int subflowInstanceIndex, String subflowName, String variableName) { + try { + List processInstanceList = processEngineRule.getHistoryService() + .createHistoricProcessInstanceQuery().processDefinitionName(subflowName).list(); + + Collections.sort(processInstanceList, new Comparator() { + public int compare(HistoricProcessInstance m1, HistoricProcessInstance m2) { + return m1.getStartTime().compareTo(m2.getStartTime()); + } + }); + + HistoricProcessInstance processInstance = processInstanceList.get(subflowInstanceIndex); + + if (processInstanceList == null) { + return null; + } + + HistoricVariableInstance v = processEngineRule.getHistoryService() + .createHistoricVariableInstanceQuery().processInstanceId(processInstance.getId()) + .variableName(variableName).singleResult(); + return v == null ? null : v.getValue(); + } catch (Exception e) { + System.out.println("Error retrieving variable " + variableName + + " from " + subflowInstanceIndex + " instance index of sub flow: " + subflowName + ", Exception is: " + e); + return null; + } + } + + + /** + * Extracts text from an XML element. This method is not namespace aware + * (namespaces are ignored). The first matching element is selected. + * @param xml the XML document or fragment + * @param tag the desired element, e.g. "" + * @return the element text, or null if the element was not found + */ + protected String getXMLTextElement(String xml, String tag) { + xml = removeXMLNamespaces(xml); + + if (!tag.startsWith("<")) { + tag = "<" + tag + ">"; + } + + int start = xml.indexOf(tag); + + if (start == -1) { + return null; + } + + int end = xml.indexOf('<', start + tag.length()); + + if (end == -1) { + return null; + } + + return xml.substring(start + tag.length(), end); + } + + /** + * Removes namespace definitions and prefixes from XML, if any. + */ + private String removeXMLNamespaces(String xml) { + // remove xmlns declaration + xml = xml.replaceAll("xmlns.*?(\"|\').*?(\"|\')", ""); + + // remove opening tag prefix + xml = xml.replaceAll("(<)(\\w+:)(.*?>)", "$1$3"); + + // remove closing tags prefix + xml = xml.replaceAll("()", "$1$3"); + + // remove extra spaces left when xmlns declarations are removed + xml = xml.replaceAll("\\s+>", ">"); + + return xml; + } + + /** + * Asserts that two XML documents are semantically equivalent. Differences + * in whitespace or in namespace usage do not affect the comparison. + * @param expected the expected XML + * @param actual the XML to test + * @throws SAXException + * @throws IOException + */ + public static void assertXMLEquals(String expected, String actual) + throws SAXException, IOException { + XMLUnit.setIgnoreWhitespace(true); + XMLUnit.setIgnoreAttributeOrder(true); + DetailedDiff diff = new DetailedDiff(XMLUnit.compareXML(expected, actual)); + List allDifferences = diff.getAllDifferences(); + assertEquals("Differences found: " + diff.toString(), 0, allDifferences.size()); + } + + /** + * A test implementation of AsynchronousResponse. + */ + public class TestAsyncResponse implements AsynchronousResponse { + Response response = null; + + /** + * {@inheritDoc} + */ + @Override + public synchronized void setResponse(Response response) { + this.response = response; + } + + /** + * Gets the response. + * @return the response, or null if none has been produced yet + */ + public synchronized Response getResponse() { + return response; + } + } + + /** + * An object that contains callback data for a "program". + */ + public class CallbackSet { + private final Map map = new HashMap(); + + /** + * Add callback data to the set. + * @param action the action with which the data is associated + * @param content the callback data + */ + public void put(String action, String content) { + map.put(action, content); + } + + /** + * Retrieve callback data from the set. + * @param action the action with which the data is associated + * @return the callback data, or null if there is none for the specified operation + */ + public String get(String action) { + return map.get(action); + } + } + + /** + * A tool for evaluating XPath expressions. + */ + protected class XPathTool { + private final DocumentBuilderFactory factory; + private final SimpleNamespaceContext context = new SimpleNamespaceContext(); + private final XPath xpath = XPathFactory.newInstance().newXPath(); + private String xml = null; + private Document doc = null; + + /** + * Constructor. + */ + public XPathTool() { + factory = DocumentBuilderFactory.newInstance(); + factory.setNamespaceAware(true); + xpath.setNamespaceContext(context); + } + + /** + * Adds a namespace. + * @param prefix the namespace prefix + * @param uri the namespace uri + */ + public synchronized void addNamespace(String prefix, String uri) { + context.add(prefix, uri); + } + + /** + * Sets the XML content to be operated on. + * @param xml the XML content + */ + public synchronized void setXML(String xml) { + this.xml = xml; + this.doc = null; + } + + /** + * Returns the document object. + * @return the document object, or null if XML has not been set + * @throws SAXException + * @throws IOException + * @throws ParserConfigurationException + */ + public synchronized Document getDocument() + throws ParserConfigurationException, IOException, SAXException { + if (xml == null) { + return null; + } + + buildDocument(); + return doc; + } + + /** + * Evaluates the specified XPath expression and returns a string result. + * This method throws exceptions on error. + * @param expression the expression + * @return the result object + * @throws ParserConfigurationException + * @throws IOException + * @throws SAXException + * @throws XPathExpressionException on error + */ + public synchronized String evaluate(String expression) + throws ParserConfigurationException, SAXException, + IOException, XPathExpressionException { + return (String) evaluate(expression, XPathConstants.STRING); + } + + /** + * Evaluates the specified XPath expression. + * This method throws exceptions on error. + * @param expression the expression + * @param returnType the return type + * @return the result object + * @throws ParserConfigurationException + * @throws IOException + * @throws SAXException + * @throws XPathExpressionException on error + */ + public synchronized Object evaluate(String expression, QName returnType) + throws ParserConfigurationException, SAXException, + IOException, XPathExpressionException { + + buildDocument(); + XPathExpression expr = xpath.compile(expression); + return expr.evaluate(doc, returnType); + } + + /** + * Private helper method that builds the document object. + * Assumes the calling method is synchronized. + * @throws ParserConfigurationException + * @throws IOException + * @throws SAXException + */ + private void buildDocument() throws ParserConfigurationException, + IOException, SAXException { + if (doc == null) { + if (xml == null) { + throw new IOException("XML input is null"); + } + + DocumentBuilder builder = factory.newDocumentBuilder(); + InputSource source = new InputSource(new StringReader(xml)); + doc = builder.parse(source); + } + } + } + + /** + * A NamespaceContext class based on a Map. + */ + private class SimpleNamespaceContext implements NamespaceContext { + private Map prefixMap = new HashMap(); + private Map uriMap = new HashMap(); + + public synchronized void add(String prefix, String uri) { + prefixMap.put(prefix, uri); + uriMap.put(uri, prefix); + } + + @Override + public synchronized String getNamespaceURI(String prefix) { + return prefixMap.get(prefix); + } + + @Override + public Iterator getPrefixes(String uri) { + List list = new ArrayList(); + String prefix = uriMap.get(uri); + if (prefix != null) { + list.add(prefix); + } + return list.iterator(); + } + + @Override + public String getPrefix(String uri) { + return uriMap.get(uri); + } + } + + /** + * A VnfNotify XPathTool. + */ + protected class VnfNotifyXPathTool extends XPathTool { + public VnfNotifyXPathTool() { + addNamespace("tns", "http://org.openecomp.mso/vnfNotify"); + } + } + + /** + * Helper class to make it easier to create this type. + */ + private static class CreateVnfNotificationOutputs + extends org.openecomp.mso.bpmn.common.adapter.vnf.CreateVnfNotification.Outputs { + public void add(String key, String value) { + Entry entry = new Entry(); + entry.setKey(key); + entry.setValue(value); + getEntry().add(entry); + } + } + + /** + * Helper class to make it easier to create this type. + */ + private static class UpdateVnfNotificationOutputs + extends org.openecomp.mso.bpmn.common.adapter.vnf.UpdateVnfNotification.Outputs { + public void add(String key, String value) { + Entry entry = new Entry(); + entry.setKey(key); + entry.setValue(value); + getEntry().add(entry); + } + } +} diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/WorkflowTestTransformer.java b/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/WorkflowTestTransformer.java index 4aa6fbe0bb..c4b236a817 100644 --- a/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/WorkflowTestTransformer.java +++ b/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/WorkflowTestTransformer.java @@ -1,21 +1,21 @@ -package org.openecomp.mso.bpmn.common; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * Allows a subclass of WorkflowTest to specify one or more WireMock - * response transformers. A transformer must be declared as a public - * static field in the subclass. For example: - *
- *     @WorkflowTestTransformer
- *     public static final ResponseTransformer sdncAdapterMockTransformer =
- *         new SDNCAdapterMockTransformer();
- * 
- */ -@Retention(RetentionPolicy.RUNTIME) -@Target(ElementType.FIELD) -public @interface WorkflowTestTransformer { +package org.openecomp.mso.bpmn.common; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * Allows a subclass of WorkflowTest to specify one or more WireMock + * response transformers. A transformer must be declared as a public + * static field in the subclass. For example: + *
+ *     @WorkflowTestTransformer
+ *     public static final ResponseTransformer sdncAdapterMockTransformer =
+ *         new SDNCAdapterMockTransformer();
+ * 
+ */ +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.FIELD) +public @interface WorkflowTestTransformer { } \ No newline at end of file diff --git a/bpmn/MSOCommonBPMN/src/test/resources/__files/CRTGVNF_queryAAIResponseVolume.xml b/bpmn/MSOCommonBPMN/src/test/resources/__files/CRTGVNF_queryAAIResponseVolume.xml index 52d2b01201..182d7c9a11 100644 --- a/bpmn/MSOCommonBPMN/src/test/resources/__files/CRTGVNF_queryAAIResponseVolume.xml +++ b/bpmn/MSOCommonBPMN/src/test/resources/__files/CRTGVNF_queryAAIResponseVolume.xml @@ -1,22 +1,22 @@ - - a8399879-31b3-4973-be26-0a0cbe776b58 - MoG_CinderVolumes_2 - MoG_CinderVolumes_2/19387dc6-060f-446e-b41f-dcfd29c73845 - VmogSvc/moge2e2 - Active - 1458839419 - - - tenant - https://aai-app-e2e.test.att.com:8443/aai/v6/cloud-infrastructure/tenants/tenant/7dd5365547234ee8937416c65507d266/ - - tenant.tenant-id - 7dd5365547234ee8937416c65507d266 - - - tenant.tenant-name - MOG-25208-D-01 - - - + + a8399879-31b3-4973-be26-0a0cbe776b58 + MoG_CinderVolumes_2 + MoG_CinderVolumes_2/19387dc6-060f-446e-b41f-dcfd29c73845 + VmogSvc/moge2e2 + Active + 1458839419 + + + tenant + https://aai-app-e2e.test.com:8443/aai/v6/cloud-infrastructure/tenants/tenant/7dd5365547234ee8937416c65507d266/ + + tenant.tenant-id + 7dd5365547234ee8937416c65507d266 + + + tenant.tenant-name + MOG-25208-D-01 + + + \ No newline at end of file diff --git a/bpmn/MSOCommonBPMN/src/test/resources/__files/CRTGVNF_queryAAIResponseVolume_idsNotMatch.xml b/bpmn/MSOCommonBPMN/src/test/resources/__files/CRTGVNF_queryAAIResponseVolume_idsNotMatch.xml index 79e7d84ed8..9b91bc5beb 100644 --- a/bpmn/MSOCommonBPMN/src/test/resources/__files/CRTGVNF_queryAAIResponseVolume_idsNotMatch.xml +++ b/bpmn/MSOCommonBPMN/src/test/resources/__files/CRTGVNF_queryAAIResponseVolume_idsNotMatch.xml @@ -1,22 +1,22 @@ - - a8399879-31b3-4973-be26-0a0cbe776b58 - MoG_CinderVolumes_2 - MoG_CinderVolumes_2/19387dc6-060f-446e-b41f-dcfd29c73845 - VmogSvc/moge2e2 - Active - 1458839419 - - - tenant - https://aai-app-e2e.test.att.com:8443/aai/v6/cloud-infrastructure/tenants/tenant/7dd5365547234ee8937416c65507d266/ - - tenant.tenant-id - 83464847234ee8937416c65507d267 - - - tenant.tenant-name - MOG-25208-D-01 - - - + + a8399879-31b3-4973-be26-0a0cbe776b58 + MoG_CinderVolumes_2 + MoG_CinderVolumes_2/19387dc6-060f-446e-b41f-dcfd29c73845 + VmogSvc/moge2e2 + Active + 1458839419 + + + tenant + https://aai-app-e2e.test.com:8443/aai/v6/cloud-infrastructure/tenants/tenant/7dd5365547234ee8937416c65507d266/ + + tenant.tenant-id + 83464847234ee8937416c65507d267 + + + tenant.tenant-name + MOG-25208-D-01 + + + \ No newline at end of file diff --git a/bpmn/MSOCommonBPMN/src/test/resources/__files/CreateServiceInstance/createServiceInstance_genericQueryByInstanceName_AAIResponse_200.xml b/bpmn/MSOCommonBPMN/src/test/resources/__files/CreateServiceInstance/createServiceInstance_genericQueryByInstanceName_AAIResponse_200.xml index 742ec13a04..fce5afafec 100644 --- a/bpmn/MSOCommonBPMN/src/test/resources/__files/CreateServiceInstance/createServiceInstance_genericQueryByInstanceName_AAIResponse_200.xml +++ b/bpmn/MSOCommonBPMN/src/test/resources/__files/CreateServiceInstance/createServiceInstance_genericQueryByInstanceName_AAIResponse_200.xml @@ -1,13 +1,13 @@ - - - - f70e927b-6087-4974-9ef8-c5e4d5847ca4 - gg0e927b-6087-5574-9ef8-c5e4d5847db5 - V1.0 - vMOG-AKRON-1234 - 1462561835 - - - - + + + + f70e927b-6087-4974-9ef8-c5e4d5847ca4 + gg0e927b-6087-5574-9ef8-c5e4d5847db5 + V1.0 + vMOG-AKRON-1234 + 1462561835 + + + + \ No newline at end of file diff --git a/bpmn/MSOCommonBPMN/src/test/resources/__files/GENDSI_getServiceInstanceResponse.xml b/bpmn/MSOCommonBPMN/src/test/resources/__files/GENDSI_getServiceInstanceResponse.xml index 4aeac5ccb8..30b0afb3dc 100644 --- a/bpmn/MSOCommonBPMN/src/test/resources/__files/GENDSI_getServiceInstanceResponse.xml +++ b/bpmn/MSOCommonBPMN/src/test/resources/__files/GENDSI_getServiceInstanceResponse.xml @@ -1,35 +1,35 @@ - - SDN-ETHERNET-INTERNET - 1234 - - - MIS/1604/0026/SW_INTERNET - - - cvlan-tag - https://aai-ext1.test.att.com:8443/aai/v2/network/vces/vce/832bace2-3fb0-49e0-a6a4-07c47223c535/port-groups/port-group/slcp1447vbc.ipag/cvlan-tags/cvlan-tag/2003/ - - cvlan-tag.cvlan-tag - 2003 - - - port-group.interface-id - slcp1447vbc.ipag - - - vce.vnf-id - 832bace2-3fb0-49e0-a6a4-07c47223c535 - - - - vce - https://aai-ext1.test.att.com:8443/aai/v2/network/vces/vce/832bace2-3fb0-49e0-a6a4-07c47223c535/ - - vce.vnf-id - 832bace2-3fb0-49e0-a6a4-07c47223c535 - - - - - + + SDN-ETHERNET-INTERNET + 1234 + + + MIS/1604/0026/SW_INTERNET + + + cvlan-tag + https://aai-ext1.test.com:8443/aai/v2/network/vces/vce/832bace2-3fb0-49e0-a6a4-07c47223c535/port-groups/port-group/slcp1447vbc.ipag/cvlan-tags/cvlan-tag/2003/ + + cvlan-tag.cvlan-tag + 2003 + + + port-group.interface-id + slcp1447vbc.ipag + + + vce.vnf-id + 832bace2-3fb0-49e0-a6a4-07c47223c535 + + + + vce + https://aai-ext1.test.com:8443/aai/v2/network/vces/vce/832bace2-3fb0-49e0-a6a4-07c47223c535/ + + vce.vnf-id + 832bace2-3fb0-49e0-a6a4-07c47223c535 + + + + + \ No newline at end of file diff --git a/bpmn/MSOCommonBPMN/src/test/resources/__files/GenericFlows/getGenericVnfByNameResponse.xml b/bpmn/MSOCommonBPMN/src/test/resources/__files/GenericFlows/getGenericVnfByNameResponse.xml index a397e5bcba..a609a35857 100644 --- a/bpmn/MSOCommonBPMN/src/test/resources/__files/GenericFlows/getGenericVnfByNameResponse.xml +++ b/bpmn/MSOCommonBPMN/src/test/resources/__files/GenericFlows/getGenericVnfByNameResponse.xml @@ -1,23 +1,23 @@ - - - 2f1cc940-455f-4ee2-9411-a7899cd4f124 - testVnfName123 - mmsc-capacity - a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb - vMMSC - pending-create - testReVer123 - - - nothing - https://aai-app-e2e.test.att.com:8443/aai/v3/network/l3-networks/l3-network/c597ab81-fece-49f4-a4f5-710cebb13c29/ - - l3-network.network-id - c597ab81-fece-49f4-a4f5-710cebb13c29 - - - - - - + + + 2f1cc940-455f-4ee2-9411-a7899cd4f124 + testVnfName123 + mmsc-capacity + a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb + vMMSC + pending-create + testReVer123 + + + nothing + https://aai-app-e2e.test.com:8443/aai/v3/network/l3-networks/l3-network/c597ab81-fece-49f4-a4f5-710cebb13c29/ + + l3-network.network-id + c597ab81-fece-49f4-a4f5-710cebb13c29 + + + + + + \ No newline at end of file diff --git a/bpmn/MSOCommonBPMN/src/test/resources/__files/GenericFlows/getGenericVnfResponse.xml b/bpmn/MSOCommonBPMN/src/test/resources/__files/GenericFlows/getGenericVnfResponse.xml index 3227a038af..2b70f0b600 100644 --- a/bpmn/MSOCommonBPMN/src/test/resources/__files/GenericFlows/getGenericVnfResponse.xml +++ b/bpmn/MSOCommonBPMN/src/test/resources/__files/GenericFlows/getGenericVnfResponse.xml @@ -1,90 +1,90 @@ - - - 2f1cc940-455f-4ee2-9411-a7899cd4f124 - testVnfName123 - mmsc-capacity - a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb - vMMSC - pending-create - - - l3-network - https://aai-app-e2e.test.att.com:8443/aai/v3/network/l3-networks/l3-network/c597ab81-fece-49f4-a4f5-710cebb13c29/ - - l3-network.network-id - c597ab81-fece-49f4-a4f5-710cebb13c29 - - - - l3-network - https://aai-app-e2e.test.att.com:8443/aai/v3/network/l3-networks/l3-network/53956c91-6e5e-49aa-88dd-535f57e66e70/ - - l3-network.network-id - 53956c91-6e5e-49aa-88dd-535f57e66e70 - - - - l3-network - https://aai-app-e2e.test.att.com:8443/aai/v3/network/l3-networks/l3-network/44e0d9e0-9334-4ec6-9344-07a96dac629f/ - - l3-network.network-id - 44e0d9e0-9334-4ec6-9344-07a96dac629f - - - - l3-network - https://aai-app-e2e.test.att.com:8443/aai/v3/network/l3-networks/l3-network/ac49d99b-5daf-4624-9f8e-188b126ea166/ - - l3-network.network-id - ac49d99b-5daf-4624-9f8e-188b126ea166 - - - - - - - - 802767b3-18a6-4432-96db-25522786aee0 - ZRDM1MMSC03 - mmsc-capacity - a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb - vMMSC - pending-create - - - l3-network - https://aai-app-e2e.test.att.com:8443/aai/v3/network/l3-networks/l3-network/c597ab81-fece-49f4-a4f5-710cebb13c29/ - - l3-network.network-id - c597ab81-fece-49f4-a4f5-710cebb13c29 - - - - l3-network - https://aai-app-e2e.test.att.com:8443/aai/v3/network/l3-networks/l3-network/53956c91-6e5e-49aa-88dd-535f57e66e70/ - - l3-network.network-id - 53956c91-6e5e-49aa-88dd-535f57e66e70 - - - - l3-network - https://aai-app-e2e.test.att.com:8443/aai/v3/network/l3-networks/l3-network/44e0d9e0-9334-4ec6-9344-07a96dac629f/ - - l3-network.network-id - 44e0d9e0-9334-4ec6-9344-07a96dac629f - - - - l3-network - https://aai-app-e2e.test.att.com:8443/aai/v3/network/l3-networks/l3-network/ac49d99b-5daf-4624-9f8e-188b126ea166/ - - l3-network.network-id - ac49d99b-5daf-4624-9f8e-188b126ea166 - - - - - - + + + 2f1cc940-455f-4ee2-9411-a7899cd4f124 + testVnfName123 + mmsc-capacity + a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb + vMMSC + pending-create + + + l3-network + https://aai-app-e2e.test.com:8443/aai/v3/network/l3-networks/l3-network/c597ab81-fece-49f4-a4f5-710cebb13c29/ + + l3-network.network-id + c597ab81-fece-49f4-a4f5-710cebb13c29 + + + + l3-network + https://aai-app-e2e.test.com:8443/aai/v3/network/l3-networks/l3-network/53956c91-6e5e-49aa-88dd-535f57e66e70/ + + l3-network.network-id + 53956c91-6e5e-49aa-88dd-535f57e66e70 + + + + l3-network + https://aai-app-e2e.test.com:8443/aai/v3/network/l3-networks/l3-network/44e0d9e0-9334-4ec6-9344-07a96dac629f/ + + l3-network.network-id + 44e0d9e0-9334-4ec6-9344-07a96dac629f + + + + l3-network + https://aai-app-e2e.test.com:8443/aai/v3/network/l3-networks/l3-network/ac49d99b-5daf-4624-9f8e-188b126ea166/ + + l3-network.network-id + ac49d99b-5daf-4624-9f8e-188b126ea166 + + + + + + + + 802767b3-18a6-4432-96db-25522786aee0 + ZRDM1MMSC03 + mmsc-capacity + a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb + vMMSC + pending-create + + + l3-network + https://aai-app-e2e.test.com:8443/aai/v3/network/l3-networks/l3-network/c597ab81-fece-49f4-a4f5-710cebb13c29/ + + l3-network.network-id + c597ab81-fece-49f4-a4f5-710cebb13c29 + + + + l3-network + https://aai-app-e2e.test.com:8443/aai/v3/network/l3-networks/l3-network/53956c91-6e5e-49aa-88dd-535f57e66e70/ + + l3-network.network-id + 53956c91-6e5e-49aa-88dd-535f57e66e70 + + + + l3-network + https://aai-app-e2e.test.com:8443/aai/v3/network/l3-networks/l3-network/44e0d9e0-9334-4ec6-9344-07a96dac629f/ + + l3-network.network-id + 44e0d9e0-9334-4ec6-9344-07a96dac629f + + + + l3-network + https://aai-app-e2e.test.com:8443/aai/v3/network/l3-networks/l3-network/ac49d99b-5daf-4624-9f8e-188b126ea166/ + + l3-network.network-id + ac49d99b-5daf-4624-9f8e-188b126ea166 + + + + + + \ No newline at end of file diff --git a/bpmn/MSOCommonBPMN/src/test/resources/__files/GenericFlows/getGenericVnfResponse_hasRelationships.xml b/bpmn/MSOCommonBPMN/src/test/resources/__files/GenericFlows/getGenericVnfResponse_hasRelationships.xml index 3227a038af..2b70f0b600 100644 --- a/bpmn/MSOCommonBPMN/src/test/resources/__files/GenericFlows/getGenericVnfResponse_hasRelationships.xml +++ b/bpmn/MSOCommonBPMN/src/test/resources/__files/GenericFlows/getGenericVnfResponse_hasRelationships.xml @@ -1,90 +1,90 @@ - - - 2f1cc940-455f-4ee2-9411-a7899cd4f124 - testVnfName123 - mmsc-capacity - a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb - vMMSC - pending-create - - - l3-network - https://aai-app-e2e.test.att.com:8443/aai/v3/network/l3-networks/l3-network/c597ab81-fece-49f4-a4f5-710cebb13c29/ - - l3-network.network-id - c597ab81-fece-49f4-a4f5-710cebb13c29 - - - - l3-network - https://aai-app-e2e.test.att.com:8443/aai/v3/network/l3-networks/l3-network/53956c91-6e5e-49aa-88dd-535f57e66e70/ - - l3-network.network-id - 53956c91-6e5e-49aa-88dd-535f57e66e70 - - - - l3-network - https://aai-app-e2e.test.att.com:8443/aai/v3/network/l3-networks/l3-network/44e0d9e0-9334-4ec6-9344-07a96dac629f/ - - l3-network.network-id - 44e0d9e0-9334-4ec6-9344-07a96dac629f - - - - l3-network - https://aai-app-e2e.test.att.com:8443/aai/v3/network/l3-networks/l3-network/ac49d99b-5daf-4624-9f8e-188b126ea166/ - - l3-network.network-id - ac49d99b-5daf-4624-9f8e-188b126ea166 - - - - - - - - 802767b3-18a6-4432-96db-25522786aee0 - ZRDM1MMSC03 - mmsc-capacity - a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb - vMMSC - pending-create - - - l3-network - https://aai-app-e2e.test.att.com:8443/aai/v3/network/l3-networks/l3-network/c597ab81-fece-49f4-a4f5-710cebb13c29/ - - l3-network.network-id - c597ab81-fece-49f4-a4f5-710cebb13c29 - - - - l3-network - https://aai-app-e2e.test.att.com:8443/aai/v3/network/l3-networks/l3-network/53956c91-6e5e-49aa-88dd-535f57e66e70/ - - l3-network.network-id - 53956c91-6e5e-49aa-88dd-535f57e66e70 - - - - l3-network - https://aai-app-e2e.test.att.com:8443/aai/v3/network/l3-networks/l3-network/44e0d9e0-9334-4ec6-9344-07a96dac629f/ - - l3-network.network-id - 44e0d9e0-9334-4ec6-9344-07a96dac629f - - - - l3-network - https://aai-app-e2e.test.att.com:8443/aai/v3/network/l3-networks/l3-network/ac49d99b-5daf-4624-9f8e-188b126ea166/ - - l3-network.network-id - ac49d99b-5daf-4624-9f8e-188b126ea166 - - - - - - + + + 2f1cc940-455f-4ee2-9411-a7899cd4f124 + testVnfName123 + mmsc-capacity + a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb + vMMSC + pending-create + + + l3-network + https://aai-app-e2e.test.com:8443/aai/v3/network/l3-networks/l3-network/c597ab81-fece-49f4-a4f5-710cebb13c29/ + + l3-network.network-id + c597ab81-fece-49f4-a4f5-710cebb13c29 + + + + l3-network + https://aai-app-e2e.test.com:8443/aai/v3/network/l3-networks/l3-network/53956c91-6e5e-49aa-88dd-535f57e66e70/ + + l3-network.network-id + 53956c91-6e5e-49aa-88dd-535f57e66e70 + + + + l3-network + https://aai-app-e2e.test.com:8443/aai/v3/network/l3-networks/l3-network/44e0d9e0-9334-4ec6-9344-07a96dac629f/ + + l3-network.network-id + 44e0d9e0-9334-4ec6-9344-07a96dac629f + + + + l3-network + https://aai-app-e2e.test.com:8443/aai/v3/network/l3-networks/l3-network/ac49d99b-5daf-4624-9f8e-188b126ea166/ + + l3-network.network-id + ac49d99b-5daf-4624-9f8e-188b126ea166 + + + + + + + + 802767b3-18a6-4432-96db-25522786aee0 + ZRDM1MMSC03 + mmsc-capacity + a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb + vMMSC + pending-create + + + l3-network + https://aai-app-e2e.test.com:8443/aai/v3/network/l3-networks/l3-network/c597ab81-fece-49f4-a4f5-710cebb13c29/ + + l3-network.network-id + c597ab81-fece-49f4-a4f5-710cebb13c29 + + + + l3-network + https://aai-app-e2e.test.com:8443/aai/v3/network/l3-networks/l3-network/53956c91-6e5e-49aa-88dd-535f57e66e70/ + + l3-network.network-id + 53956c91-6e5e-49aa-88dd-535f57e66e70 + + + + l3-network + https://aai-app-e2e.test.com:8443/aai/v3/network/l3-networks/l3-network/44e0d9e0-9334-4ec6-9344-07a96dac629f/ + + l3-network.network-id + 44e0d9e0-9334-4ec6-9344-07a96dac629f + + + + l3-network + https://aai-app-e2e.test.com:8443/aai/v3/network/l3-networks/l3-network/ac49d99b-5daf-4624-9f8e-188b126ea166/ + + l3-network.network-id + ac49d99b-5daf-4624-9f8e-188b126ea166 + + + + + + \ No newline at end of file diff --git a/bpmn/MSOCommonBPMN/src/test/resources/__files/GenericFlows/getSIUrlById.xml b/bpmn/MSOCommonBPMN/src/test/resources/__files/GenericFlows/getSIUrlById.xml index 28ce8ef1b7..b1f640f47f 100644 --- a/bpmn/MSOCommonBPMN/src/test/resources/__files/GenericFlows/getSIUrlById.xml +++ b/bpmn/MSOCommonBPMN/src/test/resources/__files/GenericFlows/getSIUrlById.xml @@ -1,6 +1,6 @@ - - - service-instance - https://aai-ext1.test.att.com:8443/aai/v7/business/customers/customer/SDN-ETHERNET-INTERNET/service-subscriptions/service-subscription/123456789/service-instances/service-instance/MIS%252F1604%252F0026%252FSW_INTERNET - + + + service-instance + https://aai-ext1.test.com:8443/aai/v7/business/customers/customer/SDN-ETHERNET-INTERNET/service-subscriptions/service-subscription/123456789/service-instances/service-instance/MIS%252F1604%252F0026%252FSW_INTERNET + \ No newline at end of file diff --git a/bpmn/MSOCommonBPMN/src/test/resources/__files/GenericFlows/getSIUrlByName.xml b/bpmn/MSOCommonBPMN/src/test/resources/__files/GenericFlows/getSIUrlByName.xml index 28ce8ef1b7..b1f640f47f 100644 --- a/bpmn/MSOCommonBPMN/src/test/resources/__files/GenericFlows/getSIUrlByName.xml +++ b/bpmn/MSOCommonBPMN/src/test/resources/__files/GenericFlows/getSIUrlByName.xml @@ -1,6 +1,6 @@ - - - service-instance - https://aai-ext1.test.att.com:8443/aai/v7/business/customers/customer/SDN-ETHERNET-INTERNET/service-subscriptions/service-subscription/123456789/service-instances/service-instance/MIS%252F1604%252F0026%252FSW_INTERNET - + + + service-instance + https://aai-ext1.test.com:8443/aai/v7/business/customers/customer/SDN-ETHERNET-INTERNET/service-subscriptions/service-subscription/123456789/service-instances/service-instance/MIS%252F1604%252F0026%252FSW_INTERNET + \ No newline at end of file diff --git a/bpmn/MSOCommonBPMN/src/test/resources/__files/GenericFlows/getServiceInstance.xml b/bpmn/MSOCommonBPMN/src/test/resources/__files/GenericFlows/getServiceInstance.xml index 5ffdda268f..84d8600eac 100644 --- a/bpmn/MSOCommonBPMN/src/test/resources/__files/GenericFlows/getServiceInstance.xml +++ b/bpmn/MSOCommonBPMN/src/test/resources/__files/GenericFlows/getServiceInstance.xml @@ -1,30 +1,30 @@ - - MIS/1604/0026/SW_INTERNET - 123456789 - - - cvlan-tag - https://aai-ext1.test.att.com:8443/aai/v2/network/vces/vce/832bace2-3fb0-49e0-a6a4-07c47223c535/port-groups/port-group/slcp1447vbc.ipag/cvlan-tags/cvlan-tag/2003/ - - cvlan-tag.cvlan-tag - 2003 - - - port-group.interface-id - slcp1447vbc.ipag - - - vce.vnf-id - 832bace2-3fb0-49e0-a6a4-07c47223c535 - - - - vce - https://aai-ext1.test.att.com:8443/aai/v2/network/vces/vce/832bace2-3fb0-49e0-a6a4-07c47223c535/ - - vce.vnf-id - 832bace2-3fb0-49e0-a6a4-07c47223c535 - - - + + MIS/1604/0026/SW_INTERNET + 123456789 + + + cvlan-tag + https://aai-ext1.test.com:8443/aai/v2/network/vces/vce/832bace2-3fb0-49e0-a6a4-07c47223c535/port-groups/port-group/slcp1447vbc.ipag/cvlan-tags/cvlan-tag/2003/ + + cvlan-tag.cvlan-tag + 2003 + + + port-group.interface-id + slcp1447vbc.ipag + + + vce.vnf-id + 832bace2-3fb0-49e0-a6a4-07c47223c535 + + + + vce + https://aai-ext1.test.com:8443/aai/v2/network/vces/vce/832bace2-3fb0-49e0-a6a4-07c47223c535/ + + vce.vnf-id + 832bace2-3fb0-49e0-a6a4-07c47223c535 + + + \ No newline at end of file diff --git a/bpmn/MSOCommonBPMN/src/test/resources/__files/GenericFlows/getServiceSubscription.xml b/bpmn/MSOCommonBPMN/src/test/resources/__files/GenericFlows/getServiceSubscription.xml index 41815d46e6..85cd5d605a 100644 --- a/bpmn/MSOCommonBPMN/src/test/resources/__files/GenericFlows/getServiceSubscription.xml +++ b/bpmn/MSOCommonBPMN/src/test/resources/__files/GenericFlows/getServiceSubscription.xml @@ -1,34 +1,34 @@ - - SDN-ETHERNET-INTERNET - 1234 - - MIS/1604/0026/SW_INTERNET - 123456789 - - - cvlan-tag - https://aai-ext1.test.att.com:8443/aai/v2/network/vces/vce/832bace2-3fb0-49e0-a6a4-07c47223c535/port-groups/port-group/slcp1447vbc.ipag/cvlan-tags/cvlan-tag/2003/ - - cvlan-tag.cvlan-tag - 2003 - - - port-group.interface-id - slcp1447vbc.ipag - - - vce.vnf-id - 832bace2-3fb0-49e0-a6a4-07c47223c535 - - - - vce - https://aai-ext1.test.att.com:8443/aai/v2/network/vces/vce/832bace2-3fb0-49e0-a6a4-07c47223c535/ - - vce.vnf-id - 832bace2-3fb0-49e0-a6a4-07c47223c535 - - - - + + SDN-ETHERNET-INTERNET + 1234 + + MIS/1604/0026/SW_INTERNET + 123456789 + + + cvlan-tag + https://aai-ext1.test.com:8443/aai/v2/network/vces/vce/832bace2-3fb0-49e0-a6a4-07c47223c535/port-groups/port-group/slcp1447vbc.ipag/cvlan-tags/cvlan-tag/2003/ + + cvlan-tag.cvlan-tag + 2003 + + + port-group.interface-id + slcp1447vbc.ipag + + + vce.vnf-id + 832bace2-3fb0-49e0-a6a4-07c47223c535 + + + + vce + https://aai-ext1.test.com:8443/aai/v2/network/vces/vce/832bace2-3fb0-49e0-a6a4-07c47223c535/ + + vce.vnf-id + 832bace2-3fb0-49e0-a6a4-07c47223c535 + + + + \ No newline at end of file diff --git a/bpmn/MSOCommonBPMN/src/test/resources/__files/GenericFlows/getVceByNameResponse.xml b/bpmn/MSOCommonBPMN/src/test/resources/__files/GenericFlows/getVceByNameResponse.xml index a83e06ee6f..7ada696cb7 100644 --- a/bpmn/MSOCommonBPMN/src/test/resources/__files/GenericFlows/getVceByNameResponse.xml +++ b/bpmn/MSOCommonBPMN/src/test/resources/__files/GenericFlows/getVceByNameResponse.xml @@ -1,97 +1,97 @@ - - 1936628a-d22f-4943-8587-a57bab2ece7a - testVnfName123 - US0112SLCP1VBRT076 - esx-vce - NVTPROV - created - 0000020 - slcp1476vbc/94a3c72b-94d5-444b-9a1f-647a36c2181d - - VPESAT-mtanjrsv126 - 135.21.249.160 - - - slcp1476vbc.vpe - e7568706-a2a9-45f8-aef8-95a0e2910953 - dvspg-VCE_VPE-slcp1476vbc - Internet - dvspg-VCE_VPE-slcp1476vbc - 0000020 - dvs-slcp1-01 - created - dvspg-VCE_VPE-slcp1476vbc/c1299f74-da35-4228-b1e0-d2fd07176196 - - - - 3012 - 0000020 - - - - - slcp1476vbc.ipag - 3477ddb6-b925-4971-ab62-c84b69634c49 - dvspg-IPAG_VCE-slcp1476vbc - Customer - dvspg-IPAG_VCE-slcp1476vbc - dvs-slcp1-01 - 0000020 - created - dvspg-IPAG_VCE-slcp1476vbc/1e9c033a-2eef-47f5-9d48-98e0b59538e7 - - - - 2003 - 0000020 - - - - - - - service-instance - https://aai-ext1.test.att.com:8443/aai/v2/business/customers/customer/011216-1602-SDNC001/service-subscriptions/service-subscription/SDN-ETHERNET-INTERNET/service-instances/service-instance/SDNC%2FVLXM%2F0112001%2F%2FSW_INTERNET/ - - service-instance.service-instance-id - SDNC/VLXM/0112001//SW_INTERNET - - - service-subscription.service-type - SDN-ETHERNET-INTERNET - - - customer.global-customer-id - 011216-1602-SDNC001 - - - - vserver - https://aai-ext1.test.att.com:8443/aai/servers/v2/3d5f3fe23821416fac2b69af65248c74/vservers/ecab47d5-3450-4507-ada9-2b3c58485c51/ - - vserver.vserver-id - ecab47d5-3450-4507-ada9-2b3c58485c51 - - - tenant.tenant-id - 3d5f3fe23821416fac2b69af65248c74 - - - - complex - https://aai-ext1.test.att.com:8443/aai/v2/cloud-infrastructure/complexes/complex/MDTWNJ21A4/ - - complex.physical-location-id - MDTWNJ21A4 - - - - availability-zone - https://aai-ext1.test.att.com:8443/aai/v2/cloud-infrastructure/availability-zones/availability-zone/slcp1-esx-az01/ - - availability-zone.availability-zone-name - slcp1-esx-az01 - - - + + 1936628a-d22f-4943-8587-a57bab2ece7a + testVnfName123 + US0112SLCP1VBRT076 + esx-vce + NVTPROV + created + 0000020 + slcp1476vbc/94a3c72b-94d5-444b-9a1f-647a36c2181d + + VPESAT-mtanjrsv126 + 135.21.249.160 + + + slcp1476vbc.vpe + e7568706-a2a9-45f8-aef8-95a0e2910953 + dvspg-VCE_VPE-slcp1476vbc + Internet + dvspg-VCE_VPE-slcp1476vbc + 0000020 + dvs-slcp1-01 + created + dvspg-VCE_VPE-slcp1476vbc/c1299f74-da35-4228-b1e0-d2fd07176196 + + + + 3012 + 0000020 + + + + + slcp1476vbc.ipag + 3477ddb6-b925-4971-ab62-c84b69634c49 + dvspg-IPAG_VCE-slcp1476vbc + Customer + dvspg-IPAG_VCE-slcp1476vbc + dvs-slcp1-01 + 0000020 + created + dvspg-IPAG_VCE-slcp1476vbc/1e9c033a-2eef-47f5-9d48-98e0b59538e7 + + + + 2003 + 0000020 + + + + + + + service-instance + https://aai-ext1.test.com:8443/aai/v2/business/customers/customer/011216-1602-SDNC001/service-subscriptions/service-subscription/SDN-ETHERNET-INTERNET/service-instances/service-instance/SDNC%2FVLXM%2F0112001%2F%2FSW_INTERNET/ + + service-instance.service-instance-id + SDNC/VLXM/0112001//SW_INTERNET + + + service-subscription.service-type + SDN-ETHERNET-INTERNET + + + customer.global-customer-id + 011216-1602-SDNC001 + + + + vserver + https://aai-ext1.test.com:8443/aai/servers/v2/3d5f3fe23821416fac2b69af65248c74/vservers/ecab47d5-3450-4507-ada9-2b3c58485c51/ + + vserver.vserver-id + ecab47d5-3450-4507-ada9-2b3c58485c51 + + + tenant.tenant-id + 3d5f3fe23821416fac2b69af65248c74 + + + + complex + https://aai-ext1.test.com:8443/aai/v2/cloud-infrastructure/complexes/complex/MDTWNJ21A4/ + + complex.physical-location-id + MDTWNJ21A4 + + + + availability-zone + https://aai-ext1.test.com:8443/aai/v2/cloud-infrastructure/availability-zones/availability-zone/slcp1-esx-az01/ + + availability-zone.availability-zone-name + slcp1-esx-az01 + + + \ No newline at end of file diff --git a/bpmn/MSOCommonBPMN/src/test/resources/__files/GenericFlows/getVceResponse.xml b/bpmn/MSOCommonBPMN/src/test/resources/__files/GenericFlows/getVceResponse.xml index a83e06ee6f..5dc3033445 100644 --- a/bpmn/MSOCommonBPMN/src/test/resources/__files/GenericFlows/getVceResponse.xml +++ b/bpmn/MSOCommonBPMN/src/test/resources/__files/GenericFlows/getVceResponse.xml @@ -1,97 +1,97 @@ - - 1936628a-d22f-4943-8587-a57bab2ece7a - testVnfName123 - US0112SLCP1VBRT076 - esx-vce - NVTPROV - created - 0000020 - slcp1476vbc/94a3c72b-94d5-444b-9a1f-647a36c2181d - - VPESAT-mtanjrsv126 - 135.21.249.160 - - - slcp1476vbc.vpe - e7568706-a2a9-45f8-aef8-95a0e2910953 - dvspg-VCE_VPE-slcp1476vbc - Internet - dvspg-VCE_VPE-slcp1476vbc - 0000020 - dvs-slcp1-01 - created - dvspg-VCE_VPE-slcp1476vbc/c1299f74-da35-4228-b1e0-d2fd07176196 - - - - 3012 - 0000020 - - - - - slcp1476vbc.ipag - 3477ddb6-b925-4971-ab62-c84b69634c49 - dvspg-IPAG_VCE-slcp1476vbc - Customer - dvspg-IPAG_VCE-slcp1476vbc - dvs-slcp1-01 - 0000020 - created - dvspg-IPAG_VCE-slcp1476vbc/1e9c033a-2eef-47f5-9d48-98e0b59538e7 - - - - 2003 - 0000020 - - - - - - - service-instance - https://aai-ext1.test.att.com:8443/aai/v2/business/customers/customer/011216-1602-SDNC001/service-subscriptions/service-subscription/SDN-ETHERNET-INTERNET/service-instances/service-instance/SDNC%2FVLXM%2F0112001%2F%2FSW_INTERNET/ - - service-instance.service-instance-id - SDNC/VLXM/0112001//SW_INTERNET - - - service-subscription.service-type - SDN-ETHERNET-INTERNET - - - customer.global-customer-id - 011216-1602-SDNC001 - - - - vserver - https://aai-ext1.test.att.com:8443/aai/servers/v2/3d5f3fe23821416fac2b69af65248c74/vservers/ecab47d5-3450-4507-ada9-2b3c58485c51/ - - vserver.vserver-id - ecab47d5-3450-4507-ada9-2b3c58485c51 - - - tenant.tenant-id - 3d5f3fe23821416fac2b69af65248c74 - - - - complex - https://aai-ext1.test.att.com:8443/aai/v2/cloud-infrastructure/complexes/complex/MDTWNJ21A4/ - - complex.physical-location-id - MDTWNJ21A4 - - - - availability-zone - https://aai-ext1.test.att.com:8443/aai/v2/cloud-infrastructure/availability-zones/availability-zone/slcp1-esx-az01/ - - availability-zone.availability-zone-name - slcp1-esx-az01 - - - + + 1936628a-d22f-4943-8587-a57bab2ece7a + testVnfName123 + US0112SLCP1VBRT076 + esx-vce + NVTPROV + created + 0000020 + slcp1476vbc/94a3c72b-94d5-444b-9a1f-647a36c2181d + + VPESAT-mtanjrsv126 + 135.21.249.160 + + + slcp1476vbc.vpe + e7568706-a2a9-45f8-aef8-95a0e2910953 + dvspg-VCE_VPE-slcp1476vbc + Internet + dvspg-VCE_VPE-slcp1476vbc + 0000020 + dvs-slcp1-01 + created + dvspg-VCE_VPE-slcp1476vbc/c1299f74-da35-4228-b1e0-d2fd07176196 + + + + 3012 + 0000020 + + + + + slcp1476vbc.ipag + 3477ddb6-b925-4971-ab62-c84b69634c49 + dvspg-IPAG_VCE-slcp1476vbc + Customer + dvspg-IPAG_VCE-slcp1476vbc + dvs-slcp1-01 + 0000020 + created + dvspg-IPAG_VCE-slcp1476vbc/1e9c033a-2eef-47f5-9d48-98e0b59538e7 + + + + 2003 + 0000020 + + + + + + + service-instance + https://aai-ext1.test.com:8443/aai/v2/business/customers/customer/011216-1602-SDNC001/service-subscriptions/service-subscription/SDN-ETHERNET-INTERNET/service-instances/service-instance/SDNC%2FVLXM%2F0112001%2F%2FSW_INTERNET/ + + service-instance.service-instance-id + SDNC/VLXM/0112001//SW_INTERNET + + + service-subscription.service-type + SDN-ETHERNET-INTERNET + + + customer.global-customer-id + 011216-1602-SDNC001 + + + + vserver + https://aai-ext1.test.com:8443/aai/servers/v2/3d5f3fe23821416fac2b69af65248c74/vservers/ecab47d5-3450-4507-ada9-2b3c58485c51/ + + vserver.vserver-id + ecab47d5-3450-4507-ada9-2b3c58485c51 + + + tenant.tenant-id + 3d5f3fe23821416fac2b69af65248c74 + + + + complex + https://aai-ext1.test.com:8443/aai/v2/cloud-infrastructure/complexes/complex/MDTWNJ21A4/ + + complex.physical-location-id + MDTWNJ21A4 + + + + availability-zone + https://aai-ext1.test..com:8443/aai/v2/cloud-infrastructure/availability-zones/availability-zone/slcp1-esx-az01/ + + availability-zone.availability-zone-name + slcp1-esx-az01 + + + \ No newline at end of file diff --git a/bpmn/MSOCommonBPMN/src/test/resources/__files/SDN-ETHERNET-INTERNET/SDNCAdapterV1mock/sdncadaptercallbackrequest.xml b/bpmn/MSOCommonBPMN/src/test/resources/__files/SDN-ETHERNET-INTERNET/SDNCAdapterV1mock/sdncadaptercallbackrequest.xml index b72004778b..3d1e03916d 100644 --- a/bpmn/MSOCommonBPMN/src/test/resources/__files/SDN-ETHERNET-INTERNET/SDNCAdapterV1mock/sdncadaptercallbackrequest.xml +++ b/bpmn/MSOCommonBPMN/src/test/resources/__files/SDN-ETHERNET-INTERNET/SDNCAdapterV1mock/sdncadaptercallbackrequest.xml @@ -1,350 +1,350 @@ - - - - - - - testRequestId - 200 - OK - - <layer3-service-list xmlns="com:att:sdnctl:l3api"> - <service-instance-id>FK/VLXM/003717//SW_INTERNET</service-instance-id> - <service-status> - <rpc-name>service-configuration-operation</rpc-name> - <rpc-action>activate</rpc-action> - <request-status>synccomplete</request-status> - <final-indicator>N</final-indicator> - <l3sdn-action>Layer3ServiceActivateRequest</l3sdn-action> - <l3sdn-subaction>SUPP</l3sdn-subaction> - <response-timestamp>2015-04-28T21:32:11.386Z</response-timestamp> - </service-status> - <service-data> - <internet-evc-access-information> - <ip-version>ds</ip-version> - <internet-evc-speed-value>8</internet-evc-speed-value> - <internet-evc-speed-units>Mbps</internet-evc-speed-units> - </internet-evc-access-information> - <vr-lan xmlns="com:att:sdnctl:l3api"> - <vr-lan-interface> - <static-routes> - <v6-static-routes> - <v6-next-hop-address>2001:1890:12e3:2da::</v6-next-hop-address> - <v6-static-route-prefix>2001:1890:12e3:2da::</v6-static-route-prefix> - <v6-static-route-prefix-length>28</v6-static-route-prefix-length> - </v6-static-routes> - <v4-static-routes> - <v4-static-route-prefix>255.255.252.1</v4-static-route-prefix> - <v4-next-hop-address>192.168.1.15</v4-next-hop-address> - <v4-static-route-prefix-length>28</v4-static-route-prefix-length> - </v4-static-routes> - <v6-static-routes> - <v6-next-hop-address>2001:1890:12e3:2da::</v6-next-hop-address> - <v6-static-route-prefix>2001:1890:12e3:2da::</v6-static-route-prefix> - <v6-static-route-prefix-length>28</v6-static-route-prefix-length> - </v6-static-routes> - <v4-static-routes> - <v4-static-route-prefix>255.255.252.2</v4-static-route-prefix> - <v4-next-hop-address>192.168.1.15</v4-next-hop-address> - <v4-static-route-prefix-length>28</v4-static-route-prefix-length> - </v4-static-routes> - <v4-static-routes> - <v4-static-route-prefix>255.255.252.3</v4-static-route-prefix> - <v4-next-hop-address>192.168.1.15</v4-next-hop-address> - <v4-static-route-prefix-length>28</v4-static-route-prefix-length> - </v4-static-routes> - </static-routes> - <dhcp> - <v6-dhcp-server-enabled>N</v6-dhcp-server-enabled> - <v4-dhcp-server-enabled>Y</v4-dhcp-server-enabled> - <use-v6-default-pool>N</use-v6-default-pool> - <excluded-v4-dhcp-addresses-from-default-pool> - <excluded-v4-address>192.168.1.7</excluded-v4-address> - </excluded-v4-dhcp-addresses-from-default-pool> - <excluded-v4-dhcp-addresses-from-default-pool> - <excluded-v4-address>192.168.1.8</excluded-v4-address> - </excluded-v4-dhcp-addresses-from-default-pool> - <v4-dhcp-pools> - <v4-dhcp-relay-next-hop-address>1.1.1.1</v4-dhcp-relay-next-hop-address> - <v4-dhcp-pool-prefix-length>28</v4-dhcp-pool-prefix-length> - <excluded-v4-addresses> - <excluded-v4-address>192.168.1.5</excluded-v4-address> - </excluded-v4-addresses> - <v4-dhcp-relay-gateway-address>2.2.2.1</v4-dhcp-relay-gateway-address> - <excluded-v4-addresses> - <excluded-v4-address>192.168.1.6</excluded-v4-address> - </excluded-v4-addresses> - <v4-dhcp-pool-prefix>192.155.2.3</v4-dhcp-pool-prefix> - </v4-dhcp-pools> - <v4-dhcp-pools> - <v4-dhcp-relay-next-hop-address>1.1.1.2</v4-dhcp-relay-next-hop-address> - <v4-dhcp-pool-prefix-length>28</v4-dhcp-pool-prefix-length> - <excluded-v4-addresses> - <excluded-v4-address>192.168.1.6</excluded-v4-address> - </excluded-v4-addresses> - <v4-dhcp-relay-gateway-address>2.2.2.2</v4-dhcp-relay-gateway-address> - <excluded-v4-addresses> - <excluded-v4-address>192.168.1.7</excluded-v4-address> - </excluded-v4-addresses> - <v4-dhcp-pool-prefix>192.155.2.4</v4-dhcp-pool-prefix> - </v4-dhcp-pools> - <use-v4-default-pool>Y</use-v4-default-pool> - <excluded-v6-dhcp-addresses-from-default-pool> - <excluded-v6-address>1:5</excluded-v6-address> - </excluded-v6-dhcp-addresses-from-default-pool> - <excluded-v6-dhcp-addresses-from-default-pool> - <excluded-v6-address>1:6</excluded-v6-address> - </excluded-v6-dhcp-addresses-from-default-pool> - <v6-dhcp-pools> - <v6-dhcp-relay-next-hop-address>4:4</v6-dhcp-relay-next-hop-address> - <v6-dhcp-pool-prefix-length>28</v6-dhcp-pool-prefix-length> - <excluded-v6-addresses> - <excluded-v6-address>1:1</excluded-v6-address> - </excluded-v6-addresses> - <v6-dhcp-relay-gateway-address>3:3</v6-dhcp-relay-gateway-address> - <excluded-v6-addresses> - <excluded-v6-address>2:2</excluded-v6-address> - </excluded-v6-addresses> - <v6-dhcp-pool-prefix>0:0</v6-dhcp-pool-prefix> - </v6-dhcp-pools> - <v6-dhcp-pools> - <v6-dhcp-relay-next-hop-address>4:4</v6-dhcp-relay-next-hop-address> - <v6-dhcp-pool-prefix-length>28</v6-dhcp-pool-prefix-length> - <excluded-v6-addresses> - <excluded-v6-address>1:1</excluded-v6-address> - </excluded-v6-addresses> - <v6-dhcp-relay-gateway-address>3:3</v6-dhcp-relay-gateway-address> - <excluded-v6-addresses> - <excluded-v6-address>2:2</excluded-v6-address> - </excluded-v6-addresses> - <v6-dhcp-pool-prefix>0:0</v6-dhcp-pool-prefix> - </v6-dhcp-pools> - </dhcp> - <firewall-lite> - <stateful-firewall-lite-v6-enabled>N</stateful-firewall-lite-v6-enabled> - <stateful-firewall-lite-v4-enabled>Y</stateful-firewall-lite-v4-enabled> - <v4-firewall-packet-filters> - <v4-firewall-prefix>0.0.0.1</v4-firewall-prefix> - <v4-firewall-prefix-length>1</v4-firewall-prefix-length> - <allow-icmp-ping>Y</allow-icmp-ping> - <udp-ports> - <port-number>1</port-number> - </udp-ports> - <tcp-ports> - <port-number>1</port-number> - </tcp-ports> - </v4-firewall-packet-filters> - <v4-firewall-packet-filters> - <v4-firewall-prefix>0.0.0.2</v4-firewall-prefix> - <v4-firewall-prefix-length>2</v4-firewall-prefix-length> - <allow-icmp-ping>Y</allow-icmp-ping> - <udp-ports> - <port-number>2</port-number> - </udp-ports> - <tcp-ports> - <port-number>2</port-number> - </tcp-ports> - </v4-firewall-packet-filters> - <v6-firewall-packet-filters> - <v6-firewall-prefix>:</v6-firewall-prefix> - <v6-firewall-prefix-length>0</v6-firewall-prefix-length> - <allow-icmp-ping>Y</allow-icmp-ping> - <udp-ports> - <port-number>3</port-number> - </udp-ports> - <tcp-ports> - <port-number>3</port-number> - </tcp-ports> - </v6-firewall-packet-filters> - <v6-firewall-packet-filters> - <v6-firewall-prefix>:</v6-firewall-prefix> - <v6-firewall-prefix-length>1</v6-firewall-prefix-length> - <allow-icmp-ping>Y</allow-icmp-ping> - <udp-ports> - <port-number>4</port-number> - </udp-ports> - <tcp-ports> - <port-number>4</port-number> - </tcp-ports> - </v6-firewall-packet-filters> - </firewall-lite> - <pat> - <v4-pat-pools> - <v4-pat-pool-prefix>192.168.1.44</v4-pat-pool-prefix> - <v4-pat-pool-next-hop-address>192.168.1.5</v4-pat-pool-next-hop-address> - <v4-pat-pool-prefix-length>0</v4-pat-pool-prefix-length> - </v4-pat-pools> - <use-v4-default-pool>Y</use-v4-default-pool> - <v4-pat-enabled>N</v4-pat-enabled> - <v4-pat-pools> - <v4-pat-pool-prefix>192.168.1.45</v4-pat-pool-prefix> - <v4-pat-pool-next-hop-address>192.168.1.6</v4-pat-pool-next-hop-address> - <v4-pat-pool-prefix-length>28</v4-pat-pool-prefix-length> - </v4-pat-pools> - </pat> - <nat> - <v4-nat-enabled>Y</v4-nat-enabled> - <v4-nat-mapping-entries> - <v4-nat-internal>0.0.0.0</v4-nat-internal> - <v4-nat-next-hop-address>0.0.0.0</v4-nat-next-hop-address> - <v4-nat-external>0.0.0.0</v4-nat-external> - </v4-nat-mapping-entries> - <v4-nat-mapping-entries> - <v4-nat-internal>0.0.0.1</v4-nat-internal> - <v4-nat-next-hop-address>0.0.0.1</v4-nat-next-hop-address> - <v4-nat-external>0.0.0.1</v4-nat-external> - </v4-nat-mapping-entries> - </nat> - <vr-designation>primary</vr-designation> - <v4-vce-loopback-address>162.200.3.144</v4-vce-loopback-address> - <v6-vr-lan-prefix-length>64</v6-vr-lan-prefix-length> - <v6-vce-wan-address>2001:1890:12e3:2da::</v6-vce-wan-address> - <v6-vr-lan-prefix>2620:0:10d0:f:ffff:ffff:ffff:fffe</v6-vr-lan-prefix> - <v4-vr-lan-prefix-length>24</v4-vr-lan-prefix-length> - <v4-vr-lan-prefix>10.192.27.254</v4-vr-lan-prefix> - <v4-public-lan-prefixes> - <t-provided-v4-lan-public-prefixes> - <request-index>1</request-index> - <v4-next-hop-address>192.168.1.2</v4-next-hop-address> - <v4-lan-public-prefix>192.168.1.1</v4-lan-public-prefix> - <v4-lan-public-prefix-length>28</v4-lan-public-prefix-length> - </t-provided-v4-lan-public-prefixes> - <t-provided-v4-lan-public-prefixes> - <request-index>1</request-index> - <v4-next-hop-address>192.168.1.72</v4-next-hop-address> - <v4-lan-public-prefix>192.168.1.71</v4-lan-public-prefix> - <v4-lan-public-prefix-length>28</v4-lan-public-prefix-length> - </t-provided-v4-lan-public-prefixes> - <t-provided-v4-lan-public-prefixes> - <request-index>1</request-index> - <v4-next-hop-address>192.168.1.68</v4-next-hop-address> - <v4-lan-public-prefix>192.168.1.67</v4-lan-public-prefix> - <v4-lan-public-prefix-length>28</v4-lan-public-prefix-length> - </t-provided-v4-lan-public-prefixes> - </v4-public-lan-prefixes> - <v6-public-lan-prefixes> - <t-provided-v6-lan-public-prefixes> - <request-index>1</request-index> - <v6-next-hop-address>2001:1890:12e3:2da::</v6-next-hop-address> - <v6-lan-public-prefix>2001:1890:12e3:2da::</v6-lan-public-prefix> - <v6-lan-public-prefix-length>28</v6-lan-public-prefix-length> - </t-provided-v6-lan-public-prefixes> - <t-provided-v6-lan-public-prefixes> - <request-index>1</request-index> - <v6-next-hop-address>2001:1890:12e3:2da::</v6-next-hop-address> - <v6-lan-public-prefix>2001:1890:12e3:3da::</v6-lan-public-prefix> - <v6-lan-public-prefix-length>28</v6-lan-public-prefix-length> - </t-provided-v6-lan-public-prefixes> - <t-provided-v6-lan-public-prefixes> - <request-index>1</request-index> - <v6-next-hop-address>2001:1890:12e3:2da::</v6-next-hop-address> - <v6-lan-public-prefix>2001:1890:12e3:4da::</v6-lan-public-prefix> - <v6-lan-public-prefix-length>28</v6-lan-public-prefix-length> - </t-provided-v6-lan-public-prefixes> - </v6-public-lan-prefixes> - </vr-lan-interface> - <routing-protocol>none</routing-protocol> - </vr-lan> -<ucpe-vms-service-information> - <transport-service-information> - <transport-service-type>AVPN</transport-service-type> - <access-circuit-info> - <access-circuit-id>1</access-circuit-id> - <dual-mode>Active</dual-mode> - </access-circuit-info> - <access-circuit-info> - <access-circuit-id>2</access-circuit-id> - <dual-mode>Standby</dual-mode> - </access-circuit-info> - </transport-service-information> - <ucpe-information> - <ucpe-host-name>hostname</ucpe-host-name> - <ucpe-activation-code>activecode</ucpe-activation-code> - <out-of-band-management-modem>OOB</out-of-band-management-modem> - </ucpe-information> - <vnf-list> - <vnf-information> - <vnf-instance-id>1</vnf-instance-id> - <vnf-sequence-number>1</vnf-sequence-number> - <vnf-type>ZZ</vnf-type> - <vnf-vendor>JUNIPER</vnf-vendor> - <vnf-model>MODEL1</vnf-model> - <vnf-id>1</vnf-id> - <prov-status>1</prov-status> - <operational-state>1</operational-state> - <orchestration-status>1</orchestration-status> - <equipment-role>1</equipment-role> - </vnf-information> - <vnf-information> - <vnf-instance-id>2</vnf-instance-id> - <vnf-sequence-number>2</vnf-sequence-number> - <vnf-type>HY</vnf-type> - <vnf-vendor>JUNIPER</vnf-vendor> - <vnf-model>MODEL2</vnf-model> - <vnf-id>2</vnf-id> - <prov-status>2</prov-status> - <operational-state>2</operational-state> - <orchestration-status>2</orchestration-status> - <equipment-role>2</equipment-role> - </vnf-information> - </vnf-list> - </ucpe-vms-service-information> - <request-information> - <request-action>Layer3ServiceActivateRequest</request-action> - <order-number>4281555</order-number> - <request-id>155415ab-b4a7-4382-b4c6-d17d9sm42855</request-id> - <notification-url>https://csi-tst-q22.it.att.com:22443/Services/com/cingular/csi/sdn/SendManagedNetworkStatusNotification.jws</notification-url> - <source>OMX</source> - <order-version>1</order-version> - </request-information> - <sdnc-request-header> - <svc-action>activate</svc-action> - <svc-notification-url>https://msojra.mtsnjdcp1.aic.cip.att.com:8443/adapters/rest/SDNCNotify</svc-notification-url> - <svc-request-id>5b1f3c5d-cdf9-488d-8a4b-d3f1229d7760</svc-request-id> - </sdnc-request-header> - <l2-homing-information> - <topology>MultiPoint</topology> - <preferred-aic-clli>MTSNJA4LCP1</preferred-aic-clli> - <evc-name>AS/VLXM/003717//SW</evc-name> - </l2-homing-information> - <service-information> - <service-instance-id>FK/VLXM/003717//SW_INTERNET</service-instance-id> - <subscriber-name>ST E2E Test42855_1300004281555</subscriber-name> - <service-type>SDN-ETHERNET-INTERNET</service-type> - </service-information> - <internet-service-change-details> - <internet-evc-speed-value>10</internet-evc-speed-value> - <internet-evc-speed-units>Kbps</internet-evc-speed-units> - <t-provided-v4-lan-public-prefixes> - <request-index>1</request-index> - <v4-next-hop-address>192.168.1.15</v4-next-hop-address> - <v4-lan-public-prefix>192.168.1.15</v4-lan-public-prefix> - <v4-lan-public-prefix-length>28</v4-lan-public-prefix-length> - </t-provided-v4-lan-public-prefixes> - <t-provided-v4-lan-public-prefixes> - <request-index>2</request-index> - <v4-next-hop-address>192.168.1.16</v4-next-hop-address> - <v4-lan-public-prefix>192.168.1.16</v4-lan-public-prefix> - <v4-lan-public-prefix-length>28</v4-lan-public-prefix-length> - </t-provided-v4-lan-public-prefixes> - <t-provided-v6-lan-public-prefixes> - <request-index>1</request-index> - <v6-next-hop-address>2001:1890:12e3:2da::</v6-next-hop-address> - <v6-lan-public-prefix>2001:1890:12e3:2da::</v6-lan-public-prefix> - <v6-lan-public-prefix-length>28</v6-lan-public-prefix-length> - </t-provided-v6-lan-public-prefixes> - <t-provided-v6-lan-public-prefixes> - <request-index>1</request-index> - <v6-next-hop-address>2001:1890:12e3:2da::</v6-next-hop-address> - <v6-lan-public-prefix>2001:1890:12e3:2da::</v6-lan-public-prefix> - <v6-lan-public-prefix-length>28</v6-lan-public-prefix-length> - </t-provided-v6-lan-public-prefixes> - </internet-service-change-details> - </service-data> - </layer3-service-list> - - - - + + + + + + + testRequestId + 200 + OK + + <layer3-service-list xmlns="com:att:sdnctl:l3api"> + <service-instance-id>FK/VLXM/003717//SW_INTERNET</service-instance-id> + <service-status> + <rpc-name>service-configuration-operation</rpc-name> + <rpc-action>activate</rpc-action> + <request-status>synccomplete</request-status> + <final-indicator>N</final-indicator> + <l3sdn-action>Layer3ServiceActivateRequest</l3sdn-action> + <l3sdn-subaction>SUPP</l3sdn-subaction> + <response-timestamp>2015-04-28T21:32:11.386Z</response-timestamp> + </service-status> + <service-data> + <internet-evc-access-information> + <ip-version>ds</ip-version> + <internet-evc-speed-value>8</internet-evc-speed-value> + <internet-evc-speed-units>Mbps</internet-evc-speed-units> + </internet-evc-access-information> + <vr-lan xmlns="com:att:sdnctl:l3api"> + <vr-lan-interface> + <static-routes> + <v6-static-routes> + <v6-next-hop-address>2001:1890:12e3:2da::</v6-next-hop-address> + <v6-static-route-prefix>2001:1890:12e3:2da::</v6-static-route-prefix> + <v6-static-route-prefix-length>28</v6-static-route-prefix-length> + </v6-static-routes> + <v4-static-routes> + <v4-static-route-prefix>255.255.252.1</v4-static-route-prefix> + <v4-next-hop-address>192.168.1.15</v4-next-hop-address> + <v4-static-route-prefix-length>28</v4-static-route-prefix-length> + </v4-static-routes> + <v6-static-routes> + <v6-next-hop-address>2001:1890:12e3:2da::</v6-next-hop-address> + <v6-static-route-prefix>2001:1890:12e3:2da::</v6-static-route-prefix> + <v6-static-route-prefix-length>28</v6-static-route-prefix-length> + </v6-static-routes> + <v4-static-routes> + <v4-static-route-prefix>255.255.252.2</v4-static-route-prefix> + <v4-next-hop-address>192.168.1.15</v4-next-hop-address> + <v4-static-route-prefix-length>28</v4-static-route-prefix-length> + </v4-static-routes> + <v4-static-routes> + <v4-static-route-prefix>255.255.252.3</v4-static-route-prefix> + <v4-next-hop-address>192.168.1.15</v4-next-hop-address> + <v4-static-route-prefix-length>28</v4-static-route-prefix-length> + </v4-static-routes> + </static-routes> + <dhcp> + <v6-dhcp-server-enabled>N</v6-dhcp-server-enabled> + <v4-dhcp-server-enabled>Y</v4-dhcp-server-enabled> + <use-v6-default-pool>N</use-v6-default-pool> + <excluded-v4-dhcp-addresses-from-default-pool> + <excluded-v4-address>192.168.1.7</excluded-v4-address> + </excluded-v4-dhcp-addresses-from-default-pool> + <excluded-v4-dhcp-addresses-from-default-pool> + <excluded-v4-address>192.168.1.8</excluded-v4-address> + </excluded-v4-dhcp-addresses-from-default-pool> + <v4-dhcp-pools> + <v4-dhcp-relay-next-hop-address>1.1.1.1</v4-dhcp-relay-next-hop-address> + <v4-dhcp-pool-prefix-length>28</v4-dhcp-pool-prefix-length> + <excluded-v4-addresses> + <excluded-v4-address>192.168.1.5</excluded-v4-address> + </excluded-v4-addresses> + <v4-dhcp-relay-gateway-address>2.2.2.1</v4-dhcp-relay-gateway-address> + <excluded-v4-addresses> + <excluded-v4-address>192.168.1.6</excluded-v4-address> + </excluded-v4-addresses> + <v4-dhcp-pool-prefix>192.155.2.3</v4-dhcp-pool-prefix> + </v4-dhcp-pools> + <v4-dhcp-pools> + <v4-dhcp-relay-next-hop-address>1.1.1.2</v4-dhcp-relay-next-hop-address> + <v4-dhcp-pool-prefix-length>28</v4-dhcp-pool-prefix-length> + <excluded-v4-addresses> + <excluded-v4-address>192.168.1.6</excluded-v4-address> + </excluded-v4-addresses> + <v4-dhcp-relay-gateway-address>2.2.2.2</v4-dhcp-relay-gateway-address> + <excluded-v4-addresses> + <excluded-v4-address>192.168.1.7</excluded-v4-address> + </excluded-v4-addresses> + <v4-dhcp-pool-prefix>192.155.2.4</v4-dhcp-pool-prefix> + </v4-dhcp-pools> + <use-v4-default-pool>Y</use-v4-default-pool> + <excluded-v6-dhcp-addresses-from-default-pool> + <excluded-v6-address>1:5</excluded-v6-address> + </excluded-v6-dhcp-addresses-from-default-pool> + <excluded-v6-dhcp-addresses-from-default-pool> + <excluded-v6-address>1:6</excluded-v6-address> + </excluded-v6-dhcp-addresses-from-default-pool> + <v6-dhcp-pools> + <v6-dhcp-relay-next-hop-address>4:4</v6-dhcp-relay-next-hop-address> + <v6-dhcp-pool-prefix-length>28</v6-dhcp-pool-prefix-length> + <excluded-v6-addresses> + <excluded-v6-address>1:1</excluded-v6-address> + </excluded-v6-addresses> + <v6-dhcp-relay-gateway-address>3:3</v6-dhcp-relay-gateway-address> + <excluded-v6-addresses> + <excluded-v6-address>2:2</excluded-v6-address> + </excluded-v6-addresses> + <v6-dhcp-pool-prefix>0:0</v6-dhcp-pool-prefix> + </v6-dhcp-pools> + <v6-dhcp-pools> + <v6-dhcp-relay-next-hop-address>4:4</v6-dhcp-relay-next-hop-address> + <v6-dhcp-pool-prefix-length>28</v6-dhcp-pool-prefix-length> + <excluded-v6-addresses> + <excluded-v6-address>1:1</excluded-v6-address> + </excluded-v6-addresses> + <v6-dhcp-relay-gateway-address>3:3</v6-dhcp-relay-gateway-address> + <excluded-v6-addresses> + <excluded-v6-address>2:2</excluded-v6-address> + </excluded-v6-addresses> + <v6-dhcp-pool-prefix>0:0</v6-dhcp-pool-prefix> + </v6-dhcp-pools> + </dhcp> + <firewall-lite> + <stateful-firewall-lite-v6-enabled>N</stateful-firewall-lite-v6-enabled> + <stateful-firewall-lite-v4-enabled>Y</stateful-firewall-lite-v4-enabled> + <v4-firewall-packet-filters> + <v4-firewall-prefix>0.0.0.1</v4-firewall-prefix> + <v4-firewall-prefix-length>1</v4-firewall-prefix-length> + <allow-icmp-ping>Y</allow-icmp-ping> + <udp-ports> + <port-number>1</port-number> + </udp-ports> + <tcp-ports> + <port-number>1</port-number> + </tcp-ports> + </v4-firewall-packet-filters> + <v4-firewall-packet-filters> + <v4-firewall-prefix>0.0.0.2</v4-firewall-prefix> + <v4-firewall-prefix-length>2</v4-firewall-prefix-length> + <allow-icmp-ping>Y</allow-icmp-ping> + <udp-ports> + <port-number>2</port-number> + </udp-ports> + <tcp-ports> + <port-number>2</port-number> + </tcp-ports> + </v4-firewall-packet-filters> + <v6-firewall-packet-filters> + <v6-firewall-prefix>:</v6-firewall-prefix> + <v6-firewall-prefix-length>0</v6-firewall-prefix-length> + <allow-icmp-ping>Y</allow-icmp-ping> + <udp-ports> + <port-number>3</port-number> + </udp-ports> + <tcp-ports> + <port-number>3</port-number> + </tcp-ports> + </v6-firewall-packet-filters> + <v6-firewall-packet-filters> + <v6-firewall-prefix>:</v6-firewall-prefix> + <v6-firewall-prefix-length>1</v6-firewall-prefix-length> + <allow-icmp-ping>Y</allow-icmp-ping> + <udp-ports> + <port-number>4</port-number> + </udp-ports> + <tcp-ports> + <port-number>4</port-number> + </tcp-ports> + </v6-firewall-packet-filters> + </firewall-lite> + <pat> + <v4-pat-pools> + <v4-pat-pool-prefix>192.168.1.44</v4-pat-pool-prefix> + <v4-pat-pool-next-hop-address>192.168.1.5</v4-pat-pool-next-hop-address> + <v4-pat-pool-prefix-length>0</v4-pat-pool-prefix-length> + </v4-pat-pools> + <use-v4-default-pool>Y</use-v4-default-pool> + <v4-pat-enabled>N</v4-pat-enabled> + <v4-pat-pools> + <v4-pat-pool-prefix>192.168.1.45</v4-pat-pool-prefix> + <v4-pat-pool-next-hop-address>192.168.1.6</v4-pat-pool-next-hop-address> + <v4-pat-pool-prefix-length>28</v4-pat-pool-prefix-length> + </v4-pat-pools> + </pat> + <nat> + <v4-nat-enabled>Y</v4-nat-enabled> + <v4-nat-mapping-entries> + <v4-nat-internal>0.0.0.0</v4-nat-internal> + <v4-nat-next-hop-address>0.0.0.0</v4-nat-next-hop-address> + <v4-nat-external>0.0.0.0</v4-nat-external> + </v4-nat-mapping-entries> + <v4-nat-mapping-entries> + <v4-nat-internal>0.0.0.1</v4-nat-internal> + <v4-nat-next-hop-address>0.0.0.1</v4-nat-next-hop-address> + <v4-nat-external>0.0.0.1</v4-nat-external> + </v4-nat-mapping-entries> + </nat> + <vr-designation>primary</vr-designation> + <v4-vce-loopback-address>162.200.3.144</v4-vce-loopback-address> + <v6-vr-lan-prefix-length>64</v6-vr-lan-prefix-length> + <v6-vce-wan-address>2001:1890:12e3:2da::</v6-vce-wan-address> + <v6-vr-lan-prefix>2620:0:10d0:f:ffff:ffff:ffff:fffe</v6-vr-lan-prefix> + <v4-vr-lan-prefix-length>24</v4-vr-lan-prefix-length> + <v4-vr-lan-prefix>10.192.27.254</v4-vr-lan-prefix> + <v4-public-lan-prefixes> + <t-provided-v4-lan-public-prefixes> + <request-index>1</request-index> + <v4-next-hop-address>192.168.1.2</v4-next-hop-address> + <v4-lan-public-prefix>192.168.1.1</v4-lan-public-prefix> + <v4-lan-public-prefix-length>28</v4-lan-public-prefix-length> + </t-provided-v4-lan-public-prefixes> + <t-provided-v4-lan-public-prefixes> + <request-index>1</request-index> + <v4-next-hop-address>192.168.1.72</v4-next-hop-address> + <v4-lan-public-prefix>192.168.1.71</v4-lan-public-prefix> + <v4-lan-public-prefix-length>28</v4-lan-public-prefix-length> + </t-provided-v4-lan-public-prefixes> + <t-provided-v4-lan-public-prefixes> + <request-index>1</request-index> + <v4-next-hop-address>192.168.1.68</v4-next-hop-address> + <v4-lan-public-prefix>192.168.1.67</v4-lan-public-prefix> + <v4-lan-public-prefix-length>28</v4-lan-public-prefix-length> + </t-provided-v4-lan-public-prefixes> + </v4-public-lan-prefixes> + <v6-public-lan-prefixes> + <t-provided-v6-lan-public-prefixes> + <request-index>1</request-index> + <v6-next-hop-address>2001:1890:12e3:2da::</v6-next-hop-address> + <v6-lan-public-prefix>2001:1890:12e3:2da::</v6-lan-public-prefix> + <v6-lan-public-prefix-length>28</v6-lan-public-prefix-length> + </t-provided-v6-lan-public-prefixes> + <t-provided-v6-lan-public-prefixes> + <request-index>1</request-index> + <v6-next-hop-address>2001:1890:12e3:2da::</v6-next-hop-address> + <v6-lan-public-prefix>2001:1890:12e3:3da::</v6-lan-public-prefix> + <v6-lan-public-prefix-length>28</v6-lan-public-prefix-length> + </t-provided-v6-lan-public-prefixes> + <t-provided-v6-lan-public-prefixes> + <request-index>1</request-index> + <v6-next-hop-address>2001:1890:12e3:2da::</v6-next-hop-address> + <v6-lan-public-prefix>2001:1890:12e3:4da::</v6-lan-public-prefix> + <v6-lan-public-prefix-length>28</v6-lan-public-prefix-length> + </t-provided-v6-lan-public-prefixes> + </v6-public-lan-prefixes> + </vr-lan-interface> + <routing-protocol>none</routing-protocol> + </vr-lan> +<ucpe-vms-service-information> + <transport-service-information> + <transport-service-type>AVPN</transport-service-type> + <access-circuit-info> + <access-circuit-id>1</access-circuit-id> + <dual-mode>Active</dual-mode> + </access-circuit-info> + <access-circuit-info> + <access-circuit-id>2</access-circuit-id> + <dual-mode>Standby</dual-mode> + </access-circuit-info> + </transport-service-information> + <ucpe-information> + <ucpe-host-name>hostname</ucpe-host-name> + <ucpe-activation-code>activecode</ucpe-activation-code> + <out-of-band-management-modem>OOB</out-of-band-management-modem> + </ucpe-information> + <vnf-list> + <vnf-information> + <vnf-instance-id>1</vnf-instance-id> + <vnf-sequence-number>1</vnf-sequence-number> + <vnf-type>ZZ</vnf-type> + <vnf-vendor>JUNIPER</vnf-vendor> + <vnf-model>MODEL1</vnf-model> + <vnf-id>1</vnf-id> + <prov-status>1</prov-status> + <operational-state>1</operational-state> + <orchestration-status>1</orchestration-status> + <equipment-role>1</equipment-role> + </vnf-information> + <vnf-information> + <vnf-instance-id>2</vnf-instance-id> + <vnf-sequence-number>2</vnf-sequence-number> + <vnf-type>HY</vnf-type> + <vnf-vendor>JUNIPER</vnf-vendor> + <vnf-model>MODEL2</vnf-model> + <vnf-id>2</vnf-id> + <prov-status>2</prov-status> + <operational-state>2</operational-state> + <orchestration-status>2</orchestration-status> + <equipment-role>2</equipment-role> + </vnf-information> + </vnf-list> + </ucpe-vms-service-information> + <request-information> + <request-action>Layer3ServiceActivateRequest</request-action> + <order-number>4281555</order-number> + <request-id>155415ab-b4a7-4382-b4c6-d17d9sm42855</request-id> + <notification-url>https://csi-tst-q22.it.com:22443/Services/com/cingular/csi/sdn/SendManagedNetworkStatusNotification.jws</notification-url> + <source>OMX</source> + <order-version>1</order-version> + </request-information> + <sdnc-request-header> + <svc-action>activate</svc-action> + <svc-notification-url>https://msojra.mtsnjdcp1.aic.cip.com:8443/adapters/rest/SDNCNotify</svc-notification-url> + <svc-request-id>5b1f3c5d-cdf9-488d-8a4b-d3f1229d7760</svc-request-id> + </sdnc-request-header> + <l2-homing-information> + <topology>MultiPoint</topology> + <preferred-aic-clli>MTSNJA4LCP1</preferred-aic-clli> + <evc-name>AS/VLXM/003717//SW</evc-name> + </l2-homing-information> + <service-information> + <service-instance-id>FK/VLXM/003717//SW_INTERNET</service-instance-id> + <subscriber-name>ST E2E Test42855_1300004281555</subscriber-name> + <service-type>SDN-ETHERNET-INTERNET</service-type> + </service-information> + <internet-service-change-details> + <internet-evc-speed-value>10</internet-evc-speed-value> + <internet-evc-speed-units>Kbps</internet-evc-speed-units> + <t-provided-v4-lan-public-prefixes> + <request-index>1</request-index> + <v4-next-hop-address>192.168.1.15</v4-next-hop-address> + <v4-lan-public-prefix>192.168.1.15</v4-lan-public-prefix> + <v4-lan-public-prefix-length>28</v4-lan-public-prefix-length> + </t-provided-v4-lan-public-prefixes> + <t-provided-v4-lan-public-prefixes> + <request-index>2</request-index> + <v4-next-hop-address>192.168.1.16</v4-next-hop-address> + <v4-lan-public-prefix>192.168.1.16</v4-lan-public-prefix> + <v4-lan-public-prefix-length>28</v4-lan-public-prefix-length> + </t-provided-v4-lan-public-prefixes> + <t-provided-v6-lan-public-prefixes> + <request-index>1</request-index> + <v6-next-hop-address>2001:1890:12e3:2da::</v6-next-hop-address> + <v6-lan-public-prefix>2001:1890:12e3:2da::</v6-lan-public-prefix> + <v6-lan-public-prefix-length>28</v6-lan-public-prefix-length> + </t-provided-v6-lan-public-prefixes> + <t-provided-v6-lan-public-prefixes> + <request-index>1</request-index> + <v6-next-hop-address>2001:1890:12e3:2da::</v6-next-hop-address> + <v6-lan-public-prefix>2001:1890:12e3:2da::</v6-lan-public-prefix> + <v6-lan-public-prefix-length>28</v6-lan-public-prefix-length> + </t-provided-v6-lan-public-prefixes> + </internet-service-change-details> + </service-data> + </layer3-service-list> + + + + \ No newline at end of file diff --git a/bpmn/MSOCommonBPMN/src/test/resources/__files/UpdateNetworkV2/updateNetwork_queryInstance_Success.xml b/bpmn/MSOCommonBPMN/src/test/resources/__files/UpdateNetworkV2/updateNetwork_queryInstance_Success.xml index a7ac309507..09f01fb7ca 100644 --- a/bpmn/MSOCommonBPMN/src/test/resources/__files/UpdateNetworkV2/updateNetwork_queryInstance_Success.xml +++ b/bpmn/MSOCommonBPMN/src/test/resources/__files/UpdateNetworkV2/updateNetwork_queryInstance_Success.xml @@ -1,4 +1,4 @@ - - service-instance - https://aai-conexus-e2e.test.att.com:8443/aai/v8/business/customers/customer/8310000058863/service-subscriptions/service-subscription/vMOG/service-instances/service-instance/f70e927b-6087-4974-9ef8-c5e4d5847ca4 + + service-instance + https://aai-conexus-e2e.test.com:8443/aai/v8/business/customers/customer/8310000058863/service-subscriptions/service-subscription/vMOG/service-instances/service-instance/f70e927b-6087-4974-9ef8-c5e4d5847ca4 \ No newline at end of file diff --git a/bpmn/MSOCommonBPMN/src/test/resources/__files/UpdateNetworkV2/updateNetwork_queryNetworkId_AAIResponse_NoPayload_Success.xml b/bpmn/MSOCommonBPMN/src/test/resources/__files/UpdateNetworkV2/updateNetwork_queryNetworkId_AAIResponse_NoPayload_Success.xml index d8d10db65e..196558633b 100644 --- a/bpmn/MSOCommonBPMN/src/test/resources/__files/UpdateNetworkV2/updateNetwork_queryNetworkId_AAIResponse_NoPayload_Success.xml +++ b/bpmn/MSOCommonBPMN/src/test/resources/__files/UpdateNetworkV2/updateNetwork_queryNetworkId_AAIResponse_NoPayload_Success.xml @@ -1,73 +1,73 @@ - - - 49c86598-f766-46f8-84f8-8d1c1b10f9b4 - MNS-25180-L-01-dmz_direct_net_1 - CONTRAIL_EXTERNAL - dmz_direct - contrail - a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb - 0 - pending-create - networkName - false - true - false - - - 57e9a1ff-d14f-4071-a828-b19ae98eb2fc - 107.239.52.1 - 107.239.52.0 - 24 - 4 - pending-create - true - subnetName - - - - - 413 - 4132176 - - - - vpn-binding - https://aai-app-e2e.test.att.com:8443/aai/v8/network/vpn-bindings/vpn-binding/85f015d0-2e32-4c30-96d2-87a1a27f8017/ - - vpn-binding.vpn-id - 85f015d0-2e32-4c30-96d2-87a1a27f8017 - - - - vpn-binding - https://aai-app-e2e.test.att.com:8443/aai/v8/network/vpn-bindings/vpn-binding/c980a6ef-3b88-49f0-9751-dbad8608d0a6/ - - vpn-binding.vpn-id - c980a6ef-3b88-49f0-9751-dbad8608d0a6 - - - - tenant - https://aai-app-e2e.test.att.com:8443/aai/v8/cloud-infrastructure/tenants/tenant/7dd5365547234ee8937416c65507d266/ - - tenant.tenant-id - 7dd5365547234ee8937416c65507d266 - - - - network-policy - https://aai-app-e2e.test.att.com:8443/aai/v8/network/network-policies/network-policy/cee6d136-e378-4678-a024-2cd15f0ee0cg - - network-policy.network-policy-id - cee6d136-e378-4678-a024-2cd15f0ee0cg - - - - route-table-reference - - route-table-reference.route-table-reference-id - cee6d136-e378-4678-a024-2cd15f0ee0hi - - - - + + + 49c86598-f766-46f8-84f8-8d1c1b10f9b4 + MNS-25180-L-01-dmz_direct_net_1 + CONTRAIL_EXTERNAL + dmz_direct + contrail + a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb + 0 + pending-create + networkName + false + true + false + + + 57e9a1ff-d14f-4071-a828-b19ae98eb2fc + 107.239.52.1 + 107.239.52.0 + 24 + 4 + pending-create + true + subnetName + + + + + 413 + 4132176 + + + + vpn-binding + https://aai-app-e2e.test.com:8443/aai/v8/network/vpn-bindings/vpn-binding/85f015d0-2e32-4c30-96d2-87a1a27f8017/ + + vpn-binding.vpn-id + 85f015d0-2e32-4c30-96d2-87a1a27f8017 + + + + vpn-binding + https://aai-app-e2e.test.com:8443/aai/v8/network/vpn-bindings/vpn-binding/c980a6ef-3b88-49f0-9751-dbad8608d0a6/ + + vpn-binding.vpn-id + c980a6ef-3b88-49f0-9751-dbad8608d0a6 + + + + tenant + https://aai-app-e2e.test.com:8443/aai/v8/cloud-infrastructure/tenants/tenant/7dd5365547234ee8937416c65507d266/ + + tenant.tenant-id + 7dd5365547234ee8937416c65507d266 + + + + network-policy + https://aai-app-e2e.test.com:8443/aai/v8/network/network-policies/network-policy/cee6d136-e378-4678-a024-2cd15f0ee0cg + + network-policy.network-policy-id + cee6d136-e378-4678-a024-2cd15f0ee0cg + + + + route-table-reference + + route-table-reference.route-table-reference-id + cee6d136-e378-4678-a024-2cd15f0ee0hi + + + + diff --git a/bpmn/MSOCommonBPMN/src/test/resources/__files/UpdateNetworkV2/updateNetwork_queryNetworkTableRef1_AAIResponse_Success.xml b/bpmn/MSOCommonBPMN/src/test/resources/__files/UpdateNetworkV2/updateNetwork_queryNetworkTableRef1_AAIResponse_Success.xml index 292b5e8420..48f652cc0e 100644 --- a/bpmn/MSOCommonBPMN/src/test/resources/__files/UpdateNetworkV2/updateNetwork_queryNetworkTableRef1_AAIResponse_Success.xml +++ b/bpmn/MSOCommonBPMN/src/test/resources/__files/UpdateNetworkV2/updateNetwork_queryNetworkTableRef1_AAIResponse_Success.xml @@ -1,20 +1,20 @@ - - - - - - - - - - - - - 5938baec-03ca-2bd5-a3f1-d54x123e253a - refFQDN1 - 12345 - - + + + + + + + + + + + + + 5938baec-03ca-2bd5-a3f1-d54x123e253a + refFQDN1 + 12345 + + \ No newline at end of file diff --git a/bpmn/MSOCommonBPMN/src/test/resources/__files/UpdateNetworkV2/updateNetwork_queryNetworkTableRef2_AAIResponse_Success.xml b/bpmn/MSOCommonBPMN/src/test/resources/__files/UpdateNetworkV2/updateNetwork_queryNetworkTableRef2_AAIResponse_Success.xml index 910f7014e4..c911d320ec 100644 --- a/bpmn/MSOCommonBPMN/src/test/resources/__files/UpdateNetworkV2/updateNetwork_queryNetworkTableRef2_AAIResponse_Success.xml +++ b/bpmn/MSOCommonBPMN/src/test/resources/__files/UpdateNetworkV2/updateNetwork_queryNetworkTableRef2_AAIResponse_Success.xml @@ -1,20 +1,20 @@ - - - - - - - - - - - - - 5938baec-03ca-2bd5-a3f1-d54x123e253a - refFQDN2 - 12345 - - + + + + + + + + + + + + + 5938baec-03ca-2bd5-a3f1-d54x123e253a + refFQDN2 + 12345 + + \ No newline at end of file diff --git a/bpmn/MSOCommonBPMN/src/test/resources/__files/VfModularity/AddNetworkPolicy_AAIResponse_Success.xml b/bpmn/MSOCommonBPMN/src/test/resources/__files/VfModularity/AddNetworkPolicy_AAIResponse_Success.xml index d968bcc1fe..d3f9c1eaf3 100644 --- a/bpmn/MSOCommonBPMN/src/test/resources/__files/VfModularity/AddNetworkPolicy_AAIResponse_Success.xml +++ b/bpmn/MSOCommonBPMN/src/test/resources/__files/VfModularity/AddNetworkPolicy_AAIResponse_Success.xml @@ -1,21 +1,21 @@ - - - - - - - - - - - - - 9a7b327d9-287aa00-82c4b0-105757 - fqdn123 - slowburn - 145878989 - - + + + + + + + + + + + + + 9a7b327d9-287aa00-82c4b0-105757 + fqdn123 + slowburn + 145878989 + + \ No newline at end of file diff --git a/bpmn/MSOCommonBPMN/src/test/resources/__files/VfModularity/GenericVnf.xml b/bpmn/MSOCommonBPMN/src/test/resources/__files/VfModularity/GenericVnf.xml index 60f3d01cb7..c159e2eae2 100644 --- a/bpmn/MSOCommonBPMN/src/test/resources/__files/VfModularity/GenericVnf.xml +++ b/bpmn/MSOCommonBPMN/src/test/resources/__files/VfModularity/GenericVnf.xml @@ -1,38 +1,38 @@ - - skask - STMTN5MMSC20 - pcrf-capacity - SDN-MOBILITY - vPCRF - pending-create - false - false - introvert - 2.0 - 0000020 - - - lukewarm - PCRF::module-0-0 - introvert - 2.0 - true - fastburn - pending-create - 0000074 - - - supercool - PCRF::module-1-0 - extrovert - 2.0 - false - slowburn - pending-create - 0000075 - - - - - - + + skask + STMTN5MMSC20 + pcrf-capacity + SDN-MOBILITY + vPCRF + pending-create + false + false + introvert + 2.0 + 0000020 + + + lukewarm + PCRF::module-0-0 + introvert + 2.0 + true + fastburn + pending-create + 0000074 + + + supercool + PCRF::module-1-0 + extrovert + 2.0 + false + slowburn + pending-create + 0000075 + + + + + + diff --git a/bpmn/MSOCommonBPMN/src/test/resources/__files/VfModularity/QueryNetworkPolicy_AAIResponse_Success.xml b/bpmn/MSOCommonBPMN/src/test/resources/__files/VfModularity/QueryNetworkPolicy_AAIResponse_Success.xml index 0442afca90..94e00427a2 100644 --- a/bpmn/MSOCommonBPMN/src/test/resources/__files/VfModularity/QueryNetworkPolicy_AAIResponse_Success.xml +++ b/bpmn/MSOCommonBPMN/src/test/resources/__files/VfModularity/QueryNetworkPolicy_AAIResponse_Success.xml @@ -1,21 +1,21 @@ - - - - - - - - - - - - - 9a7b327d9-287aa00-82c4b0-105757 - GN_EVPN_Test - 195159195 - 14567890 - - + + + + + + + + + + + + + 9a7b327d9-287aa00-82c4b0-105757 + GN_EVPN_Test + 195159195 + 14567890 + + \ No newline at end of file diff --git a/bpmn/MSOCommonBPMN/src/test/resources/__files/VfModularity/SDNCTopologyQueryCallback.xml b/bpmn/MSOCommonBPMN/src/test/resources/__files/VfModularity/SDNCTopologyQueryCallback.xml index b143e3b17a..7c67095af1 100644 --- a/bpmn/MSOCommonBPMN/src/test/resources/__files/VfModularity/SDNCTopologyQueryCallback.xml +++ b/bpmn/MSOCommonBPMN/src/test/resources/__files/VfModularity/SDNCTopologyQueryCallback.xml @@ -1,315 +1,315 @@ - - - bd1b3789-6474-4935-94b2-90b656e035d0 - - bd1b3789-6474-4935-94b2-90b656e035d0 - - 9ddf628a-9eca-430e-8974-22d520a31be1 - assign - https://msojra.infra.aic.att.net:8443/adapters/rest/SDNCNotify - - - notsurewecare - bd1b3789-6474-4935-94b2-90b656e035d0 - a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb - a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb - - - PendingCreate - - - VNN1CA52LCP - ZVNNMOGX01_base - afd0f02a-1ddb-43bb-aded-5113e46e82ae - ZVNN1MOGX01-SVC/ZVNN1MOGX01 - VF AUG 1 1 - ZVNN1MOGX01 - 33d209df14ac4c08ad60747185d2f3e0 - bd1b3789-6474-4935-94b2-90b656e035d0 - ZVNN1MOGX01 - VF AUG 1::module-0 - - - - - mog_exn - 03dbd833-785c-40c0-bf32-37594b5334bc - MNS-25180-P-VNNYCA01_exn_protected_net_1 - - - 6f82d234-41a4-48e9-a9e8-415667a72929 - - filter1 - - - filter2 - - - - mog_oam - 3f181cde-9380-4c20-9d3a-e1a4ee74f994 - MNS-25180-P-VNNYCA01_oam_protected_net_1 - - - 713b6770-13fa-4949-8dbb-a1288c5e5932 - - - mog_cor_B - 821a550a-3f50-4725-995b-f212d5caec7c - MNS-25180-P-VNNYCA01_cor_direct_net_1 - - - 18926e56-12b6-4a4d-98b6-37e0c05626ee - - - mog_cor_A - 3dabf5c0-cffb-420c-8960-8499c74eb25f - MNS-25180-P-VNNYCA01_cor_direct_net_2 - - - 35530b29-a4de-48ff-a014-111110ccc652 - - - mog_gn - 3ce97321-6e7f-49af-bd12-f833e377c310 - MNS-25180-P-VNNYCA01_gn_direct_net_1 - - - 32bfdd2c-28e1-4895-87a6-373bf12c3129 - - - mog_dmz - d43ca910-02a5-47dc-8510-100a68a3c9e0 - MNS-25180-P-VNNYCA01_dmz_protected_net_1 - - - cb9500fb-943f-412e-aea6-458711564a75 - - - nova - - - ps - - ZVNN1MOGX01MPS001 - - - ZVNN1MOGX01MPS002 - - - ZVNN1MOGX01MPS003 - - - ZVNN1MOGX01MPS004 - - 4 - - mog_cor_B - - 107.224.36.251 - - - 107.224.36.252 - - - 107.224.36.253 - - - 107.224.36.254 - - N - - - - cm - - ZVNN1MOGX01MCM001 - - - ZVNN1MOGX01OAM002 - - 1 - - mog_cor_B - - 107.224.36.249 - - - 107.224.36.250 - - N - - - mog_oam - - 107.239.167.250 - - - 107.239.167.251 - - N - - - - oam - - ZVNN1MOGX01OAM001 - - - ZVNN1MOGX01OAM002 - - 2 - - mog_oam - - 107.239.167.252 - - - 107.239.167.251 - - N - - - mog_cor_B - - 107.224.36.249 - - - 107.224.36.250 - - N - - - - pd - - ZVNN1MOGX01MPD001 - - - ZVNN1MOGX01MPD002 - - 2 - - mog_dmz - - 107.225.25.253 - - - 107.225.25.254 - - N - 107.225.254.253 - - - mog_oam - - 107.239.167.254 - - - 107.239.167.253 - - N - 107.239.167.249 - - - mog_exn - - 107.224.46.253 - - - 107.224.46.254 - - N - 107.224.46.252 - - - mog_cor_B - - 107.224.36.247 - - - 107.224.36.248 - - N - 107.224.41.252 - - - mog_gn - - 107.224.41.253 - - - 107.224.41.254 - - N - 107.224.41.252 - - - mog_cor_A - - 107.224.38.253 - - - 107.224.38.254 - - N - - - - sm - - ZVNN1MOGX01MSM001 - - - ZVNN1MOGX01MSM002 - - - ZVNN1MOGX01MSM003 - - - ZVNN1MOGX01MSM004 - - 4 - - mog_cor_B - - 107.224.36.243 - - - 107.224.36.244 - - - 107.224.36.245 - - - 107.224.36.246 - - N - - - - - ZVNNMOGX01_base - SDN-MOBILITY - ZVNN1MOGX01 - VF AUG 1::module-0 - ZVNN1MOGX01-SVC/ZVNN1MOGX01 - VF AUG 1 1 - ZVNN1MOGX01 - - - - 9ddf628a-9eca-430e-8974-22d520a31be1 - - PORTAL - VNFActivateRequest - - - - 200 - Y - synccomplete - 2016-08-05T16:15:19.398Z - vnf-topology-operation - VNFActivateRequest - assign - - - - + + + bd1b3789-6474-4935-94b2-90b656e035d0 + + bd1b3789-6474-4935-94b2-90b656e035d0 + + 9ddf628a-9eca-430e-8974-22d520a31be1 + assign + https://msojra.infra.aic.net:8443/adapters/rest/SDNCNotify + + + notsurewecare + bd1b3789-6474-4935-94b2-90b656e035d0 + a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb + a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb + + + PendingCreate + + + VNN1CA52LCP + ZVNNMOGX01_base + afd0f02a-1ddb-43bb-aded-5113e46e82ae + ZVNN1MOGX01-SVC/ZVNN1MOGX01 - VF AUG 1 1 + ZVNN1MOGX01 + 33d209df14ac4c08ad60747185d2f3e0 + bd1b3789-6474-4935-94b2-90b656e035d0 + ZVNN1MOGX01 - VF AUG 1::module-0 + + + + + mog_exn + 03dbd833-785c-40c0-bf32-37594b5334bc + MNS-25180-P-VNNYCA01_exn_protected_net_1 + + + 6f82d234-41a4-48e9-a9e8-415667a72929 + + filter1 + + + filter2 + + + + mog_oam + 3f181cde-9380-4c20-9d3a-e1a4ee74f994 + MNS-25180-P-VNNYCA01_oam_protected_net_1 + + + 713b6770-13fa-4949-8dbb-a1288c5e5932 + + + mog_cor_B + 821a550a-3f50-4725-995b-f212d5caec7c + MNS-25180-P-VNNYCA01_cor_direct_net_1 + + + 18926e56-12b6-4a4d-98b6-37e0c05626ee + + + mog_cor_A + 3dabf5c0-cffb-420c-8960-8499c74eb25f + MNS-25180-P-VNNYCA01_cor_direct_net_2 + + + 35530b29-a4de-48ff-a014-111110ccc652 + + + mog_gn + 3ce97321-6e7f-49af-bd12-f833e377c310 + MNS-25180-P-VNNYCA01_gn_direct_net_1 + + + 32bfdd2c-28e1-4895-87a6-373bf12c3129 + + + mog_dmz + d43ca910-02a5-47dc-8510-100a68a3c9e0 + MNS-25180-P-VNNYCA01_dmz_protected_net_1 + + + cb9500fb-943f-412e-aea6-458711564a75 + + + nova + + + ps + + ZVNN1MOGX01MPS001 + + + ZVNN1MOGX01MPS002 + + + ZVNN1MOGX01MPS003 + + + ZVNN1MOGX01MPS004 + + 4 + + mog_cor_B + + 107.224.36.251 + + + 107.224.36.252 + + + 107.224.36.253 + + + 107.224.36.254 + + N + + + + cm + + ZVNN1MOGX01MCM001 + + + ZVNN1MOGX01OAM002 + + 1 + + mog_cor_B + + 107.224.36.249 + + + 107.224.36.250 + + N + + + mog_oam + + 107.239.167.250 + + + 107.239.167.251 + + N + + + + oam + + ZVNN1MOGX01OAM001 + + + ZVNN1MOGX01OAM002 + + 2 + + mog_oam + + 107.239.167.252 + + + 107.239.167.251 + + N + + + mog_cor_B + + 107.224.36.249 + + + 107.224.36.250 + + N + + + + pd + + ZVNN1MOGX01MPD001 + + + ZVNN1MOGX01MPD002 + + 2 + + mog_dmz + + 107.225.25.253 + + + 107.225.25.254 + + N + 107.225.254.253 + + + mog_oam + + 107.239.167.254 + + + 107.239.167.253 + + N + 107.239.167.249 + + + mog_exn + + 107.224.46.253 + + + 107.224.46.254 + + N + 107.224.46.252 + + + mog_cor_B + + 107.224.36.247 + + + 107.224.36.248 + + N + 107.224.41.252 + + + mog_gn + + 107.224.41.253 + + + 107.224.41.254 + + N + 107.224.41.252 + + + mog_cor_A + + 107.224.38.253 + + + 107.224.38.254 + + N + + + + sm + + ZVNN1MOGX01MSM001 + + + ZVNN1MOGX01MSM002 + + + ZVNN1MOGX01MSM003 + + + ZVNN1MOGX01MSM004 + + 4 + + mog_cor_B + + 107.224.36.243 + + + 107.224.36.244 + + + 107.224.36.245 + + + 107.224.36.246 + + N + + + + + ZVNNMOGX01_base + SDN-MOBILITY + ZVNN1MOGX01 - VF AUG 1::module-0 + ZVNN1MOGX01-SVC/ZVNN1MOGX01 - VF AUG 1 1 + ZVNN1MOGX01 + + + + 9ddf628a-9eca-430e-8974-22d520a31be1 + + PORTAL + VNFActivateRequest + + + + 200 + Y + synccomplete + 2016-08-05T16:15:19.398Z + vnf-topology-operation + VNFActivateRequest + assign + + + + diff --git a/bpmn/MSOCommonBPMN/src/test/resources/__files/VfModularity/SDNCTopologyQueryCallbackVfModule.xml b/bpmn/MSOCommonBPMN/src/test/resources/__files/VfModularity/SDNCTopologyQueryCallbackVfModule.xml index c9f9cf3262..9b69fdc053 100644 --- a/bpmn/MSOCommonBPMN/src/test/resources/__files/VfModularity/SDNCTopologyQueryCallbackVfModule.xml +++ b/bpmn/MSOCommonBPMN/src/test/resources/__files/VfModularity/SDNCTopologyQueryCallbackVfModule.xml @@ -1,141 +1,141 @@ - - - 28455973-1ee5-4ad1-8d35-c4732679743a - - 200 - Y - synccomplete - 2016-06-08T19:44:59.138Z - vnf-topology-operation - VNFActivateRequest - assign - - - 28455973-1ee5-4ad1-8d35-c4732679743 - - notsurewecare - 28455973-1ee5-4ad1-8d35-c4732679743a - a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb - a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb - - - 5e168556-a5c6-4813-bff3-cc03007afbbc - http://mtanjv9moja01-eth1-0.aic.cip.att.com:28080/adapters/rest/SDNCNotify - assign - - - AAIAIC25 - MSOTEST06-vSAMP3::base::module-0 - 91ad7ab0-9ffd-471d-971c-3eb913a2cc75 - Test/vSAMP3 1 - MSOTEST06 - 4ae1d3446a4c48b2bec44b6cfba06d68 - 28455973-1ee5-4ad1-8d35-c4732679743a - vSAMP3::base::module-0 - - - PendingCreate - - - - image - Ubuntu_Perf - - - flavor - m1.small - - - - int_imbl - 680b7453-0ec4-4d96-b355-280d981d418f - Nimbus-25193-T-Willows2_int_imbl_net_1 - default-domain:Nimbus-25193-T-Willows2:Nimbus-25193-T-Willows2_int_imbl_net_1 - - 775607fb-e16a-45ef-94a7-82fba0d16eec - 640d07fb-e16a-45ef-94a7-82fba0d169bf - - filter1 - - - filter2 - - - - sgi_protected - f9039ce9-e3cf-4716-b2d1-ec7912178ea4 - Nimbus-25193-T-Willows2_sgi_protected_net_1 - default-domain:Nimbus-25193-T-Willows2:Nimbus-25193-T-Willows2_sgi_protected_net_1 - b9999ce9-e3cf-4716-b2d1-ec791217678c - - bf11bba8-b971-4ab5-8281-215b3fedcd3c - - - cm - - ZVNN1MOGX01MCM001 - - - ZVNN1MOGX01OAM002 - - 1 - - mog_cor_B - - 107.224.36.249 - - - 107.224.36.250 - - - 2606:ae00:2e01:800::67 - - N - 107.224.41.252 - 2001:1890:1001:2B32::29:C - - - mog_oam - - 107.239.167.250 - - - 107.239.167.251 - - - aa::aa::aa::aa::aa::aa - - - bb::bb::bb::bb::bb::bb - - - 1.2.3.4/26 - - - 2002::/64 - - N - 1111:1890:1001:2B32::29:D - - - - nova - - - - MSOTEST06-vSAMP3::base::module-0 - SDN-MOBILITY - vSAMP3::base::module-0 - Test/vSAMP3 1 - MSOTEST06 - - - - 5e168556-a5c6-4813-bff3-cc03007afbbc - - SoapUI-bns-vf-base-vSAMP3-9001 - VNFActivateRequest - - - - + + + 28455973-1ee5-4ad1-8d35-c4732679743a + + 200 + Y + synccomplete + 2016-06-08T19:44:59.138Z + vnf-topology-operation + VNFActivateRequest + assign + + + 28455973-1ee5-4ad1-8d35-c4732679743 + + notsurewecare + 28455973-1ee5-4ad1-8d35-c4732679743a + a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb + a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb + + + 5e168556-a5c6-4813-bff3-cc03007afbbc + http://mtanjv9moja01-eth1-0.aic.cip.com:28080/adapters/rest/SDNCNotify + assign + + + AAIAIC25 + MSOTEST06-vSAMP3::base::module-0 + 91ad7ab0-9ffd-471d-971c-3eb913a2cc75 + Test/vSAMP3 1 + MSOTEST06 + 4ae1d3446a4c48b2bec44b6cfba06d68 + 28455973-1ee5-4ad1-8d35-c4732679743a + vSAMP3::base::module-0 + + + PendingCreate + + + + image + Ubuntu_Perf + + + flavor + m1.small + + + + int_imbl + 680b7453-0ec4-4d96-b355-280d981d418f + Nimbus-25193-T-Willows2_int_imbl_net_1 + default-domain:Nimbus-25193-T-Willows2:Nimbus-25193-T-Willows2_int_imbl_net_1 + + 775607fb-e16a-45ef-94a7-82fba0d16eec + 640d07fb-e16a-45ef-94a7-82fba0d169bf + + filter1 + + + filter2 + + + + sgi_protected + f9039ce9-e3cf-4716-b2d1-ec7912178ea4 + Nimbus-25193-T-Willows2_sgi_protected_net_1 + default-domain:Nimbus-25193-T-Willows2:Nimbus-25193-T-Willows2_sgi_protected_net_1 + b9999ce9-e3cf-4716-b2d1-ec791217678c + + bf11bba8-b971-4ab5-8281-215b3fedcd3c + + + cm + + ZVNN1MOGX01MCM001 + + + ZVNN1MOGX01OAM002 + + 1 + + mog_cor_B + + 107.224.36.249 + + + 107.224.36.250 + + + 2606:ae00:2e01:800::67 + + N + 107.224.41.252 + 2001:1890:1001:2B32::29:C + + + mog_oam + + 107.239.167.250 + + + 107.239.167.251 + + + aa::aa::aa::aa::aa::aa + + + bb::bb::bb::bb::bb::bb + + + 1.2.3.4/26 + + + 2002::/64 + + N + 1111:1890:1001:2B32::29:D + + + + nova + + + + MSOTEST06-vSAMP3::base::module-0 + SDN-MOBILITY + vSAMP3::base::module-0 + Test/vSAMP3 1 + MSOTEST06 + + + + 5e168556-a5c6-4813-bff3-cc03007afbbc + + SoapUI-bns-vf-base-vSAMP3-9001 + VNFActivateRequest + + + + diff --git a/bpmn/MSOCommonBPMN/src/test/resources/__files/VfModularity/VfModule-lukewarm.xml b/bpmn/MSOCommonBPMN/src/test/resources/__files/VfModularity/VfModule-lukewarm.xml index ad3c3591ed..cfbf903ce9 100644 --- a/bpmn/MSOCommonBPMN/src/test/resources/__files/VfModularity/VfModule-lukewarm.xml +++ b/bpmn/MSOCommonBPMN/src/test/resources/__files/VfModularity/VfModule-lukewarm.xml @@ -1,10 +1,10 @@ - - lukewarm - PCRF::module-1 - slowburn - pending-create - true - 330-90 - introvert - 2.0 + + lukewarm + PCRF::module-1 + slowburn + pending-create + true + 330-90 + introvert + 2.0 \ No newline at end of file diff --git a/bpmn/MSOCommonBPMN/src/test/resources/__files/VfModularity/VfModule-new.xml b/bpmn/MSOCommonBPMN/src/test/resources/__files/VfModularity/VfModule-new.xml index eba91a7a84..27c8ecf60a 100644 --- a/bpmn/MSOCommonBPMN/src/test/resources/__files/VfModularity/VfModule-new.xml +++ b/bpmn/MSOCommonBPMN/src/test/resources/__files/VfModularity/VfModule-new.xml @@ -1,9 +1,9 @@ - - b37d96db-7d2c-47ce-bf61-a6c7b82fe161 - PCRF::module-0-2 - 00000000-0000-0000-0000-000000000000 - 1.0 - false - pending-create - 330-90 + + b37d96db-7d2c-47ce-bf61-a6c7b82fe161 + PCRF::module-0-2 + 00000000-0000-0000-0000-000000000000 + 1.0 + false + pending-create + 330-90 \ No newline at end of file diff --git a/bpmn/MSOCommonBPMN/src/test/resources/__files/VfModularity/VfModule-supercool.xml b/bpmn/MSOCommonBPMN/src/test/resources/__files/VfModularity/VfModule-supercool.xml index 6d365f7d51..3370e33ce2 100644 --- a/bpmn/MSOCommonBPMN/src/test/resources/__files/VfModularity/VfModule-supercool.xml +++ b/bpmn/MSOCommonBPMN/src/test/resources/__files/VfModularity/VfModule-supercool.xml @@ -1,27 +1,27 @@ - - supercool - PCRF::module-2 - fastburn - pending-create - false - 330-89 - introvert - 2.0 - - - volume-group - - cloud-region.cloud-owner - att-aic - - - cloud-region.cloud-region-id - pdk1 - - - volume-group.volume-group-id - 78987 - - - + + supercool + PCRF::module-2 + fastburn + pending-create + false + 330-89 + introvert + 2.0 + + + volume-group + + cloud-region.cloud-owner + att-aic + + + cloud-region.cloud-region-id + pdk1 + + + volume-group.volume-group-id + 78987 + + + \ No newline at end of file diff --git a/bpmn/MSOCommonBPMN/src/test/resources/__files/VfModularity/VolumeGroup.xml b/bpmn/MSOCommonBPMN/src/test/resources/__files/VfModularity/VolumeGroup.xml index 241e5e3e3f..b44c977eaf 100644 --- a/bpmn/MSOCommonBPMN/src/test/resources/__files/VfModularity/VolumeGroup.xml +++ b/bpmn/MSOCommonBPMN/src/test/resources/__files/VfModularity/VolumeGroup.xml @@ -1,25 +1,25 @@ - - 78987 - Volume_2 - slowburn - pcrf-capacity - Active - 0000020 - - - tenant - - cloud-region.cloud-owner - att-aic - - - cloud-region.cloud-region-id - MDTWNJ21 - - - tenant.tenant-id - fba1bd1e195a404cacb9ce17a9b2b421 - - - + + 78987 + Volume_2 + slowburn + pcrf-capacity + Active + 0000020 + + + tenant + + cloud-region.cloud-owner + att-aic + + + cloud-region.cloud-region-id + MDTWNJ21 + + + tenant.tenant-id + fba1bd1e195a404cacb9ce17a9b2b421 + + + \ No newline at end of file diff --git a/bpmn/MSOCommonBPMN/src/test/resources/__files/aai-volume-group-id-info.xml b/bpmn/MSOCommonBPMN/src/test/resources/__files/aai-volume-group-id-info.xml index 37c5155c48..396f553b60 100644 --- a/bpmn/MSOCommonBPMN/src/test/resources/__files/aai-volume-group-id-info.xml +++ b/bpmn/MSOCommonBPMN/src/test/resources/__files/aai-volume-group-id-info.xml @@ -1,28 +1,28 @@ - - - VOLUME_GROUP_ID_1 - VOLUME_GROUP_ID_1_NAME - heat-stack-id - vnf-type - OK - 1 - - - tenant - - cloud-region.cloud-owner - att-aic - - - cloud-region.cloud-region-id - pdk1 - - - tenant.tenant-id - cee6d136-e378-4678-a024-2cd15f0ee0cg - - - - - - + + + VOLUME_GROUP_ID_1 + VOLUME_GROUP_ID_1_NAME + heat-stack-id + vnf-type + OK + 1 + + + tenant + + cloud-region.cloud-owner + att-aic + + + cloud-region.cloud-region-id + pdk1 + + + tenant.tenant-id + cee6d136-e378-4678-a024-2cd15f0ee0cg + + + + + + diff --git a/bpmn/MSOCommonBPMN/src/test/resources/mso.bpmn.urn.properties b/bpmn/MSOCommonBPMN/src/test/resources/mso.bpmn.urn.properties index f1a82225ff..133f58593c 100644 --- a/bpmn/MSOCommonBPMN/src/test/resources/mso.bpmn.urn.properties +++ b/bpmn/MSOCommonBPMN/src/test/resources/mso.bpmn.urn.properties @@ -1,86 +1,86 @@ -# Default URN Mappings for unit tests - -mso.rollback=true - -canopi.auth=757A94191D685FD2092AC1490730A4FC -csi.aots.addincidentmanagement.endpoint=http://localhost:28090/AddIncidentManagementTicketRequest -csi.networkstatus.endpoint=http://localhost:28090/SendManagedNetworkStatusNotification -mso.csi.pwd=4EA237303511EFBBC37F17A351562131 -mso.csi.usrname=mso -mso.msoKey=07a7159d3bf51a0e53be7a8f89699be7 - -mso.adapters.completemsoprocess.endpoint=http://localhost:28090/CompleteMsoProcess - -mso.adapters.db.endpoint=http://localhost:28090/dbadapters/RequestsDbAdapter -mso.adapters.db.auth=757A94191D685FD2092AC1490730A4FC - -mso.adapters.network.endpoint=http://localhost:28090/networks/NetworkAdapter -mso.adapters.network.rest.endpoint=http://localhost:28090/networks/NetworkAdapter - -mso.adapters.po.auth=757A94191D685FD2092AC1490730A4FC -mso.adapters.po.password=3141634BF7E070AA289CF2892C986C0B -mso.po.timeout=PT60S - -aai.auth=757A94191D685FD2092AC1490730A4FC - -mso.adapters.sdnc.endpoint=http://localhost:28090/SDNCAdapter -mso.adapters.sdnc.rest.endpoint=http://localhost:28090/SDNCAdapter/v1/sdnc -mso.adapters.sdnc.timeout=PT60S -mso.sdnc.firewall.yang.model=http://com/openecomp/svc/mis/firewall-lite-gui -mso.sdnc.firewall.yang.model.version=2015-05-15 -mso.sdnc.password=3141634BF7E070AA289CF2892C986C0B -mso.sdnc.timeout.firewall.minutes=20 -mso.callbackRetryAttempts=5 -mso.sdnc.timeout=PT10S -mso.sdnc.timeout.ucpe.async.hours=120 -mso.sdnc.timeout.ucpe.async.minutes=5 -mso.workflow.message.endpoint=http://localhost:28080/mso/WorkflowMesssage -mso.workflow.sdncadapter.callback=http://localhost:28080/mso/SDNCAdapterCallbackService - -mso.catalog.db.endpoint=http://localhost:28090/ - -mso.adapters.tenant.endpoint=http://localhost:28090/tenantAdapterMock -mso.adapters.vnf-async.endpoint=http://localhost:28090/vnfs/VnfAdapterAsync -mso.adapters.vnf.endpoint=http://localhost:28090/vnfs/VnfAdapter -mso.adapters.vnf.rest.endpoint=http://localhost:28090/vnfs/v1/vnfs -mso.workflow.vnfadapter.create.callback=http://localhost:28080/mso/vnfAdapterNotify -mso.workflow.vnfadapter.delete.callback=http://localhost:28080/mso/vnfAdapterNotify -mso.workflow.vnfadapter.query.callback=http://localhost:28080/mso/services/VNFAdapterQuerCallbackV1 -mso.workflow.vnfadapter.rollback.callback=http://localhost:28080/mso/vnfAdapterNotify -mso.workflow.createvce.delay.seconds=1 -mso.infra.customer.id=testCustIdInfra - -aai.endpoint=http://localhost:28090 - -# AAI version mappings - -# Example to override default version for a resource: -#mso.workflow.default.aai.vce.version=6 -#mso.workflow.default.aai.v6.vce.uri=/aai/v6/network/vces/vce - -mso.workflow.global.default.aai.version=8 -mso.workflow.default.aai.cloud-region.version=9 -mso.workflow.default.aai.generic-vnf.version=9 - -mso.workflow.default.aai.v9.cloud-region.uri=/aai/v9/cloud-infrastructure/cloud-regions/cloud-region/att-aic -mso.workflow.default.aai.v8.customer.uri=/aai/v8/business/customers/customer -mso.workflow.default.aai.v8.generic-query.uri=/aai/v8/search/generic-query -mso.workflow.default.aai.v9.generic-vnf.uri=/aai/v9/network/generic-vnfs/generic-vnf -mso.workflow.default.aai.v8.l3-network.uri=/aai/v8/network/l3-networks/l3-network -mso.workflow.default.aai.v8.network-policy.uri=/aai/v8/network/network-policies/network-policy -mso.workflow.default.aai.v8.nodes-query.uri=/aai/v8/search/nodes-query -mso.workflow.default.aai.v8.route-table-reference.uri=/aai/v8/network/route-table-references/route-table-reference -mso.workflow.default.aai.v8.tenant.uri=/aai/v8/cloud-infrastructure/cloud-regions/cloud-region/att-aic/AAIAIC25/tenants/tenant -mso.workflow.default.aai.v8.vce.uri=/aai/v8/network/vces/vce -mso.workflow.default.aai.v8.vpn-binding.uri=/aai/v8/network/vpn-bindings/vpn-binding - - -log.debug.CompleteMsoProcess=true -log.debug.CreateNetworkInstanceInfra=true -log.debug.CreateServiceInstanceInfra=true -log.debug.DeleteNetworkInstanceInfra=true -log.debug.FalloutHandler=true -log.debug.GenericGetService=true -log.debug.sdncAdapter=true -log.debug.UpdateNetworkInstanceInfra=true +# Default URN Mappings for unit tests + +mso.rollback=true + +canopi.auth=757A94191D685FD2092AC1490730A4FC +csi.aots.addincidentmanagement.endpoint=http://localhost:28090/AddIncidentManagementTicketRequest +csi.networkstatus.endpoint=http://localhost:28090/SendManagedNetworkStatusNotification +mso.csi.pwd=4EA237303511EFBBC37F17A351562131 +mso.csi.usrname=mso +mso.msoKey=07a7159d3bf51a0e53be7a8f89699be7 + +mso.adapters.completemsoprocess.endpoint=http://localhost:28090/CompleteMsoProcess + +mso.adapters.db.endpoint=http://localhost:28090/dbadapters/RequestsDbAdapter +mso.adapters.db.auth=757A94191D685FD2092AC1490730A4FC + +mso.adapters.network.endpoint=http://localhost:28090/networks/NetworkAdapter +mso.adapters.network.rest.endpoint=http://localhost:28090/networks/NetworkAdapter + +mso.adapters.po.auth=757A94191D685FD2092AC1490730A4FC +mso.adapters.po.password=3141634BF7E070AA289CF2892C986C0B +mso.po.timeout=PT60S + +aai.auth=757A94191D685FD2092AC1490730A4FC + +mso.adapters.sdnc.endpoint=http://localhost:28090/SDNCAdapter +mso.adapters.sdnc.rest.endpoint=http://localhost:28090/SDNCAdapter/v1/sdnc +mso.adapters.sdnc.timeout=PT60S +mso.sdnc.firewall.yang.model=http://com/openecomp/svc/mis/firewall-lite-gui +mso.sdnc.firewall.yang.model.version=2015-05-15 +mso.sdnc.password=3141634BF7E070AA289CF2892C986C0B +mso.sdnc.timeout.firewall.minutes=20 +mso.callbackRetryAttempts=5 +mso.sdnc.timeout=PT10S +mso.sdnc.timeout.ucpe.async.hours=120 +mso.sdnc.timeout.ucpe.async.minutes=5 +mso.workflow.message.endpoint=http://localhost:28080/mso/WorkflowMesssage +mso.workflow.sdncadapter.callback=http://localhost:28080/mso/SDNCAdapterCallbackService + +mso.catalog.db.endpoint=http://localhost:28090/ + +mso.adapters.tenant.endpoint=http://localhost:28090/tenantAdapterMock +mso.adapters.vnf-async.endpoint=http://localhost:28090/vnfs/VnfAdapterAsync +mso.adapters.vnf.endpoint=http://localhost:28090/vnfs/VnfAdapter +mso.adapters.vnf.rest.endpoint=http://localhost:28090/vnfs/v1/vnfs +mso.workflow.vnfadapter.create.callback=http://localhost:28080/mso/vnfAdapterNotify +mso.workflow.vnfadapter.delete.callback=http://localhost:28080/mso/vnfAdapterNotify +mso.workflow.vnfadapter.query.callback=http://localhost:28080/mso/services/VNFAdapterQuerCallbackV1 +mso.workflow.vnfadapter.rollback.callback=http://localhost:28080/mso/vnfAdapterNotify +mso.workflow.createvce.delay.seconds=1 +mso.infra.customer.id=testCustIdInfra + +aai.endpoint=http://localhost:28090 + +# AAI version mappings + +# Example to override default version for a resource: +#mso.workflow.default.aai.vce.version=6 +#mso.workflow.default.aai.v6.vce.uri=/aai/v6/network/vces/vce + +mso.workflow.global.default.aai.version=8 +mso.workflow.default.aai.cloud-region.version=9 +mso.workflow.default.aai.generic-vnf.version=9 + +mso.workflow.default.aai.v9.cloud-region.uri=/aai/v9/cloud-infrastructure/cloud-regions/cloud-region/att-aic +mso.workflow.default.aai.v8.customer.uri=/aai/v8/business/customers/customer +mso.workflow.default.aai.v8.generic-query.uri=/aai/v8/search/generic-query +mso.workflow.default.aai.v9.generic-vnf.uri=/aai/v9/network/generic-vnfs/generic-vnf +mso.workflow.default.aai.v8.l3-network.uri=/aai/v8/network/l3-networks/l3-network +mso.workflow.default.aai.v8.network-policy.uri=/aai/v8/network/network-policies/network-policy +mso.workflow.default.aai.v8.nodes-query.uri=/aai/v8/search/nodes-query +mso.workflow.default.aai.v8.route-table-reference.uri=/aai/v8/network/route-table-references/route-table-reference +mso.workflow.default.aai.v8.tenant.uri=/aai/v8/cloud-infrastructure/cloud-regions/cloud-region/att-aic/AAIAIC25/tenants/tenant +mso.workflow.default.aai.v8.vce.uri=/aai/v8/network/vces/vce +mso.workflow.default.aai.v8.vpn-binding.uri=/aai/v8/network/vpn-bindings/vpn-binding +mso.workflow.notification.name=GenericNotificationService + +log.debug.CompleteMsoProcess=true +log.debug.CreateNetworkInstanceInfra=true +log.debug.CreateServiceInstanceInfra=true +log.debug.DeleteNetworkInstanceInfra=true +log.debug.FalloutHandler=true +log.debug.GenericGetService=true +log.debug.sdncAdapter=true +log.debug.UpdateNetworkInstanceInfra=true log.debug.VnfAdapterRestV1=true \ No newline at end of file diff --git a/bpmn/MSOCommonBPMN/src/test/resources/sdncCallbackErrorResponse.xml b/bpmn/MSOCommonBPMN/src/test/resources/sdncCallbackErrorResponse.xml index df3a4c42e5..136917c5ff 100644 --- a/bpmn/MSOCommonBPMN/src/test/resources/sdncCallbackErrorResponse.xml +++ b/bpmn/MSOCommonBPMN/src/test/resources/sdncCallbackErrorResponse.xml @@ -1 +1 @@ -1a152f97-566e-4f22-b17b-761f807bfedc404Error processing request to SDNC. Not Found. https://sdncodl.it.us.aic.cip.att.com:8443/restconf/config/L3SDN-API:services/layer3-service-list/AS%2FVLXM%2F000199%2F%2FSB_INTERNET. SDNC Returned-[error-type:application, error-tag:data-missing, error-message:Request could not be completed because the relevant data model content does not exist.] \ No newline at end of file +1a152f97-566e-4f22-b17b-761f807bfedc404Error processing request to SDNC. Not Found. https://sdncodl.it.us.aic.cip.com:8443/restconf/config/L3SDN-API:services/layer3-service-list/AS%2FVLXM%2F000199%2F%2FSB_INTERNET. SDNC Returned-[error-type:application, error-tag:data-missing, error-message:Request could not be completed because the relevant data model content does not exist.] \ No newline at end of file diff --git a/bpmn/MSOCommonBPMN/src/test/resources/sdncDeleteResponse.xml b/bpmn/MSOCommonBPMN/src/test/resources/sdncDeleteResponse.xml index d656d04187..c8a2e30282 100644 --- a/bpmn/MSOCommonBPMN/src/test/resources/sdncDeleteResponse.xml +++ b/bpmn/MSOCommonBPMN/src/test/resources/sdncDeleteResponse.xml @@ -1,212 +1,212 @@ - - - - - - Y - SK-2016-10-22-001 - - - SUCCESS - ERROR - - - 15001417 - - ALPRTR2 - 1.1.1.2 - - 1255.ae81 - VDBE - VIRTUAL - - ALPVDBE1 - 3.1.1.0/22 - ae81 - 3:1:1::0/22 - - - 1995.ae81 - ASBG - VIRTUAL - - ALPASBG1 - 3.1.1.0/22 - ae81 - 3:1:1::0/22 - - - 85.xe-10/0/2 - BGF2 - PHYSICAL - xe-10/0/2 - ALPBGF2 - 3.1.2.0/22 - - 3:1:2::0/22 - - - 85.xe-10/0/1 - BGF1 - PHYSICAL - xe-10/0/1 - ALPBGF1 - 3.1.2.0/22 - - 3:1:2::0/22 - - 2 - - - ALPRTR1 - 1.1.1.1 - - 1255.ae81 - VDBE - VIRTUAL - - ALPVDBE1 - 3.1.1.0/22 - ae81 - 3:1:1::0/22 - - - 1995.ae81 - ASBG - VIRTUAL - - ALPASBG1 - 3.1.1.0/22 - ae81 - 3:1:1::0/22 - - - 85.xe-10/0/2 - BGF2 - PHYSICAL - xe-10/0/2 - ALPBGF2 - 3.1.2.0/22 - - 3:1:2::0/22 - - - 85.xe-10/0/1 - BGF1 - PHYSICAL - xe-10/0/1 - ALPBGF1 - 3.1.2.0/22 - - 3:1:2::0/22 - - 1 - - - - 15001418 - - SANRTR1 - 2.1.1.1 - - 1255.ae81 - VDBE - VIRTUAL - - SANVDBE1 - 4.1.1.0/22 - ae81 - 4:1:1::0/22 - - - 1995.ae81 - ASBG - VIRTUAL - - SANASBG1 - 4.1.1.0/22 - ae81 - 4:1:1::0/22 - - - 85.xe-10/0/2 - BGF2 - PHYSICAL - xe-10/0/2 - SANBGF2 - 4.1.2.0/22 - - 4:1:2::0/22 - - - 85.xe-10/0/1 - BGF1 - PHYSICAL - xe-10/0/1 - SANBGF1 - 4.1.2.0/22 - - 4:1:2::0/22 - - 1 - - - SANRTR2 - 2.1.1.2 - - 1255.ae81 - VDBE - VIRTUAL - - SANVDBE1 - 4.1.1.0/22 - ae81 - 4:1:1::0/22 - - - 1995.ae81 - ASBG - VIRTUAL - - SANASBG1 - 4.1.1.0/22 - ae81 - 4:1:1::0/22 - - - 85.xe-10/0/2 - BGF2 - PHYSICAL - xe-10/0/2 - SANBGF2 - 4.1.2.0/22 - - 4:1:2::0/22 - - - 85.xe-10/0/1 - BGF1 - PHYSICAL - xe-10/0/1 - SANBGF1 - 4.1.2.0/22 - - 4:1:2::0/22 - - 2 - - - ATT-COLLABORATE - DISABLE - custid-888 - SII-2016-10-22-001 - CUSTOMER - 100668 - - - - + + + + + + Y + SK-2016-10-22-001 + + + SUCCESS + ERROR + + + 15001417 + + ALPRTR2 + 1.1.1.2 + + 1255.ae81 + VDBE + VIRTUAL + + ALPVDBE1 + 3.1.1.0/22 + ae81 + 3:1:1::0/22 + + + 1995.ae81 + ASBG + VIRTUAL + + ALPASBG1 + 3.1.1.0/22 + ae81 + 3:1:1::0/22 + + + 85.xe-10/0/2 + BGF2 + PHYSICAL + xe-10/0/2 + ALPBGF2 + 3.1.2.0/22 + + 3:1:2::0/22 + + + 85.xe-10/0/1 + BGF1 + PHYSICAL + xe-10/0/1 + ALPBGF1 + 3.1.2.0/22 + + 3:1:2::0/22 + + 2 + + + ALPRTR1 + 1.1.1.1 + + 1255.ae81 + VDBE + VIRTUAL + + ALPVDBE1 + 3.1.1.0/22 + ae81 + 3:1:1::0/22 + + + 1995.ae81 + ASBG + VIRTUAL + + ALPASBG1 + 3.1.1.0/22 + ae81 + 3:1:1::0/22 + + + 85.xe-10/0/2 + BGF2 + PHYSICAL + xe-10/0/2 + ALPBGF2 + 3.1.2.0/22 + + 3:1:2::0/22 + + + 85.xe-10/0/1 + BGF1 + PHYSICAL + xe-10/0/1 + ALPBGF1 + 3.1.2.0/22 + + 3:1:2::0/22 + + 1 + + + + 15001418 + + SANRTR1 + 2.1.1.1 + + 1255.ae81 + VDBE + VIRTUAL + + SANVDBE1 + 4.1.1.0/22 + ae81 + 4:1:1::0/22 + + + 1995.ae81 + ASBG + VIRTUAL + + SANASBG1 + 4.1.1.0/22 + ae81 + 4:1:1::0/22 + + + 85.xe-10/0/2 + BGF2 + PHYSICAL + xe-10/0/2 + SANBGF2 + 4.1.2.0/22 + + 4:1:2::0/22 + + + 85.xe-10/0/1 + BGF1 + PHYSICAL + xe-10/0/1 + SANBGF1 + 4.1.2.0/22 + + 4:1:2::0/22 + + 1 + + + SANRTR2 + 2.1.1.2 + + 1255.ae81 + VDBE + VIRTUAL + + SANVDBE1 + 4.1.1.0/22 + ae81 + 4:1:1::0/22 + + + 1995.ae81 + ASBG + VIRTUAL + + SANASBG1 + 4.1.1.0/22 + ae81 + 4:1:1::0/22 + + + 85.xe-10/0/2 + BGF2 + PHYSICAL + xe-10/0/2 + SANBGF2 + 4.1.2.0/22 + + 4:1:2::0/22 + + + 85.xe-10/0/1 + BGF1 + PHYSICAL + xe-10/0/1 + SANBGF1 + 4.1.2.0/22 + + 4:1:2::0/22 + + 2 + + + COLLABORATE + DISABLE + custid-888 + SII-2016-10-22-001 + CUSTOMER + 100668 + + + + \ No newline at end of file diff --git a/bpmn/MSOCommonBPMN/src/test/resources/sdncadaptercallbackrequest.xml b/bpmn/MSOCommonBPMN/src/test/resources/sdncadaptercallbackrequest.xml index 89e4fef705..754dc20ee6 100644 --- a/bpmn/MSOCommonBPMN/src/test/resources/sdncadaptercallbackrequest.xml +++ b/bpmn/MSOCommonBPMN/src/test/resources/sdncadaptercallbackrequest.xml @@ -1,342 +1,342 @@ - - - 2f7d1b38-2b78-4ef2-8ad6-1552d88620fa - 200 - OK - - <layer3-service-list xmlns="com:att:sdnctl:l3api"> - <service-instance-id>FK/VLXM/003717//SW_INTERNET</service-instance-id> - <service-status> - <rpc-name>service-configuration-operation</rpc-name> - <rpc-action>activate</rpc-action> - <request-status>synccomplete</request-status> - <final-indicator>N</final-indicator> - <l3sdn-action>Layer3ServiceActivateRequest</l3sdn-action> - <l3sdn-subaction>SUPP</l3sdn-subaction> - <response-timestamp>2015-04-28T21:32:11.386Z</response-timestamp> - </service-status> - <service-data> - <internet-evc-access-information> - <ip-version>ds</ip-version> - <internet-evc-speed-value>8</internet-evc-speed-value> - <internet-evc-speed-units>Mbps</internet-evc-speed-units> - </internet-evc-access-information> - <vr-lan xmlns="com:att:sdnctl:l3api"> - <vr-lan-interface> - <static-routes> - <v6-static-routes> - <v6-next-hop-address>2001:1890:12e3:2da::</v6-next-hop-address> - <v6-static-route-prefix>2001:1890:12e3:2da::</v6-static-route-prefix> - <v6-static-route-prefix-length>28</v6-static-route-prefix-length> - </v6-static-routes> - <v4-static-routes> - <v4-static-route-prefix>255.255.252.1</v4-static-route-prefix> - <v4-next-hop-address>192.168.1.15</v4-next-hop-address> - <v4-static-route-prefix-length>28</v4-static-route-prefix-length> - </v4-static-routes> - <v6-static-routes> - <v6-next-hop-address>2001:1890:12e3:2da::</v6-next-hop-address> - <v6-static-route-prefix>2001:1890:12e3:2da::</v6-static-route-prefix> - <v6-static-route-prefix-length>28</v6-static-route-prefix-length> - </v6-static-routes> - <v4-static-routes> - <v4-static-route-prefix>255.255.252.2</v4-static-route-prefix> - <v4-next-hop-address>192.168.1.15</v4-next-hop-address> - <v4-static-route-prefix-length>28</v4-static-route-prefix-length> - </v4-static-routes> - <v4-static-routes> - <v4-static-route-prefix>255.255.252.3</v4-static-route-prefix> - <v4-next-hop-address>192.168.1.15</v4-next-hop-address> - <v4-static-route-prefix-length>28</v4-static-route-prefix-length> - </v4-static-routes> - </static-routes> - <dhcp> - <v6-dhcp-server-enabled>N</v6-dhcp-server-enabled> - <v4-dhcp-server-enabled>Y</v4-dhcp-server-enabled> - <use-v6-default-pool>N</use-v6-default-pool> - <excluded-v4-dhcp-addresses-from-default-pool> - <excluded-v4-address>192.168.1.7</excluded-v4-address> - </excluded-v4-dhcp-addresses-from-default-pool> - <excluded-v4-dhcp-addresses-from-default-pool> - <excluded-v4-address>192.168.1.8</excluded-v4-address> - </excluded-v4-dhcp-addresses-from-default-pool> - <v4-dhcp-pools> - <v4-dhcp-relay-next-hop-address>1.1.1.1</v4-dhcp-relay-next-hop-address> - <v4-dhcp-pool-prefix-length>28</v4-dhcp-pool-prefix-length> - <excluded-v4-addresses> - <excluded-v4-address>192.168.1.5</excluded-v4-address> - </excluded-v4-addresses> - <v4-dhcp-relay-gateway-address>2.2.2.1</v4-dhcp-relay-gateway-address> - <excluded-v4-addresses> - <excluded-v4-address>192.168.1.6</excluded-v4-address> - </excluded-v4-addresses> - <v4-dhcp-pool-prefix>192.155.2.3</v4-dhcp-pool-prefix> - </v4-dhcp-pools> - <v4-dhcp-pools> - <v4-dhcp-relay-next-hop-address>1.1.1.2</v4-dhcp-relay-next-hop-address> - <v4-dhcp-pool-prefix-length>28</v4-dhcp-pool-prefix-length> - <excluded-v4-addresses> - <excluded-v4-address>192.168.1.6</excluded-v4-address> - </excluded-v4-addresses> - <v4-dhcp-relay-gateway-address>2.2.2.2</v4-dhcp-relay-gateway-address> - <excluded-v4-addresses> - <excluded-v4-address>192.168.1.7</excluded-v4-address> - </excluded-v4-addresses> - <v4-dhcp-pool-prefix>192.155.2.4</v4-dhcp-pool-prefix> - </v4-dhcp-pools> - <use-v4-default-pool>Y</use-v4-default-pool> - <excluded-v6-dhcp-addresses-from-default-pool> - <excluded-v6-address>1:5</excluded-v6-address> - </excluded-v6-dhcp-addresses-from-default-pool> - <excluded-v6-dhcp-addresses-from-default-pool> - <excluded-v6-address>1:6</excluded-v6-address> - </excluded-v6-dhcp-addresses-from-default-pool> - <v6-dhcp-pools> - <v6-dhcp-relay-next-hop-address>4:4</v6-dhcp-relay-next-hop-address> - <v6-dhcp-pool-prefix-length>28</v6-dhcp-pool-prefix-length> - <excluded-v6-addresses> - <excluded-v6-address>1:1</excluded-v6-address> - </excluded-v6-addresses> - <v6-dhcp-relay-gateway-address>3:3</v6-dhcp-relay-gateway-address> - <excluded-v6-addresses> - <excluded-v6-address>2:2</excluded-v6-address> - </excluded-v6-addresses> - <v6-dhcp-pool-prefix>0:0</v6-dhcp-pool-prefix> - </v6-dhcp-pools> - <v6-dhcp-pools> - <v6-dhcp-relay-next-hop-address>4:4</v6-dhcp-relay-next-hop-address> - <v6-dhcp-pool-prefix-length>28</v6-dhcp-pool-prefix-length> - <excluded-v6-addresses> - <excluded-v6-address>1:1</excluded-v6-address> - </excluded-v6-addresses> - <v6-dhcp-relay-gateway-address>3:3</v6-dhcp-relay-gateway-address> - <excluded-v6-addresses> - <excluded-v6-address>2:2</excluded-v6-address> - </excluded-v6-addresses> - <v6-dhcp-pool-prefix>0:0</v6-dhcp-pool-prefix> - </v6-dhcp-pools> - </dhcp> - <firewall-lite> - <stateful-firewall-lite-v6-enabled>N</stateful-firewall-lite-v6-enabled> - <stateful-firewall-lite-v4-enabled>Y</stateful-firewall-lite-v4-enabled> - <v4-firewall-packet-filters> - <v4-firewall-prefix>0.0.0.1</v4-firewall-prefix> - <v4-firewall-prefix-length>1</v4-firewall-prefix-length> - <allow-icmp-ping>Y</allow-icmp-ping> - <udp-ports> - <port-number>1</port-number> - </udp-ports> - <tcp-ports> - <port-number>1</port-number> - </tcp-ports> - </v4-firewall-packet-filters> - <v4-firewall-packet-filters> - <v4-firewall-prefix>0.0.0.2</v4-firewall-prefix> - <v4-firewall-prefix-length>2</v4-firewall-prefix-length> - <allow-icmp-ping>Y</allow-icmp-ping> - <udp-ports> - <port-number>2</port-number> - </udp-ports> - <tcp-ports> - <port-number>2</port-number> - </tcp-ports> - </v4-firewall-packet-filters> - <v6-firewall-packet-filters> - <v6-firewall-prefix>:</v6-firewall-prefix> - <v6-firewall-prefix-length>0</v6-firewall-prefix-length> - <allow-icmp-ping>Y</allow-icmp-ping> - <udp-ports> - <port-number>3</port-number> - </udp-ports> - <tcp-ports> - <port-number>3</port-number> - </tcp-ports> - </v6-firewall-packet-filters> - <v6-firewall-packet-filters> - <v6-firewall-prefix>:</v6-firewall-prefix> - <v6-firewall-prefix-length>1</v6-firewall-prefix-length> - <allow-icmp-ping>Y</allow-icmp-ping> - <udp-ports> - <port-number>4</port-number> - </udp-ports> - <tcp-ports> - <port-number>4</port-number> - </tcp-ports> - </v6-firewall-packet-filters> - </firewall-lite> - <pat> - <v4-pat-pools> - <v4-pat-pool-prefix>192.168.1.44</v4-pat-pool-prefix> - <v4-pat-pool-next-hop-address>192.168.1.5</v4-pat-pool-next-hop-address> - <v4-pat-pool-prefix-length>0</v4-pat-pool-prefix-length> - </v4-pat-pools> - <use-v4-default-pool>Y</use-v4-default-pool> - <v4-pat-enabled>N</v4-pat-enabled> - <v4-pat-pools> - <v4-pat-pool-prefix>192.168.1.45</v4-pat-pool-prefix> - <v4-pat-pool-next-hop-address>192.168.1.6</v4-pat-pool-next-hop-address> - <v4-pat-pool-prefix-length>28</v4-pat-pool-prefix-length> - </v4-pat-pools> - </pat> - <nat> - <v4-nat-enabled>Y</v4-nat-enabled> - <v4-nat-mapping-entries> - <v4-nat-internal>0.0.0.0</v4-nat-internal> - <v4-nat-next-hop-address>0.0.0.0</v4-nat-next-hop-address> - <v4-nat-external>0.0.0.0</v4-nat-external> - </v4-nat-mapping-entries> - <v4-nat-mapping-entries> - <v4-nat-internal>0.0.0.1</v4-nat-internal> - <v4-nat-next-hop-address>0.0.0.1</v4-nat-next-hop-address> - <v4-nat-external>0.0.0.1</v4-nat-external> - </v4-nat-mapping-entries> - </nat> - <vr-designation>primary</vr-designation> - <v4-vce-loopback-address>162.200.3.144</v4-vce-loopback-address> - <v6-vr-lan-prefix-length>64</v6-vr-lan-prefix-length> - <v6-vce-wan-address>2001:1890:12e3:2da::</v6-vce-wan-address> - <v6-vr-lan-prefix>2620:0:10d0:f:ffff:ffff:ffff:fffe</v6-vr-lan-prefix> - <v4-vr-lan-prefix-length>24</v4-vr-lan-prefix-length> - <v4-vr-lan-prefix>10.192.27.254</v4-vr-lan-prefix> - <v4-public-lan-prefixes> - <t-provided-v4-lan-public-prefixes> - <request-index>1</request-index> - <v4-next-hop-address>192.168.1.2</v4-next-hop-address> - <v4-lan-public-prefix>192.168.1.1</v4-lan-public-prefix> - <v4-lan-public-prefix-length>28</v4-lan-public-prefix-length> - </t-provided-v4-lan-public-prefixes> - <t-provided-v4-lan-public-prefixes> - <request-index>1</request-index> - <v4-next-hop-address>192.168.1.72</v4-next-hop-address> - <v4-lan-public-prefix>192.168.1.71</v4-lan-public-prefix> - <v4-lan-public-prefix-length>28</v4-lan-public-prefix-length> - </t-provided-v4-lan-public-prefixes> - <t-provided-v4-lan-public-prefixes> - <request-index>1</request-index> - <v4-next-hop-address>192.168.1.68</v4-next-hop-address> - <v4-lan-public-prefix>192.168.1.67</v4-lan-public-prefix> - <v4-lan-public-prefix-length>28</v4-lan-public-prefix-length> - </t-provided-v4-lan-public-prefixes> - </v4-public-lan-prefixes> - <v6-public-lan-prefixes> - <t-provided-v6-lan-public-prefixes> - <request-index>1</request-index> - <v6-next-hop-address>2001:1890:12e3:2da::</v6-next-hop-address> - <v6-lan-public-prefix>2001:1890:12e3:2da::</v6-lan-public-prefix> - <v6-lan-public-prefix-length>28</v6-lan-public-prefix-length> - </t-provided-v6-lan-public-prefixes> - <t-provided-v6-lan-public-prefixes> - <request-index>1</request-index> - <v6-next-hop-address>2001:1890:12e3:2da::</v6-next-hop-address> - <v6-lan-public-prefix>2001:1890:12e3:3da::</v6-lan-public-prefix> - <v6-lan-public-prefix-length>28</v6-lan-public-prefix-length> - </t-provided-v6-lan-public-prefixes> - <t-provided-v6-lan-public-prefixes> - <request-index>1</request-index> - <v6-next-hop-address>2001:1890:12e3:2da::</v6-next-hop-address> - <v6-lan-public-prefix>2001:1890:12e3:4da::</v6-lan-public-prefix> - <v6-lan-public-prefix-length>28</v6-lan-public-prefix-length> - </t-provided-v6-lan-public-prefixes> - </v6-public-lan-prefixes> - </vr-lan-interface> - <routing-protocol>none</routing-protocol> - </vr-lan> -<ucpe-vms-service-information> - <transport-service-information> - <transport-service-type>AVPN</transport-service-type> - <access-circuit-info> - <access-circuit-id>1</access-circuit-id> - <dual-mode>Active</dual-mode> - </access-circuit-info> - <access-circuit-info> - <access-circuit-id>2</access-circuit-id> - <dual-mode>Standby</dual-mode> - </access-circuit-info> - </transport-service-information> - <ucpe-information> - <ucpe-host-name>hostname</ucpe-host-name> - <ucpe-activation-code>activecode</ucpe-activation-code> - <out-of-band-management-modem>OOB</out-of-band-management-modem> - </ucpe-information> - <vnf-list> - <vnf-information> - <vnf-instance-id>1</vnf-instance-id> - <vnf-sequence-number>1</vnf-sequence-number> - <vnf-type>ZZ</vnf-type> - <vnf-vendor>JUNIPER</vnf-vendor> - <vnf-model>MODEL1</vnf-model> - <vnf-id>1</vnf-id> - <prov-status>1</prov-status> - <operational-state>1</operational-state> - <orchestration-status>1</orchestration-status> - <equipment-role>1</equipment-role> - </vnf-information> - <vnf-information> - <vnf-instance-id>2</vnf-instance-id> - <vnf-sequence-number>2</vnf-sequence-number> - <vnf-type>HY</vnf-type> - <vnf-vendor>JUNIPER</vnf-vendor> - <vnf-model>MODEL2</vnf-model> - <vnf-id>2</vnf-id> - <prov-status>2</prov-status> - <operational-state>2</operational-state> - <orchestration-status>2</orchestration-status> - <equipment-role>2</equipment-role> - </vnf-information> - </vnf-list> - </ucpe-vms-service-information> - <request-information> - <request-action>Layer3ServiceActivateRequest</request-action> - <order-number>4281555</order-number> - <request-id>155415ab-b4a7-4382-b4c6-d17d9sm42855</request-id> - <notification-url>https://csi-tst-q22.it.att.com:22443/Services/com/cingular/csi/sdn/SendManagedNetworkStatusNotification.jws</notification-url> - <source>OMX</source> - <order-version>1</order-version> - </request-information> - <sdnc-request-header> - <svc-action>activate</svc-action> - <svc-notification-url>https://msojra.mtsnjdcp1.aic.cip.att.com:8443/adapters/rest/SDNCNotify</svc-notification-url> - <svc-request-id>5b1f3c5d-cdf9-488d-8a4b-d3f1229d7760</svc-request-id> - </sdnc-request-header> - <l2-homing-information> - <topology>MultiPoint</topology> - <preferred-aic-clli>MTSNJA4LCP1</preferred-aic-clli> - <evc-name>AS/VLXM/003717//SW</evc-name> - </l2-homing-information> - <service-information> - <service-instance-id>FK/VLXM/003717//SW_INTERNET</service-instance-id> - <subscriber-name>FOUR SEASONS HEATING & COOLING_8310006378683</subscriber-name> - <service-type>SDN-ETHERNET-INTERNET</service-type> - </service-information> - <internet-service-change-details> - <internet-evc-speed-value>10</internet-evc-speed-value> - <internet-evc-speed-units>Kbps</internet-evc-speed-units> - <t-provided-v4-lan-public-prefixes> - <request-index>1</request-index> - <v4-next-hop-address>192.168.1.15</v4-next-hop-address> - <v4-lan-public-prefix>192.168.1.15</v4-lan-public-prefix> - <v4-lan-public-prefix-length>28</v4-lan-public-prefix-length> - </t-provided-v4-lan-public-prefixes> - <t-provided-v4-lan-public-prefixes> - <request-index>2</request-index> - <v4-next-hop-address>192.168.1.16</v4-next-hop-address> - <v4-lan-public-prefix>192.168.1.16</v4-lan-public-prefix> - <v4-lan-public-prefix-length>28</v4-lan-public-prefix-length> - </t-provided-v4-lan-public-prefixes> - <t-provided-v6-lan-public-prefixes> - <request-index>1</request-index> - <v6-next-hop-address>2001:1890:12e3:2da::</v6-next-hop-address> - <v6-lan-public-prefix>2001:1890:12e3:2da::</v6-lan-public-prefix> - <v6-lan-public-prefix-length>28</v6-lan-public-prefix-length> - </t-provided-v6-lan-public-prefixes> - <t-provided-v6-lan-public-prefixes> - <request-index>1</request-index> - <v6-next-hop-address>2001:1890:12e3:2da::</v6-next-hop-address> - <v6-lan-public-prefix>2001:1890:12e3:2da::</v6-lan-public-prefix> - <v6-lan-public-prefix-length>28</v6-lan-public-prefix-length> - </t-provided-v6-lan-public-prefixes> - </internet-service-change-details> - </service-data> - </layer3-service-list> - - + + + 2f7d1b38-2b78-4ef2-8ad6-1552d88620fa + 200 + OK + + <layer3-service-list xmlns="com:att:sdnctl:l3api"> + <service-instance-id>FK/VLXM/003717//SW_INTERNET</service-instance-id> + <service-status> + <rpc-name>service-configuration-operation</rpc-name> + <rpc-action>activate</rpc-action> + <request-status>synccomplete</request-status> + <final-indicator>N</final-indicator> + <l3sdn-action>Layer3ServiceActivateRequest</l3sdn-action> + <l3sdn-subaction>SUPP</l3sdn-subaction> + <response-timestamp>2015-04-28T21:32:11.386Z</response-timestamp> + </service-status> + <service-data> + <internet-evc-access-information> + <ip-version>ds</ip-version> + <internet-evc-speed-value>8</internet-evc-speed-value> + <internet-evc-speed-units>Mbps</internet-evc-speed-units> + </internet-evc-access-information> + <vr-lan xmlns="com:att:sdnctl:l3api"> + <vr-lan-interface> + <static-routes> + <v6-static-routes> + <v6-next-hop-address>2001:1890:12e3:2da::</v6-next-hop-address> + <v6-static-route-prefix>2001:1890:12e3:2da::</v6-static-route-prefix> + <v6-static-route-prefix-length>28</v6-static-route-prefix-length> + </v6-static-routes> + <v4-static-routes> + <v4-static-route-prefix>255.255.252.1</v4-static-route-prefix> + <v4-next-hop-address>192.168.1.15</v4-next-hop-address> + <v4-static-route-prefix-length>28</v4-static-route-prefix-length> + </v4-static-routes> + <v6-static-routes> + <v6-next-hop-address>2001:1890:12e3:2da::</v6-next-hop-address> + <v6-static-route-prefix>2001:1890:12e3:2da::</v6-static-route-prefix> + <v6-static-route-prefix-length>28</v6-static-route-prefix-length> + </v6-static-routes> + <v4-static-routes> + <v4-static-route-prefix>255.255.252.2</v4-static-route-prefix> + <v4-next-hop-address>192.168.1.15</v4-next-hop-address> + <v4-static-route-prefix-length>28</v4-static-route-prefix-length> + </v4-static-routes> + <v4-static-routes> + <v4-static-route-prefix>255.255.252.3</v4-static-route-prefix> + <v4-next-hop-address>192.168.1.15</v4-next-hop-address> + <v4-static-route-prefix-length>28</v4-static-route-prefix-length> + </v4-static-routes> + </static-routes> + <dhcp> + <v6-dhcp-server-enabled>N</v6-dhcp-server-enabled> + <v4-dhcp-server-enabled>Y</v4-dhcp-server-enabled> + <use-v6-default-pool>N</use-v6-default-pool> + <excluded-v4-dhcp-addresses-from-default-pool> + <excluded-v4-address>192.168.1.7</excluded-v4-address> + </excluded-v4-dhcp-addresses-from-default-pool> + <excluded-v4-dhcp-addresses-from-default-pool> + <excluded-v4-address>192.168.1.8</excluded-v4-address> + </excluded-v4-dhcp-addresses-from-default-pool> + <v4-dhcp-pools> + <v4-dhcp-relay-next-hop-address>1.1.1.1</v4-dhcp-relay-next-hop-address> + <v4-dhcp-pool-prefix-length>28</v4-dhcp-pool-prefix-length> + <excluded-v4-addresses> + <excluded-v4-address>192.168.1.5</excluded-v4-address> + </excluded-v4-addresses> + <v4-dhcp-relay-gateway-address>2.2.2.1</v4-dhcp-relay-gateway-address> + <excluded-v4-addresses> + <excluded-v4-address>192.168.1.6</excluded-v4-address> + </excluded-v4-addresses> + <v4-dhcp-pool-prefix>192.155.2.3</v4-dhcp-pool-prefix> + </v4-dhcp-pools> + <v4-dhcp-pools> + <v4-dhcp-relay-next-hop-address>1.1.1.2</v4-dhcp-relay-next-hop-address> + <v4-dhcp-pool-prefix-length>28</v4-dhcp-pool-prefix-length> + <excluded-v4-addresses> + <excluded-v4-address>192.168.1.6</excluded-v4-address> + </excluded-v4-addresses> + <v4-dhcp-relay-gateway-address>2.2.2.2</v4-dhcp-relay-gateway-address> + <excluded-v4-addresses> + <excluded-v4-address>192.168.1.7</excluded-v4-address> + </excluded-v4-addresses> + <v4-dhcp-pool-prefix>192.155.2.4</v4-dhcp-pool-prefix> + </v4-dhcp-pools> + <use-v4-default-pool>Y</use-v4-default-pool> + <excluded-v6-dhcp-addresses-from-default-pool> + <excluded-v6-address>1:5</excluded-v6-address> + </excluded-v6-dhcp-addresses-from-default-pool> + <excluded-v6-dhcp-addresses-from-default-pool> + <excluded-v6-address>1:6</excluded-v6-address> + </excluded-v6-dhcp-addresses-from-default-pool> + <v6-dhcp-pools> + <v6-dhcp-relay-next-hop-address>4:4</v6-dhcp-relay-next-hop-address> + <v6-dhcp-pool-prefix-length>28</v6-dhcp-pool-prefix-length> + <excluded-v6-addresses> + <excluded-v6-address>1:1</excluded-v6-address> + </excluded-v6-addresses> + <v6-dhcp-relay-gateway-address>3:3</v6-dhcp-relay-gateway-address> + <excluded-v6-addresses> + <excluded-v6-address>2:2</excluded-v6-address> + </excluded-v6-addresses> + <v6-dhcp-pool-prefix>0:0</v6-dhcp-pool-prefix> + </v6-dhcp-pools> + <v6-dhcp-pools> + <v6-dhcp-relay-next-hop-address>4:4</v6-dhcp-relay-next-hop-address> + <v6-dhcp-pool-prefix-length>28</v6-dhcp-pool-prefix-length> + <excluded-v6-addresses> + <excluded-v6-address>1:1</excluded-v6-address> + </excluded-v6-addresses> + <v6-dhcp-relay-gateway-address>3:3</v6-dhcp-relay-gateway-address> + <excluded-v6-addresses> + <excluded-v6-address>2:2</excluded-v6-address> + </excluded-v6-addresses> + <v6-dhcp-pool-prefix>0:0</v6-dhcp-pool-prefix> + </v6-dhcp-pools> + </dhcp> + <firewall-lite> + <stateful-firewall-lite-v6-enabled>N</stateful-firewall-lite-v6-enabled> + <stateful-firewall-lite-v4-enabled>Y</stateful-firewall-lite-v4-enabled> + <v4-firewall-packet-filters> + <v4-firewall-prefix>0.0.0.1</v4-firewall-prefix> + <v4-firewall-prefix-length>1</v4-firewall-prefix-length> + <allow-icmp-ping>Y</allow-icmp-ping> + <udp-ports> + <port-number>1</port-number> + </udp-ports> + <tcp-ports> + <port-number>1</port-number> + </tcp-ports> + </v4-firewall-packet-filters> + <v4-firewall-packet-filters> + <v4-firewall-prefix>0.0.0.2</v4-firewall-prefix> + <v4-firewall-prefix-length>2</v4-firewall-prefix-length> + <allow-icmp-ping>Y</allow-icmp-ping> + <udp-ports> + <port-number>2</port-number> + </udp-ports> + <tcp-ports> + <port-number>2</port-number> + </tcp-ports> + </v4-firewall-packet-filters> + <v6-firewall-packet-filters> + <v6-firewall-prefix>:</v6-firewall-prefix> + <v6-firewall-prefix-length>0</v6-firewall-prefix-length> + <allow-icmp-ping>Y</allow-icmp-ping> + <udp-ports> + <port-number>3</port-number> + </udp-ports> + <tcp-ports> + <port-number>3</port-number> + </tcp-ports> + </v6-firewall-packet-filters> + <v6-firewall-packet-filters> + <v6-firewall-prefix>:</v6-firewall-prefix> + <v6-firewall-prefix-length>1</v6-firewall-prefix-length> + <allow-icmp-ping>Y</allow-icmp-ping> + <udp-ports> + <port-number>4</port-number> + </udp-ports> + <tcp-ports> + <port-number>4</port-number> + </tcp-ports> + </v6-firewall-packet-filters> + </firewall-lite> + <pat> + <v4-pat-pools> + <v4-pat-pool-prefix>192.168.1.44</v4-pat-pool-prefix> + <v4-pat-pool-next-hop-address>192.168.1.5</v4-pat-pool-next-hop-address> + <v4-pat-pool-prefix-length>0</v4-pat-pool-prefix-length> + </v4-pat-pools> + <use-v4-default-pool>Y</use-v4-default-pool> + <v4-pat-enabled>N</v4-pat-enabled> + <v4-pat-pools> + <v4-pat-pool-prefix>192.168.1.45</v4-pat-pool-prefix> + <v4-pat-pool-next-hop-address>192.168.1.6</v4-pat-pool-next-hop-address> + <v4-pat-pool-prefix-length>28</v4-pat-pool-prefix-length> + </v4-pat-pools> + </pat> + <nat> + <v4-nat-enabled>Y</v4-nat-enabled> + <v4-nat-mapping-entries> + <v4-nat-internal>0.0.0.0</v4-nat-internal> + <v4-nat-next-hop-address>0.0.0.0</v4-nat-next-hop-address> + <v4-nat-external>0.0.0.0</v4-nat-external> + </v4-nat-mapping-entries> + <v4-nat-mapping-entries> + <v4-nat-internal>0.0.0.1</v4-nat-internal> + <v4-nat-next-hop-address>0.0.0.1</v4-nat-next-hop-address> + <v4-nat-external>0.0.0.1</v4-nat-external> + </v4-nat-mapping-entries> + </nat> + <vr-designation>primary</vr-designation> + <v4-vce-loopback-address>162.200.3.144</v4-vce-loopback-address> + <v6-vr-lan-prefix-length>64</v6-vr-lan-prefix-length> + <v6-vce-wan-address>2001:1890:12e3:2da::</v6-vce-wan-address> + <v6-vr-lan-prefix>2620:0:10d0:f:ffff:ffff:ffff:fffe</v6-vr-lan-prefix> + <v4-vr-lan-prefix-length>24</v4-vr-lan-prefix-length> + <v4-vr-lan-prefix>10.192.27.254</v4-vr-lan-prefix> + <v4-public-lan-prefixes> + <t-provided-v4-lan-public-prefixes> + <request-index>1</request-index> + <v4-next-hop-address>192.168.1.2</v4-next-hop-address> + <v4-lan-public-prefix>192.168.1.1</v4-lan-public-prefix> + <v4-lan-public-prefix-length>28</v4-lan-public-prefix-length> + </t-provided-v4-lan-public-prefixes> + <t-provided-v4-lan-public-prefixes> + <request-index>1</request-index> + <v4-next-hop-address>192.168.1.72</v4-next-hop-address> + <v4-lan-public-prefix>192.168.1.71</v4-lan-public-prefix> + <v4-lan-public-prefix-length>28</v4-lan-public-prefix-length> + </t-provided-v4-lan-public-prefixes> + <t-provided-v4-lan-public-prefixes> + <request-index>1</request-index> + <v4-next-hop-address>192.168.1.68</v4-next-hop-address> + <v4-lan-public-prefix>192.168.1.67</v4-lan-public-prefix> + <v4-lan-public-prefix-length>28</v4-lan-public-prefix-length> + </t-provided-v4-lan-public-prefixes> + </v4-public-lan-prefixes> + <v6-public-lan-prefixes> + <t-provided-v6-lan-public-prefixes> + <request-index>1</request-index> + <v6-next-hop-address>2001:1890:12e3:2da::</v6-next-hop-address> + <v6-lan-public-prefix>2001:1890:12e3:2da::</v6-lan-public-prefix> + <v6-lan-public-prefix-length>28</v6-lan-public-prefix-length> + </t-provided-v6-lan-public-prefixes> + <t-provided-v6-lan-public-prefixes> + <request-index>1</request-index> + <v6-next-hop-address>2001:1890:12e3:2da::</v6-next-hop-address> + <v6-lan-public-prefix>2001:1890:12e3:3da::</v6-lan-public-prefix> + <v6-lan-public-prefix-length>28</v6-lan-public-prefix-length> + </t-provided-v6-lan-public-prefixes> + <t-provided-v6-lan-public-prefixes> + <request-index>1</request-index> + <v6-next-hop-address>2001:1890:12e3:2da::</v6-next-hop-address> + <v6-lan-public-prefix>2001:1890:12e3:4da::</v6-lan-public-prefix> + <v6-lan-public-prefix-length>28</v6-lan-public-prefix-length> + </t-provided-v6-lan-public-prefixes> + </v6-public-lan-prefixes> + </vr-lan-interface> + <routing-protocol>none</routing-protocol> + </vr-lan> +<ucpe-vms-service-information> + <transport-service-information> + <transport-service-type>AVPN</transport-service-type> + <access-circuit-info> + <access-circuit-id>1</access-circuit-id> + <dual-mode>Active</dual-mode> + </access-circuit-info> + <access-circuit-info> + <access-circuit-id>2</access-circuit-id> + <dual-mode>Standby</dual-mode> + </access-circuit-info> + </transport-service-information> + <ucpe-information> + <ucpe-host-name>hostname</ucpe-host-name> + <ucpe-activation-code>activecode</ucpe-activation-code> + <out-of-band-management-modem>OOB</out-of-band-management-modem> + </ucpe-information> + <vnf-list> + <vnf-information> + <vnf-instance-id>1</vnf-instance-id> + <vnf-sequence-number>1</vnf-sequence-number> + <vnf-type>ZZ</vnf-type> + <vnf-vendor>JUNIPER</vnf-vendor> + <vnf-model>MODEL1</vnf-model> + <vnf-id>1</vnf-id> + <prov-status>1</prov-status> + <operational-state>1</operational-state> + <orchestration-status>1</orchestration-status> + <equipment-role>1</equipment-role> + </vnf-information> + <vnf-information> + <vnf-instance-id>2</vnf-instance-id> + <vnf-sequence-number>2</vnf-sequence-number> + <vnf-type>HY</vnf-type> + <vnf-vendor>JUNIPER</vnf-vendor> + <vnf-model>MODEL2</vnf-model> + <vnf-id>2</vnf-id> + <prov-status>2</prov-status> + <operational-state>2</operational-state> + <orchestration-status>2</orchestration-status> + <equipment-role>2</equipment-role> + </vnf-information> + </vnf-list> + </ucpe-vms-service-information> + <request-information> + <request-action>Layer3ServiceActivateRequest</request-action> + <order-number>4281555</order-number> + <request-id>155415ab-b4a7-4382-b4c6-d17d9sm42855</request-id> + <notification-url>https://csi-tst-q22.it.com:22443/Services/com/cingular/csi/sdn/SendManagedNetworkStatusNotification.jws</notification-url> + <source>OMX</source> + <order-version>1</order-version> + </request-information> + <sdnc-request-header> + <svc-action>activate</svc-action> + <svc-notification-url>https://msojra.mtsnjdcp1.aic.cip.com:8443/adapters/rest/SDNCNotify</svc-notification-url> + <svc-request-id>5b1f3c5d-cdf9-488d-8a4b-d3f1229d7760</svc-request-id> + </sdnc-request-header> + <l2-homing-information> + <topology>MultiPoint</topology> + <preferred-aic-clli>MTSNJA4LCP1</preferred-aic-clli> + <evc-name>AS/VLXM/003717//SW</evc-name> + </l2-homing-information> + <service-information> + <service-instance-id>FK/VLXM/003717//SW_INTERNET</service-instance-id> + <subscriber-name>FOUR SEASONS HEATING & COOLING_8310006378683</subscriber-name> + <service-type>SDN-ETHERNET-INTERNET</service-type> + </service-information> + <internet-service-change-details> + <internet-evc-speed-value>10</internet-evc-speed-value> + <internet-evc-speed-units>Kbps</internet-evc-speed-units> + <t-provided-v4-lan-public-prefixes> + <request-index>1</request-index> + <v4-next-hop-address>192.168.1.15</v4-next-hop-address> + <v4-lan-public-prefix>192.168.1.15</v4-lan-public-prefix> + <v4-lan-public-prefix-length>28</v4-lan-public-prefix-length> + </t-provided-v4-lan-public-prefixes> + <t-provided-v4-lan-public-prefixes> + <request-index>2</request-index> + <v4-next-hop-address>192.168.1.16</v4-next-hop-address> + <v4-lan-public-prefix>192.168.1.16</v4-lan-public-prefix> + <v4-lan-public-prefix-length>28</v4-lan-public-prefix-length> + </t-provided-v4-lan-public-prefixes> + <t-provided-v6-lan-public-prefixes> + <request-index>1</request-index> + <v6-next-hop-address>2001:1890:12e3:2da::</v6-next-hop-address> + <v6-lan-public-prefix>2001:1890:12e3:2da::</v6-lan-public-prefix> + <v6-lan-public-prefix-length>28</v6-lan-public-prefix-length> + </t-provided-v6-lan-public-prefixes> + <t-provided-v6-lan-public-prefixes> + <request-index>1</request-index> + <v6-next-hop-address>2001:1890:12e3:2da::</v6-next-hop-address> + <v6-lan-public-prefix>2001:1890:12e3:2da::</v6-lan-public-prefix> + <v6-lan-public-prefix-length>28</v6-lan-public-prefix-length> + </t-provided-v6-lan-public-prefixes> + </internet-service-change-details> + </service-data> + </layer3-service-list> + + diff --git a/bpmn/MSOCommonBPMN/src/test/resources/sdncadaptercallbackrequest_404CallBack.xml b/bpmn/MSOCommonBPMN/src/test/resources/sdncadaptercallbackrequest_404CallBack.xml index 5808444d12..aa481ea600 100644 --- a/bpmn/MSOCommonBPMN/src/test/resources/sdncadaptercallbackrequest_404CallBack.xml +++ b/bpmn/MSOCommonBPMN/src/test/resources/sdncadaptercallbackrequest_404CallBack.xml @@ -1,13 +1,13 @@ - - - - 39542e39-ccc3-4d1a-8b79-04ce88526613 - 404 - Error processing request to SDNC. Not Found. - https://sdncodl.us.aic.cip.att.com:8443/restconf/config/L3SDN-API:services/layer3-service-list/MVM%2FVLXP%2F000855%2F%2FShakeout. - SDNC Returned-[error-type:application, error-tag:data-missing, - error-message:Request could not be completed because the relevant - data model content does not exist.] - + + + + 39542e39-ccc3-4d1a-8b79-04ce88526613 + 404 + Error processing request to SDNC. Not Found. + https://sdncodl.us.aic.cip.com:8443/restconf/config/L3SDN-API:services/layer3-service-list/MVM%2FVLXP%2F000855%2F%2FShakeout. + SDNC Returned-[error-type:application, error-tag:data-missing, + error-message:Request could not be completed because the relevant + data model content does not exist.] + \ No newline at end of file diff --git a/bpmn/MSOCoreBPMN/src/main/java/org/openecomp/mso/bpmn/core/XQueryScriptTask.java b/bpmn/MSOCoreBPMN/src/main/java/org/openecomp/mso/bpmn/core/XQueryScriptTask.java index 926f2af9aa..31da7376be 100644 --- a/bpmn/MSOCoreBPMN/src/main/java/org/openecomp/mso/bpmn/core/XQueryScriptTask.java +++ b/bpmn/MSOCoreBPMN/src/main/java/org/openecomp/mso/bpmn/core/XQueryScriptTask.java @@ -1,243 +1,243 @@ -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - MSO - * ================================================================================ - * 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.openecomp.mso.bpmn.core; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.math.BigDecimal; -import java.net.URI; -import java.util.Iterator; - -import javax.xml.transform.stream.StreamSource; - -import org.camunda.bpm.engine.ProcessEngineException; -import org.camunda.bpm.engine.delegate.DelegateExecution; -//import java.util.logging.Logger; -import org.camunda.bpm.engine.delegate.Expression; - -import org.openecomp.mso.logger.MessageEnum; -import org.openecomp.mso.logger.MsoLogger; - -import net.sf.saxon.Configuration; -import net.sf.saxon.s9api.DocumentBuilder; -import net.sf.saxon.s9api.Processor; -import net.sf.saxon.s9api.QName; -import net.sf.saxon.s9api.XQueryCompiler; -import net.sf.saxon.s9api.XQueryEvaluator; -import net.sf.saxon.s9api.XQueryExecutable; -import net.sf.saxon.s9api.XdmAtomicValue; -import net.sf.saxon.s9api.XdmItem; -import net.sf.saxon.s9api.XdmNode; - -/** - * Executes an XQuery script. - *

- * Required fields:

- *     scriptFile: the XQuery script file path
- *     outputVariable: the output variable name
- *

- * Optional fields:

- *     xmlInputVariables: CSV list of variables containing - * XML data to be injected into the script
- *     atomicInputVariables: CSV list of variables containing - * atomic data to be injected into the script
- */ -public class XQueryScriptTask extends BaseTask { - - private static MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL); - - private Expression scriptFile; - private Expression xmlInputVariables; - private Expression atomicInputVariables; - private Expression outputVariable; - - public void execute(DelegateExecution execution) throws Exception { - if (msoLogger.isDebugEnabled()) { - msoLogger.debug("Started Executing " + getTaskName()); - } - - String theScriptFile = - getStringField(scriptFile, execution, "scriptFile"); - String theXmlInputVariables = - getOptionalStringField(xmlInputVariables, execution, "xmlInputVariables"); - String theAtomicInputVariables = - getOptionalStringField(atomicInputVariables, execution, "atomicInputVariables"); - String theOutputVariable = - getStringField(outputVariable, execution, "outputVariable"); - - if (msoLogger.isDebugEnabled()) { - System.out.println("scriptFile = " + theScriptFile - + " xmlInputVariables = " + theXmlInputVariables - + " atomicInputVariables = " + theAtomicInputVariables - + "outputVariable = " + theOutputVariable); - } - - String[] xmlInputVariableArray = (theXmlInputVariables == null) - ? new String[0] : theXmlInputVariables.split(",[ ]*"); - - String[] atomicInputVariableArray = (theAtomicInputVariables == null) - ? new String[0] : theAtomicInputVariables.split(",[ ]*"); - - Boolean shouldFail = (Boolean) execution.getVariable("shouldFail"); - - if (shouldFail != null && shouldFail) { - throw new ProcessEngineException(getClass().getSimpleName() + " Failed"); - } - - // The script could be compiled once and reused, but we are reading it - // and compiling it every time. - Configuration configuration = new Configuration(); - Processor processor = new Processor(configuration); - XQueryCompiler compiler = processor.newXQueryCompiler(); - XQueryExecutable executable = compile(compiler, theScriptFile); - - // The evaluator must not be shared by multiple threads. Here is where - // the initial context may be set, as well as values of external variables. - XQueryEvaluator evaluator = executable.load(); - - // Convert XML string variable content to document-node objects and inject - // these into the evaluator. Note: the script must accept the document-node - // type. Most MSO scripts today expect element() input, not document-node - // input. TODO: figure out how to pass the variable data as element() types. - - for (String xmlInputVariable : xmlInputVariableArray) { - if (msoLogger.isDebugEnabled()) { - msoLogger.debug("Injecting XML variable '" + xmlInputVariable + "'"); - msoLogger.debug("printing the variable content>>'" + execution.getVariable(xmlInputVariable) +"'"); - } - - String xml = (String) execution.getVariable(xmlInputVariable); - DocumentBuilder documentBuilder = processor.newDocumentBuilder(); - StreamSource source = new StreamSource(new ByteArrayInputStream(xml.getBytes("UTF-8"))); - XdmNode xdmNode = documentBuilder.build(source); - - // Inject the document-node object into the XQueryEvaluator. - // TODO: transform it to an element() - QName variable = new QName(xmlInputVariable); - evaluator.setExternalVariable(variable, xdmNode); - } - - // Inject atomic variables into the evaluator. - - for (String atomicInputVariable : atomicInputVariableArray) { - - if (msoLogger.isDebugEnabled()) { - System.out.println("Injecting object variable '" - + atomicInputVariable + "'"); - } - - QName variable = new QName(atomicInputVariable); - Object value = execution.getVariable(atomicInputVariable); - - if (value == null) { - // The variable value is null, so we have no way to know what - // type it is. I don't know how to deal with this, so for - // now, just skip it. - - msoLogger.warn (MessageEnum.BPMN_VARIABLE_NULL, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.DataError, atomicInputVariable); - - continue; - } - - // There might be a better way to do this... - if (value instanceof BigDecimal) { - evaluator.setExternalVariable(variable, - new XdmAtomicValue((BigDecimal) value)); - } else if (value instanceof Boolean) { - evaluator.setExternalVariable(variable, - new XdmAtomicValue((Boolean) value)); - } else if (value instanceof Double) { - evaluator.setExternalVariable(variable, - new XdmAtomicValue((Double) value)); - } else if (value instanceof Float) { - evaluator.setExternalVariable(variable, - new XdmAtomicValue((Float) value)); - } else if (value instanceof Long) { - evaluator.setExternalVariable(variable, - new XdmAtomicValue((Long) value)); - } else if (value instanceof String) { - evaluator.setExternalVariable(variable, - new XdmAtomicValue((String) value)); - } else if (value instanceof URI) { - evaluator.setExternalVariable(variable, - new XdmAtomicValue((URI) value)); - } else { - throw new BadInjectedFieldException( - "atomicInputVariables", getTaskName(), - "'" + atomicInputVariable + "' type is not supported: " - + value.getClass()); - } - } - - // Evaluate the query and collect the output. - StringBuilder output = new StringBuilder(); - Iterator xdmItems = evaluator.iterator(); - while (xdmItems.hasNext()) { - XdmItem item = xdmItems.next(); - - if (msoLogger.isDebugEnabled()) { - msoLogger.debug("XQuery result item = " + item); - } - - output.append(item.toString()); - } - - // Set the output variable. - execution.setVariable(theOutputVariable, output.toString()); - - if (msoLogger.isDebugEnabled()) { - msoLogger.debug("Done Executing " + getTaskName()); - } - } - - /** - * Compiles an XQuery script contained in a resource (file). - * @param compiler the XQueryCompiler - * @param resource the resource path - * @return an XQueryExecutable - * @throws Exception on error - */ - private XQueryExecutable compile(XQueryCompiler compiler, String resource) - throws Exception { - InputStream xqStream = null; - try { - xqStream = getClass().getResourceAsStream(resource); - - if (xqStream == null) { - throw new IOException("Resource not found: " + resource); - } - - XQueryExecutable executable = compiler.compile(xqStream); - xqStream.close(); - xqStream = null; - return executable; - } finally { - if (xqStream != null) { - try { - xqStream.close(); - } catch (Exception e) { - // Do nothing - } - } - } - } +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.bpmn.core; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.math.BigDecimal; +import java.net.URI; +import java.util.Iterator; + +import javax.xml.transform.stream.StreamSource; + +import org.camunda.bpm.engine.ProcessEngineException; +import org.camunda.bpm.engine.delegate.DelegateExecution; +//import java.util.logging.Logger; +import org.camunda.bpm.engine.delegate.Expression; + +import org.openecomp.mso.logger.MessageEnum; +import org.openecomp.mso.logger.MsoLogger; + +import net.sf.saxon.Configuration; +import net.sf.saxon.s9api.DocumentBuilder; +import net.sf.saxon.s9api.Processor; +import net.sf.saxon.s9api.QName; +import net.sf.saxon.s9api.XQueryCompiler; +import net.sf.saxon.s9api.XQueryEvaluator; +import net.sf.saxon.s9api.XQueryExecutable; +import net.sf.saxon.s9api.XdmAtomicValue; +import net.sf.saxon.s9api.XdmItem; +import net.sf.saxon.s9api.XdmNode; + +/** + * Executes an XQuery script. + *

+ * Required fields:

+ *     scriptFile: the XQuery script file path
+ *     outputVariable: the output variable name
+ *

+ * Optional fields:

+ *     xmlInputVariables: CSV list of variables containing + * XML data to be injected into the script
+ *     atomicInputVariables: CSV list of variables containing + * atomic data to be injected into the script
+ */ +public class XQueryScriptTask extends BaseTask { + + private static MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL); + + private Expression scriptFile; + private Expression xmlInputVariables; + private Expression atomicInputVariables; + private Expression outputVariable; + + public void execute(DelegateExecution execution) throws Exception { + if (msoLogger.isDebugEnabled()) { + msoLogger.debug("Started Executing " + getTaskName()); + } + + String theScriptFile = + getStringField(scriptFile, execution, "scriptFile"); + String theXmlInputVariables = + getOptionalStringField(xmlInputVariables, execution, "xmlInputVariables"); + String theAtomicInputVariables = + getOptionalStringField(atomicInputVariables, execution, "atomicInputVariables"); + String theOutputVariable = + getStringField(outputVariable, execution, "outputVariable"); + + if (msoLogger.isDebugEnabled()) { + System.out.println("scriptFile = " + theScriptFile + + " xmlInputVariables = " + theXmlInputVariables + + " atomicInputVariables = " + theAtomicInputVariables + + "outputVariable = " + theOutputVariable); + } + + String[] xmlInputVariableArray = (theXmlInputVariables == null) + ? new String[0] : theXmlInputVariables.split(",[ ]*"); + + String[] atomicInputVariableArray = (theAtomicInputVariables == null) + ? new String[0] : theAtomicInputVariables.split(",[ ]*"); + + Boolean shouldFail = (Boolean) execution.getVariable("shouldFail"); + + if (shouldFail != null && shouldFail) { + throw new ProcessEngineException(getClass().getSimpleName() + " Failed"); + } + + // The script could be compiled once and reused, but we are reading it + // and compiling it every time. + Configuration configuration = new Configuration(); + Processor processor = new Processor(configuration); + XQueryCompiler compiler = processor.newXQueryCompiler(); + XQueryExecutable executable = compile(compiler, theScriptFile); + + // The evaluator must not be shared by multiple threads. Here is where + // the initial context may be set, as well as values of external variables. + XQueryEvaluator evaluator = executable.load(); + + // Convert XML string variable content to document-node objects and inject + // these into the evaluator. Note: the script must accept the document-node + // type. Most MSO scripts today expect element() input, not document-node + // input. TODO: figure out how to pass the variable data as element() types. + + for (String xmlInputVariable : xmlInputVariableArray) { + if (msoLogger.isDebugEnabled()) { + msoLogger.debug("Injecting XML variable '" + xmlInputVariable + "'"); + msoLogger.debug("printing the variable content>>'" + execution.getVariable(xmlInputVariable) +"'"); + } + + String xml = (String) execution.getVariable(xmlInputVariable); + DocumentBuilder documentBuilder = processor.newDocumentBuilder(); + StreamSource source = new StreamSource(new ByteArrayInputStream(xml.getBytes("UTF-8"))); + XdmNode xdmNode = documentBuilder.build(source); + + // Inject the document-node object into the XQueryEvaluator. + // TODO: transform it to an element() + QName variable = new QName(xmlInputVariable); + evaluator.setExternalVariable(variable, xdmNode); + } + + // Inject atomic variables into the evaluator. + + for (String atomicInputVariable : atomicInputVariableArray) { + + if (msoLogger.isDebugEnabled()) { + System.out.println("Injecting object variable '" + + atomicInputVariable + "'"); + } + + QName variable = new QName(atomicInputVariable); + Object value = execution.getVariable(atomicInputVariable); + + if (value == null) { + // The variable value is null, so we have no way to know what + // type it is. I don't know how to deal with this, so for + // now, just skip it. + + msoLogger.warn (MessageEnum.BPMN_VARIABLE_NULL, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.DataError, atomicInputVariable); + + continue; + } + + // There might be a better way to do this... + if (value instanceof BigDecimal) { + evaluator.setExternalVariable(variable, + new XdmAtomicValue((BigDecimal) value)); + } else if (value instanceof Boolean) { + evaluator.setExternalVariable(variable, + new XdmAtomicValue((Boolean) value)); + } else if (value instanceof Double) { + evaluator.setExternalVariable(variable, + new XdmAtomicValue((Double) value)); + } else if (value instanceof Float) { + evaluator.setExternalVariable(variable, + new XdmAtomicValue((Float) value)); + } else if (value instanceof Long) { + evaluator.setExternalVariable(variable, + new XdmAtomicValue((Long) value)); + } else if (value instanceof String) { + evaluator.setExternalVariable(variable, + new XdmAtomicValue((String) value)); + } else if (value instanceof URI) { + evaluator.setExternalVariable(variable, + new XdmAtomicValue((URI) value)); + } else { + throw new BadInjectedFieldException( + "atomicInputVariables", getTaskName(), + "'" + atomicInputVariable + "' type is not supported: " + + value.getClass()); + } + } + + // Evaluate the query and collect the output. + StringBuilder output = new StringBuilder(); + Iterator xdmItems = evaluator.iterator(); + while (xdmItems.hasNext()) { + XdmItem item = xdmItems.next(); + + if (msoLogger.isDebugEnabled()) { + msoLogger.debug("XQuery result item = " + item); + } + + output.append(item.toString()); + } + + // Set the output variable. + execution.setVariable(theOutputVariable, output.toString()); + + if (msoLogger.isDebugEnabled()) { + msoLogger.debug("Done Executing " + getTaskName()); + } + } + + /** + * Compiles an XQuery script contained in a resource (file). + * @param compiler the XQueryCompiler + * @param resource the resource path + * @return an XQueryExecutable + * @throws Exception on error + */ + private XQueryExecutable compile(XQueryCompiler compiler, String resource) + throws Exception { + InputStream xqStream = null; + try { + xqStream = getClass().getResourceAsStream(resource); + + if (xqStream == null) { + throw new IOException("Resource not found: " + resource); + } + + XQueryExecutable executable = compiler.compile(xqStream); + xqStream.close(); + xqStream = null; + return executable; + } finally { + if (xqStream != null) { + try { + xqStream.close(); + } catch (Exception e) { + // Do nothing + } + } + } + } } \ No newline at end of file diff --git a/bpmn/MSOCoreBPMN/src/main/java/org/openecomp/mso/bpmn/core/json/JsonUtils.java b/bpmn/MSOCoreBPMN/src/main/java/org/openecomp/mso/bpmn/core/json/JsonUtils.java index 462bda8077..4c0d068b28 100644 --- a/bpmn/MSOCoreBPMN/src/main/java/org/openecomp/mso/bpmn/core/json/JsonUtils.java +++ b/bpmn/MSOCoreBPMN/src/main/java/org/openecomp/mso/bpmn/core/json/JsonUtils.java @@ -1,830 +1,830 @@ -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - MSO - * ================================================================================ - * 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.openecomp.mso.bpmn.core.json; - -import java.util.Iterator; -import java.util.Map; -import java.util.HashMap; -import java.util.StringTokenizer; - -import org.camunda.bpm.engine.runtime.Execution; -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; -import org.json.XML; - -//import org.openecomp.mso.bpmn.core.BPMNLogger; -import org.openecomp.mso.bpmn.core.xml.XmlTool; -import org.openecomp.mso.logger.MsoLogger; - -/** - * Utility class for JSON processing - * - * @version 1.0 - */ - -public class JsonUtils { - - private static MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL); - private static int MSOJsonIndentFactor = 3; - - /** - * Uses the JSONObject static method to convert a XML doc to JSON. - * - * @param xml String containing the XML doc - * @param pretty flag to determine if the output should be formatted - * @return String containing the JSON translation - */ - public static String xml2json(String xml, Boolean pretty) { -// String isDebugLogEnabled = "true"; - try { - // name spaces cause problems, so just remove them - JSONObject jsonObj = XML.toJSONObject(XmlTool.removeNamespaces(xml)); - if (!pretty) { - return jsonObj.toString(); - } else { - // add an indent to make it 'pretty' - return jsonObj.toString(MSOJsonIndentFactor); - } - } catch (Exception e){ - msoLogger.debug("xml2json(): unable to parse xml and convert to json. Exception was: " + e.toString()); - return null; - } - } - - /** - * Invokes xml2json(String, Boolean) defaulting to 'pretty' output. - * - * @param xml String containing the XML doc - * @return String containing the JSON translation - */ - public static String xml2json(String xml) { - return xml2json(xml, true); - } - - /** - * Uses the JSONObject static method to convert a JSON doc to XML. - * Note: this method may not generate valid XML if the JSONObject - * contains JSONArrays which are used to represent XML attributes - * in the JSON doc. - * - * @param jsonStr String containing the JSON doc - * @param pretty flag to determine if the output should be formatted - * @return String containing the XML translation - */ - public static String json2xml(String jsonStr, Boolean pretty) { -// String isDebugLogEnabled = "true"; - try { - JSONObject jsonObj = new JSONObject(jsonStr); - if (pretty) { - // use the local class method which properly handles certain JSONArray content - return XmlTool.normalize(toXMLString(jsonObj, null)); - } else { -// use the local class method which properly handles certain JSONArray content - return toXMLString(jsonObj, null); - } - } catch (Exception e){ - msoLogger.debug("json2xml(): unable to parse json and convert to xml. Exception was: " + e.toString()); - return null; - } - } - - /** - * Uses a modified version of the org.json.XML toString() algorithm - * to convert a JSONObject to an XML Doc. The intent of this is to - * correctly generate XML from JSON including TAGs for JSONArrays - * - * @param jsonObj org.json.JSON object to be converted to XML - * @param tagName optional XML tagname supplied primarily during recursive calls - * @return String containing the XML translation - */ - public static String toXMLString(Object obj, String tagName) throws JSONException { - StringBuffer strBuf = new StringBuffer(); - int i; - JSONArray jsonArr; - JSONObject jsonObj; - String key; - Iterator keys; - int len; - String str; - Object curObj; - if (obj instanceof JSONObject) { - // msoLogger.debug("toXMLString(): is a JSONObject"); - // append "" to the XML output - if (tagName != null) { -// msoLogger.debug("toXMLString(): adding opening tagName: " + tagName); - strBuf.append("<"); - strBuf.append(tagName); - strBuf.append(">"); - } - // iterate thru the keys. - jsonObj = (JSONObject) obj; - keys = jsonObj.keys(); - while (keys.hasNext()) { - key = keys.next().toString(); - // msoLogger.debug("toXMLString(): key is " + k); - curObj = jsonObj.opt(key); - if (curObj == null) { - curObj = ""; - } - if (curObj instanceof String) { - str = (String) curObj; - } else { - str = null; - } - // append the content to the XML output - if (key.equals("content")) { - if (curObj instanceof JSONArray) { - jsonArr = (JSONArray) curObj; - len = jsonArr.length(); - for (i = 0; i < len; i += 1) { - if (i > 0) { - strBuf.append('\n'); - } - strBuf.append(XML.escape(jsonArr.get(i).toString())); - } - } else { - strBuf.append(XML.escape(curObj.toString())); - } - // append an array of similar keys to the XML output - } else if (curObj instanceof JSONArray) { - jsonArr = (JSONArray) curObj; - len = jsonArr.length(); -// msoLogger.debug("toXMLString(): found JSONArray: " + key + ", size: " + len); - for (i = 0; i < len; i += 1) { - curObj = jsonArr.get(i); - if (curObj instanceof JSONArray) { -// The XML tags for the nested array should be generated below when this method -// is called recursively and the JSONArray object is passed -// strBuf.append("<"); -// strBuf.append(key); -// strBuf.append(">"); - strBuf.append(toXMLString(curObj, null)); -// strBuf.append(""); - } else { -// msoLogger.debug("toXMLString(): recursive call toXML() with tagName null"); - // append the opening tag for the array (before 1st element) - if (i == 0) { - strBuf.append("<"); - strBuf.append(key); - strBuf.append(">"); - } - // append the opening tag for the array - strBuf.append(toXMLString(curObj, null)); - // append the closing tag for the array (after last element) - if (i == (len - 1)) { - strBuf.append(""); - } - } - } - } else if (curObj.equals("")) { - // append a closing tag "" to the XML output - strBuf.append("<"); - strBuf.append(key); - strBuf.append("/>"); - } else { -// msoLogger.debug("toXMLString(): recursive call toXMLString() with tagName: " + key); - strBuf.append(toXMLString(curObj, key)); - } - // msoLogger.debug("toXML(): partial XML: " + strBuf.toString()); - } - if (tagName != null) { - // append the closing tag "" to the XML output -// msoLogger.debug("toXMLString(): adding closing tagName: " + tagName); - strBuf.append(""); - } - return strBuf.toString(); - // XML does not have good support for arrays. If an array appears in a place - // where XML is lacking, synthesize an < array > element. - } else if (obj instanceof JSONArray) { - jsonArr = (JSONArray) obj; - len = jsonArr.length(); - for (i = 0; i < len; ++i) { - curObj = jsonArr.opt(i); - strBuf.append(toXMLString(curObj, (tagName == null) ? "array" - : tagName)); - } - return strBuf.toString(); - } else { -// msoLogger.debug("toXML(): in else block with tagName: " + tagName); - str = (obj == null) ? "null" : XML.escape(obj.toString()); - return (tagName == null) ? "\"" + str + "\"" - : (str.length() == 0) ? "<" + tagName + "/>" : "<" - + tagName + ">" + str + ""; - } - } - - /** - * Formats the JSON String using the value of MSOJsonIndentFactor. - * - * @param jsonStr String containing the JSON doc - * @return String containing the formatted JSON doc - */ - public static String prettyJson(String jsonStr) { -// String isDebugLogEnabled = "true"; - try { - JSONObject jsonObj = new JSONObject(jsonStr); - return jsonObj.toString(MSOJsonIndentFactor); - } catch (Exception e){ - msoLogger.debug("prettyJson(): unable to parse/format json input. Exception was: " + e.toString()); - return null; - } - } - - /** - * Invokes json2xml(String, Boolean) defaulting to 'pretty' output. - * - * @param jsonStr String containing the XML doc - * @return String containing the JSON translation - */ - public static String json2xml(String jsonStr) { - return json2xml(jsonStr, true); - } - - /** - * Returns an Iterator over the JSON keys in the specified JSON doc. - * - * @param jsonStr String containing the JSON doc - * @return Iterator over the JSON keys - * @throws JSONException if the doc cannot be parsed - */ - public static Iterator getJsonIterator(String jsonStr) throws JSONException { - return new JSONObject(jsonStr).keys(); - } - - /** - * Returns the name of the "root" property in the specified JSON doc. The - * "root" property is the single top-level property in the JSON doc. An - * exception is thrown if the doc is empty or if it contains more than one - * top-level property. - * - * @param jsonStr String containing the JSON doc - * @return the name of the "root" property - * @throws JSONException if the doc cannot be parsed, or if it is empty, or if - * it contains more than one top-level property - */ - public static String getJsonRootProperty(String jsonStr) throws JSONException { - Iterator iter = getJsonIterator(jsonStr); - - if (!iter.hasNext()) { - throw new JSONException("Empty JSON object"); - } - - String rootPropertyName = iter.next(); - - if (iter.hasNext()) { - throw new JSONException("JSON object has more than one root property"); - } - - return rootPropertyName; - } - - /** - * Invokes the getJsonRawValue() method and returns the String equivalent of - * the object returned. - * - * TBD: May need separate methods for boolean, float, and integer fields if the - * String representation is not sufficient to meet client needs. - * - * @param jsonStr String containing the JSON doc - * @param keys full key path to the target value in the format of "key1.key2.key3..." - * @return String field value associated with keys - */ - public static String getJsonValue(String jsonStr, String keys) { -// String isDebugLogEnabled = "true"; - try { - Object rawValue = getJsonRawValue(jsonStr, keys); - if (rawValue == null) { - return null; - } else { - if (rawValue instanceof String) { - msoLogger.debug("getJsonValue(): the raw value is a String Object=" + ((String) rawValue).toString()); - return (String) rawValue; - } else { - msoLogger.debug("getJsonValue(): the raw value is NOT a String Object=" + rawValue.toString()); - return rawValue.toString(); - } - } - } catch (Exception e) { - msoLogger.debug("getJsonValue(): unable to parse json to retrieve value for field=" + keys + ". Exception was: " + e.toString()); - } - return null; - } - - - /** - * Invokes the getJsonRawValue() method with the wrap flag set to true - * and returns the String equivalent of the json node object returned. - * - * @param jsonStr String containing the JSON doc - * @param keys full key path to the target value in the format of "key1.key2.key3..." - * @return String field value associated with keys - */ - public static String getJsonNodeValue(String jsonStr, String keys) { -// String isDebugLogEnabled = "true"; - try { - Object rawValue = getJsonRawValue(jsonStr, keys, true); - if (rawValue == null) { - return null; - } else { - if (rawValue instanceof String) { - msoLogger.debug("getJsonNodeValue(): the raw value is a String Object=" + ((String) rawValue).toString()); - return (String) rawValue; - } else { - msoLogger.debug("getJsonNodeValue(): the raw value is NOT a String Object=" + rawValue.toString()); - return rawValue.toString(); - } - } - } catch (Exception e) { - msoLogger.debug("getJsonNodeValue(): unable to parse json to retrieve node for field=" + keys + ". Exception was: " + e.toString()); - } - return null; - } - - /** - * Invokes the getJsonRawValue() method and returns the String equivalent of - * the object returned. - * - * TBD: May need separate methods for boolean, float, and integer fields if the - * String representation is not sufficient to meet client needs. - * - * @param jsonStr String containing the JSON doc - * @param keys full key path to the target value in the format of "key1.key2.key3..." - * @return String field value associated with keys - */ - public static int getJsonIntValue(String jsonStr, String keys) { -// String isDebugLogEnabled = "true"; - try { - Object rawValue = getJsonRawValue(jsonStr, keys); - if (rawValue == null) { - return 0; - } else { - if (rawValue instanceof Integer) { - msoLogger.debug("getJsonValue(): the raw value is an Integer Object=" + ((String) rawValue).toString()); - return (Integer) rawValue; - } else { - msoLogger.debug("getJsonValue(): the raw value is NOT an Integer Object=" + rawValue.toString()); - return 0; - } - } - } catch (Exception e) { - msoLogger.debug("getJsonValue(): unable to parse json to retrieve value for field=" + keys + ". Exception was: " + e.toString()); - } - return 0; - } - - /** - * Invokes the getJsonParamValue() method to obtain the JSONArray associated with - * the specified keys. The JSONArray is then walked to retrieve the first array - * value associated with the specified field name (index=0). - * - * @param jsonStr String containing the JSON doc - * @param keys full key path to the target value in the format of "key1.key2.key3..." - * @param name field name for the param to be retrieved - * @return String param value associated with field name - */ - public static String getJsonParamValue(String jsonStr, String keys, String name) { - return getJsonParamValue(jsonStr, keys, name, 0); - } - - /** - * Invokes the getJsonRawValue() method to obtain the JSONArray associated with - * the specified keys. The JSONArray is then walked to retrieve the nth array - * value associated with the specified field name and index - * - * @param jsonStr String containing the JSON doc - * @param keys full key path to the target value in the format of "key1.key2.key3..." - * @param name field name for the param to be retrieved - * @param index the nth param associated with name starting at 0 - * @return String param value associated with field name - */ - public static String getJsonParamValue(String jsonStr, String keys, String name, int index) { -// String isDebugLogEnabled = "true"; - try { - Object rawValue = getJsonRawValue(jsonStr, keys); - if (rawValue == null) { - return null; - } else { - if (rawValue instanceof JSONArray) { - msoLogger.debug("getJsonParamValue(): keys=" + keys + " points to JSONArray: " + ((JSONArray) rawValue).toString()); - int arrayLen = ((JSONArray) rawValue).length(); - if (index < 0 || arrayLen < index+1) { - msoLogger.debug("getJsonParamValue(): index: " + index + " is out of bounds for array size of " + arrayLen); - return null; - } - int foundCnt = 0; - for (int i = 0; i < arrayLen; i++) { - msoLogger.debug("getJsonParamValue(): index: " + i + ", value: " + ((JSONArray) rawValue).get(i).toString()); - if (((JSONArray) rawValue).get(i) instanceof JSONObject) { - msoLogger.debug("getJsonParamValue(): index: " + i + " is a JSONObject"); - JSONObject jsonObj = (JSONObject)((JSONArray) rawValue).get(i); - String parmValue = jsonObj.get(name).toString(); - if (parmValue != null) { - msoLogger.debug("getJsonParamValue(): found value: " + parmValue + " for name: " + name + " and index: " + i); - if (foundCnt == index) { - return parmValue; - } else { - foundCnt++; - continue; - } - } else { - continue; - } - } else { - msoLogger.debug("getJsonParamValue(): the JSONArray element is NOT a JSONObject=" + rawValue.toString()); - return null; - } - } - msoLogger.debug("getJsonParamValue(): content value NOT found for name: " + name); - return null; - } else { - msoLogger.debug("getJsonParamValue(): the raw value is NOT a JSONArray Object=" + rawValue.toString()); - return null; - } - } - } catch (JSONException je) { - // JSONObject::get() throws this exception if one of the specified keys is not found - msoLogger.debug("getJsonParamValue(): caught JSONException attempting to retrieve param value for keys:" + keys + ", name=" + name); - } catch (Exception e) { - msoLogger.debug("getJsonParamValue(): unable to parse json to retrieve value for field=" + keys + ". Exception was: " + e.toString()); - } - return null; - } - - /** - * Wrapper to generate the JSONObject to pass to the getJsonValueForKey(JSONObject, String) - * method so that recursion over the subobjects can be supported there - * - * @param jsonStr String containing the JSON doc - * @param key key to the target value - * @return String field value associated with key - */ - public static String getJsonValueForKey(String jsonStr, String key) { -// String isDebugLogEnabled = "true"; - try { - JSONObject jsonObj = new JSONObject(jsonStr); - if (jsonObj != null) { - return getJsonValueForKey(jsonObj, key); - } - } catch (Exception e) { - msoLogger.debug("getJsonValueForKey(): unable to parse json to retrieve value for field=" + key + ". Exception was: " + e.toString()); - } - return null; - } - - /** - * Walks the JSONObject (and sub-objects recursively), searching for the first value associated with the - * single key/field name specified. Returns the associated value if found or null if the key is not found - * - * @param jsonObj JSONObject representation of the the JSON doc - * @param key key to the target value - * @return String field value associated with key - */ - public static String getJsonValueForKey(JSONObject jsonObj, String key) { -// String isDebugLogEnabled = "true"; - String keyValue = null; - try { - if (jsonObj.has(key)) { - msoLogger.debug("getJsonValueForKey(): found value for key=" + key); - return ((String) jsonObj.get(key)); - } else { - msoLogger.debug("getJsonValueForKey(): iterating over the keys"); - Iterator itr = jsonObj.keys(); - while (itr.hasNext()) { - String nextKey = (String) itr.next(); - Object obj = jsonObj.get(nextKey); - if (obj instanceof JSONObject) { - msoLogger.debug("getJsonValueForKey(): key=" + nextKey + ", points to JSONObject, recursive call"); - keyValue = getJsonValueForKey((JSONObject) obj, key); - if (keyValue != null) { - msoLogger.debug("getJsonValueForKey(): found value=" + keyValue + ", for key=" + key); - break; - } - } else { - msoLogger.debug("getJsonValueForKey(): key=" + nextKey + ", does not point to a JSONObject, next key"); - } - } - } - } catch (JSONException je) { - // JSONObject::get() throws this exception if one of the specified keys is not found - msoLogger.debug("getJsonValueForKey(): caught JSONException attempting to retrieve value for key=" + key); - keyValue = null; - } catch (Exception e) { - msoLogger.debug("getJsonValueForKey(): unable to parse json to retrieve value for field=" + key + ". Exception was: " + e.toString()); - } - return keyValue; - } - - /** - * Walks the JSONObject (and sub-objects recursively), searching for the first value associated with the - * single key/field name specified. Returns the associated value if found or null if the key is not found - * - * @param jsonObj JSONObject representation of the the JSON doc - * @param key key to the target value - * @return String field value associated with key - */ - public static Integer getJsonIntValueForKey(JSONObject jsonObj, String key) { -// String isDebugLogEnabled = "true"; - Integer keyValue = 0; - try { - if (jsonObj.has(key)) { - msoLogger.debug("getJsonValueForKey(): found value for key=" + key); - return ((Integer) jsonObj.get(key)); - } else { - msoLogger.debug("getJsonValueForKey(): iterating over the keys"); - Iterator itr = jsonObj.keys(); - while (itr.hasNext()) { - String nextKey = (String) itr.next(); - Object obj = jsonObj.get(nextKey); - if (obj instanceof JSONObject) { - msoLogger.debug("getJsonValueForKey(): key=" + nextKey + ", points to JSONObject, recursive call"); - keyValue = getJsonIntValueForKey((JSONObject) obj, key); - if (keyValue != null) { - msoLogger.debug("getJsonValueForKey(): found value=" + keyValue + ", for key=" + key); - break; - } - } else { - msoLogger.debug("getJsonValueForKey(): key=" + nextKey + ", does not point to a JSONObject, next key"); - } - } - } - } catch (JSONException je) { - // JSONObject::get() throws this exception if one of the specified keys is not found - msoLogger.debug("getJsonValueForKey(): caught JSONException attempting to retrieve value for key=" + key); - keyValue = null; - } catch (Exception e) { - msoLogger.debug("getJsonValueForKey(): unable to parse json to retrieve value for field=" + key + ". Exception was: " + e.toString()); - } - return keyValue; - } - - /** - * Boolean method to determine if a key path is valid for the JSON doc. Invokes - * getJsonValue(). - * - * @param jsonStr String containing the JSON doc - * @param keys full key path to the target value in the format of "key1.key2.key3..." - * @return Boolean true if keys points to value in the JSON doc - */ - public static Boolean jsonValueExists(String jsonStr, String keys) { - if (getJsonRawValue(jsonStr, keys) == null) { - return false; - } else { - return true; - } - } - - /** - * Inserts the new key/value pair at the appropriate location in the JSON - * document after first determining if keyed field already exists. If - * it does exist, return the JSON unmodified, otherwise return the new JSON - * Note: this method currently only supports String value inserts. - * - * @param jsonStr String containing the JSON doc - * @param keys full key path to the value to be added in the format of "key1.key2.key3..." - * @return String containing the updated JSON doc - */ - public static String addJsonValue(String jsonStr, String keys, String value) { -// String isDebugLogEnabled = "true"; - // only attempt to insert the key/value pair if it does not exist - if (!jsonValueExists(jsonStr, keys)) { - return putJsonValue(jsonStr, keys, value); - } else { - msoLogger.debug("addJsonValue(): JSON add failed, key=" + keys + "/value=" + (String) value + " already exists"); - return jsonStr; - } - } - - /** - * Updates the value for the specified key in the JSON document - * after first determining if keyed field exists. If it does - * not exist, return the JSON unmodified, otherwise return the updated JSON. - * Note: this method currently only supports String value updates. - * - * @param jsonStr String containing the JSON doc - * @param keys full key path to the value to be updated in the format of "key1.key2.key3..." - * @return String containing the updated JSON doc - */ - public static String updJsonValue(String jsonStr, String keys, String newValue) { -// String isDebugLogEnabled = "true"; - // only attempt to modify the key/value pair if it exists - if (jsonValueExists(jsonStr, keys)) { - return putJsonValue(jsonStr, keys, newValue); - } else { - msoLogger.debug("updJsonValue(): JSON update failed, no value exists for key=" + keys); - return jsonStr; - } - } - - /** - * Deletes the value for the specified key in the JSON document - * after first determining if keyed field exists. If it does - * not exist, return the JSON unmodified, otherwise return the updated JSON - * - * @param jsonStr String containing the JSON doc - * @param keys full key path to the value to be deleted in the format of "key1.key2.key3..." - * @return String containing the updated JSON doc - */ - public static String delJsonValue(String jsonStr, String keys) { -// String isDebugLogEnabled = "true"; - // only attempt to remove the key/value pair if it exists - if (jsonValueExists(jsonStr, keys)) { - // passing a null value results in a delete - return putJsonValue(jsonStr, keys, null); - } else { - msoLogger.debug("delJsonValue(): JSON delete failed, no value exists for key=" + keys); - return jsonStr; - } - } - - /** - * Walks the JSON doc using the full key path to retrieve the associated - * value. All but the last key points to the 'parent' object name(s) in order - * in the JSON hierarchy with the last key pointing to the target value. - * The value returned is a Java object. - * - * @param jsonStr String containing the JSON doc - * @param keys full key path to the target value in the format of "key1.key2.key3..." - * @return Object field value associated with keys - */ - private static Object getJsonRawValue(String jsonStr, String keys) { - return getJsonRawValue(jsonStr, keys, false); - } - - /** - * Walks the JSON doc using the full key path to retrieve the associated - * value. All but the last key points to the 'parent' object name(s) in order - * in the JSON hierarchy with the last key pointing to the target value. - * The value returned is a Java object. - * - * @param jsonStr String containing the JSON doc - * @param keys full key path to the target value in the format of "key1.key2.key3..." - * * @param wrap Boolean which determines if returned JSONObjects sould be "wrapped" - * Note: wrap does not apply to returned scalar values - * @return Object field value associated with keys - */ - private static Object getJsonRawValue(String jsonStr, String keys, Boolean wrap) { -// String isDebugLogEnabled = "true"; - String keyStr = ""; - try { - JSONObject jsonObj = new JSONObject(jsonStr); - StringTokenizer keyTokens = new StringTokenizer(keys, "."); - while (keyTokens.hasMoreElements()) { - keyStr = keyTokens.nextToken(); - Object keyValue = jsonObj.get(keyStr); - if (keyValue instanceof JSONObject) { - msoLogger.debug("getJsonRawValue(): key=" + keyStr + " points to json object"); - jsonObj = (JSONObject) keyValue; - } else { - if (keyTokens.hasMoreElements()) { - msoLogger.debug("getJsonRawValue(): value found prior to last key for key=" + keyStr); - } - return keyValue; - } - } - // return the json 'node' that the key points to - // note: since this is a json object and not a scalar value, - // use the wrap flag to determine if the object should - // be wrapped with a root node value - // (the last key in the keys String) - if (wrap) { - JSONObject wrappedJsonObj = new JSONObject(); - wrappedJsonObj.put(keyStr, jsonObj); - return wrappedJsonObj.toString(); - } else { - return jsonObj.toString(); - } - - } catch (JSONException je) { - // JSONObject::get() throws this exception if one of the specified keys is not found - msoLogger.debug("getJsonRawValue(): caught JSONException attempting to retrieve raw value for key=" + keyStr); - } catch (Exception e) { - msoLogger.debug("getJsonRawValue(): unable to parse json to retrieve value for field=" + keys + ". Exception was: " + e.toString()); - } - return null; - } - - /** - * Private method invoked by the public add, update, and delete methods. - * - * @param jsonStr String containing the JSON doc - * @param keys full key path to the value to be deleted in the format of "key1.key2.key3..." - * @return String containing the updated JSON doc - */ - private static String putJsonValue(String jsonStr, String keys, String value) { -// String isDebugLogEnabled = "true"; - String keyStr = ""; - try { - JSONObject jsonObj = new JSONObject(jsonStr); - JSONObject jsonObjOut = jsonObj; - StringTokenizer keyTokens = new StringTokenizer(keys, "."); - while (keyTokens.hasMoreElements()) { - keyStr = keyTokens.nextToken(); - if (keyTokens.hasMoreElements()) { - Object keyValue = jsonObj.get(keyStr); - if (keyValue instanceof JSONObject) { - msoLogger.debug("putJsonValue(): key=" + keyStr + " points to json object"); - jsonObj = (JSONObject) keyValue; - } else { - msoLogger.debug("putJsonValue(): key=" + keyStr + " not the last key but points to non-json object: " + (String) keyValue); - return null; - } - } else { // at the last/new key value - jsonObj.put(keyStr, value); - return jsonObjOut.toString(3); - } - } - // should not hit this point if the key points to a valid key value - return null; - - } catch (JSONException je) { - // JSONObject::get() throws this exception if one of the specified keys is not found - msoLogger.debug("putJsonValue(): caught JSONException attempting to retrieve value for key=" + keyStr); - return null; - } catch (Exception e) { - msoLogger.debug("putJsonValue(): unable to parse json to put value for key=" + keys + ". Exception was: " + e.toString()); - } - return null; - } - - /** - * This json util method converts a json "Key" and "Value" - * entry Array to a Java map. - * - * @param execution - * @param entryArray - the json value of the entry Array - * - * @return map - a Map containing the entries - * - */ - public Map entryArrayToMap(Execution execution, String entryArray) { - msoLogger.debug("Started Entry Array To Map Util Method"); - - Map map = new HashMap(); - - //Populate Map - String entryListJson = "{ \"entry\":" + entryArray + "}"; - JSONObject obj = new JSONObject(entryListJson); - JSONArray arr = obj.getJSONArray("entry"); - for (int i = 0; i < arr.length(); i++){ - JSONObject jo = arr.getJSONObject(i); - String key = jo.getString("key"); - String value =jo.getString("value"); - map.put(key, value); - } - msoLogger.debug("Outgoing Map is: " + map); - msoLogger.debug("Completed Entry Array To Map Util Method"); - return map; - } - - - /** - * Invokes the getJsonRawValue() method to determine if the - * json element/variable exist. Returns true if the - * json element exist - * - * @param jsonStr String containing the JSON doc - * @param keys full key path to the target value in the format of "key1.key2.key3..." - * @return boolean field value associated with keys - */ - public static boolean jsonElementExist(String jsonStr, String keys) { - - try { - Object rawValue = getJsonRawValue(jsonStr, keys); - if (rawValue == null) { - return false; - } else { - return true; - } - } catch (Exception e) { - msoLogger.debug("jsonElementExist(): unable to determine if json element exist. Exception is: " + e.toString()); - } - return true; - } - -} - +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.bpmn.core.json; + +import java.util.Iterator; +import java.util.Map; +import java.util.HashMap; +import java.util.StringTokenizer; + +import org.camunda.bpm.engine.runtime.Execution; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; +import org.json.XML; + +//import org.openecomp.mso.bpmn.core.BPMNLogger; +import org.openecomp.mso.bpmn.core.xml.XmlTool; +import org.openecomp.mso.logger.MsoLogger; + +/** + * Utility class for JSON processing + * + * @version 1.0 + */ + +public class JsonUtils { + + private static MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL); + private static int MSOJsonIndentFactor = 3; + + /** + * Uses the JSONObject static method to convert a XML doc to JSON. + * + * @param xml String containing the XML doc + * @param pretty flag to determine if the output should be formatted + * @return String containing the JSON translation + */ + public static String xml2json(String xml, Boolean pretty) { +// String isDebugLogEnabled = "true"; + try { + // name spaces cause problems, so just remove them + JSONObject jsonObj = XML.toJSONObject(XmlTool.removeNamespaces(xml)); + if (!pretty) { + return jsonObj.toString(); + } else { + // add an indent to make it 'pretty' + return jsonObj.toString(MSOJsonIndentFactor); + } + } catch (Exception e){ + msoLogger.debug("xml2json(): unable to parse xml and convert to json. Exception was: " + e.toString()); + return null; + } + } + + /** + * Invokes xml2json(String, Boolean) defaulting to 'pretty' output. + * + * @param xml String containing the XML doc + * @return String containing the JSON translation + */ + public static String xml2json(String xml) { + return xml2json(xml, true); + } + + /** + * Uses the JSONObject static method to convert a JSON doc to XML. + * Note: this method may not generate valid XML if the JSONObject + * contains JSONArrays which are used to represent XML attributes + * in the JSON doc. + * + * @param jsonStr String containing the JSON doc + * @param pretty flag to determine if the output should be formatted + * @return String containing the XML translation + */ + public static String json2xml(String jsonStr, Boolean pretty) { +// String isDebugLogEnabled = "true"; + try { + JSONObject jsonObj = new JSONObject(jsonStr); + if (pretty) { + // use the local class method which properly handles certain JSONArray content + return XmlTool.normalize(toXMLString(jsonObj, null)); + } else { +// use the local class method which properly handles certain JSONArray content + return toXMLString(jsonObj, null); + } + } catch (Exception e){ + msoLogger.debug("json2xml(): unable to parse json and convert to xml. Exception was: " + e.toString()); + return null; + } + } + + /** + * Uses a modified version of the org.json.XML toString() algorithm + * to convert a JSONObject to an XML Doc. The intent of this is to + * correctly generate XML from JSON including TAGs for JSONArrays + * + * @param jsonObj org.json.JSON object to be converted to XML + * @param tagName optional XML tagname supplied primarily during recursive calls + * @return String containing the XML translation + */ + public static String toXMLString(Object obj, String tagName) throws JSONException { + StringBuffer strBuf = new StringBuffer(); + int i; + JSONArray jsonArr; + JSONObject jsonObj; + String key; + Iterator keys; + int len; + String str; + Object curObj; + if (obj instanceof JSONObject) { + // msoLogger.debug("toXMLString(): is a JSONObject"); + // append "" to the XML output + if (tagName != null) { +// msoLogger.debug("toXMLString(): adding opening tagName: " + tagName); + strBuf.append("<"); + strBuf.append(tagName); + strBuf.append(">"); + } + // iterate thru the keys. + jsonObj = (JSONObject) obj; + keys = jsonObj.keys(); + while (keys.hasNext()) { + key = keys.next().toString(); + // msoLogger.debug("toXMLString(): key is " + k); + curObj = jsonObj.opt(key); + if (curObj == null) { + curObj = ""; + } + if (curObj instanceof String) { + str = (String) curObj; + } else { + str = null; + } + // append the content to the XML output + if (key.equals("content")) { + if (curObj instanceof JSONArray) { + jsonArr = (JSONArray) curObj; + len = jsonArr.length(); + for (i = 0; i < len; i += 1) { + if (i > 0) { + strBuf.append('\n'); + } + strBuf.append(XML.escape(jsonArr.get(i).toString())); + } + } else { + strBuf.append(XML.escape(curObj.toString())); + } + // append an array of similar keys to the XML output + } else if (curObj instanceof JSONArray) { + jsonArr = (JSONArray) curObj; + len = jsonArr.length(); +// msoLogger.debug("toXMLString(): found JSONArray: " + key + ", size: " + len); + for (i = 0; i < len; i += 1) { + curObj = jsonArr.get(i); + if (curObj instanceof JSONArray) { +// The XML tags for the nested array should be generated below when this method +// is called recursively and the JSONArray object is passed +// strBuf.append("<"); +// strBuf.append(key); +// strBuf.append(">"); + strBuf.append(toXMLString(curObj, null)); +// strBuf.append(""); + } else { +// msoLogger.debug("toXMLString(): recursive call toXML() with tagName null"); + // append the opening tag for the array (before 1st element) + if (i == 0) { + strBuf.append("<"); + strBuf.append(key); + strBuf.append(">"); + } + // append the opening tag for the array + strBuf.append(toXMLString(curObj, null)); + // append the closing tag for the array (after last element) + if (i == (len - 1)) { + strBuf.append(""); + } + } + } + } else if (curObj.equals("")) { + // append a closing tag "" to the XML output + strBuf.append("<"); + strBuf.append(key); + strBuf.append("/>"); + } else { +// msoLogger.debug("toXMLString(): recursive call toXMLString() with tagName: " + key); + strBuf.append(toXMLString(curObj, key)); + } + // msoLogger.debug("toXML(): partial XML: " + strBuf.toString()); + } + if (tagName != null) { + // append the closing tag "" to the XML output +// msoLogger.debug("toXMLString(): adding closing tagName: " + tagName); + strBuf.append(""); + } + return strBuf.toString(); + // XML does not have good support for arrays. If an array appears in a place + // where XML is lacking, synthesize an < array > element. + } else if (obj instanceof JSONArray) { + jsonArr = (JSONArray) obj; + len = jsonArr.length(); + for (i = 0; i < len; ++i) { + curObj = jsonArr.opt(i); + strBuf.append(toXMLString(curObj, (tagName == null) ? "array" + : tagName)); + } + return strBuf.toString(); + } else { +// msoLogger.debug("toXML(): in else block with tagName: " + tagName); + str = (obj == null) ? "null" : XML.escape(obj.toString()); + return (tagName == null) ? "\"" + str + "\"" + : (str.length() == 0) ? "<" + tagName + "/>" : "<" + + tagName + ">" + str + ""; + } + } + + /** + * Formats the JSON String using the value of MSOJsonIndentFactor. + * + * @param jsonStr String containing the JSON doc + * @return String containing the formatted JSON doc + */ + public static String prettyJson(String jsonStr) { +// String isDebugLogEnabled = "true"; + try { + JSONObject jsonObj = new JSONObject(jsonStr); + return jsonObj.toString(MSOJsonIndentFactor); + } catch (Exception e){ + msoLogger.debug("prettyJson(): unable to parse/format json input. Exception was: " + e.toString()); + return null; + } + } + + /** + * Invokes json2xml(String, Boolean) defaulting to 'pretty' output. + * + * @param jsonStr String containing the XML doc + * @return String containing the JSON translation + */ + public static String json2xml(String jsonStr) { + return json2xml(jsonStr, true); + } + + /** + * Returns an Iterator over the JSON keys in the specified JSON doc. + * + * @param jsonStr String containing the JSON doc + * @return Iterator over the JSON keys + * @throws JSONException if the doc cannot be parsed + */ + public static Iterator getJsonIterator(String jsonStr) throws JSONException { + return new JSONObject(jsonStr).keys(); + } + + /** + * Returns the name of the "root" property in the specified JSON doc. The + * "root" property is the single top-level property in the JSON doc. An + * exception is thrown if the doc is empty or if it contains more than one + * top-level property. + * + * @param jsonStr String containing the JSON doc + * @return the name of the "root" property + * @throws JSONException if the doc cannot be parsed, or if it is empty, or if + * it contains more than one top-level property + */ + public static String getJsonRootProperty(String jsonStr) throws JSONException { + Iterator iter = getJsonIterator(jsonStr); + + if (!iter.hasNext()) { + throw new JSONException("Empty JSON object"); + } + + String rootPropertyName = iter.next(); + + if (iter.hasNext()) { + throw new JSONException("JSON object has more than one root property"); + } + + return rootPropertyName; + } + + /** + * Invokes the getJsonRawValue() method and returns the String equivalent of + * the object returned. + * + * TBD: May need separate methods for boolean, float, and integer fields if the + * String representation is not sufficient to meet client needs. + * + * @param jsonStr String containing the JSON doc + * @param keys full key path to the target value in the format of "key1.key2.key3..." + * @return String field value associated with keys + */ + public static String getJsonValue(String jsonStr, String keys) { +// String isDebugLogEnabled = "true"; + try { + Object rawValue = getJsonRawValue(jsonStr, keys); + if (rawValue == null) { + return null; + } else { + if (rawValue instanceof String) { + msoLogger.debug("getJsonValue(): the raw value is a String Object=" + ((String) rawValue).toString()); + return (String) rawValue; + } else { + msoLogger.debug("getJsonValue(): the raw value is NOT a String Object=" + rawValue.toString()); + return rawValue.toString(); + } + } + } catch (Exception e) { + msoLogger.debug("getJsonValue(): unable to parse json to retrieve value for field=" + keys + ". Exception was: " + e.toString()); + } + return null; + } + + + /** + * Invokes the getJsonRawValue() method with the wrap flag set to true + * and returns the String equivalent of the json node object returned. + * + * @param jsonStr String containing the JSON doc + * @param keys full key path to the target value in the format of "key1.key2.key3..." + * @return String field value associated with keys + */ + public static String getJsonNodeValue(String jsonStr, String keys) { +// String isDebugLogEnabled = "true"; + try { + Object rawValue = getJsonRawValue(jsonStr, keys, true); + if (rawValue == null) { + return null; + } else { + if (rawValue instanceof String) { + msoLogger.debug("getJsonNodeValue(): the raw value is a String Object=" + ((String) rawValue).toString()); + return (String) rawValue; + } else { + msoLogger.debug("getJsonNodeValue(): the raw value is NOT a String Object=" + rawValue.toString()); + return rawValue.toString(); + } + } + } catch (Exception e) { + msoLogger.debug("getJsonNodeValue(): unable to parse json to retrieve node for field=" + keys + ". Exception was: " + e.toString()); + } + return null; + } + + /** + * Invokes the getJsonRawValue() method and returns the String equivalent of + * the object returned. + * + * TBD: May need separate methods for boolean, float, and integer fields if the + * String representation is not sufficient to meet client needs. + * + * @param jsonStr String containing the JSON doc + * @param keys full key path to the target value in the format of "key1.key2.key3..." + * @return String field value associated with keys + */ + public static int getJsonIntValue(String jsonStr, String keys) { +// String isDebugLogEnabled = "true"; + try { + Object rawValue = getJsonRawValue(jsonStr, keys); + if (rawValue == null) { + return 0; + } else { + if (rawValue instanceof Integer) { + msoLogger.debug("getJsonValue(): the raw value is an Integer Object=" + ((String) rawValue).toString()); + return (Integer) rawValue; + } else { + msoLogger.debug("getJsonValue(): the raw value is NOT an Integer Object=" + rawValue.toString()); + return 0; + } + } + } catch (Exception e) { + msoLogger.debug("getJsonValue(): unable to parse json to retrieve value for field=" + keys + ". Exception was: " + e.toString()); + } + return 0; + } + + /** + * Invokes the getJsonParamValue() method to obtain the JSONArray associated with + * the specified keys. The JSONArray is then walked to retrieve the first array + * value associated with the specified field name (index=0). + * + * @param jsonStr String containing the JSON doc + * @param keys full key path to the target value in the format of "key1.key2.key3..." + * @param name field name for the param to be retrieved + * @return String param value associated with field name + */ + public static String getJsonParamValue(String jsonStr, String keys, String name) { + return getJsonParamValue(jsonStr, keys, name, 0); + } + + /** + * Invokes the getJsonRawValue() method to obtain the JSONArray associated with + * the specified keys. The JSONArray is then walked to retrieve the nth array + * value associated with the specified field name and index + * + * @param jsonStr String containing the JSON doc + * @param keys full key path to the target value in the format of "key1.key2.key3..." + * @param name field name for the param to be retrieved + * @param index the nth param associated with name starting at 0 + * @return String param value associated with field name + */ + public static String getJsonParamValue(String jsonStr, String keys, String name, int index) { +// String isDebugLogEnabled = "true"; + try { + Object rawValue = getJsonRawValue(jsonStr, keys); + if (rawValue == null) { + return null; + } else { + if (rawValue instanceof JSONArray) { + msoLogger.debug("getJsonParamValue(): keys=" + keys + " points to JSONArray: " + ((JSONArray) rawValue).toString()); + int arrayLen = ((JSONArray) rawValue).length(); + if (index < 0 || arrayLen < index+1) { + msoLogger.debug("getJsonParamValue(): index: " + index + " is out of bounds for array size of " + arrayLen); + return null; + } + int foundCnt = 0; + for (int i = 0; i < arrayLen; i++) { + msoLogger.debug("getJsonParamValue(): index: " + i + ", value: " + ((JSONArray) rawValue).get(i).toString()); + if (((JSONArray) rawValue).get(i) instanceof JSONObject) { + msoLogger.debug("getJsonParamValue(): index: " + i + " is a JSONObject"); + JSONObject jsonObj = (JSONObject)((JSONArray) rawValue).get(i); + String parmValue = jsonObj.get(name).toString(); + if (parmValue != null) { + msoLogger.debug("getJsonParamValue(): found value: " + parmValue + " for name: " + name + " and index: " + i); + if (foundCnt == index) { + return parmValue; + } else { + foundCnt++; + continue; + } + } else { + continue; + } + } else { + msoLogger.debug("getJsonParamValue(): the JSONArray element is NOT a JSONObject=" + rawValue.toString()); + return null; + } + } + msoLogger.debug("getJsonParamValue(): content value NOT found for name: " + name); + return null; + } else { + msoLogger.debug("getJsonParamValue(): the raw value is NOT a JSONArray Object=" + rawValue.toString()); + return null; + } + } + } catch (JSONException je) { + // JSONObject::get() throws this exception if one of the specified keys is not found + msoLogger.debug("getJsonParamValue(): caught JSONException attempting to retrieve param value for keys:" + keys + ", name=" + name); + } catch (Exception e) { + msoLogger.debug("getJsonParamValue(): unable to parse json to retrieve value for field=" + keys + ". Exception was: " + e.toString()); + } + return null; + } + + /** + * Wrapper to generate the JSONObject to pass to the getJsonValueForKey(JSONObject, String) + * method so that recursion over the subobjects can be supported there + * + * @param jsonStr String containing the JSON doc + * @param key key to the target value + * @return String field value associated with key + */ + public static String getJsonValueForKey(String jsonStr, String key) { +// String isDebugLogEnabled = "true"; + try { + JSONObject jsonObj = new JSONObject(jsonStr); + if (jsonObj != null) { + return getJsonValueForKey(jsonObj, key); + } + } catch (Exception e) { + msoLogger.debug("getJsonValueForKey(): unable to parse json to retrieve value for field=" + key + ". Exception was: " + e.toString()); + } + return null; + } + + /** + * Walks the JSONObject (and sub-objects recursively), searching for the first value associated with the + * single key/field name specified. Returns the associated value if found or null if the key is not found + * + * @param jsonObj JSONObject representation of the the JSON doc + * @param key key to the target value + * @return String field value associated with key + */ + public static String getJsonValueForKey(JSONObject jsonObj, String key) { +// String isDebugLogEnabled = "true"; + String keyValue = null; + try { + if (jsonObj.has(key)) { + msoLogger.debug("getJsonValueForKey(): found value for key=" + key); + return ((String) jsonObj.get(key)); + } else { + msoLogger.debug("getJsonValueForKey(): iterating over the keys"); + Iterator itr = jsonObj.keys(); + while (itr.hasNext()) { + String nextKey = (String) itr.next(); + Object obj = jsonObj.get(nextKey); + if (obj instanceof JSONObject) { + msoLogger.debug("getJsonValueForKey(): key=" + nextKey + ", points to JSONObject, recursive call"); + keyValue = getJsonValueForKey((JSONObject) obj, key); + if (keyValue != null) { + msoLogger.debug("getJsonValueForKey(): found value=" + keyValue + ", for key=" + key); + break; + } + } else { + msoLogger.debug("getJsonValueForKey(): key=" + nextKey + ", does not point to a JSONObject, next key"); + } + } + } + } catch (JSONException je) { + // JSONObject::get() throws this exception if one of the specified keys is not found + msoLogger.debug("getJsonValueForKey(): caught JSONException attempting to retrieve value for key=" + key); + keyValue = null; + } catch (Exception e) { + msoLogger.debug("getJsonValueForKey(): unable to parse json to retrieve value for field=" + key + ". Exception was: " + e.toString()); + } + return keyValue; + } + + /** + * Walks the JSONObject (and sub-objects recursively), searching for the first value associated with the + * single key/field name specified. Returns the associated value if found or null if the key is not found + * + * @param jsonObj JSONObject representation of the the JSON doc + * @param key key to the target value + * @return String field value associated with key + */ + public static Integer getJsonIntValueForKey(JSONObject jsonObj, String key) { +// String isDebugLogEnabled = "true"; + Integer keyValue = 0; + try { + if (jsonObj.has(key)) { + msoLogger.debug("getJsonValueForKey(): found value for key=" + key); + return ((Integer) jsonObj.get(key)); + } else { + msoLogger.debug("getJsonValueForKey(): iterating over the keys"); + Iterator itr = jsonObj.keys(); + while (itr.hasNext()) { + String nextKey = (String) itr.next(); + Object obj = jsonObj.get(nextKey); + if (obj instanceof JSONObject) { + msoLogger.debug("getJsonValueForKey(): key=" + nextKey + ", points to JSONObject, recursive call"); + keyValue = getJsonIntValueForKey((JSONObject) obj, key); + if (keyValue != null) { + msoLogger.debug("getJsonValueForKey(): found value=" + keyValue + ", for key=" + key); + break; + } + } else { + msoLogger.debug("getJsonValueForKey(): key=" + nextKey + ", does not point to a JSONObject, next key"); + } + } + } + } catch (JSONException je) { + // JSONObject::get() throws this exception if one of the specified keys is not found + msoLogger.debug("getJsonValueForKey(): caught JSONException attempting to retrieve value for key=" + key); + keyValue = null; + } catch (Exception e) { + msoLogger.debug("getJsonValueForKey(): unable to parse json to retrieve value for field=" + key + ". Exception was: " + e.toString()); + } + return keyValue; + } + + /** + * Boolean method to determine if a key path is valid for the JSON doc. Invokes + * getJsonValue(). + * + * @param jsonStr String containing the JSON doc + * @param keys full key path to the target value in the format of "key1.key2.key3..." + * @return Boolean true if keys points to value in the JSON doc + */ + public static Boolean jsonValueExists(String jsonStr, String keys) { + if (getJsonRawValue(jsonStr, keys) == null) { + return false; + } else { + return true; + } + } + + /** + * Inserts the new key/value pair at the appropriate location in the JSON + * document after first determining if keyed field already exists. If + * it does exist, return the JSON unmodified, otherwise return the new JSON + * Note: this method currently only supports String value inserts. + * + * @param jsonStr String containing the JSON doc + * @param keys full key path to the value to be added in the format of "key1.key2.key3..." + * @return String containing the updated JSON doc + */ + public static String addJsonValue(String jsonStr, String keys, String value) { +// String isDebugLogEnabled = "true"; + // only attempt to insert the key/value pair if it does not exist + if (!jsonValueExists(jsonStr, keys)) { + return putJsonValue(jsonStr, keys, value); + } else { + msoLogger.debug("addJsonValue(): JSON add failed, key=" + keys + "/value=" + (String) value + " already exists"); + return jsonStr; + } + } + + /** + * Updates the value for the specified key in the JSON document + * after first determining if keyed field exists. If it does + * not exist, return the JSON unmodified, otherwise return the updated JSON. + * Note: this method currently only supports String value updates. + * + * @param jsonStr String containing the JSON doc + * @param keys full key path to the value to be updated in the format of "key1.key2.key3..." + * @return String containing the updated JSON doc + */ + public static String updJsonValue(String jsonStr, String keys, String newValue) { +// String isDebugLogEnabled = "true"; + // only attempt to modify the key/value pair if it exists + if (jsonValueExists(jsonStr, keys)) { + return putJsonValue(jsonStr, keys, newValue); + } else { + msoLogger.debug("updJsonValue(): JSON update failed, no value exists for key=" + keys); + return jsonStr; + } + } + + /** + * Deletes the value for the specified key in the JSON document + * after first determining if keyed field exists. If it does + * not exist, return the JSON unmodified, otherwise return the updated JSON + * + * @param jsonStr String containing the JSON doc + * @param keys full key path to the value to be deleted in the format of "key1.key2.key3..." + * @return String containing the updated JSON doc + */ + public static String delJsonValue(String jsonStr, String keys) { +// String isDebugLogEnabled = "true"; + // only attempt to remove the key/value pair if it exists + if (jsonValueExists(jsonStr, keys)) { + // passing a null value results in a delete + return putJsonValue(jsonStr, keys, null); + } else { + msoLogger.debug("delJsonValue(): JSON delete failed, no value exists for key=" + keys); + return jsonStr; + } + } + + /** + * Walks the JSON doc using the full key path to retrieve the associated + * value. All but the last key points to the 'parent' object name(s) in order + * in the JSON hierarchy with the last key pointing to the target value. + * The value returned is a Java object. + * + * @param jsonStr String containing the JSON doc + * @param keys full key path to the target value in the format of "key1.key2.key3..." + * @return Object field value associated with keys + */ + private static Object getJsonRawValue(String jsonStr, String keys) { + return getJsonRawValue(jsonStr, keys, false); + } + + /** + * Walks the JSON doc using the full key path to retrieve the associated + * value. All but the last key points to the 'parent' object name(s) in order + * in the JSON hierarchy with the last key pointing to the target value. + * The value returned is a Java object. + * + * @param jsonStr String containing the JSON doc + * @param keys full key path to the target value in the format of "key1.key2.key3..." + * * @param wrap Boolean which determines if returned JSONObjects sould be "wrapped" + * Note: wrap does not apply to returned scalar values + * @return Object field value associated with keys + */ + private static Object getJsonRawValue(String jsonStr, String keys, Boolean wrap) { +// String isDebugLogEnabled = "true"; + String keyStr = ""; + try { + JSONObject jsonObj = new JSONObject(jsonStr); + StringTokenizer keyTokens = new StringTokenizer(keys, "."); + while (keyTokens.hasMoreElements()) { + keyStr = keyTokens.nextToken(); + Object keyValue = jsonObj.get(keyStr); + if (keyValue instanceof JSONObject) { + msoLogger.debug("getJsonRawValue(): key=" + keyStr + " points to json object"); + jsonObj = (JSONObject) keyValue; + } else { + if (keyTokens.hasMoreElements()) { + msoLogger.debug("getJsonRawValue(): value found prior to last key for key=" + keyStr); + } + return keyValue; + } + } + // return the json 'node' that the key points to + // note: since this is a json object and not a scalar value, + // use the wrap flag to determine if the object should + // be wrapped with a root node value + // (the last key in the keys String) + if (wrap) { + JSONObject wrappedJsonObj = new JSONObject(); + wrappedJsonObj.put(keyStr, jsonObj); + return wrappedJsonObj.toString(); + } else { + return jsonObj.toString(); + } + + } catch (JSONException je) { + // JSONObject::get() throws this exception if one of the specified keys is not found + msoLogger.debug("getJsonRawValue(): caught JSONException attempting to retrieve raw value for key=" + keyStr); + } catch (Exception e) { + msoLogger.debug("getJsonRawValue(): unable to parse json to retrieve value for field=" + keys + ". Exception was: " + e.toString()); + } + return null; + } + + /** + * Private method invoked by the public add, update, and delete methods. + * + * @param jsonStr String containing the JSON doc + * @param keys full key path to the value to be deleted in the format of "key1.key2.key3..." + * @return String containing the updated JSON doc + */ + private static String putJsonValue(String jsonStr, String keys, String value) { +// String isDebugLogEnabled = "true"; + String keyStr = ""; + try { + JSONObject jsonObj = new JSONObject(jsonStr); + JSONObject jsonObjOut = jsonObj; + StringTokenizer keyTokens = new StringTokenizer(keys, "."); + while (keyTokens.hasMoreElements()) { + keyStr = keyTokens.nextToken(); + if (keyTokens.hasMoreElements()) { + Object keyValue = jsonObj.get(keyStr); + if (keyValue instanceof JSONObject) { + msoLogger.debug("putJsonValue(): key=" + keyStr + " points to json object"); + jsonObj = (JSONObject) keyValue; + } else { + msoLogger.debug("putJsonValue(): key=" + keyStr + " not the last key but points to non-json object: " + (String) keyValue); + return null; + } + } else { // at the last/new key value + jsonObj.put(keyStr, value); + return jsonObjOut.toString(3); + } + } + // should not hit this point if the key points to a valid key value + return null; + + } catch (JSONException je) { + // JSONObject::get() throws this exception if one of the specified keys is not found + msoLogger.debug("putJsonValue(): caught JSONException attempting to retrieve value for key=" + keyStr); + return null; + } catch (Exception e) { + msoLogger.debug("putJsonValue(): unable to parse json to put value for key=" + keys + ". Exception was: " + e.toString()); + } + return null; + } + + /** + * This json util method converts a json "Key" and "Value" + * entry Array to a Java map. + * + * @param execution + * @param entryArray - the json value of the entry Array + * + * @return map - a Map containing the entries + * + */ + public Map entryArrayToMap(Execution execution, String entryArray) { + msoLogger.debug("Started Entry Array To Map Util Method"); + + Map map = new HashMap(); + + //Populate Map + String entryListJson = "{ \"entry\":" + entryArray + "}"; + JSONObject obj = new JSONObject(entryListJson); + JSONArray arr = obj.getJSONArray("entry"); + for (int i = 0; i < arr.length(); i++){ + JSONObject jo = arr.getJSONObject(i); + String key = jo.getString("key"); + String value =jo.getString("value"); + map.put(key, value); + } + msoLogger.debug("Outgoing Map is: " + map); + msoLogger.debug("Completed Entry Array To Map Util Method"); + return map; + } + + + /** + * Invokes the getJsonRawValue() method to determine if the + * json element/variable exist. Returns true if the + * json element exist + * + * @param jsonStr String containing the JSON doc + * @param keys full key path to the target value in the format of "key1.key2.key3..." + * @return boolean field value associated with keys + */ + public static boolean jsonElementExist(String jsonStr, String keys) { + + try { + Object rawValue = getJsonRawValue(jsonStr, keys); + if (rawValue == null) { + return false; + } else { + return true; + } + } catch (Exception e) { + msoLogger.debug("jsonElementExist(): unable to determine if json element exist. Exception is: " + e.toString()); + } + return true; + } + +} + diff --git a/bpmn/MSOInfrastructureBPMN/WebContent/META-INF/MANIFEST.MF b/bpmn/MSOInfrastructureBPMN/WebContent/META-INF/MANIFEST.MF index 254272e1c0..5e9495128c 100644 --- a/bpmn/MSOInfrastructureBPMN/WebContent/META-INF/MANIFEST.MF +++ b/bpmn/MSOInfrastructureBPMN/WebContent/META-INF/MANIFEST.MF @@ -1,3 +1,3 @@ -Manifest-Version: 1.0 -Class-Path: - +Manifest-Version: 1.0 +Class-Path: + diff --git a/bpmn/MSOInfrastructureBPMN/pom.xml b/bpmn/MSOInfrastructureBPMN/pom.xml index 21eb490f6e..ca9ce57912 100644 --- a/bpmn/MSOInfrastructureBPMN/pom.xml +++ b/bpmn/MSOInfrastructureBPMN/pom.xml @@ -1,389 +1,389 @@ - - - org.openecomp.mso - bpmn - 1.1.0-SNAPSHOT - - 4.0.0 - MSOInfrastructureBPMN - war - - - - - org.apache.maven.plugins - maven-war-plugin - 2.3 - - false - - - - org.apache.maven.plugins - maven-jar-plugin - 2.6 - - - default-jar - package - - jar - - - - org/openecomp/mso/bpmn/infrastructure/MSOInfrastructureApplication.class - META-INF/ - - - - - - - org.codehaus.mojo - build-helper-maven-plugin - 3.0.0 - - - - attach-artifact - - package - - - - ${project.build.directory}/${project.artifactId}-${project.version}.jar - jar - - - - - - - - org.apache.cxf - cxf-codegen-plugin - 2.5.2 - - - org.apache.maven.plugins - maven-eclipse-plugin - 2.8 - - - org.eclipse.jdt.groovy.core.groovyNature - - - **/*.groovy - - - - - maven-antrun-plugin - - - compile - compile - - - - - - - - - - - - - - run - - - - test-compile - test-compile - - - - - - - - - - - - - - run - - - - - - - org.apache.maven.plugins - maven-dependency-plugin - - - maven-failsafe-plugin - 2.6 - - - - integration-test - verify - - - - - - - - - - org.eclipse.m2e - lifecycle-mapping - 1.0.0 - - - - - - - org.apache.maven.plugins - - - maven-antrun-plugin - - - [1.3,) - - - run - - - - - - - - - - - - - - - - - - org.camunda.bpm - camunda-engine - compile - - - org.slf4j - slf4j-api - - - - - - - org.camunda.bpm - camunda-engine-cdi - - - - - org.camunda.bpm.extension - camunda-bpm-assert - 1.2 - test - - - org.mockito - mockito-all - 1.10.19 - test - - - - org.camunda.bpm.workbench - camunda-workbench-dist-embeddable - 1.0.0-alpha8 - test - - - - - org.camunda.spin - camunda-spin-dataformat-all - compile - - - org.camunda.bpm - camunda-engine-plugin-spin - compile - - - - org.camunda.bpm - camunda-engine-plugin-connect - compile - - - - - org.webjars - bootstrap - 2.3.2 - - - - org.jboss.resteasy - resteasy-client - 3.0.19.Final - provided - - - org.apache.httpcomponents - httpclient - - - - - - - com.h2database - h2 - test - - - - com.fasterxml.uuid - java-uuid-generator - - - org.codehaus.groovy - groovy-all - - - org.apache.commons - commons-lang3 - 3.4 - - - org.openecomp.mso - MSOCoreBPMN - ${project.version} - - - org.openecomp.mso - MSOCommonBPMN - ${project.version} - - - org.openecomp.mso - MSOCommonBPMN - ${project.version} - tests - test - - - - org.openecomp.mso - MSOCoreBPMN - ${project.version} - tests - test - - - javax.ws.rs - javax.ws.rs-api - 2.0 - - - - org.springframework - spring-web - 4.3.2.RELEASE - - - org.openecomp.mso - MSOMockServer - ${project.version} - test - classes - - - org.openecomp.mso - MSORESTClient - ${project.version} - - - - com.github.tomakehurst - wiremock - 1.56 - test - standalone - - - org.mortbay.jetty - jetty - - - com.google.guava - guava - - - com.fasterxml.jackson.core - jackson-core - - - com.fasterxml.jackson.core - jackson-annotations - - - com.fasterxml.jackson.core - jackson-databind - - - org.apache.httpcomponents - httpclient - - - org.skyscreamer - jsonassert - - - xmlunit - xmlunit - - - com.jayway.jsonpath - json-path - - - net.sf.jopt-simple - jopt-simple - - - - - javax.servlet - javax.servlet-api - 3.0.1 - provided - - + + + org.openecomp.mso + bpmn + 1.1.0-SNAPSHOT + + 4.0.0 + MSOInfrastructureBPMN + war + + + + + org.apache.maven.plugins + maven-war-plugin + 2.3 + + false + + + + org.apache.maven.plugins + maven-jar-plugin + 2.6 + + + default-jar + package + + jar + + + + org/openecomp/mso/bpmn/infrastructure/MSOInfrastructureApplication.class + + + + + + + + org.codehaus.mojo + build-helper-maven-plugin + 3.0.0 + + + + attach-artifact + + package + + + + ${project.build.directory}/${project.artifactId}-${project.version}.jar + jar + + + + + + + + org.apache.cxf + cxf-codegen-plugin + 2.5.2 + + + org.apache.maven.plugins + maven-eclipse-plugin + 2.8 + + + org.eclipse.jdt.groovy.core.groovyNature + + + **/*.groovy + + + + + maven-antrun-plugin + + + compile + compile + + + + + + + + + + + + + + run + + + + test-compile + test-compile + + + + + + + + + + + + + + run + + + + + + + org.apache.maven.plugins + maven-dependency-plugin + + + maven-failsafe-plugin + 2.6 + + + + integration-test + verify + + + + + + + + + + org.eclipse.m2e + lifecycle-mapping + 1.0.0 + + + + + + + org.apache.maven.plugins + + + maven-antrun-plugin + + + [1.3,) + + + run + + + + + + + + + + + + + + + + + + org.camunda.bpm + camunda-engine + compile + + + org.slf4j + slf4j-api + + + + + + + org.camunda.bpm + camunda-engine-cdi + + + + + org.camunda.bpm.extension + camunda-bpm-assert + 1.2 + test + + + org.mockito + mockito-all + 1.10.19 + test + + + + org.camunda.bpm.workbench + camunda-workbench-dist-embeddable + 1.0.0-alpha8 + test + + + + + org.camunda.spin + camunda-spin-dataformat-all + compile + + + org.camunda.bpm + camunda-engine-plugin-spin + compile + + + + org.camunda.bpm + camunda-engine-plugin-connect + compile + + + + + org.webjars + bootstrap + 2.3.2 + + + + org.jboss.resteasy + resteasy-client + 3.0.19.Final + provided + + + org.apache.httpcomponents + httpclient + + + + + + + com.h2database + h2 + test + + + + com.fasterxml.uuid + java-uuid-generator + + + org.codehaus.groovy + groovy-all + + + org.apache.commons + commons-lang3 + 3.4 + + + org.openecomp.mso + MSOCoreBPMN + ${project.version} + + + org.openecomp.mso + MSOCommonBPMN + ${project.version} + + + org.openecomp.mso + MSOCommonBPMN + ${project.version} + tests + test + + + + org.openecomp.mso + MSOCoreBPMN + ${project.version} + tests + test + + + javax.ws.rs + javax.ws.rs-api + 2.0 + + + + org.springframework + spring-web + 4.3.2.RELEASE + + + org.openecomp.mso + MSOMockServer + ${project.version} + test + classes + + + org.openecomp.mso + MSORESTClient + ${project.version} + + + + com.github.tomakehurst + wiremock + 1.56 + test + standalone + + + org.mortbay.jetty + jetty + + + com.google.guava + guava + + + com.fasterxml.jackson.core + jackson-core + + + com.fasterxml.jackson.core + jackson-annotations + + + com.fasterxml.jackson.core + jackson-databind + + + org.apache.httpcomponents + httpclient + + + org.skyscreamer + jsonassert + + + xmlunit + xmlunit + + + com.jayway.jsonpath + json-path + + + net.sf.jopt-simple + jopt-simple + + + + + javax.servlet + javax.servlet-api + 3.0.1 + provided + + \ No newline at end of file diff --git a/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/CreateGenericMacroServiceNetworkVnf.groovy b/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/CreateGenericMacroServiceNetworkVnf.groovy index b48e07f158..88e2396078 100644 --- a/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/CreateGenericMacroServiceNetworkVnf.groovy +++ b/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/CreateGenericMacroServiceNetworkVnf.groovy @@ -1,749 +1,752 @@ -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - MSO - * ================================================================================ - * 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.openecomp.mso.bpmn.infrastructure.scripts; - -import groovy.xml.XmlUtil -import groovy.json.* - -import org.openecomp.mso.bpmn.core.json.JsonUtils -import org.openecomp.mso.bpmn.common.scripts.AbstractServiceTaskProcessor -import org.openecomp.mso.bpmn.common.scripts.CatalogDbUtils -import org.openecomp.mso.bpmn.common.scripts.ExceptionUtil -import org.openecomp.mso.bpmn.common.scripts.VidUtils -import org.openecomp.mso.bpmn.core.WorkflowException -import org.openecomp.mso.rest.APIResponse; -import org.openecomp.mso.rest.RESTClient -import org.openecomp.mso.rest.RESTConfig - -import java.util.UUID; - -import org.camunda.bpm.engine.delegate.BpmnError -import org.camunda.bpm.engine.runtime.Execution -import org.json.JSONObject; -import org.json.JSONArray; -import org.apache.commons.lang3.* -import org.apache.commons.codec.binary.Base64; -import org.springframework.web.util.UriUtils; - -/** - * This groovy class supports the CreateGenericMacroServiceNetworkVnf.bpmn process. - * - */ -public class CreateGenericMacroServiceNetworkVnf extends AbstractServiceTaskProcessor { - - String Prefix="CREVAS_" - ExceptionUtil exceptionUtil = new ExceptionUtil() - JsonUtils jsonUtil = new JsonUtils() - VidUtils vidUtils = new VidUtils() - CatalogDbUtils catalogDbUtils = new CatalogDbUtils() - - /** - * This method is executed during the preProcessRequest task of the CreateServiceInstance.bpmn process. - * @param execution - */ - public InitializeProcessVariables(Execution execution){ - /* Initialize all the process variables in this block */ - - execution.setVariable("createGenericMacroServiceNetworkVnfRequest", "") - execution.setVariable("globalSubscriberId", "") - execution.setVariable("serviceInstanceName", "") - execution.setVariable("msoRequestId", "") - execution.setVariable("CREVAS_NetworksCreatedCount", 0) - execution.setVariable("CREVAS_VnfsCreatedCount", 0) - execution.setVariable("productFamilyId", "") - - - //TODO - execution.setVariable("sdncVersion", "1702") - } - - // ************************************************** - // Pre or Prepare Request Section - // ************************************************** - /** - * This method is executed during the preProcessRequest task of the CreateServiceInstance.bpmn process. - * @param execution - */ - public void preProcessRequest (Execution execution) { - def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - execution.setVariable("prefix",Prefix) - - utils.log("DEBUG", " ***** Inside preProcessRequest CreateGenericMacroServiceNetworkVnf Request ***** ", isDebugEnabled) - - try { - // initialize flow variables - InitializeProcessVariables(execution) - - // check for incoming json message/input - String createGenericMacroServiceNetworkVnfRequest = execution.getVariable("bpmnRequest") - utils.logAudit(createGenericMacroServiceNetworkVnfRequest) - execution.setVariable("createGenericMacroServiceNetworkVnfRequest", createGenericMacroServiceNetworkVnfRequest); - println 'createGenericMacroServiceNetworkVnfRequest - ' + createGenericMacroServiceNetworkVnfRequest - - // extract requestId - String requestId = execution.getVariable("mso-request-id") - execution.setVariable("msoRequestId", requestId) - - String serviceInstanceId = execution.getVariable("serviceInstanceId") - - if ((serviceInstanceId == null) || (serviceInstanceId.isEmpty())) { - serviceInstanceId = UUID.randomUUID().toString() - utils.log("DEBUG", " Generated new Service Instance: " + serviceInstanceId , isDebugEnabled) - } else { - utils.log("DEBUG", "Using provided Service Instance ID: " + serviceInstanceId , isDebugEnabled) - } - - serviceInstanceId = UriUtils.encode(serviceInstanceId,"UTF-8") - execution.setVariable("serviceInstanceId", serviceInstanceId) - - String requestAction = execution.getVariable("requestAction") - execution.setVariable("requestAction", requestAction) - - String source = jsonUtil.getJsonValue(createGenericMacroServiceNetworkVnfRequest, "requestDetails.requestInfo.source") - if ((source == null) || (source.isEmpty())) { - execution.setVariable("source", "VID") - } else { - execution.setVariable("source", source) - } - - // extract globalSubscriberId - String globalSubscriberId = jsonUtil.getJsonValue(createGenericMacroServiceNetworkVnfRequest, "requestDetails.subscriberInfo.globalSubscriberId") - - // verify element global-customer-id is sent from JSON input, throw exception if missing - if ((globalSubscriberId == null) || (globalSubscriberId.isEmpty())) { - String dataErrorMessage = " Element 'globalSubscriberId' is missing. " - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) - - } else { - execution.setVariable("globalSubscriberId", globalSubscriberId) - execution.setVariable("globalCustomerId", globalSubscriberId) - } - - // extract subscriptionServiceType - String subscriptionServiceType = jsonUtil.getJsonValue(createGenericMacroServiceNetworkVnfRequest, "requestDetails.requestParameters.subscriptionServiceType") - execution.setVariable("subscriptionServiceType", subscriptionServiceType) - utils.log("DEBUG", "Incoming subscriptionServiceType is: " + subscriptionServiceType, isDebugEnabled) - - String suppressRollback = jsonUtil.getJsonValue(createGenericMacroServiceNetworkVnfRequest, "requestDetails.requestInfo.suppressRollback") - execution.setVariable("disableRollback", suppressRollback) - utils.log("DEBUG", "Incoming Suppress/Disable Rollback is: " + suppressRollback, isDebugEnabled) - - String productFamilyId = jsonUtil.getJsonValue(createGenericMacroServiceNetworkVnfRequest, "requestDetails.requestInfo.productFamilyId") - execution.setVariable("productFamilyId", productFamilyId) - utils.log("DEBUG", "Incoming productFamilyId is: " + productFamilyId, isDebugEnabled) - - //For Completion Handler & Fallout Handler - String requestInfo = - """ - ${requestId} - CREATE - ${source} - """ - - execution.setVariable("CREVAS_requestInfo", requestInfo) - - utils.log("DEBUG", " ***** Completed preProcessRequest CreateGenericMacroServiceNetworkVnf Request ***** ", isDebugEnabled) - - } catch (BpmnError e) { - throw e; - - } catch (Exception ex){ - String exceptionMessage = "Bpmn error encountered in CreateGenericMacroServiceNetworkVnf flow. Unexpected from method preProcessRequest() - " + ex.getMessage() - exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) - } - } - - public void sendSyncResponse (Execution execution) { - def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - - utils.log("DEBUG", " ***** Inside sendSyncResponse of CreateGenericMacroServiceNetworkVnf ***** ", isDebugEnabled) - - try { - String serviceInstanceId = execution.getVariable("serviceInstanceId") - String requestId = execution.getVariable("mso-request-id") - - // RESTResponse (for API Handler (APIH) Reply Task) - String syncResponse ="""{"requestReferences":{"instanceId":"${serviceInstanceId}","requestId":"${requestId}"}}""".trim() - - utils.log("DEBUG", " sendSynchResponse: xmlSyncResponse - " + "\n" + syncResponse, isDebugEnabled) - sendWorkflowResponse(execution, 202, syncResponse) - - } catch (Exception ex) { - String exceptionMessage = "Bpmn error encountered in CreateGenericMacroServiceNetworkVnf flow. Unexpected from method sendSyncResponse() - " + ex.getMessage() - exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) - } - } - - // ******************************* - // - // ******************************* - public void prepareCreateServiceInstance(Execution execution) { - def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - - try { - utils.log("DEBUG", " ***** Inside prepareCreateServiceInstance of CreateGenericMacroServiceNetworkVnf ***** ", isDebugEnabled) - - String createGenericMacroServiceNetworkVnfRequest = execution.getVariable("createGenericMacroServiceNetworkVnfRequest") - String serviceModelInfo = jsonUtil.getJsonValue(createGenericMacroServiceNetworkVnfRequest, "requestDetails.modelInfo") - execution.setVariable("serviceModelInfo", serviceModelInfo) - - String serviceInputParams = jsonUtil.getJsonValue(createGenericMacroServiceNetworkVnfRequest, "requestDetails.requestParameters") - execution.setVariable("serviceInputParams", serviceInputParams) - - String serviceInstanceName = jsonUtil.getJsonValue(createGenericMacroServiceNetworkVnfRequest, "requestDetails.requestInfo.instanceName") - execution.setVariable("serviceInstanceName", serviceInstanceName) - - utils.log("DEBUG", " ***** Completed prepareCreateServiceInstance of CreateGenericMacroServiceNetworkVnf ***** ", isDebugEnabled) - } catch (Exception ex) { - // try error in method block - String exceptionMessage = "Bpmn error encountered in CreateGenericMacroServiceNetworkVnf flow. Unexpected Error from method prepareCreateService() - " + ex.getMessage() - exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) - } - } - - - public void postProcessServiceInstanceCreate (Execution execution){ - def method = getClass().getSimpleName() + '.postProcessServiceInstanceCreate(' +'execution=' + execution.getId() +')' - def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') - logDebug('Entered ' + method, isDebugLogEnabled) - - String source = execution.getVariable("source") - String requestId = execution.getVariable("mso-request-id") - String serviceInstanceId = execution.getVariable("serviceInstanceId") - String serviceInstanceName = execution.getVariable("serviceInstanceName") - - try { - - String payload = """ - - - - - ${requestId} - BPEL - ${serviceInstanceId} - ${serviceInstanceName} - - - - """ - execution.setVariable("CREVAS_setUpdateDbInstancePayload", payload) - utils.logAudit("CREVAS_setUpdateDbInstancePayload: " + payload) - logDebug('Exited ' + method, isDebugLogEnabled) - //println("CMSO_updateDBStatusToSuccessPayload --> " + execution.getVariable("CMSO_updateDBStatusToSuccessPayload")) - - } catch (BpmnError e) { - throw e; - } catch (Exception e) { - logError('Caught exception in ' + method, e) - exceptionUtil.buildAndThrowWorkflowException(execution, 2000, "Internal Error - Occured in" + method) - } - } - - - public void callDBCatalog (Execution execution) { - def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - - utils.log("DEBUG", " ***** Inside callDBCatalog() of CreateGenericMacroServiceNetworkVnf ***** ", isDebugEnabled) - - try { - - // get variable within incoming json - String createGenericMacroServiceNetworkVnfRequest = execution.getVariable("createGenericMacroServiceNetworkVnfRequest"); - - String catalog_db_endpoint = execution.getVariable("URN_mso_catalog_db_endpoint") - utils.log("DEBUG", "catalog_db_endpoint: "+catalog_db_endpoint, isDebugEnabled) - - String serviceModelInvariantId = jsonUtil.getJsonValue(createGenericMacroServiceNetworkVnfRequest, "requestDetails.modelInfo.modelInvariantId") - String serviceModelVersion = jsonUtil.getJsonValue(createGenericMacroServiceNetworkVnfRequest, "requestDetails.modelInfo.modelVersion") - utils.log("DEBUG", "getting network list ", isDebugEnabled) - - JSONArray networkList = catalogDbUtils.getAllNetworksByServiceModelInvariantUuidAndServiceModelVersion(catalog_db_endpoint, serviceModelInvariantId, serviceModelVersion) - - //utils.log("DEBUG", "got network list: "+ networkList.toString(), isDebugEnabled) - execution.setVariable("networkList", networkList) - execution.setVariable("networkListString", networkList.toString()) - - if (networkList != null && networkList.length() > 0) { - - execution.setVariable("CREVAS_NetworksCount", networkList.length()) - utils.log("DEBUG", "networks to create: "+ networkList.length(), isDebugEnabled) - } else { - execution.setVariable("CREVAS_NetworksCount", 0) - utils.log("DEBUG", "no networks to create based upon Catalog DB response", isDebugEnabled) - } - - // VNFs - JSONArray vnfList = catalogDbUtils.getAllVnfsByServiceModelInvariantUuidAndServiceModelVersion(catalog_db_endpoint, serviceModelInvariantId, serviceModelVersion) - execution.setVariable("vnfList", vnfList) - - String vnfModelInfoString = "" - if (vnfList != null && vnfList.length() > 0) { - execution.setVariable("CREVAS_VNFsCount", vnfList.length()) - utils.log("DEBUG", "vnfs to create: "+ vnfList.length(), isDebugEnabled) - JSONObject vnfModelInfo = vnfList.getJSONObject(0).getJSONObject("modelInfo") - vnfModelInfoString = vnfModelInfo.toString() - } else { - execution.setVariable("CREVAS_VNFsCount", 0) - utils.log("DEBUG", "no vnfs to create based upon Catalog DB response", isDebugEnabled) - } - - execution.setVariable("vnfModelInfo", vnfModelInfoString) - //utils.log("DEBUG", " vnfModelInfoString :" + vnfModelInfoString, isDebugEnabled) - - utils.log("DEBUG", " ***** Completed callDBCatalog() of CreateGenericMacroServiceNetworkVnf ***** ", isDebugEnabled) - } catch (Exception ex) { - sendSyncError(execution) - String exceptionMessage = "Bpmn error encountered in CreateGenericMacroServiceNetworkVnf flow. callDBCatalog() - " + ex.getMessage() - utils.log("DEBUG", exceptionMessage, isDebugEnabled) - exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) - } - } - - // ******************************* - // Generate Network request Section - // ******************************* - public void prepareNetworkCreate (Execution execution) { - def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - - try { - utils.log("DEBUG", " ***** Inside preparenNetworkCreate of CreateGenericMacroServiceNetworkVnf ***** ", isDebugEnabled) - -// String disableRollback = execution.getVariable("disableRollback") -// def backoutOnFailure = "" -// if(disableRollback != null){ -// if ( disableRollback == true) { -// backoutOnFailure = "false" -// } else if ( disableRollback == false) { -// backoutOnFailure = "true" -// } -// } - //failIfExists - optional - - String createGenericMacroServiceNetworkVnfRequest = execution.getVariable("createGenericMacroServiceNetworkVnfRequest") - - JSONArray networkList = execution.getVariable("networkList") - utils.log("DEBUG", "array networkList: "+ networkList, isDebugEnabled) - - if (networkList == null || networkList.length() < 1){ - networkList = new JSONArray(execution.getVariable("networkListString")) - utils.log("DEBUG", "array from string networkList: "+ networkList, isDebugEnabled) - } - - Integer networksCreatedCount = execution.getVariable("CREVAS_NetworksCreatedCount") - String networkModelInfoString = "" - - if (networkList != null) { - utils.log("DEBUG", " getting model info for network # :" + networksCreatedCount, isDebugEnabled) - JSONObject networkModelInfo = networkList.getJSONObject(networksCreatedCount.intValue()).getJSONObject("modelInfo") - networkModelInfoString = networkModelInfo.toString() - } else { - String exceptionMessage = "Bpmn error encountered in CreateGenericMacroServiceNetworkVnf flow. Unexpected number of networks to create - " + ex.getMessage() - exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) - } - - execution.setVariable("networkModelInfo", networkModelInfoString) - utils.log("DEBUG", " networkModelInfoString :" + networkModelInfoString, isDebugEnabled) - -// String networkModelInfo = execution.getVariable("networkModelInfo") - // extract cloud configuration - String lcpCloudRegionId = jsonUtil.getJsonValue(createGenericMacroServiceNetworkVnfRequest, "requestDetails.cloudConfiguration.lcpCloudRegionId") - execution.setVariable("lcpCloudRegionId", lcpCloudRegionId) - utils.log("DEBUG","lcpCloudRegionId: "+ lcpCloudRegionId, isDebugEnabled) - String tenantId = jsonUtil.getJsonValue(createGenericMacroServiceNetworkVnfRequest, "requestDetails.cloudConfiguration.tenantId") - execution.setVariable("tenantId", tenantId) - utils.log("DEBUG","tenantId: "+ tenantId, isDebugEnabled) - - String sdncVersion = execution.getVariable("sdncVersion") - utils.log("DEBUG","sdncVersion: "+ sdncVersion, isDebugEnabled) - - JSONArray vnfList = execution.getVariable("vnfList") - utils.log("DEBUG", "vnfList: "+ vnfList, isDebugEnabled) - - String vnfModelInfo = execution.getVariable("vnfModelInfo") - utils.log("DEBUG", "vnfModelInfo: "+ vnfModelInfo, isDebugEnabled) - - networkList = execution.getVariable("networkList") - utils.log("DEBUG", "networkList: "+ networkList, isDebugEnabled) - - utils.log("DEBUG", " ***** Completed preparenNetworkCreate of CreateGenericMacroServiceNetworkVnf ***** ", isDebugEnabled) - } catch (Exception ex) { - // try error in method block - String exceptionMessage = "Bpmn error encountered in CreateGenericMacroServiceNetworkVnf flow. Unexpected Error from method prepareNetworkCreate() - " + ex.getMessage() - exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) - } - } - - // ******************************* - // Validate Network request Section -> increment count - // ******************************* - public void validateNetworkCreate (Execution execution) { - def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - - try { - utils.log("DEBUG", " ***** Inside validateNetworkCreate of CreateGenericMacroServiceNetworkVnf ***** ", isDebugEnabled) - - Integer networksCreatedCount = execution.getVariable("CREVAS_NetworksCreatedCount") - networksCreatedCount++ - - execution.setVariable("CREVAS_NetworksCreatedCount", networksCreatedCount) - - execution.setVariable("DCRENI_rollbackData"+networksCreatedCount, execution.getVariable("DCRENI_rollbackData")) - - utils.log("DEBUG", "networksCreatedCount: "+ networksCreatedCount, isDebugEnabled) - utils.log("DEBUG", "DCRENI_rollbackData N : "+ execution.getVariable("DCRENI_rollbackData"+networksCreatedCount), isDebugEnabled) - - JSONArray vnfList = execution.getVariable("vnfList") - utils.log("DEBUG", "vnfList: "+ vnfList, isDebugEnabled) - - String vnfModelInfo = execution.getVariable("vnfModelInfo") - utils.log("DEBUG", "vnfModelInfo: "+ vnfModelInfo, isDebugEnabled) - - JSONArray networkList = execution.getVariable("networkList") - utils.log("DEBUG", "networkList: "+ networkList, isDebugEnabled) - - utils.log("DEBUG", " ***** Completed validateNetworkCreate of CreateGenericMacroServiceNetworkVnf ***** "+" network # "+networksCreatedCount, isDebugEnabled) - } catch (Exception ex) { - // try error in method block - String exceptionMessage = "Bpmn error encountered in CreateGenericMacroServiceNetworkVnf flow. Unexpected Error from method validateNetworkCreate() - " + ex.getMessage() - exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) - } - } - - // ******************************* - // Generate Network request Section - // ******************************* - public void prepareVnfAndModulesCreate (Execution execution) { - def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - - try { - utils.log("DEBUG", " ***** Inside prepareVnfAndModulesCreate of CreateGenericMacroServiceNetworkVnf ***** ", isDebugEnabled) - - // String disableRollback = execution.getVariable("disableRollback") - // def backoutOnFailure = "" - // if(disableRollback != null){ - // if ( disableRollback == true) { - // backoutOnFailure = "false" - // } else if ( disableRollback == false) { - // backoutOnFailure = "true" - // } - // } - //failIfExists - optional - - String createGenericMacroServiceNetworkVnfRequest = execution.getVariable("createGenericMacroServiceNetworkVnfRequest") - String productFamilyId = jsonUtil.getJsonValue(createGenericMacroServiceNetworkVnfRequest, "requestDetails.requestInfo.productFamilyId") - execution.setVariable("productFamilyId", productFamilyId) - utils.log("DEBUG","productFamilyId: "+ productFamilyId, isDebugEnabled) - - JSONArray vnfList = execution.getVariable("vnfList") - - Integer vnfsCreatedCount = execution.getVariable("CREVAS_VnfsCreatedCount") - String vnfModelInfoString = null; - - if (vnfList != null && vnfList.length() > 0 ) { - utils.log("DEBUG", "getting model info for vnf # " + vnfsCreatedCount, isDebugEnabled) - JSONObject vnfModelInfo1 = vnfList.getJSONObject(0).getJSONObject("modelInfo") - utils.log("DEBUG", "got 0 ", isDebugEnabled) - JSONObject vnfModelInfo = vnfList.getJSONObject(vnfsCreatedCount.intValue()).getJSONObject("modelInfo") - vnfModelInfoString = vnfModelInfo.toString() - } else { - //TODO: vnfList does not contain data. Need to investigate why ... . Fro VIPR use model stored - vnfModelInfoString = execution.getVariable("vnfModelInfo") - } - - utils.log("DEBUG", " vnfModelInfoString :" + vnfModelInfoString, isDebugEnabled) - - // extract cloud configuration - String lcpCloudRegionId = jsonUtil.getJsonValue(createGenericMacroServiceNetworkVnfRequest, "requestDetails.cloudConfiguration.lcpCloudRegionId") - execution.setVariable("lcpCloudRegionId", lcpCloudRegionId) - utils.log("DEBUG","lcpCloudRegionId: "+ lcpCloudRegionId, isDebugEnabled) - String tenantId = jsonUtil.getJsonValue(createGenericMacroServiceNetworkVnfRequest, "requestDetails.cloudConfiguration.tenantId") - execution.setVariable("tenantId", tenantId) - utils.log("DEBUG","tenantId: "+ tenantId, isDebugEnabled) - - String sdncVersion = execution.getVariable("sdncVersion") - utils.log("DEBUG","sdncVersion: "+ sdncVersion, isDebugEnabled) - - utils.log("DEBUG", " ***** Completed prepareVnfAndModulesCreate of CreateGenericMacroServiceNetworkVnf ***** ", isDebugEnabled) - } catch (Exception ex) { - // try error in method block - String exceptionMessage = "Bpmn error encountered in CreateGenericMacroServiceNetworkVnf flow. Unexpected Error from method prepareVnfAndModulesCreate() - " + ex.getMessage() - exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) - } - } - - // ******************************* - // Validate Vnf request Section -> increment count - // ******************************* - public void validateVnfCreate (Execution execution) { - def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - - try { - utils.log("DEBUG", " ***** Inside validateVnfCreate of CreateGenericMacroServiceNetworkVnf ***** ", isDebugEnabled) - - Integer vnfsCreatedCount = execution.getVariable("CREVAS_VnfsCreatedCount") - vnfsCreatedCount++ - - execution.setVariable("CREVAS_VnfsCreatedCount", vnfsCreatedCount) - - utils.log("DEBUG", " ***** Completed validateVnfCreate of CreateGenericMacroServiceNetworkVnf ***** "+" vnf # "+vnfsCreatedCount, isDebugEnabled) - } catch (Exception ex) { - // try error in method block - String exceptionMessage = "Bpmn error encountered in CreateGenericMacroServiceNetworkVnf flow. Unexpected Error from method validateVnfCreate() - " + ex.getMessage() - exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) - } - } - - // ******************************* - // Validate Network request Section -> decrement count - // ******************************* - public void validateNetworkRollback (Execution execution) { - def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - - try { - utils.log("DEBUG", " ***** Inside validateNetworkRollback of CreateGenericMacroServiceNetworkVnf ***** ", isDebugEnabled) - - Integer networksCreatedCount = execution.getVariable("CREVAS_NetworksCreatedCount") - networksCreatedCount-- - - execution.setVariable("CREVAS_NetworksCreatedCount", networksCreatedCount) - - execution.setVariable("DCRENI_rollbackData", execution.getVariable("DCRENI_rollbackData"+networksCreatedCount)) - - utils.log("DEBUG", " ***** Completed validateNetworkRollback of CreateGenericMacroServiceNetworkVnf ***** "+" network # "+networksCreatedCount, isDebugEnabled) - } catch (Exception ex) { - // try error in method block - String exceptionMessage = "Bpmn error encountered in CreateGenericMacroServiceNetworkVnf flow. Unexpected Error from method validateNetworkRollback() - " + ex.getMessage() - //exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) - utils.log("DEBUG", exceptionMessage, isDebugEnabled) - execution.setVariable("CREVAS_NetworksCreatedCount", 0) - utils.log("ERROR", exceptionMessage, true) - } - } - // ******************************* - // Build DB request Section - // ******************************* -// public void prepareDBRequest (Execution execution) { -// def isDebugEnabled=execution.getVariable("isDebugLogEnabled") -// -// try { -// utils.log("DEBUG", " ***** Inside prepareDBRequest of CreateGenericMacroServiceNetworkVnf ***** ", isDebugEnabled) -// -// String requestId = execution.getVariable("CREVAS_requestId") -// String statusMessage = "vIPR ATM Service Instance successfully created." -// String serviceInstanceId = execution.getVariable("CREVAS_serviceInstanceId") -// -// //TODO - verify the format for Service Instance Create, -// String dbRequest = -// """ -// -// -// -// ${requestId} -// BPMN -// ${statusMessage} -// -// COMPLETED -// 100 -// -// ${serviceInstanceId} -// -// -// """ -// -// String buildDeleteDBRequestAsString = utils.formatXml(dbRequest) -// execution.setVariable("CREVAS_createDBRequest", buildDeleteDBRequestAsString) -// utils.logAudit(buildDeleteDBRequestAsString) -// -// utils.log("DEBUG", " ***** Completed prepareDBRequest of CreateGenericMacroServiceNetworkVnf ***** ", isDebugEnabled) -// } catch (Exception ex) { -// // try error in method block -// String exceptionMessage = "Bpmn error encountered in CreateGenericMacroServiceNetworkVnf flow. Unexpected Error from method prepareDBRequest() - " + ex.getMessage() -// exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) -// -// } -// -// } - - - // ***************************************** - // Prepare Completion request Section - // ***************************************** - public void postProcessResponse (Execution execution) { - def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - - utils.log("DEBUG", " ***** Inside postProcessResponse of CreateGenericMacroServiceNetworkVnf ***** ", isDebugEnabled) - - try { - String source = execution.getVariable("source") - String requestId = execution.getVariable("mso-request-id") - String serviceInstanceId = execution.getVariable("serviceInstanceId") - - String msoCompletionRequest = - """ - - ${requestId} - CREATE - ${source} - - Service Instance has been created successfully via macro orchestration - ${serviceInstanceId} - BPMN macro create - """ - - // Format Response - String xmlMsoCompletionRequest = utils.formatXml(msoCompletionRequest) - - utils.logAudit(xmlMsoCompletionRequest) - execution.setVariable("CREVAS_Success", true) - execution.setVariable("CREVAS_CompleteMsoProcessRequest", xmlMsoCompletionRequest) - utils.log("DEBUG", " SUCCESS flow, going to CompleteMsoProcess - " + "\n" + xmlMsoCompletionRequest, isDebugEnabled) - } catch (BpmnError e) { - throw e; - } catch (Exception ex) { - // try error in method block - String exceptionMessage = "Bpmn error encountered in CreateServiceInstance flow. Unexpected Error from method postProcessResponse() - " + ex.getMessage() - exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) - } - } - - public void preProcessRollback (Execution execution) { - def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - utils.log("DEBUG"," ***** preProcessRollback of CreateGenericMacroServiceNetworkVnf ***** ", isDebugEnabled) - try { - - Object workflowException = execution.getVariable("WorkflowException"); - - if (workflowException instanceof WorkflowException) { - utils.log("DEBUG", "Prev workflowException: " + workflowException.getErrorMessage(), isDebugEnabled) - execution.setVariable("prevWorkflowException", workflowException); - //execution.setVariable("WorkflowException", null); - } - } catch (BpmnError e) { - utils.log("DEBUG", "BPMN Error during preProcessRollback", isDebugEnabled) - } catch(Exception ex) { - String msg = "Exception in preProcessRollback. " + ex.getMessage() - utils.log("DEBUG", msg, isDebugEnabled) - } - utils.log("DEBUG"," *** Exit preProcessRollback of CreateGenericMacroServiceNetworkVnf *** ", isDebugEnabled) - } - - public void postProcessRollback (Execution execution) { - def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - utils.log("DEBUG"," ***** postProcessRollback of CreateGenericMacroServiceNetworkVnf ***** ", isDebugEnabled) - String msg = "" - try { - Object workflowException = execution.getVariable("prevWorkflowException"); - if (workflowException instanceof WorkflowException) { - utils.log("DEBUG", "Setting prevException to WorkflowException: ", isDebugEnabled) - execution.setVariable("WorkflowException", workflowException); - } - } catch (BpmnError b) { - utils.log("DEBUG", "BPMN Error during postProcessRollback", isDebugEnabled) - throw b; - } catch(Exception ex) { - msg = "Exception in postProcessRollback. " + ex.getMessage() - utils.log("DEBUG", msg, isDebugEnabled) - } - utils.log("DEBUG"," *** Exit postProcessRollback of CreateGenericMacroServiceNetworkVnf *** ", isDebugEnabled) - } - - public void prepareFalloutRequest(Execution execution){ - def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - - utils.log("DEBUG", " *** STARTED CreateGenericMacroServiceNetworkVnf prepareFalloutRequest Process *** ", isDebugEnabled) - - try { - WorkflowException wfex = execution.getVariable("WorkflowException") - utils.log("DEBUG", " Incoming Workflow Exception: " + wfex.toString(), isDebugEnabled) - String requestInfo = execution.getVariable("CREVAS_requestInfo") - utils.log("DEBUG", " Incoming Request Info: " + requestInfo, isDebugEnabled) - - //TODO. hmmm. there is no way to UPDATE error message. -// String errorMessage = wfex.getErrorMessage() -// boolean successIndicator = execution.getVariable("DCRESI_rollbackSuccessful") -// if (successIndicator){ -// errorMessage = errorMessage + ". Rollback successful." -// } else { -// errorMessage = errorMessage + ". Rollback not completed." -// } - - String falloutRequest = exceptionUtil.processMainflowsBPMNException(execution, requestInfo) - - execution.setVariable("CREVAS_falloutRequest", falloutRequest) - - } catch (Exception ex) { - utils.log("DEBUG", "Error Occured in CreateGenericMacroServiceNetworkVnf prepareFalloutRequest Process " + ex.getMessage(), isDebugEnabled) - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured in CreateGenericMacroServiceNetworkVnf prepareFalloutRequest Process") - } - utils.log("DEBUG", "*** COMPLETED CreateGenericMacroServiceNetworkVnf prepareFalloutRequest Process ***", isDebugEnabled) - } - - - public void sendSyncError (Execution execution) { - def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - execution.setVariable("prefix", Prefix) - - utils.log("DEBUG", " ***** Inside sendSyncError() of CreateServiceInstanceInfra ***** ", isDebugEnabled) - - try { - String errorMessage = "" - if (execution.getVariable("WorkflowException") instanceof WorkflowException) { - WorkflowException wfe = execution.getVariable("WorkflowException") - errorMessage = wfe.getErrorMessage() - } else { - errorMessage = "Sending Sync Error." - } - - String buildworkflowException = - """ - ${errorMessage} - 7000 - """ - - utils.logAudit(buildworkflowException) - sendWorkflowResponse(execution, 500, buildworkflowException) - } catch (Exception ex) { - utils.log("DEBUG", " Sending Sync Error Activity Failed. " + "\n" + ex.getMessage(), isDebugEnabled) - } - } - - public void processJavaException(Execution execution){ - def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - execution.setVariable("prefix",Prefix) - try{ - utils.log("DEBUG", "Caught a Java Exception", isDebugEnabled) - utils.log("DEBUG", "Started processJavaException Method", isDebugEnabled) - utils.log("DEBUG", "Variables List: " + execution.getVariables(), isDebugEnabled) - execution.setVariable("CRESI_unexpectedError", "Caught a Java Lang Exception") // Adding this line temporarily until this flows error handling gets updated - exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Caught a Java Lang Exception") - }catch(BpmnError b){ - utils.log("ERROR", "Rethrowing MSOWorkflowException", isDebugEnabled) - throw b - }catch(Exception e){ - utils.log("DEBUG", "Caught Exception during processJavaException Method: " + e, isDebugEnabled) - execution.setVariable("CRESI_unexpectedError", "Exception in processJavaException method") // Adding this line temporarily until this flows error handling gets updated - exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Exception in processJavaException method") - } - utils.log("DEBUG", "Completed processJavaException Method", isDebugEnabled) - } +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.bpmn.infrastructure.scripts; + +import groovy.xml.XmlUtil +import groovy.json.* + +import org.openecomp.mso.bpmn.core.json.JsonUtils +import org.openecomp.mso.bpmn.common.scripts.AbstractServiceTaskProcessor +import org.openecomp.mso.bpmn.common.scripts.CatalogDbUtils +import org.openecomp.mso.bpmn.common.scripts.ExceptionUtil +import org.openecomp.mso.bpmn.common.scripts.VidUtils +import org.openecomp.mso.bpmn.core.WorkflowException +import org.openecomp.mso.rest.APIResponse; +import org.openecomp.mso.rest.RESTClient +import org.openecomp.mso.rest.RESTConfig + +import java.util.UUID; + +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.runtime.Execution +import org.json.JSONObject; +import org.json.JSONArray; +import org.apache.commons.lang3.* +import org.apache.commons.codec.binary.Base64; +import org.springframework.web.util.UriUtils; + +/** + * This groovy class supports the CreateGenericMacroServiceNetworkVnf.bpmn process. + * + */ +public class CreateGenericMacroServiceNetworkVnf extends AbstractServiceTaskProcessor { + + String Prefix="CREVAS_" + ExceptionUtil exceptionUtil = new ExceptionUtil() + JsonUtils jsonUtil = new JsonUtils() + VidUtils vidUtils = new VidUtils() + CatalogDbUtils catalogDbUtils = new CatalogDbUtils() + + /** + * This method is executed during the preProcessRequest task of the CreateServiceInstance.bpmn process. + * @param execution + */ + public InitializeProcessVariables(Execution execution){ + /* Initialize all the process variables in this block */ + + execution.setVariable("createGenericMacroServiceNetworkVnfRequest", "") + execution.setVariable("globalSubscriberId", "") + execution.setVariable("serviceInstanceName", "") + execution.setVariable("msoRequestId", "") + execution.setVariable("CREVAS_NetworksCreatedCount", 0) + execution.setVariable("CREVAS_VnfsCreatedCount", 0) + execution.setVariable("productFamilyId", "") + + + //TODO + execution.setVariable("sdncVersion", "1702") + } + + // ************************************************** + // Pre or Prepare Request Section + // ************************************************** + /** + * This method is executed during the preProcessRequest task of the CreateServiceInstance.bpmn process. + * @param execution + */ + public void preProcessRequest (Execution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix",Prefix) + + utils.log("DEBUG", " ***** Inside preProcessRequest CreateGenericMacroServiceNetworkVnf Request ***** ", isDebugEnabled) + + try { + // initialize flow variables + InitializeProcessVariables(execution) + + // check for incoming json message/input + String createGenericMacroServiceNetworkVnfRequest = execution.getVariable("bpmnRequest") + utils.logAudit(createGenericMacroServiceNetworkVnfRequest) + execution.setVariable("createGenericMacroServiceNetworkVnfRequest", createGenericMacroServiceNetworkVnfRequest); + println 'createGenericMacroServiceNetworkVnfRequest - ' + createGenericMacroServiceNetworkVnfRequest + + // extract requestId + String requestId = execution.getVariable("mso-request-id") + execution.setVariable("msoRequestId", requestId) + + String serviceInstanceId = execution.getVariable("serviceInstanceId") + + if ((serviceInstanceId == null) || (serviceInstanceId.isEmpty())) { + serviceInstanceId = UUID.randomUUID().toString() + utils.log("DEBUG", " Generated new Service Instance: " + serviceInstanceId , isDebugEnabled) + } else { + utils.log("DEBUG", "Using provided Service Instance ID: " + serviceInstanceId , isDebugEnabled) + } + + serviceInstanceId = UriUtils.encode(serviceInstanceId,"UTF-8") + execution.setVariable("serviceInstanceId", serviceInstanceId) + + String requestAction = execution.getVariable("requestAction") + execution.setVariable("requestAction", requestAction) + + String source = jsonUtil.getJsonValue(createGenericMacroServiceNetworkVnfRequest, "requestDetails.requestInfo.source") + if ((source == null) || (source.isEmpty())) { + execution.setVariable("source", "VID") + } else { + execution.setVariable("source", source) + } + + // extract globalSubscriberId + String globalSubscriberId = jsonUtil.getJsonValue(createGenericMacroServiceNetworkVnfRequest, "requestDetails.subscriberInfo.globalSubscriberId") + + // verify element global-customer-id is sent from JSON input, throw exception if missing + if ((globalSubscriberId == null) || (globalSubscriberId.isEmpty())) { + String dataErrorMessage = " Element 'globalSubscriberId' is missing. " + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) + + } else { + execution.setVariable("globalSubscriberId", globalSubscriberId) + execution.setVariable("globalCustomerId", globalSubscriberId) + } + + // extract subscriptionServiceType + String subscriptionServiceType = jsonUtil.getJsonValue(createGenericMacroServiceNetworkVnfRequest, "requestDetails.requestParameters.subscriptionServiceType") + execution.setVariable("subscriptionServiceType", subscriptionServiceType) + utils.log("DEBUG", "Incoming subscriptionServiceType is: " + subscriptionServiceType, isDebugEnabled) + + String suppressRollback = jsonUtil.getJsonValue(createGenericMacroServiceNetworkVnfRequest, "requestDetails.requestInfo.suppressRollback") + execution.setVariable("disableRollback", suppressRollback) + utils.log("DEBUG", "Incoming Suppress/Disable Rollback is: " + suppressRollback, isDebugEnabled) + + String productFamilyId = jsonUtil.getJsonValue(createGenericMacroServiceNetworkVnfRequest, "requestDetails.requestInfo.productFamilyId") + execution.setVariable("productFamilyId", productFamilyId) + utils.log("DEBUG", "Incoming productFamilyId is: " + productFamilyId, isDebugEnabled) + + //For Completion Handler & Fallout Handler + String requestInfo = + """ + ${requestId} + CREATE + ${source} + """ + + execution.setVariable("CREVAS_requestInfo", requestInfo) + + utils.log("DEBUG", " ***** Completed preProcessRequest CreateGenericMacroServiceNetworkVnf Request ***** ", isDebugEnabled) + + } catch (BpmnError e) { + throw e; + + } catch (Exception ex){ + String exceptionMessage = "Bpmn error encountered in CreateGenericMacroServiceNetworkVnf flow. Unexpected from method preProcessRequest() - " + ex.getMessage() + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + } + } + + public void sendSyncResponse (Execution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + + utils.log("DEBUG", " ***** Inside sendSyncResponse of CreateGenericMacroServiceNetworkVnf ***** ", isDebugEnabled) + + try { + String serviceInstanceId = execution.getVariable("serviceInstanceId") + String requestId = execution.getVariable("mso-request-id") + + // RESTResponse (for API Handler (APIH) Reply Task) + String syncResponse ="""{"requestReferences":{"instanceId":"${serviceInstanceId}","requestId":"${requestId}"}}""".trim() + + utils.log("DEBUG", " sendSynchResponse: xmlSyncResponse - " + "\n" + syncResponse, isDebugEnabled) + sendWorkflowResponse(execution, 202, syncResponse) + + } catch (Exception ex) { + String exceptionMessage = "Bpmn error encountered in CreateGenericMacroServiceNetworkVnf flow. Unexpected from method sendSyncResponse() - " + ex.getMessage() + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + } + } + + // ******************************* + // + // ******************************* + public void prepareCreateServiceInstance(Execution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + + try { + utils.log("DEBUG", " ***** Inside prepareCreateServiceInstance of CreateGenericMacroServiceNetworkVnf ***** ", isDebugEnabled) + + String createGenericMacroServiceNetworkVnfRequest = execution.getVariable("createGenericMacroServiceNetworkVnfRequest") + String serviceModelInfo = jsonUtil.getJsonValue(createGenericMacroServiceNetworkVnfRequest, "requestDetails.modelInfo") + execution.setVariable("serviceModelInfo", serviceModelInfo) + + String serviceInputParams = jsonUtil.getJsonValue(createGenericMacroServiceNetworkVnfRequest, "requestDetails.requestParameters") + execution.setVariable("serviceInputParams", serviceInputParams) + + String serviceInstanceName = jsonUtil.getJsonValue(createGenericMacroServiceNetworkVnfRequest, "requestDetails.requestInfo.instanceName") + execution.setVariable("serviceInstanceName", serviceInstanceName) + + utils.log("DEBUG", " ***** Completed prepareCreateServiceInstance of CreateGenericMacroServiceNetworkVnf ***** ", isDebugEnabled) + } catch (Exception ex) { + // try error in method block + String exceptionMessage = "Bpmn error encountered in CreateGenericMacroServiceNetworkVnf flow. Unexpected Error from method prepareCreateService() - " + ex.getMessage() + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + } + } + + + public void postProcessServiceInstanceCreate (Execution execution){ + def method = getClass().getSimpleName() + '.postProcessServiceInstanceCreate(' +'execution=' + execution.getId() +')' + def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') + logDebug('Entered ' + method, isDebugLogEnabled) + + String source = execution.getVariable("source") + String requestId = execution.getVariable("mso-request-id") + String serviceInstanceId = execution.getVariable("serviceInstanceId") + String serviceInstanceName = execution.getVariable("serviceInstanceName") + + try { + + String payload = """ + + + + + ${requestId} + BPEL + ${serviceInstanceId} + ${serviceInstanceName} + + + + """ + execution.setVariable("CREVAS_setUpdateDbInstancePayload", payload) + utils.logAudit("CREVAS_setUpdateDbInstancePayload: " + payload) + logDebug('Exited ' + method, isDebugLogEnabled) + //println("CMSO_updateDBStatusToSuccessPayload --> " + execution.getVariable("CMSO_updateDBStatusToSuccessPayload")) + + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + logError('Caught exception in ' + method, e) + exceptionUtil.buildAndThrowWorkflowException(execution, 2000, "Internal Error - Occured in" + method) + } + } + + + public void callDBCatalog (Execution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + + utils.log("DEBUG", " ***** Inside callDBCatalog() of CreateGenericMacroServiceNetworkVnf ***** ", isDebugEnabled) + + try { + + // get variable within incoming json + String createGenericMacroServiceNetworkVnfRequest = execution.getVariable("createGenericMacroServiceNetworkVnfRequest"); + + String catalog_db_endpoint = execution.getVariable("URN_mso_catalog_db_endpoint") + utils.log("DEBUG", "catalog_db_endpoint: "+catalog_db_endpoint, isDebugEnabled) + + String serviceModelInvariantId = jsonUtil.getJsonValue(createGenericMacroServiceNetworkVnfRequest, "requestDetails.modelInfo.modelInvariantId") + String serviceModelVersion = jsonUtil.getJsonValue(createGenericMacroServiceNetworkVnfRequest, "requestDetails.modelInfo.modelVersion") + utils.log("DEBUG", "getting network list ", isDebugEnabled) + + JSONArray networkList = catalogDbUtils.getAllNetworksByServiceModelInvariantUuidAndServiceModelVersion(catalog_db_endpoint, serviceModelInvariantId, serviceModelVersion) + + //utils.log("DEBUG", "got network list: "+ networkList.toString(), isDebugEnabled) + execution.setVariable("networkList", networkList) + execution.setVariable("networkListString", networkList.toString()) + + networkList = execution.getVariable("networkList"); + utils.log("DEBUG", "networkList: "+ networkList, isDebugEnabled) + + if (networkList != null && networkList.length() > 0) { + + execution.setVariable("CREVAS_NetworksCount", networkList.length()) + utils.log("DEBUG", "networks to create: "+ networkList.length(), isDebugEnabled) + } else { + execution.setVariable("CREVAS_NetworksCount", 0) + utils.log("DEBUG", "no networks to create based upon Catalog DB response", isDebugEnabled) + } + + // VNFs + JSONArray vnfList = catalogDbUtils.getAllVnfsByServiceModelInvariantUuidAndServiceModelVersion(catalog_db_endpoint, serviceModelInvariantId, serviceModelVersion) + execution.setVariable("vnfList", vnfList) + + String vnfModelInfoString = "" + if (vnfList != null && vnfList.length() > 0) { + execution.setVariable("CREVAS_VNFsCount", vnfList.length()) + utils.log("DEBUG", "vnfs to create: "+ vnfList.length(), isDebugEnabled) + JSONObject vnfModelInfo = vnfList.getJSONObject(0).getJSONObject("modelInfo") + vnfModelInfoString = vnfModelInfo.toString() + } else { + execution.setVariable("CREVAS_VNFsCount", 0) + utils.log("DEBUG", "no vnfs to create based upon Catalog DB response", isDebugEnabled) + } + + execution.setVariable("vnfModelInfo", vnfModelInfoString) + //utils.log("DEBUG", " vnfModelInfoString :" + vnfModelInfoString, isDebugEnabled) + + utils.log("DEBUG", " ***** Completed callDBCatalog() of CreateGenericMacroServiceNetworkVnf ***** ", isDebugEnabled) + } catch (Exception ex) { + sendSyncError(execution) + String exceptionMessage = "Bpmn error encountered in CreateGenericMacroServiceNetworkVnf flow. callDBCatalog() - " + ex.getMessage() + utils.log("DEBUG", exceptionMessage, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + } + } + + // ******************************* + // Generate Network request Section + // ******************************* + public void prepareNetworkCreate (Execution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + + try { + utils.log("DEBUG", " ***** Inside preparenNetworkCreate of CreateGenericMacroServiceNetworkVnf ***** ", isDebugEnabled) + +// String disableRollback = execution.getVariable("disableRollback") +// def backoutOnFailure = "" +// if(disableRollback != null){ +// if ( disableRollback == true) { +// backoutOnFailure = "false" +// } else if ( disableRollback == false) { +// backoutOnFailure = "true" +// } +// } + //failIfExists - optional + + String createGenericMacroServiceNetworkVnfRequest = execution.getVariable("createGenericMacroServiceNetworkVnfRequest") + + JSONArray networkList = execution.getVariable("networkList") + utils.log("DEBUG", "array networkList: "+ networkList, isDebugEnabled) + + if (networkList == null || networkList.length() < 1){ + networkList = new JSONArray(execution.getVariable("networkListString")) + utils.log("DEBUG", "array from string networkList: "+ networkList, isDebugEnabled) + } + + Integer networksCreatedCount = execution.getVariable("CREVAS_NetworksCreatedCount") + String networkModelInfoString = "" + + if (networkList != null) { + utils.log("DEBUG", " getting model info for network # :" + networksCreatedCount, isDebugEnabled) + JSONObject networkModelInfo = networkList.getJSONObject(networksCreatedCount.intValue()).getJSONObject("modelInfo") + networkModelInfoString = networkModelInfo.toString() + } else { + String exceptionMessage = "Bpmn error encountered in CreateGenericMacroServiceNetworkVnf flow. Unexpected number of networks to create - " + ex.getMessage() + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + } + + execution.setVariable("networkModelInfo", networkModelInfoString) + utils.log("DEBUG", " networkModelInfoString :" + networkModelInfoString, isDebugEnabled) + +// String networkModelInfo = execution.getVariable("networkModelInfo") + // extract cloud configuration + String lcpCloudRegionId = jsonUtil.getJsonValue(createGenericMacroServiceNetworkVnfRequest, "requestDetails.cloudConfiguration.lcpCloudRegionId") + execution.setVariable("lcpCloudRegionId", lcpCloudRegionId) + utils.log("DEBUG","lcpCloudRegionId: "+ lcpCloudRegionId, isDebugEnabled) + String tenantId = jsonUtil.getJsonValue(createGenericMacroServiceNetworkVnfRequest, "requestDetails.cloudConfiguration.tenantId") + execution.setVariable("tenantId", tenantId) + utils.log("DEBUG","tenantId: "+ tenantId, isDebugEnabled) + + String sdncVersion = execution.getVariable("sdncVersion") + utils.log("DEBUG","sdncVersion: "+ sdncVersion, isDebugEnabled) + + JSONArray vnfList = execution.getVariable("vnfList") + utils.log("DEBUG", "vnfList: "+ vnfList, isDebugEnabled) + + String vnfModelInfo = execution.getVariable("vnfModelInfo") + utils.log("DEBUG", "vnfModelInfo: "+ vnfModelInfo, isDebugEnabled) + + networkList = execution.getVariable("networkList") + utils.log("DEBUG", "networkList: "+ networkList, isDebugEnabled) + + utils.log("DEBUG", " ***** Completed preparenNetworkCreate of CreateGenericMacroServiceNetworkVnf ***** ", isDebugEnabled) + } catch (Exception ex) { + // try error in method block + String exceptionMessage = "Bpmn error encountered in CreateGenericMacroServiceNetworkVnf flow. Unexpected Error from method prepareNetworkCreate() - " + ex.getMessage() + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + } + } + + // ******************************* + // Validate Network request Section -> increment count + // ******************************* + public void validateNetworkCreate (Execution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + + try { + utils.log("DEBUG", " ***** Inside validateNetworkCreate of CreateGenericMacroServiceNetworkVnf ***** ", isDebugEnabled) + + Integer networksCreatedCount = execution.getVariable("CREVAS_NetworksCreatedCount") + networksCreatedCount++ + + execution.setVariable("CREVAS_NetworksCreatedCount", networksCreatedCount) + + execution.setVariable("DCRENI_rollbackData"+networksCreatedCount, execution.getVariable("DCRENI_rollbackData")) + + utils.log("DEBUG", "networksCreatedCount: "+ networksCreatedCount, isDebugEnabled) + utils.log("DEBUG", "DCRENI_rollbackData N : "+ execution.getVariable("DCRENI_rollbackData"+networksCreatedCount), isDebugEnabled) + + JSONArray vnfList = execution.getVariable("vnfList") + utils.log("DEBUG", "vnfList: "+ vnfList, isDebugEnabled) + + String vnfModelInfo = execution.getVariable("vnfModelInfo") + utils.log("DEBUG", "vnfModelInfo: "+ vnfModelInfo, isDebugEnabled) + + JSONArray networkList = execution.getVariable("networkList") + utils.log("DEBUG", "networkList: "+ networkList, isDebugEnabled) + + utils.log("DEBUG", " ***** Completed validateNetworkCreate of CreateGenericMacroServiceNetworkVnf ***** "+" network # "+networksCreatedCount, isDebugEnabled) + } catch (Exception ex) { + // try error in method block + String exceptionMessage = "Bpmn error encountered in CreateGenericMacroServiceNetworkVnf flow. Unexpected Error from method validateNetworkCreate() - " + ex.getMessage() + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + } + } + + // ******************************* + // Generate Network request Section + // ******************************* + public void prepareVnfAndModulesCreate (Execution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + + try { + utils.log("DEBUG", " ***** Inside prepareVnfAndModulesCreate of CreateGenericMacroServiceNetworkVnf ***** ", isDebugEnabled) + + // String disableRollback = execution.getVariable("disableRollback") + // def backoutOnFailure = "" + // if(disableRollback != null){ + // if ( disableRollback == true) { + // backoutOnFailure = "false" + // } else if ( disableRollback == false) { + // backoutOnFailure = "true" + // } + // } + //failIfExists - optional + + String createGenericMacroServiceNetworkVnfRequest = execution.getVariable("createGenericMacroServiceNetworkVnfRequest") + String productFamilyId = jsonUtil.getJsonValue(createGenericMacroServiceNetworkVnfRequest, "requestDetails.requestInfo.productFamilyId") + execution.setVariable("productFamilyId", productFamilyId) + utils.log("DEBUG","productFamilyId: "+ productFamilyId, isDebugEnabled) + + JSONArray vnfList = execution.getVariable("vnfList") + + Integer vnfsCreatedCount = execution.getVariable("CREVAS_VnfsCreatedCount") + String vnfModelInfoString = null; + + if (vnfList != null && vnfList.length() > 0 ) { + utils.log("DEBUG", "getting model info for vnf # " + vnfsCreatedCount, isDebugEnabled) + JSONObject vnfModelInfo1 = vnfList.getJSONObject(0).getJSONObject("modelInfo") + utils.log("DEBUG", "got 0 ", isDebugEnabled) + JSONObject vnfModelInfo = vnfList.getJSONObject(vnfsCreatedCount.intValue()).getJSONObject("modelInfo") + vnfModelInfoString = vnfModelInfo.toString() + } else { + //TODO: vnfList does not contain data. Need to investigate why ... . Fro VIPR use model stored + vnfModelInfoString = execution.getVariable("vnfModelInfo") + } + + utils.log("DEBUG", " vnfModelInfoString :" + vnfModelInfoString, isDebugEnabled) + + // extract cloud configuration + String lcpCloudRegionId = jsonUtil.getJsonValue(createGenericMacroServiceNetworkVnfRequest, "requestDetails.cloudConfiguration.lcpCloudRegionId") + execution.setVariable("lcpCloudRegionId", lcpCloudRegionId) + utils.log("DEBUG","lcpCloudRegionId: "+ lcpCloudRegionId, isDebugEnabled) + String tenantId = jsonUtil.getJsonValue(createGenericMacroServiceNetworkVnfRequest, "requestDetails.cloudConfiguration.tenantId") + execution.setVariable("tenantId", tenantId) + utils.log("DEBUG","tenantId: "+ tenantId, isDebugEnabled) + + String sdncVersion = execution.getVariable("sdncVersion") + utils.log("DEBUG","sdncVersion: "+ sdncVersion, isDebugEnabled) + + utils.log("DEBUG", " ***** Completed prepareVnfAndModulesCreate of CreateGenericMacroServiceNetworkVnf ***** ", isDebugEnabled) + } catch (Exception ex) { + // try error in method block + String exceptionMessage = "Bpmn error encountered in CreateGenericMacroServiceNetworkVnf flow. Unexpected Error from method prepareVnfAndModulesCreate() - " + ex.getMessage() + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + } + } + + // ******************************* + // Validate Vnf request Section -> increment count + // ******************************* + public void validateVnfCreate (Execution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + + try { + utils.log("DEBUG", " ***** Inside validateVnfCreate of CreateGenericMacroServiceNetworkVnf ***** ", isDebugEnabled) + + Integer vnfsCreatedCount = execution.getVariable("CREVAS_VnfsCreatedCount") + vnfsCreatedCount++ + + execution.setVariable("CREVAS_VnfsCreatedCount", vnfsCreatedCount) + + utils.log("DEBUG", " ***** Completed validateVnfCreate of CreateGenericMacroServiceNetworkVnf ***** "+" vnf # "+vnfsCreatedCount, isDebugEnabled) + } catch (Exception ex) { + // try error in method block + String exceptionMessage = "Bpmn error encountered in CreateGenericMacroServiceNetworkVnf flow. Unexpected Error from method validateVnfCreate() - " + ex.getMessage() + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + } + } + + // ******************************* + // Validate Network request Section -> decrement count + // ******************************* + public void validateNetworkRollback (Execution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + + try { + utils.log("DEBUG", " ***** Inside validateNetworkRollback of CreateGenericMacroServiceNetworkVnf ***** ", isDebugEnabled) + + Integer networksCreatedCount = execution.getVariable("CREVAS_NetworksCreatedCount") + networksCreatedCount-- + + execution.setVariable("CREVAS_NetworksCreatedCount", networksCreatedCount) + + execution.setVariable("DCRENI_rollbackData", execution.getVariable("DCRENI_rollbackData"+networksCreatedCount)) + + utils.log("DEBUG", " ***** Completed validateNetworkRollback of CreateGenericMacroServiceNetworkVnf ***** "+" network # "+networksCreatedCount, isDebugEnabled) + } catch (Exception ex) { + // try error in method block + String exceptionMessage = "Bpmn error encountered in CreateGenericMacroServiceNetworkVnf flow. Unexpected Error from method validateNetworkRollback() - " + ex.getMessage() + //exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + utils.log("DEBUG", exceptionMessage, isDebugEnabled) + execution.setVariable("CREVAS_NetworksCreatedCount", 0) + utils.log("ERROR", exceptionMessage, true) + } + } + // ******************************* + // Build DB request Section + // ******************************* +// public void prepareDBRequest (Execution execution) { +// def isDebugEnabled=execution.getVariable("isDebugLogEnabled") +// +// try { +// utils.log("DEBUG", " ***** Inside prepareDBRequest of CreateGenericMacroServiceNetworkVnf ***** ", isDebugEnabled) +// +// String requestId = execution.getVariable("CREVAS_requestId") +// String statusMessage = "vIPR ATM Service Instance successfully created." +// String serviceInstanceId = execution.getVariable("CREVAS_serviceInstanceId") +// +// //TODO - verify the format for Service Instance Create, +// String dbRequest = +// """ +// +// +// +// ${requestId} +// BPMN +// ${statusMessage} +// +// COMPLETED +// 100 +// +// ${serviceInstanceId} +// +// +// """ +// +// String buildDeleteDBRequestAsString = utils.formatXml(dbRequest) +// execution.setVariable("CREVAS_createDBRequest", buildDeleteDBRequestAsString) +// utils.logAudit(buildDeleteDBRequestAsString) +// +// utils.log("DEBUG", " ***** Completed prepareDBRequest of CreateGenericMacroServiceNetworkVnf ***** ", isDebugEnabled) +// } catch (Exception ex) { +// // try error in method block +// String exceptionMessage = "Bpmn error encountered in CreateGenericMacroServiceNetworkVnf flow. Unexpected Error from method prepareDBRequest() - " + ex.getMessage() +// exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) +// +// } +// +// } + + + // ***************************************** + // Prepare Completion request Section + // ***************************************** + public void postProcessResponse (Execution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + + utils.log("DEBUG", " ***** Inside postProcessResponse of CreateGenericMacroServiceNetworkVnf ***** ", isDebugEnabled) + + try { + String source = execution.getVariable("source") + String requestId = execution.getVariable("mso-request-id") + String serviceInstanceId = execution.getVariable("serviceInstanceId") + + String msoCompletionRequest = + """ + + ${requestId} + CREATE + ${source} + + Service Instance has been created successfully via macro orchestration + ${serviceInstanceId} + BPMN macro create + """ + + // Format Response + String xmlMsoCompletionRequest = utils.formatXml(msoCompletionRequest) + + utils.logAudit(xmlMsoCompletionRequest) + execution.setVariable("CREVAS_Success", true) + execution.setVariable("CREVAS_CompleteMsoProcessRequest", xmlMsoCompletionRequest) + utils.log("DEBUG", " SUCCESS flow, going to CompleteMsoProcess - " + "\n" + xmlMsoCompletionRequest, isDebugEnabled) + } catch (BpmnError e) { + throw e; + } catch (Exception ex) { + // try error in method block + String exceptionMessage = "Bpmn error encountered in CreateServiceInstance flow. Unexpected Error from method postProcessResponse() - " + ex.getMessage() + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + } + } + + public void preProcessRollback (Execution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + utils.log("DEBUG"," ***** preProcessRollback of CreateGenericMacroServiceNetworkVnf ***** ", isDebugEnabled) + try { + + Object workflowException = execution.getVariable("WorkflowException"); + + if (workflowException instanceof WorkflowException) { + utils.log("DEBUG", "Prev workflowException: " + workflowException.getErrorMessage(), isDebugEnabled) + execution.setVariable("prevWorkflowException", workflowException); + //execution.setVariable("WorkflowException", null); + } + } catch (BpmnError e) { + utils.log("DEBUG", "BPMN Error during preProcessRollback", isDebugEnabled) + } catch(Exception ex) { + String msg = "Exception in preProcessRollback. " + ex.getMessage() + utils.log("DEBUG", msg, isDebugEnabled) + } + utils.log("DEBUG"," *** Exit preProcessRollback of CreateGenericMacroServiceNetworkVnf *** ", isDebugEnabled) + } + + public void postProcessRollback (Execution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + utils.log("DEBUG"," ***** postProcessRollback of CreateGenericMacroServiceNetworkVnf ***** ", isDebugEnabled) + String msg = "" + try { + Object workflowException = execution.getVariable("prevWorkflowException"); + if (workflowException instanceof WorkflowException) { + utils.log("DEBUG", "Setting prevException to WorkflowException: ", isDebugEnabled) + execution.setVariable("WorkflowException", workflowException); + } + } catch (BpmnError b) { + utils.log("DEBUG", "BPMN Error during postProcessRollback", isDebugEnabled) + throw b; + } catch(Exception ex) { + msg = "Exception in postProcessRollback. " + ex.getMessage() + utils.log("DEBUG", msg, isDebugEnabled) + } + utils.log("DEBUG"," *** Exit postProcessRollback of CreateGenericMacroServiceNetworkVnf *** ", isDebugEnabled) + } + + public void prepareFalloutRequest(Execution execution){ + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + + utils.log("DEBUG", " *** STARTED CreateGenericMacroServiceNetworkVnf prepareFalloutRequest Process *** ", isDebugEnabled) + + try { + WorkflowException wfex = execution.getVariable("WorkflowException") + utils.log("DEBUG", " Incoming Workflow Exception: " + wfex.toString(), isDebugEnabled) + String requestInfo = execution.getVariable("CREVAS_requestInfo") + utils.log("DEBUG", " Incoming Request Info: " + requestInfo, isDebugEnabled) + + //TODO. hmmm. there is no way to UPDATE error message. +// String errorMessage = wfex.getErrorMessage() +// boolean successIndicator = execution.getVariable("DCRESI_rollbackSuccessful") +// if (successIndicator){ +// errorMessage = errorMessage + ". Rollback successful." +// } else { +// errorMessage = errorMessage + ". Rollback not completed." +// } + + String falloutRequest = exceptionUtil.processMainflowsBPMNException(execution, requestInfo) + + execution.setVariable("CREVAS_falloutRequest", falloutRequest) + + } catch (Exception ex) { + utils.log("DEBUG", "Error Occured in CreateGenericMacroServiceNetworkVnf prepareFalloutRequest Process " + ex.getMessage(), isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured in CreateGenericMacroServiceNetworkVnf prepareFalloutRequest Process") + } + utils.log("DEBUG", "*** COMPLETED CreateGenericMacroServiceNetworkVnf prepareFalloutRequest Process ***", isDebugEnabled) + } + + + public void sendSyncError (Execution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix", Prefix) + + utils.log("DEBUG", " ***** Inside sendSyncError() of CreateServiceInstanceInfra ***** ", isDebugEnabled) + + try { + String errorMessage = "" + if (execution.getVariable("WorkflowException") instanceof WorkflowException) { + WorkflowException wfe = execution.getVariable("WorkflowException") + errorMessage = wfe.getErrorMessage() + } else { + errorMessage = "Sending Sync Error." + } + + String buildworkflowException = + """ + ${errorMessage} + 7000 + """ + + utils.logAudit(buildworkflowException) + sendWorkflowResponse(execution, 500, buildworkflowException) + } catch (Exception ex) { + utils.log("DEBUG", " Sending Sync Error Activity Failed. " + "\n" + ex.getMessage(), isDebugEnabled) + } + } + + public void processJavaException(Execution execution){ + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix",Prefix) + try{ + utils.log("DEBUG", "Caught a Java Exception", isDebugEnabled) + utils.log("DEBUG", "Started processJavaException Method", isDebugEnabled) + utils.log("DEBUG", "Variables List: " + execution.getVariables(), isDebugEnabled) + execution.setVariable("CRESI_unexpectedError", "Caught a Java Lang Exception") // Adding this line temporarily until this flows error handling gets updated + exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Caught a Java Lang Exception") + }catch(BpmnError b){ + utils.log("ERROR", "Rethrowing MSOWorkflowException", isDebugEnabled) + throw b + }catch(Exception e){ + utils.log("DEBUG", "Caught Exception during processJavaException Method: " + e, isDebugEnabled) + execution.setVariable("CRESI_unexpectedError", "Exception in processJavaException method") // Adding this line temporarily until this flows error handling gets updated + exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Exception in processJavaException method") + } + utils.log("DEBUG", "Completed processJavaException Method", isDebugEnabled) + } } \ No newline at end of file diff --git a/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/CreateNetworkInstance.groovy b/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/CreateNetworkInstance.groovy index b9b97c7d12..11de8d9819 100644 --- a/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/CreateNetworkInstance.groovy +++ b/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/CreateNetworkInstance.groovy @@ -1,32 +1,32 @@ -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - MSO - * ================================================================================ - * 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========================================================= +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.bpmn.infrastructure.scripts; + +package org.openecomp.mso.bpmn.infrastructure.scripts; import groovy.xml.XmlUtil import groovy.json.* -import org.openecomp.mso.bpmn.common.scripts.AbstractServiceTaskProcessor -import org.openecomp.mso.bpmn.common.scripts.ExceptionUtil -import org.openecomp.mso.bpmn.core.WorkflowException -import org.openecomp.mso.bpmn.core.json.JsonUtils -import org.openecomp.mso.rest.APIResponse +import org.openecomp.mso.bpmn.common.scripts.AbstractServiceTaskProcessor +import org.openecomp.mso.bpmn.common.scripts.ExceptionUtil +import org.openecomp.mso.bpmn.core.WorkflowException +import org.openecomp.mso.bpmn.core.json.JsonUtils +import org.openecomp.mso.rest.APIResponse import java.util.UUID; @@ -105,12 +105,12 @@ public class CreateNetworkInstance extends AbstractServiceTaskProcessor { utils.log("DEBUG", " 'disableRollback' : " + execution.getVariable("disableRollback") , isDebugEnabled) } - // get/set 'msoRequestId' and 'mso-request-id' + // get/set 'msoRequestId' and 'mso-request-id' String requestId = execution.getVariable("msoRequestId") if (requestId != null) { - execution.setVariable("mso-request-id", requestId) + execution.setVariable("mso-request-id", requestId) } else { - requestId = execution.getVariable("mso-request-id") + requestId = execution.getVariable("mso-request-id") } execution.setVariable(Prefix + "requestId", requestId) @@ -161,7 +161,7 @@ public class CreateNetworkInstance extends AbstractServiceTaskProcessor { utils.log("DEBUG", " ***** Inside sendSyncResponse() of CreateNetworkInstance ***** ", isDebugEnabled) try { - String requestId = execution.getVariable("mso-request-id") + String requestId = execution.getVariable("mso-request-id") // RESTResponse (for API Handler (APIH) Reply Task) String createNetworkRestRequest = """{"requestReferences":{"instanceId":"","requestId":"${requestId}"}}""".trim() @@ -214,7 +214,7 @@ public class CreateNetworkInstance extends AbstractServiceTaskProcessor { try { - String requestId = execution.getVariable("mso-request-id") + String requestId = execution.getVariable("mso-request-id") // REST Error (for API Handler (APIH) Reply Task) String syncError = """{"requestReferences":{"instanceId":"","requestId":"${requestId}"}}""".trim() @@ -248,7 +248,7 @@ public class CreateNetworkInstance extends AbstractServiceTaskProcessor { """ - + ${requestId} BPMN ${statusMessage} @@ -280,13 +280,13 @@ public class CreateNetworkInstance extends AbstractServiceTaskProcessor { try { - String requestId = execution.getVariable("mso-request-id") + String requestId = execution.getVariable("mso-request-id") String source = execution.getVariable(Prefix + "source") String msoCompletionRequest = - """ - + """ + ${requestId} CREATE VID @@ -382,22 +382,22 @@ public class CreateNetworkInstance extends AbstractServiceTaskProcessor { utils.log("DEBUG", " ***** Prepare for FalloutHandler. FAILURE - prepare request for sub-process FalloutHandler. *****", isDebugEnabled) String falloutHandlerRequest = "" - String requestId = execution.getVariable("mso-request-id") + String requestId = execution.getVariable("mso-request-id") try { WorkflowException wfe = execution.getVariable("WorkflowException") String errorCode = String.valueOf(wfe.getErrorCode()) String errorMessage = wfe.getErrorMessage() falloutHandlerRequest = - """ - + """ + ${requestId} CREATE VID - + ${errorMessage} ${errorCode} @@ -411,15 +411,15 @@ public class CreateNetworkInstance extends AbstractServiceTaskProcessor { String errorException = " Bpmn error encountered in CreateNetworkInstance flow. FalloutHandlerRequest, buildErrorResponse() - " + ex.getMessage() utils.log("DEBUG", errorException, isDebugEnabled) falloutHandlerRequest = - """ - + """ + ${requestId} CREATE VID - + ${errorException} 7000 diff --git a/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/CreateServiceInstance.groovy b/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/CreateServiceInstance.groovy index 202829d820..2205ffd696 100644 --- a/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/CreateServiceInstance.groovy +++ b/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/CreateServiceInstance.groovy @@ -1,262 +1,262 @@ -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - MSO - * ================================================================================ - * 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.openecomp.mso.bpmn.infrastructure.scripts; - -import static org.apache.commons.lang3.StringUtils.*; -import groovy.xml.XmlUtil -import groovy.json.* -import org.openecomp.mso.bpmn.common.scripts.AbstractServiceTaskProcessor -import org.openecomp.mso.bpmn.common.scripts.ExceptionUtil -import org.openecomp.mso.bpmn.common.scripts.VidUtils -import org.openecomp.mso.bpmn.core.WorkflowException -import org.openecomp.mso.bpmn.core.json.JsonUtils -import org.openecomp.mso.rest.APIResponse - -import java.util.UUID; - -import org.camunda.bpm.engine.delegate.BpmnError -import org.camunda.bpm.engine.runtime.Execution -import org.apache.commons.lang3.* -import org.apache.commons.codec.binary.Base64; -import org.springframework.web.util.UriUtils - -/** - * This groovy class supports the CreateServiceInstance.bpmn process. - * AlaCarte flow for 1702 ServiceInstance Create - * - */ -public class CreateServiceInstance extends AbstractServiceTaskProcessor { - String Prefix="CRESI_" - ExceptionUtil exceptionUtil = new ExceptionUtil() - JsonUtils jsonUtil = new JsonUtils() - VidUtils vidUtils = new VidUtils() - - public void preProcessRequest (Execution execution) { - def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - execution.setVariable("prefix",Prefix) - String msg = "" - utils.log("DEBUG", " *** preProcessRequest() *** ", isDebugEnabled) - - try { - - String siRequest = execution.getVariable("bpmnRequest") - utils.logAudit(siRequest) - - String requestId = execution.getVariable("mso-request-id") - execution.setVariable("msoRequestId", requestId) - utils.log("DEBUG", "Input Request:" + siRequest + " reqId:" + requestId, isDebugEnabled) - - String serviceInstanceId = execution.getVariable("serviceInstanceId") - if (isBlank(serviceInstanceId)) { - serviceInstanceId = UUID.randomUUID().toString() - } - utils.log("DEBUG", "Generated new Service Instance:" + serviceInstanceId, isDebugEnabled) - serviceInstanceId = UriUtils.encode(serviceInstanceId,"UTF-8") - execution.setVariable("serviceInstanceId", serviceInstanceId) - - //subscriberInfo - String globalSubscriberId = jsonUtil.getJsonValue(siRequest, "requestDetails.subscriberInfo.globalSubscriberId") - if (isBlank(globalSubscriberId)) { - msg = "Input globalSubscriberId' is null" - exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) - } else { - execution.setVariable("globalSubscriberId", globalSubscriberId) - } - - //requestInfo - execution.setVariable("source", jsonUtil.getJsonValue(siRequest, "requestDetails.requestInfo.source")) - execution.setVariable("serviceInstanceName", jsonUtil.getJsonValue(siRequest, "requestDetails.requestInfo.instanceName")) - execution.setVariable("disableRollback", jsonUtil.getJsonValue(siRequest, "requestDetails.requestInfo.suppressRollback")) - String productFamilyId = jsonUtil.getJsonValue(siRequest, "requestDetails.requestInfo.productFamilyId") - if (isBlank(productFamilyId)) - { - msg = "Input productFamilyId is null" - utils.log("DEBUG", msg, isDebugEnabled) - //exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) - } else { - execution.setVariable("productFamilyId", productFamilyId) - } - - //modelInfo - String serviceModelInfo = jsonUtil.getJsonValue(siRequest, "requestDetails.modelInfo") - if (isBlank(serviceModelInfo)) { - msg = "Input serviceModelInfo is null" - utils.log("DEBUG", msg, isDebugEnabled) - exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) - } else - { - execution.setVariable("serviceModelInfo", serviceModelInfo) - } - - utils.log("DEBUG", "modelInfo" + serviceModelInfo, isDebugEnabled) - - //requestParameters - String subscriptionServiceType = jsonUtil.getJsonValue(siRequest, "requestDetails.requestParameters.subscriptionServiceType") - if (isBlank(subscriptionServiceType)) { - msg = "Input subscriptionServiceType is null" - utils.log("DEBUG", msg, isDebugEnabled) - exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) - } else { - execution.setVariable("subscriptionServiceType", subscriptionServiceType) - } - - //TODO - //execution.setVariable("serviceInputParams", jsonUtil.getJsonValue(siRequest, "requestDetails.requestParameters.userParams")) - //execution.setVariable("failExists", true) - - } catch (BpmnError e) { - throw e; - } catch (Exception ex){ - msg = "Exception in preProcessRequest " + ex.getMessage() - utils.log("DEBUG", msg, isDebugEnabled) - exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) - } - utils.log("DEBUG"," ***** Exit preProcessRequest *****", isDebugEnabled) - } - - public void sendSyncResponse (Execution execution) { - def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - utils.log("DEBUG", " *** sendSyncResponse *** ", isDebugEnabled) - - try { - String requestId = execution.getVariable("msoRequestId") - String serviceInstanceId = execution.getVariable("serviceInstanceId") - // RESTResponse for API Handler (APIH) Reply Task - String createServiceRestRequest = """{"requestReferences":{"instanceId":"${serviceInstanceId}","requestId":"${requestId}"}}""".trim() - utils.log("DEBUG", " sendSyncResponse to APIH:" + "\n" + createServiceRestRequest, isDebugEnabled) - sendWorkflowResponse(execution, 202, createServiceRestRequest) - execution.setVariable("sentSyncResponse", true) - - } catch (Exception ex) { - String msg = "Exceptuion in sendSyncResponse:" + ex.getMessage() - utils.log("DEBUG", exceptionMessage, isDebugEnabled) - exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) - } - utils.log("DEBUG"," ***** Exit sendSyncResopnse *****", isDebugEnabled) - } - - - public void sendSyncError (Execution execution) { - def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - utils.log("DEBUG", " *** sendSyncError *** ", isDebugEnabled) - - try { - String errorMessage = "" - if (execution.getVariable("WorkflowException") instanceof WorkflowException) { - WorkflowException wfe = execution.getVariable("WorkflowException") - errorMessage = wfe.getErrorMessage() - } else { - errorMessage = "Sending Sync Error." - } - - String buildworkflowException = - """ - ${errorMessage} - 7000 - """ - - utils.logAudit(buildworkflowException) - sendWorkflowResponse(execution, 500, buildworkflowException) - - } catch (Exception ex) { - utils.log("DEBUG", " Sending Sync Error Activity Failed. " + "\n" + ex.getMessage(), isDebugEnabled) - } - - } - - public void prepareCompletionRequest (Execution execution) { - def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - utils.log("DEBUG", " *** prepareCompletion *** ", isDebugEnabled) - - try { - String requestId = execution.getVariable("msoRequestId") - String serviceInstanceId = execution.getVariable("serviceInstanceId") - String source = execution.getVariable("source") - - String msoCompletionRequest = - """ - - ${requestId} - CREATE - ${source} - - Service Instance was created successfully. - ${serviceInstanceId} - CreateServiceInstance - """ - - // Format Response - String xmlMsoCompletionRequest = utils.formatXml(msoCompletionRequest) - - execution.setVariable("completionRequest", xmlMsoCompletionRequest) - utils.log("DEBUG", " Overall SUCCESS Response going to CompleteMsoProcess - " + "\n" + xmlMsoCompletionRequest, isDebugEnabled) - - } catch (Exception ex) { - String msg = " Exception in prepareCompletion:" + ex.getMessage() - utils.log("DEBUG", msg, isDebugEnabled) - exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) - } - utils.log("DEBUG", "*** Exit prepareCompletionRequest ***", isDebugEnabled) - } - - public void prepareFalloutRequest(Execution execution){ - def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - utils.log("DEBUG", " *** prepareFalloutRequest *** ", isDebugEnabled) - - try { - WorkflowException wfex = execution.getVariable("WorkflowException") - utils.log("DEBUG", " Input Workflow Exception: " + wfex.toString(), isDebugEnabled) - String requestId = execution.getVariable("msoRequestId") - String source = execution.getVariable("source") - String requestInfo = - """ - ${requestId} - CREATE - ${source} - """ - - String falloutRequest = exceptionUtil.processMainflowsBPMNException(execution, requestInfo) - execution.setVariable("falloutRequest", falloutRequest) - } catch (Exception ex) { - utils.log("DEBUG", "Exception prepareFalloutRequest:" + ex.getMessage(), isDebugEnabled) - String errorException = " Bpmn error encountered in CreateServiceInstance flow. FalloutHandlerRequest, buildErrorResponse() - " + ex.getMessage() - String requestId = execution.getVariable("msoRequestId") - String falloutRequest = - """ - - ${requestId} - CREATE - VID - - - ${errorException} - 7000 - - """ - - execution.setVariable("falloutRequest", falloutRequest) - } - utils.log("DEBUG", "*** Exit prepareFalloutRequest ***", isDebugEnabled) - } +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.bpmn.infrastructure.scripts; + +import static org.apache.commons.lang3.StringUtils.*; +import groovy.xml.XmlUtil +import groovy.json.* +import org.openecomp.mso.bpmn.common.scripts.AbstractServiceTaskProcessor +import org.openecomp.mso.bpmn.common.scripts.ExceptionUtil +import org.openecomp.mso.bpmn.common.scripts.VidUtils +import org.openecomp.mso.bpmn.core.WorkflowException +import org.openecomp.mso.bpmn.core.json.JsonUtils +import org.openecomp.mso.rest.APIResponse + +import java.util.UUID; + +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.runtime.Execution +import org.apache.commons.lang3.* +import org.apache.commons.codec.binary.Base64; +import org.springframework.web.util.UriUtils + +/** + * This groovy class supports the CreateServiceInstance.bpmn process. + * AlaCarte flow for 1702 ServiceInstance Create + * + */ +public class CreateServiceInstance extends AbstractServiceTaskProcessor { + String Prefix="CRESI_" + ExceptionUtil exceptionUtil = new ExceptionUtil() + JsonUtils jsonUtil = new JsonUtils() + VidUtils vidUtils = new VidUtils() + + public void preProcessRequest (Execution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix",Prefix) + String msg = "" + utils.log("DEBUG", " *** preProcessRequest() *** ", isDebugEnabled) + + try { + + String siRequest = execution.getVariable("bpmnRequest") + utils.logAudit(siRequest) + + String requestId = execution.getVariable("mso-request-id") + execution.setVariable("msoRequestId", requestId) + utils.log("DEBUG", "Input Request:" + siRequest + " reqId:" + requestId, isDebugEnabled) + + String serviceInstanceId = execution.getVariable("serviceInstanceId") + if (isBlank(serviceInstanceId)) { + serviceInstanceId = UUID.randomUUID().toString() + } + utils.log("DEBUG", "Generated new Service Instance:" + serviceInstanceId, isDebugEnabled) + serviceInstanceId = UriUtils.encode(serviceInstanceId,"UTF-8") + execution.setVariable("serviceInstanceId", serviceInstanceId) + + //subscriberInfo + String globalSubscriberId = jsonUtil.getJsonValue(siRequest, "requestDetails.subscriberInfo.globalSubscriberId") + if (isBlank(globalSubscriberId)) { + msg = "Input globalSubscriberId' is null" + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } else { + execution.setVariable("globalSubscriberId", globalSubscriberId) + } + + //requestInfo + execution.setVariable("source", jsonUtil.getJsonValue(siRequest, "requestDetails.requestInfo.source")) + execution.setVariable("serviceInstanceName", jsonUtil.getJsonValue(siRequest, "requestDetails.requestInfo.instanceName")) + execution.setVariable("disableRollback", jsonUtil.getJsonValue(siRequest, "requestDetails.requestInfo.suppressRollback")) + String productFamilyId = jsonUtil.getJsonValue(siRequest, "requestDetails.requestInfo.productFamilyId") + if (isBlank(productFamilyId)) + { + msg = "Input productFamilyId is null" + utils.log("DEBUG", msg, isDebugEnabled) + //exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } else { + execution.setVariable("productFamilyId", productFamilyId) + } + + //modelInfo + String serviceModelInfo = jsonUtil.getJsonValue(siRequest, "requestDetails.modelInfo") + if (isBlank(serviceModelInfo)) { + msg = "Input serviceModelInfo is null" + utils.log("DEBUG", msg, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } else + { + execution.setVariable("serviceModelInfo", serviceModelInfo) + } + + utils.log("DEBUG", "modelInfo" + serviceModelInfo, isDebugEnabled) + + //requestParameters + String subscriptionServiceType = jsonUtil.getJsonValue(siRequest, "requestDetails.requestParameters.subscriptionServiceType") + if (isBlank(subscriptionServiceType)) { + msg = "Input subscriptionServiceType is null" + utils.log("DEBUG", msg, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } else { + execution.setVariable("subscriptionServiceType", subscriptionServiceType) + } + + //TODO + //execution.setVariable("serviceInputParams", jsonUtil.getJsonValue(siRequest, "requestDetails.requestParameters.userParams")) + //execution.setVariable("failExists", true) + + } catch (BpmnError e) { + throw e; + } catch (Exception ex){ + msg = "Exception in preProcessRequest " + ex.getMessage() + utils.log("DEBUG", msg, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + utils.log("DEBUG"," ***** Exit preProcessRequest *****", isDebugEnabled) + } + + public void sendSyncResponse (Execution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + utils.log("DEBUG", " *** sendSyncResponse *** ", isDebugEnabled) + + try { + String requestId = execution.getVariable("msoRequestId") + String serviceInstanceId = execution.getVariable("serviceInstanceId") + // RESTResponse for API Handler (APIH) Reply Task + String createServiceRestRequest = """{"requestReferences":{"instanceId":"${serviceInstanceId}","requestId":"${requestId}"}}""".trim() + utils.log("DEBUG", " sendSyncResponse to APIH:" + "\n" + createServiceRestRequest, isDebugEnabled) + sendWorkflowResponse(execution, 202, createServiceRestRequest) + execution.setVariable("sentSyncResponse", true) + + } catch (Exception ex) { + String msg = "Exceptuion in sendSyncResponse:" + ex.getMessage() + utils.log("DEBUG", exceptionMessage, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + utils.log("DEBUG"," ***** Exit sendSyncResopnse *****", isDebugEnabled) + } + + + public void sendSyncError (Execution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + utils.log("DEBUG", " *** sendSyncError *** ", isDebugEnabled) + + try { + String errorMessage = "" + if (execution.getVariable("WorkflowException") instanceof WorkflowException) { + WorkflowException wfe = execution.getVariable("WorkflowException") + errorMessage = wfe.getErrorMessage() + } else { + errorMessage = "Sending Sync Error." + } + + String buildworkflowException = + """ + ${errorMessage} + 7000 + """ + + utils.logAudit(buildworkflowException) + sendWorkflowResponse(execution, 500, buildworkflowException) + + } catch (Exception ex) { + utils.log("DEBUG", " Sending Sync Error Activity Failed. " + "\n" + ex.getMessage(), isDebugEnabled) + } + + } + + public void prepareCompletionRequest (Execution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + utils.log("DEBUG", " *** prepareCompletion *** ", isDebugEnabled) + + try { + String requestId = execution.getVariable("msoRequestId") + String serviceInstanceId = execution.getVariable("serviceInstanceId") + String source = execution.getVariable("source") + + String msoCompletionRequest = + """ + + ${requestId} + CREATE + ${source} + + Service Instance was created successfully. + ${serviceInstanceId} + CreateServiceInstance + """ + + // Format Response + String xmlMsoCompletionRequest = utils.formatXml(msoCompletionRequest) + + execution.setVariable("completionRequest", xmlMsoCompletionRequest) + utils.log("DEBUG", " Overall SUCCESS Response going to CompleteMsoProcess - " + "\n" + xmlMsoCompletionRequest, isDebugEnabled) + + } catch (Exception ex) { + String msg = " Exception in prepareCompletion:" + ex.getMessage() + utils.log("DEBUG", msg, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + utils.log("DEBUG", "*** Exit prepareCompletionRequest ***", isDebugEnabled) + } + + public void prepareFalloutRequest(Execution execution){ + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + utils.log("DEBUG", " *** prepareFalloutRequest *** ", isDebugEnabled) + + try { + WorkflowException wfex = execution.getVariable("WorkflowException") + utils.log("DEBUG", " Input Workflow Exception: " + wfex.toString(), isDebugEnabled) + String requestId = execution.getVariable("msoRequestId") + String source = execution.getVariable("source") + String requestInfo = + """ + ${requestId} + CREATE + ${source} + """ + + String falloutRequest = exceptionUtil.processMainflowsBPMNException(execution, requestInfo) + execution.setVariable("falloutRequest", falloutRequest) + } catch (Exception ex) { + utils.log("DEBUG", "Exception prepareFalloutRequest:" + ex.getMessage(), isDebugEnabled) + String errorException = " Bpmn error encountered in CreateServiceInstance flow. FalloutHandlerRequest, buildErrorResponse() - " + ex.getMessage() + String requestId = execution.getVariable("msoRequestId") + String falloutRequest = + """ + + ${requestId} + CREATE + VID + + + ${errorException} + 7000 + + """ + + execution.setVariable("falloutRequest", falloutRequest) + } + utils.log("DEBUG", "*** Exit prepareFalloutRequest ***", isDebugEnabled) + } } \ No newline at end of file diff --git a/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/CreateVfModuleInfra.groovy b/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/CreateVfModuleInfra.groovy index 7f5bd6138b..573deb4155 100644 --- a/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/CreateVfModuleInfra.groovy +++ b/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/CreateVfModuleInfra.groovy @@ -1,39 +1,41 @@ -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - MSO - * ================================================================================ - * 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.openecomp.mso.bpmn.infrastructure.scripts; +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.bpmn.infrastructure.scripts; import groovy.json.JsonSlurper import org.camunda.bpm.engine.delegate.BpmnError import org.camunda.bpm.engine.runtime.Execution import org.apache.commons.lang3.* -import org.openecomp.mso.bpmn.common.scripts.AbstractServiceTaskProcessor; -import org.openecomp.mso.bpmn.common.scripts.ExceptionUtil; -import org.openecomp.mso.bpmn.common.scripts.NetworkUtils; -import org.openecomp.mso.bpmn.common.scripts.SDNCAdapterUtils; -import org.openecomp.mso.bpmn.common.scripts.VidUtils; -import org.openecomp.mso.bpmn.core.RollbackData -import org.openecomp.mso.bpmn.core.WorkflowException - -public class CreateVfModuleInfra extends AbstractServiceTaskProcessor { +import org.openecomp.mso.bpmn.common.scripts.AbstractServiceTaskProcessor; +import org.openecomp.mso.bpmn.common.scripts.ExceptionUtil; +import org.openecomp.mso.bpmn.common.scripts.NetworkUtils; +import org.openecomp.mso.bpmn.common.scripts.SDNCAdapterUtils; +import org.openecomp.mso.bpmn.common.scripts.VidUtils; +import org.openecomp.mso.bpmn.core.RollbackData +import org.openecomp.mso.bpmn.core.WorkflowException + +public class CreateVfModuleInfra extends AbstractServiceTaskProcessor { + + ExceptionUtil exceptionUtil = new ExceptionUtil() /** * Validates the request message and sets up the workflow. @@ -51,68 +53,68 @@ public class CreateVfModuleInfra extends AbstractServiceTaskProcessor { execution.setVariable('prefix', prefix) logDebug('Entered 2' + method, isDebugLogEnabled) execution.setVariable("isVidRequest", "false") - - logDebug("Set variables", isDebugLogEnabled) - + + logDebug("Set variables", isDebugLogEnabled) + def rollbackData = execution.getVariable("RollbackData") if (rollbackData == null) { rollbackData = new RollbackData() } execution.setVariable("RollbackData", rollbackData) - + logDebug("Set rollback data", isDebugLogEnabled) def incomingRequest = execution.getVariable('bpmnRequest') - + utils.log("DEBUG", "Incoming Infra Request: " + incomingRequest, isDebugLogEnabled) utils.logAudit("CreateVfModule Infra incoming Request: " + incomingRequest) - + // check if request is xml or json try { def jsonSlurper = new JsonSlurper() Map reqMap = jsonSlurper.parseText(incomingRequest) utils.log("DEBUG", " Request is in JSON format.", isDebugLogEnabled) - + def serviceInstanceId = execution.getVariable('serviceInstanceId') def vnfId = execution.getVariable('vnfId') - + def vidUtils = new VidUtils(this) - + String requestInXmlFormat = vidUtils.createXmlVfModuleRequest(execution, reqMap, 'CREATE_VF_MODULE', serviceInstanceId) - + utils.log("DEBUG", " Request in XML format: " + requestInXmlFormat, isDebugLogEnabled) - + execution.setVariable(prefix + 'Request', requestInXmlFormat) execution.setVariable(prefix+'vnfId', vnfId) - execution.setVariable("isVidRequest", "true") - + execution.setVariable("isVidRequest", "true") + } catch(groovy.json.JsonException je) { utils.log("DEBUG", " Request is not in JSON format.", isDebugLogEnabled) - workflowException(execution, "Invalid request format", 400) - + exceptionUtil.buildAndThrowWorkflowException(execution, 400, "Internal Error - During PreProcessRequest") + } catch(Exception e) { String restFaultMessage = e.getMessage() //execution.setVariable("CVFMODVOL2_RESTFault", restFaultMessage) //execution.setVariable("CVFMODVOL2_isDataOk", false) utils.log("ERROR", " Exception Encountered - " + "\n" + restFaultMessage, isDebugLogEnabled) - workflowException(execution, restFaultMessage, 400) + exceptionUtil.buildAndThrowWorkflowException(execution, 400, "Internal Error - During PreProcessRequest") } try { String request = validateInfraRequest(execution) - + execution.setVariable("CreateVfModuleInfraSuccessIndicator", false) execution.setVariable("RollbackCompleted", false) execution.setVariable("DoCreateVfModuleRequest", request) execution.setVariable("isDebugLogEnabled", isDebugLogEnabled) - execution.setVariable("CVFMI_requestInfo",utils.getNodeXml(request,"request-info")) + execution.setVariable("CVFMI_requestInfo",utils.getNodeXml(request,"request-info")) execution.setVariable("CVFMI_requestId",utils.getNodeText1(request,"request-id")) execution.setVariable("CVFMI_source",utils.getNodeText1(request,"source")) - execution.setVariable("CVFMI_serviceInstanceId", utils.getNodeText1(request, "service-instance-id")) + execution.setVariable("CVFMI_serviceInstanceId", utils.getNodeText1(request, "service-instance-id")) execution.setVariable("CVFMI_vnfInputs",utils.getNodeXml(request,"vnf-inputs")) //backoutOnFailure - + NetworkUtils networkUtils = new NetworkUtils() execution.setVariable("CVFMI_rollbackEnabled", networkUtils.isRollbackEnabled(execution,request)) execution.setVariable("CVFMI_originalWorkflowException", null) @@ -121,22 +123,21 @@ public class CreateVfModuleInfra extends AbstractServiceTaskProcessor { vnfParams = utils.getNodeXml(request,"vnf-params") } execution.setVariable("CVFMI_vnfParams", vnfParams) - + def newVfModuleId = UUID.randomUUID().toString() execution.setVariable("newVfModuleId", newVfModuleId) - + logDebug('RequestInfo: ' + execution.getVariable("CVFMI_requestInfo"), isDebugLogEnabled) logDebug('VnfInputs: ' + execution.getVariable("CVFMI_vnfInputs"), isDebugLogEnabled) logDebug('VnfParams: ' + execution.getVariable("CVFMI_vnfParams"), isDebugLogEnabled) logDebug('rollbackEnabled: ' + execution.getVariable("CVFMI_rollbackEnabled"), isDebugLogEnabled) - + logDebug('Exited ' + method, isDebugLogEnabled) } catch (BpmnError bpmnError) { - buildErrorResponse(execution,bpmnError.getMessage(),"400") throw bpmnError } catch (Exception exception) { - workflowException(execution, exception.getMessage(), 400) - } + exceptionUtil.buildAndThrowWorkflowException(execution, 400, "Internal Error - During PreProcessRequest") + } } /** @@ -175,45 +176,57 @@ public class CreateVfModuleInfra extends AbstractServiceTaskProcessor { def startTime = getNodeTextForce(requestInfo, 'start-time') if (startTime.isEmpty()) { startTime = System.currentTimeMillis() - } - + } + // RESTResponse (for API Handler (APIH) Reply Task) def newVfModuleId = execution.getVariable("newVfModuleId") String synchResponse = """{"requestReferences":{"instanceId":"${newVfModuleId}","requestId":"${requestId}"}}""".trim() - + sendWorkflowResponse(execution, 200, synchResponse) - + utils.logAudit("CreateVfModule Infra Response: " + synchResponse) logDebug('Exited ' + method, isDebugLogEnabled) } catch (BpmnError e) { throw e; } catch (Exception e) { logError('Caught exception in ' + method, e) - createWorkflowException(execution, 1002, 'Error in sendResponse(): ' + e.getMessage()) + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in sendResponse(): ' + e.getMessage()) } } /** - * + * * @param execution the execution */ public void postProcessResponse(Execution execution){ def isDebugEnabled = execution.getVariable("isDebugLogEnabled") - + utils.log("DEBUG", " ======== STARTED PostProcessResponse Process ======== ", isDebugEnabled) try{ def request = execution.getVariable("DoCreateVfModuleRequest") def requestInfo = utils.getNodeXml(request, 'request-info', false) def action = utils.getNodeText1(requestInfo, "action") - - utils.log("DEBUG", "requestInfo is: " + requestInfo, isDebugEnabled) + + utils.log("DEBUG", "requestInfo is: " + requestInfo, isDebugEnabled) utils.log("DEBUG", "action is: " + action, isDebugEnabled) + try { + String basicAuthValueDB = execution.getVariable("URN_mso_adapters_db_auth") + utils.log("DEBUG", " Obtained BasicAuth userid password for Catalog DB adapter: " + basicAuthValueDB, isDebugEnabled) + + def encodedString = utils.getBasicAuth(basicAuthValueDB, execution.getVariable("URN_mso_msoKey")) + execution.setVariable("BasicAuthHeaderValueDB",encodedString) + } catch (IOException ex) { + String dataErrorMessage = " Unable to encode Catalog DB user/password string - " + ex.getMessage() + utils.log("DEBUG", dataErrorMessage, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) + } + String payload = - """ - + """ + ${requestInfo} Vf Module has been created successfully. @@ -233,10 +246,10 @@ public class CreateVfModuleInfra extends AbstractServiceTaskProcessor { utils.log("DEBUG", "======== COMPLETED PostProcessResponse Process ======== ", isDebugEnabled) } - - - - + + + + /** * Validates the request, request id and service instance id. If a problem is found, * a WorkflowException is generated and an MSOWorkflowException event is thrown. This @@ -255,7 +268,7 @@ public class CreateVfModuleInfra extends AbstractServiceTaskProcessor { def prefix = execution.getVariable("prefix") if (prefix == null) { - createWorkflowException(execution, 1002, processKey + " prefix is null") + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, processKey + " prefix is null") } try { @@ -263,34 +276,34 @@ public class CreateVfModuleInfra extends AbstractServiceTaskProcessor { 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) { - createWorkflowException(execution, 1002, processKey + " request is null") + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, processKey + " request is null") } - + /* - def requestId = execution.getVariable("mso-request-id") - + def requestId = execution.getVariable("mso-request-id") + if (requestId == null) { - createWorkflowException(execution, 1002, processKey + " request has no mso-request-id") + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, processKey + " request has no mso-request-id") } - + setVariable(execution, prefix + 'requestId', requestId) - def serviceInstanceId = execution.getVariable("mso-service-instance-id") + def serviceInstanceId = execution.getVariable("mso-service-instance-id") if (serviceInstanceId == null) { - createWorkflowException(execution, 1002, processKey + " request message has no mso-service-instance-id") + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, processKey + " request message has no mso-service-instance-id") } utils.logContext(requestId, serviceInstanceId) @@ -303,14 +316,13 @@ public class CreateVfModuleInfra extends AbstractServiceTaskProcessor { throw e; } catch (Exception e) { logError('Caught exception in ' + method, e) - createWorkflowException(execution, 1002, "Invalid Message") + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Invalid Message") } } - + public void prepareUpdateInfraRequest(Execution execution){ def isDebugEnabled = execution.getVariable("isDebugLogEnabled") - ExceptionUtil exceptionUtil = new ExceptionUtil() - + utils.log("DEBUG", " ======== STARTED prepareUpdateInfraRequest Process ======== ", isDebugEnabled) try{ @@ -325,34 +337,34 @@ public class CreateVfModuleInfra extends AbstractServiceTaskProcessor { def dbAdapterEndpoint = execution.getVariable("URN_mso_adapters_db_endpoint") execution.setVariable("CVFMI_dbAdapterEndpoint", dbAdapterEndpoint) utils.log("DEBUG", "DB Adapter Endpoint is: " + dbAdapterEndpoint, isDebugEnabled) - - try { - String basicAuthValueDB = execution.getVariable("URN_mso_adapters_db_auth") - utils.log("DEBUG", " Obtained BasicAuth userid password for Catalog DB adapter: " + basicAuthValueDB, isDebugEnabled) - - def encodedString = utils.getBasicAuth(basicAuthValueDB, execution.getVariable("URN_mso_msoKey")) - execution.setVariable("BasicAuthHeaderValueDB",encodedString) - } catch (IOException ex) { - String dataErrorMessage = " Unable to encode Catalog DB user/password string - " + ex.getMessage() - utils.log("DEBUG", dataErrorMessage, isDebugEnabled) - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) - } - + + try { + String basicAuthValueDB = execution.getVariable("URN_mso_adapters_db_auth") + utils.log("DEBUG", " Obtained BasicAuth userid password for Catalog DB adapter: " + basicAuthValueDB, isDebugEnabled) + + def encodedString = utils.getBasicAuth(basicAuthValueDB, execution.getVariable("URN_mso_msoKey")) + execution.setVariable("BasicAuthHeaderValueDB",encodedString) + } catch (IOException ex) { + String dataErrorMessage = " Unable to encode Catalog DB user/password string - " + ex.getMessage() + utils.log("DEBUG", dataErrorMessage, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) + } + String payload = """ + xmlns:ns="http://org.openecomp.mso/requestsdb"> - + ${requestId} BPMN VF Module successfully created COMPLETE 100 - <vnf-outputs xmlns="http://org.openecomp/mso/infra/vnf-request/v1" xmlns:aetgt="http://org.openecomp/mso/infra/vnf-request/v1" xmlns:rest="http://schemas.activebpel.org/REST/2007/12/01/aeREST.xsd"><vnf-id>${vnfId}</vnf-id><vf-module-id>${vfModuleId}</vf-module-id></vnf-outputs> + <vnf-outputs xmlns="http://org.openecomp/mso/infra/vnf-request/v1" xmlns:aetgt="http://org.openecomp/mso/infra/vnf-request/v1" xmlns:rest="http://schemas.activebpel.org/REST/2007/12/01/aeREST.xsd"><vnf-id>${vnfId}</vnf-id><vf-module-id>${vfModuleId}</vf-module-id></vnf-outputs> ${vfModuleId} - + """ @@ -360,17 +372,17 @@ public class CreateVfModuleInfra extends AbstractServiceTaskProcessor { execution.setVariable("CVFMI_updateInfraRequest", payload) utils.log("DEBUG", "Outgoing UpdateInfraRequest: \n" + payload, isDebugEnabled) utils.logAudit("CreateVfModuleInfra Outgoing UpdateInfra Request: " + payload) - + }catch(Exception e){ utils.log("ERROR", "Exception Occured Processing prepareUpdateInfraRequest. Exception is:\n" + e, isDebugEnabled) execution.setVariable("CVFMI_ErrorResponse", "Error Occurred during prepareUpdateInfraRequest Method:\n" + e.getMessage()) } utils.log("DEBUG", "======== COMPLETED prepareUpdateInfraRequest Process ======== ", isDebugEnabled) } - + /** * Builds a "FalloutHandler" 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 */ @@ -381,8 +393,8 @@ public class CreateVfModuleInfra extends AbstractServiceTaskProcessor { ')' def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') logDebug('Entered ' + method, isDebugLogEnabled) - - + + try { def WorkflowException workflowException = execution.getVariable("WorkflowException") def request = execution.getVariable("DoCreateVfModuleRequest") @@ -395,18 +407,18 @@ public class CreateVfModuleInfra extends AbstractServiceTaskProcessor { } String content = """ - - ${requestInformation} + + ${requestInformation} ${encErrorResponseMsg} ${errorResponseCode} - + """ - + logDebug("CONTENT before translation: " + content, isDebugLogEnabled) content = utils.formatXml(content) logDebug(resultVar + ' = ' + System.lineSeparator() + content, isDebugLogEnabled) @@ -418,34 +430,34 @@ public class CreateVfModuleInfra extends AbstractServiceTaskProcessor { throw e; } catch (Exception e) { logError('Caught exception in ' + method, e) - createWorkflowException(execution, 2000, 'Internal Error') + exceptionUtil.buildWorkflowException(execution, 2000, 'Internal Error') } } - + public void logAndSaveOriginalException(Execution execution) { def method = getClass().getSimpleName() + '.validateRollbackResponse(' + 'execution=' + execution.getId() + ')' def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') logDebug('Entered ' + method, isDebugLogEnabled) - + logWorkflowException(execution, 'CreateVfModuleInfra caught an event') saveWorkflowException(execution, 'CVFMI_originalWorkflowException') } - + public void validateRollbackResponse(Execution execution) { def method = getClass().getSimpleName() + '.validateRollbackResponse(' + 'execution=' + execution.getId() + ')' def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') logDebug('Entered ' + method, isDebugLogEnabled) - + def originalException = execution.getVariable("CVFMI_originalWorkflowException") execution.setVariable("WorkflowException", originalException) - + execution.setVariable("RollbackCompleted", true) - + } - - + + } diff --git a/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/CreateVfModuleVolumeInfraV1.groovy b/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/CreateVfModuleVolumeInfraV1.groovy index 385e9e9994..289e185522 100644 --- a/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/CreateVfModuleVolumeInfraV1.groovy +++ b/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/CreateVfModuleVolumeInfraV1.groovy @@ -1,304 +1,304 @@ -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - MSO - * ================================================================================ - * 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.openecomp.mso.bpmn.infrastructure.scripts - -import org.openecomp.mso.bpmn.common.scripts.AaiUtil; -import org.openecomp.mso.bpmn.common.scripts.AbstractServiceTaskProcessor; -import org.openecomp.mso.bpmn.common.scripts.ExceptionUtil; -import org.openecomp.mso.bpmn.common.scripts.VidUtils; -import org.openecomp.mso.bpmn.core.WorkflowException -import org.openecomp.mso.rest.APIResponse - -import groovy.json.JsonSlurper - -import org.camunda.bpm.engine.delegate.BpmnError -import org.camunda.bpm.engine.runtime.Execution; -import org.apache.commons.lang3.* - -class CreateVfModuleVolumeInfraV1 extends AbstractServiceTaskProcessor { - - public static final String prefix='CVMVINFRAV1_' - - /** - * Perform initial processing, such as request validation, initialization of variables, etc. - * * @param execution - */ - public void preProcessRequest (Execution execution) { - def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - preProcessRequest(execution, isDebugEnabled) - } - - - /** - * Perform initial processing, such as request validation, initialization of variables, etc. - * @param execution - * @param isDebugEnabled - */ - public void preProcessRequest (Execution execution, isDebugEnabled) { - - execution.setVariable("prefix",prefix) - setSuccessIndicator(execution, false) - execution.setVariable(prefix+'syncResponseSent', false) - - String createVolumeIncoming = validateRequest(execution, 'vnfId') - utils.logAudit(createVolumeIncoming) - - try { - def jsonSlurper = new JsonSlurper() - Map reqMap = jsonSlurper.parseText(createVolumeIncoming) - - def serviceInstanceId = execution.getVariable('serviceInstanceId') - def vnfId = execution.getVariable('vnfId') - - def vidUtils = new VidUtils(this) - createVolumeIncoming = vidUtils.createXmlVolumeRequest(reqMap, 'CREATE_VF_MODULE_VOL', serviceInstanceId) - - execution.setVariable(prefix+'Request', createVolumeIncoming) - execution.setVariable(prefix+'vnfId', vnfId) - execution.setVariable(prefix+'isVidRequest', true) - - utils.log("DEBUG", "XML request:\n" + createVolumeIncoming, isDebugEnabled) - - } - catch(groovy.json.JsonException je) { - (new ExceptionUtil()).buildAndThrowWorkflowException(execution, 2500, 'Request is not a valid JSON document') - } - - execution.setVariable(prefix+'source', utils.getNodeText1(createVolumeIncoming, "source")) - execution.setVariable(prefix+'volumeGroupName', utils.getNodeText1(createVolumeIncoming, 'volume-group-name')) - execution.setVariable(prefix+'volumeOutputs', utils.getNodeXml(createVolumeIncoming, 'volume-outputs', false)) - - execution.setVariable(prefix+'serviceType', 'service-instance') - execution.setVariable(prefix+'serviceInstanceId', utils.getNodeText1(createVolumeIncoming, "service-instance-id")) - - // Generate volume group id - String volumeGroupId = UUID.randomUUID() - utils.log("DEBUG", "Generated volume group id: " + volumeGroupId, isDebugEnabled) - - def testGroupId = execution.getVariable('test-volume-group-id') - if (testGroupId != null && testGroupId.trim() != '') { - volumeGroupId = testGroupId - } - - execution.setVariable(prefix+'volumeGroupId', volumeGroupId) - - } - - - public void sendSyncResponse (Execution execution, isDebugEnabled) { - def volumeGroupId = execution.getVariable(prefix+'volumeGroupId') - def requestId = execution.getVariable("mso-request-id") - def serviceInstanceId = execution.getVariable("serviceInstanceId") - - String syncResponse = """{"requestReferences":{"instanceId":"${volumeGroupId}","requestId":"${requestId}"}}""".trim() - - utils.log("DEBUG", "Sync Response: " + "\n" + syncResponse, isDebugEnabled) - sendWorkflowResponse(execution, 200, syncResponse) - - execution.setVariable(prefix+'syncResponseSent', true) - } - - - public void sendSyncError (Execution execution, isDebugEnabled) { - WorkflowException we = execution.getVariable('WorkflowException') - def errorCode = we?.getErrorCode() - def errorMessage = we?.getErrorMessage() - //default to 400 since only invalid request will trigger this method - sendWorkflowResponse(execution, 400, errorMessage) - } - - - /** - * Create a WorkflowException - * @param execution - * @param isDebugEnabled - */ - public void buildWorkflowException(Execution execution, int errorCode, errorMessage, isDebugEnabled) { - utils.log("DEBUG", errorMessage, isDebugEnabled) - (new ExceptionUtil()).buildWorkflowException(execution, 2500, errorMessage) - } - - - public void prepareDbInfraSuccessRequest(Execution execution, isDebugEnabled) { - ExceptionUtil exceptionUtil = new ExceptionUtil() - def dbVnfOutputs = execution.getVariable(prefix+'volumeOutputs') - def requestId = execution.getVariable('mso-request-id') - def statusMessage = "VolumeGroup successfully created." - def requestStatus = "COMPLETED" - def progress = "100" - - try { - String basicAuthValueDB = execution.getVariable("URN_mso_adapters_db_auth") - utils.log("DEBUG", " Obtained BasicAuth userid password for Catalog DB adapter: " + basicAuthValueDB, isDebugEnabled) - - def encodedString = utils.getBasicAuth(basicAuthValueDB, execution.getVariable("URN_mso_msoKey")) - execution.setVariable("BasicAuthHeaderValueDB",encodedString) - } catch (IOException ex) { - String dataErrorMessage = " Unable to encode Catalog DB user/password string - " + ex.getMessage() - utils.log("DEBUG", dataErrorMessage, isDebugEnabled) - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) - } - - /* - from: $gVolumeGroup/aai:volume-group-id/text() - to: vnfreq:volume-outputs/vnfreq:volume-group-id - */ - // for now assume, generated volumeGroupId is accepted - def volumeGroupId = execution.getVariable(prefix+'volumeGroupId') - - String dbRequest = - """ - - - - ${requestId} - BPMN - ${statusMessage} - - ${requestStatus} - ${progress} - ${dbVnfOutputs} - ${volumeGroupId} - - - """ - - String buildDeleteDBRequestAsString = utils.formatXml(dbRequest) - execution.setVariable(prefix+"createDBRequest", buildDeleteDBRequestAsString) - - utils.logAudit(buildDeleteDBRequestAsString) - } - - - - - - public void postProcessResponse (Execution execution, isDebugEnabled) { - - def dbReturnCode = execution.getVariable(prefix+'dbReturnCode') - def createDBResponse = execution.getVariable(prefix+'createDBResponse') - - utils.logAudit('DB return code: ' + dbReturnCode) - utils.logAudit('DB response: ' + createDBResponse) - - def requestId = execution.getVariable("mso-request-id") - def source = execution.getVariable(prefix+'source') - - String msoCompletionRequest = - """ - - ${requestId} - CREATE - ${source} - - Volume Group has been created successfully. - BPMN VF Module Volume action: CREATE - """ - - String xmlMsoCompletionRequest = utils.formatXml(msoCompletionRequest) - - utils.logAudit(createDBResponse) - utils.logAudit(xmlMsoCompletionRequest) - execution.setVariable(prefix+'Success', true) - execution.setVariable(prefix+'CompleteMsoProcessRequest', xmlMsoCompletionRequest) - utils.log("DEBUG", " Overall SUCCESS Response going to CompleteMsoProcess - " + "\n" + xmlMsoCompletionRequest, isDebugEnabled) - - } - - public void prepareFalloutHandlerRequest(Execution execution, isDebugEnabled) { - - WorkflowException we = execution.getVariable('WorkflowException') - def errorCode = we?.getErrorCode() - def errorMessage = we?.getErrorMessage() - - def requestId = execution.getVariable("mso-request-id") - def source = execution.getVariable(prefix+'source') - - String falloutHandlerRequest = - """ - - ${requestId} - CREATE - ${source} - - - ${errorMessage} - ${errorCode} - - - """ - - // Format Response - String xmlHandlerRequest = utils.formatXml(falloutHandlerRequest) - utils.logAudit(xmlHandlerRequest) - - execution.setVariable(prefix+'FalloutHandlerRequest', xmlHandlerRequest) - utils.log("ERROR", "Overall Error Response going to FalloutHandler: " + "\n" + xmlHandlerRequest, isDebugEnabled) - } - - - /** - * Query AAI service instance - * @param execution - * @param isDebugEnabled - */ - public void callRESTQueryAAIServiceInstance(Execution execution, isDebugEnabled) { - - def request = execution.getVariable(prefix+"Request") - def serviceInstanceId = utils.getNodeText1(request, "service-instance-id") - - AaiUtil aaiUtil = new AaiUtil(this) - String aaiEndpoint = aaiUtil.getSearchNodesQueryEndpoint(execution) - - def String queryAAIRequest = aaiEndpoint + "?search-node-type=service-instance&filter=service-instance-id:EQUALS:" + serviceInstanceId - utils.logAudit("AAI query service instance request: " + queryAAIRequest) - - APIResponse response = aaiUtil.executeAAIGetCall(execution, queryAAIRequest) - - String returnCode = response.getStatusCode() - String aaiResponseAsString = response.getResponseBodyAsString() - aaiResponseAsString = StringEscapeUtils.unescapeXml(aaiResponseAsString) - - utils.logAudit("AAI query service instance return code: " + returnCode) - utils.logAudit("AAI query service instance response: " + aaiResponseAsString) - - utils.log("DEBUG", "AAI query service instance return code: " + returnCode, isDebugEnabled) - utils.log("DEBUG", "AAI query service instance response: " + aaiResponseAsString, isDebugEnabled) - - ExceptionUtil exceptionUtil = new ExceptionUtil() - - if (returnCode=='200') { - utils.log("DEBUG", 'Service instance ' + serviceInstanceId + ' found in AAI.', isDebugEnabled) - } else { - if (returnCode=='404') { - def message = 'Service instance ' + serviceInstanceId + ' was not found in AAI. Return code: 404.' - utils.log("DEBUG", message, isDebugEnabled) - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, message) - } else { - WorkflowException aWorkflowException = exceptionUtil.MapAAIExceptionToWorkflowException(aaiResponseAsString, execution) - throw new BpmnError("MSOWorkflowException") - } - } - } -} +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.bpmn.infrastructure.scripts + +import org.openecomp.mso.bpmn.common.scripts.AaiUtil; +import org.openecomp.mso.bpmn.common.scripts.AbstractServiceTaskProcessor; +import org.openecomp.mso.bpmn.common.scripts.ExceptionUtil; +import org.openecomp.mso.bpmn.common.scripts.VidUtils; +import org.openecomp.mso.bpmn.core.WorkflowException +import org.openecomp.mso.rest.APIResponse + +import groovy.json.JsonSlurper + +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.runtime.Execution; +import org.apache.commons.lang3.* + +class CreateVfModuleVolumeInfraV1 extends AbstractServiceTaskProcessor { + + public static final String prefix='CVMVINFRAV1_' + + /** + * Perform initial processing, such as request validation, initialization of variables, etc. + * * @param execution + */ + public void preProcessRequest (Execution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + preProcessRequest(execution, isDebugEnabled) + } + + + /** + * Perform initial processing, such as request validation, initialization of variables, etc. + * @param execution + * @param isDebugEnabled + */ + public void preProcessRequest (Execution execution, isDebugEnabled) { + + execution.setVariable("prefix",prefix) + setSuccessIndicator(execution, false) + execution.setVariable(prefix+'syncResponseSent', false) + + String createVolumeIncoming = validateRequest(execution, 'vnfId') + utils.logAudit(createVolumeIncoming) + + try { + def jsonSlurper = new JsonSlurper() + Map reqMap = jsonSlurper.parseText(createVolumeIncoming) + + def serviceInstanceId = execution.getVariable('serviceInstanceId') + def vnfId = execution.getVariable('vnfId') + + def vidUtils = new VidUtils(this) + createVolumeIncoming = vidUtils.createXmlVolumeRequest(reqMap, 'CREATE_VF_MODULE_VOL', serviceInstanceId) + + execution.setVariable(prefix+'Request', createVolumeIncoming) + execution.setVariable(prefix+'vnfId', vnfId) + execution.setVariable(prefix+'isVidRequest', true) + + utils.log("DEBUG", "XML request:\n" + createVolumeIncoming, isDebugEnabled) + + } + catch(groovy.json.JsonException je) { + (new ExceptionUtil()).buildAndThrowWorkflowException(execution, 2500, 'Request is not a valid JSON document') + } + + execution.setVariable(prefix+'source', utils.getNodeText1(createVolumeIncoming, "source")) + execution.setVariable(prefix+'volumeGroupName', utils.getNodeText1(createVolumeIncoming, 'volume-group-name')) + execution.setVariable(prefix+'volumeOutputs', utils.getNodeXml(createVolumeIncoming, 'volume-outputs', false)) + + execution.setVariable(prefix+'serviceType', 'service-instance') + execution.setVariable(prefix+'serviceInstanceId', utils.getNodeText1(createVolumeIncoming, "service-instance-id")) + + // Generate volume group id + String volumeGroupId = UUID.randomUUID() + utils.log("DEBUG", "Generated volume group id: " + volumeGroupId, isDebugEnabled) + + def testGroupId = execution.getVariable('test-volume-group-id') + if (testGroupId != null && testGroupId.trim() != '') { + volumeGroupId = testGroupId + } + + execution.setVariable(prefix+'volumeGroupId', volumeGroupId) + + } + + + public void sendSyncResponse (Execution execution, isDebugEnabled) { + def volumeGroupId = execution.getVariable(prefix+'volumeGroupId') + def requestId = execution.getVariable("mso-request-id") + def serviceInstanceId = execution.getVariable("serviceInstanceId") + + String syncResponse = """{"requestReferences":{"instanceId":"${volumeGroupId}","requestId":"${requestId}"}}""".trim() + + utils.log("DEBUG", "Sync Response: " + "\n" + syncResponse, isDebugEnabled) + sendWorkflowResponse(execution, 200, syncResponse) + + execution.setVariable(prefix+'syncResponseSent', true) + } + + + public void sendSyncError (Execution execution, isDebugEnabled) { + WorkflowException we = execution.getVariable('WorkflowException') + def errorCode = we?.getErrorCode() + def errorMessage = we?.getErrorMessage() + //default to 400 since only invalid request will trigger this method + sendWorkflowResponse(execution, 400, errorMessage) + } + + + /** + * Create a WorkflowException + * @param execution + * @param isDebugEnabled + */ + public void buildWorkflowException(Execution execution, int errorCode, errorMessage, isDebugEnabled) { + utils.log("DEBUG", errorMessage, isDebugEnabled) + (new ExceptionUtil()).buildWorkflowException(execution, 2500, errorMessage) + } + + + public void prepareDbInfraSuccessRequest(Execution execution, isDebugEnabled) { + ExceptionUtil exceptionUtil = new ExceptionUtil() + def dbVnfOutputs = execution.getVariable(prefix+'volumeOutputs') + def requestId = execution.getVariable('mso-request-id') + def statusMessage = "VolumeGroup successfully created." + def requestStatus = "COMPLETED" + def progress = "100" + + try { + String basicAuthValueDB = execution.getVariable("URN_mso_adapters_db_auth") + utils.log("DEBUG", " Obtained BasicAuth userid password for Catalog DB adapter: " + basicAuthValueDB, isDebugEnabled) + + def encodedString = utils.getBasicAuth(basicAuthValueDB, execution.getVariable("URN_mso_msoKey")) + execution.setVariable("BasicAuthHeaderValueDB",encodedString) + } catch (IOException ex) { + String dataErrorMessage = " Unable to encode Catalog DB user/password string - " + ex.getMessage() + utils.log("DEBUG", dataErrorMessage, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) + } + + /* + from: $gVolumeGroup/aai:volume-group-id/text() + to: vnfreq:volume-outputs/vnfreq:volume-group-id + */ + // for now assume, generated volumeGroupId is accepted + def volumeGroupId = execution.getVariable(prefix+'volumeGroupId') + + String dbRequest = + """ + + + + ${requestId} + BPMN + ${statusMessage} + + ${requestStatus} + ${progress} + ${dbVnfOutputs} + ${volumeGroupId} + + + """ + + String buildDeleteDBRequestAsString = utils.formatXml(dbRequest) + execution.setVariable(prefix+"createDBRequest", buildDeleteDBRequestAsString) + + utils.logAudit(buildDeleteDBRequestAsString) + } + + + + + + public void postProcessResponse (Execution execution, isDebugEnabled) { + + def dbReturnCode = execution.getVariable(prefix+'dbReturnCode') + def createDBResponse = execution.getVariable(prefix+'createDBResponse') + + utils.logAudit('DB return code: ' + dbReturnCode) + utils.logAudit('DB response: ' + createDBResponse) + + def requestId = execution.getVariable("mso-request-id") + def source = execution.getVariable(prefix+'source') + + String msoCompletionRequest = + """ + + ${requestId} + CREATE + ${source} + + Volume Group has been created successfully. + BPMN VF Module Volume action: CREATE + """ + + String xmlMsoCompletionRequest = utils.formatXml(msoCompletionRequest) + + utils.logAudit(createDBResponse) + utils.logAudit(xmlMsoCompletionRequest) + execution.setVariable(prefix+'Success', true) + execution.setVariable(prefix+'CompleteMsoProcessRequest', xmlMsoCompletionRequest) + utils.log("DEBUG", " Overall SUCCESS Response going to CompleteMsoProcess - " + "\n" + xmlMsoCompletionRequest, isDebugEnabled) + + } + + public void prepareFalloutHandlerRequest(Execution execution, isDebugEnabled) { + + WorkflowException we = execution.getVariable('WorkflowException') + def errorCode = we?.getErrorCode() + def errorMessage = we?.getErrorMessage() + + def requestId = execution.getVariable("mso-request-id") + def source = execution.getVariable(prefix+'source') + + String falloutHandlerRequest = + """ + + ${requestId} + CREATE + ${source} + + + ${errorMessage} + ${errorCode} + + + """ + + // Format Response + String xmlHandlerRequest = utils.formatXml(falloutHandlerRequest) + utils.logAudit(xmlHandlerRequest) + + execution.setVariable(prefix+'FalloutHandlerRequest', xmlHandlerRequest) + utils.log("ERROR", "Overall Error Response going to FalloutHandler: " + "\n" + xmlHandlerRequest, isDebugEnabled) + } + + + /** + * Query AAI service instance + * @param execution + * @param isDebugEnabled + */ + public void callRESTQueryAAIServiceInstance(Execution execution, isDebugEnabled) { + + def request = execution.getVariable(prefix+"Request") + def serviceInstanceId = utils.getNodeText1(request, "service-instance-id") + + AaiUtil aaiUtil = new AaiUtil(this) + String aaiEndpoint = aaiUtil.getSearchNodesQueryEndpoint(execution) + + def String queryAAIRequest = aaiEndpoint + "?search-node-type=service-instance&filter=service-instance-id:EQUALS:" + serviceInstanceId + utils.logAudit("AAI query service instance request: " + queryAAIRequest) + + APIResponse response = aaiUtil.executeAAIGetCall(execution, queryAAIRequest) + + String returnCode = response.getStatusCode() + String aaiResponseAsString = response.getResponseBodyAsString() + aaiResponseAsString = StringEscapeUtils.unescapeXml(aaiResponseAsString) + + utils.logAudit("AAI query service instance return code: " + returnCode) + utils.logAudit("AAI query service instance response: " + aaiResponseAsString) + + utils.log("DEBUG", "AAI query service instance return code: " + returnCode, isDebugEnabled) + utils.log("DEBUG", "AAI query service instance response: " + aaiResponseAsString, isDebugEnabled) + + ExceptionUtil exceptionUtil = new ExceptionUtil() + + if (returnCode=='200') { + utils.log("DEBUG", 'Service instance ' + serviceInstanceId + ' found in AAI.', isDebugEnabled) + } else { + if (returnCode=='404') { + def message = 'Service instance ' + serviceInstanceId + ' was not found in AAI. Return code: 404.' + utils.log("DEBUG", message, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, message) + } else { + WorkflowException aWorkflowException = exceptionUtil.MapAAIExceptionToWorkflowException(aaiResponseAsString, execution) + throw new BpmnError("MSOWorkflowException") + } + } + } +} diff --git a/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/DelServiceInstance.groovy b/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/DelServiceInstance.groovy index 6e346d2ecb..aad0693948 100644 --- a/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/DelServiceInstance.groovy +++ b/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/DelServiceInstance.groovy @@ -1,353 +1,353 @@ -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - MSO - * ================================================================================ - * 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.openecomp.mso.bpmn.infrastructure.scripts; - -import groovy.xml.XmlUtil -import groovy.json.* - -import org.openecomp.mso.bpmn.core.json.JsonUtils -import org.openecomp.mso.bpmn.common.scripts.AbstractServiceTaskProcessor -import org.openecomp.mso.bpmn.common.scripts.ExceptionUtil -import org.openecomp.mso.bpmn.common.scripts.VidUtils -import org.openecomp.mso.bpmn.core.WorkflowException -import org.openecomp.mso.rest.APIResponse; - -import java.util.UUID; -import javax.xml.parsers.DocumentBuilder -import javax.xml.parsers.DocumentBuilderFactory - -import org.camunda.bpm.engine.delegate.BpmnError -import org.camunda.bpm.engine.runtime.Execution -import org.json.JSONObject; -import org.apache.commons.lang3.* -import org.apache.commons.codec.binary.Base64; -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 static org.apache.commons.lang3.StringUtils.*; - -import org.springframework.web.util.UriUtils; - -/** - * This groovy class supports the DelServiceInstance.bpmn process. - * - */ -public class DelServiceInstance extends AbstractServiceTaskProcessor { - - String Prefix="DELSI_" - ExceptionUtil exceptionUtil = new ExceptionUtil() - JsonUtils jsonUtil = new JsonUtils() - VidUtils vidUtils = new VidUtils() - - public void preProcessRequest (Execution execution) { - def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - execution.setVariable("prefix",Prefix) - String msg = "" - - utils.log("DEBUG", " *** preProcessRequest Request *** ", isDebugEnabled) - - try { - // check for incoming json message/input - String siRequest = execution.getVariable("bpmnRequest") - utils.logAudit(siRequest) - - - String requestId = execution.getVariable("mso-request-id") - execution.setVariable("msoRequestId", requestId) - utils.log("DEBUG", "Input Request:" + siRequest + " reqId:" + requestId, isDebugEnabled) - - String serviceInstanceId = execution.getVariable("serviceInstanceId") - if (isBlank(serviceInstanceId)) { - msg = "Input serviceInstanceId' is null" - exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) - } - - //String xmlRequestDetails = vidUtils.getJsonRequestDetailstoXml(siRequest) - //execution.setVariable("requestDetails", xmlRequestDetails) - - //modelInfo - String serviceModelInfo = jsonUtil.getJsonValue(siRequest, "requestDetails.modelInfo") - if (isBlank(serviceModelInfo)) { - msg = "Input serviceModelInfo is null" - utils.log("DEBUG", msg, isDebugEnabled) - } else - { - execution.setVariable("serviceModelInfo", serviceModelInfo) - //utils.log("DEBUG", "modelInfo" + serviceModelInfo, isDebugEnabled) - } - - //requestInfo - String productFamilyId = jsonUtil.getJsonValue(siRequest, "requestDetails.requestInfo.productFamilyId") - if (isBlank(productFamilyId)) - { - msg = "Input productFamilyId is null" - utils.log("DEBUG", msg, isDebugEnabled) - //exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) - } else { - execution.setVariable("productFamilyId", productFamilyId) - } - String source = jsonUtil.getJsonValue(siRequest, "requestDetails.requestInfo.source") - execution.setVariable("source", source) - - //subscriberInfo - String globalSubscriberId = jsonUtil.getJsonValue(siRequest, "requestDetails.subscriberInfo.globalSubscriberId") - if (isBlank(globalSubscriberId)) { - msg = "Input globalSubscriberId' is null" - utils.log("DEBUG", msg, isDebugEnabled) - } else { - execution.setVariable("globalSubscriberId", globalSubscriberId) - } - - //requestParameters - String subscriptionServiceType = jsonUtil.getJsonValue(siRequest, "requestDetails.requestParameters.subscriptionServiceType") - if (isBlank(subscriptionServiceType)) { - msg = "Input subscriptionServiceType is null" - utils.log("DEBUG", msg, isDebugEnabled) - //exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) - } else { - execution.setVariable("subscriptionServiceType", subscriptionServiceType) - } - - } catch (BpmnError e) { - throw e; - } catch (Exception ex){ - msg = "Exception in preProcessRequest " + ex.getMessage() - utils.log("DEBUG", msg, isDebugEnabled) - exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) - } - utils.log("DEBUG"," ***** Exit preProcessRequest *****", isDebugEnabled) - } - - public void sendSyncResponse (Execution execution) { - def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - utils.log("DEBUG", " *** sendSyncResponse *** ", isDebugEnabled) - - try { - String requestId = execution.getVariable("msoRequestId") - String serviceInstanceId = execution.getVariable("serviceInstanceId") - - // RESTResponse (for API Handler (APIH) Reply Task) - String syncResponse = """{"requestReferences":{"instanceId":"${serviceInstanceId}","requestId":"${requestId}"}}""".trim() - utils.log("DEBUG", " sendSynchResponse: xmlSyncResponse - " + "\n" + syncResponse, isDebugEnabled) - sendWorkflowResponse(execution, 202, syncResponse) - - } catch (Exception ex) { - String msg = "Exception in sendSyncResponse: " + ex.getMessage() - exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) - } - utils.log("DEBUG"," ***** Exit sendSyncResopnse *****", isDebugEnabled) - } - - public void sendSyncError (Execution execution) { - def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - utils.log("DEBUG", " *** sendSyncError *** ", isDebugEnabled) - - try { - String errorMessage = "" - if (execution.getVariable("WorkflowException") instanceof WorkflowException) { - WorkflowException wfe = execution.getVariable("WorkflowException") - errorMessage = wfe.getErrorMessage() - } else { - errorMessage = "Sending Sync Error." - } - - String buildworkflowException = - """ - ${errorMessage} - 7000 - """ - - utils.logAudit(buildworkflowException) - sendWorkflowResponse(execution, 500, buildworkflowException) - - } catch (Exception ex) { - utils.log("DEBUG", " Sending Sync Error Activity Failed. " + "\n" + ex.getMessage(), isDebugEnabled) - } - - } - - public void prepareCompletionRequest (Execution execution) { - def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - utils.log("DEBUG", " *** prepareCompletion *** ", isDebugEnabled) - - try { - String requestId = execution.getVariable("msoRequestId") - String source = execution.getVariable("source") - String msoCompletionRequest = - """ - - ${requestId} - DELETE - ${source} - - Service Instance was deleted successfully. - DelServiceInstance - """ - - // Format Response - String xmlMsoCompletionRequest = utils.formatXml(msoCompletionRequest) - - execution.setVariable("completionRequest", xmlMsoCompletionRequest) - utils.log("DEBUG", " Overall SUCCESS Response going to CompleteMsoProcess - " + "\n" + xmlMsoCompletionRequest, isDebugEnabled) - - } catch (Exception ex) { - String msg = " Exception in prepareCompletion:" + ex.getMessage() - utils.log("DEBUG", msg, isDebugEnabled) - exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) - } - utils.log("DEBUG", "*** Exit prepareCompletionRequest ***", isDebugEnabled) - } - - public void prepareFalloutRequest(Execution execution){ - def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - utils.log("DEBUG", " *** prepareFalloutRequest *** ", isDebugEnabled) - - try { - WorkflowException wfex = execution.getVariable("WorkflowException") - utils.log("DEBUG", " Input Workflow Exception: " + wfex.toString(), isDebugEnabled) - String requestId = execution.getVariable("msoRequestId") - String source = execution.getVariable("source") - String requestInfo = - """ - ${requestId} - DELETE - ${source} - """ - - String falloutRequest = exceptionUtil.processMainflowsBPMNException(execution, requestInfo) - execution.setVariable("falloutRequest", falloutRequest) - } catch (Exception ex) { - utils.log("DEBUG", "Exception prepareFalloutRequest:" + ex.getMessage(), isDebugEnabled) - String errorException = " Bpmn error encountered in CreateServiceInstance flow. FalloutHandlerRequest, buildErrorResponse() - " + ex.getMessage() - String requestId = execution.getVariable("msoRequestId") - String falloutRequest = - """ - - ${requestId} - DELETE - VID - - - ${errorException} - 7000 - - """ - - execution.setVariable("falloutRequest", falloutRequest) - } - utils.log("DEBUG", "*** Exit prepareFalloutRequest ***", isDebugEnabled) - } - - - // ******************************* - // Build DB request Section - // ******************************* - public void prepareDBRequest (Execution execution) { - def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - execution.setVariable("prefix", Prefix) - - try { - utils.log("DEBUG", " ***** Inside prepareDBRequest of DeleteServiceInstance ***** ", isDebugEnabled) - - String requestId = execution.getVariable("DELSI_requestId") - String statusMessage = "Service Instance successfully deleted." - - //TODO - verify the format for Service Instance Delete, - String dbRequest = - """ - - - - ${requestId} - BPMN - ${statusMessage} - - COMPLETED - 100 - - - """ - - String buildDeleteDBRequestAsString = utils.formatXml(dbRequest) - execution.setVariable("DELSI_createDBRequest", buildDeleteDBRequestAsString) - utils.logAudit(buildDeleteDBRequestAsString) - - } catch (Exception ex) { - // try error in method block - String exceptionMessage = "Bpmn error encountered in DeleteServiceInstance flow. Unexpected Error from method prepareDBRequest() - " + ex.getMessage() - exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) - - } - - } - - // ******************************* - // Build Error Section - // ******************************* - public void prepareDBRequestError (Execution execution) { - def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - execution.setVariable("prefix", Prefix) - - utils.log("DEBUG", " ***** Inside prepareDBRequestError of DeleteServiceInstanceInfra ***** ", isDebugEnabled) - - try { - String requestId = execution.getVariable("DELSI_requestId") - String statusMessage = "" - if (execution.getVariable("WorkflowException") instanceof WorkflowException) { - WorkflowException wfe = execution.getVariable("WorkflowException") - statusMessage = wfe.getErrorMessage() - - } else { - statusMessage = "Encountered Error during DeleteServiceInstanceInfra proccessing. " - } - - //TODO - verify the format for Service Instance Create, - String dbRequest = - """ - - - - ${requestId} - BPMN - ${statusMessage} - - FAILED - - - """ - - String buildDBRequestAsString = utils.formatXml(dbRequest) - execution.setVariable("DELSI_createDBInfraErrorRequest", buildDBRequestAsString) - utils.logAudit(buildDBRequestAsString) - - } catch (Exception ex) { - // try error in method block - String exceptionMessage = "Bpmn error encountered in DeleteServiceInstanceInfra flow. Unexpected Error from method prepareDBRequestError() - " + ex.getMessage() - exceptionUtil.buildWorkflowException(execution, 7000, exceptionMessage) - - } - - } -} +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.bpmn.infrastructure.scripts; + +import groovy.xml.XmlUtil +import groovy.json.* + +import org.openecomp.mso.bpmn.core.json.JsonUtils +import org.openecomp.mso.bpmn.common.scripts.AbstractServiceTaskProcessor +import org.openecomp.mso.bpmn.common.scripts.ExceptionUtil +import org.openecomp.mso.bpmn.common.scripts.VidUtils +import org.openecomp.mso.bpmn.core.WorkflowException +import org.openecomp.mso.rest.APIResponse; + +import java.util.UUID; +import javax.xml.parsers.DocumentBuilder +import javax.xml.parsers.DocumentBuilderFactory + +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.runtime.Execution +import org.json.JSONObject; +import org.apache.commons.lang3.* +import org.apache.commons.codec.binary.Base64; +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 static org.apache.commons.lang3.StringUtils.*; + +import org.springframework.web.util.UriUtils; + +/** + * This groovy class supports the DelServiceInstance.bpmn process. + * + */ +public class DelServiceInstance extends AbstractServiceTaskProcessor { + + String Prefix="DELSI_" + ExceptionUtil exceptionUtil = new ExceptionUtil() + JsonUtils jsonUtil = new JsonUtils() + VidUtils vidUtils = new VidUtils() + + public void preProcessRequest (Execution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix",Prefix) + String msg = "" + + utils.log("DEBUG", " *** preProcessRequest Request *** ", isDebugEnabled) + + try { + // check for incoming json message/input + String siRequest = execution.getVariable("bpmnRequest") + utils.logAudit(siRequest) + + + String requestId = execution.getVariable("mso-request-id") + execution.setVariable("msoRequestId", requestId) + utils.log("DEBUG", "Input Request:" + siRequest + " reqId:" + requestId, isDebugEnabled) + + String serviceInstanceId = execution.getVariable("serviceInstanceId") + if (isBlank(serviceInstanceId)) { + msg = "Input serviceInstanceId' is null" + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } + + //String xmlRequestDetails = vidUtils.getJsonRequestDetailstoXml(siRequest) + //execution.setVariable("requestDetails", xmlRequestDetails) + + //modelInfo + String serviceModelInfo = jsonUtil.getJsonValue(siRequest, "requestDetails.modelInfo") + if (isBlank(serviceModelInfo)) { + msg = "Input serviceModelInfo is null" + utils.log("DEBUG", msg, isDebugEnabled) + } else + { + execution.setVariable("serviceModelInfo", serviceModelInfo) + //utils.log("DEBUG", "modelInfo" + serviceModelInfo, isDebugEnabled) + } + + //requestInfo + String productFamilyId = jsonUtil.getJsonValue(siRequest, "requestDetails.requestInfo.productFamilyId") + if (isBlank(productFamilyId)) + { + msg = "Input productFamilyId is null" + utils.log("DEBUG", msg, isDebugEnabled) + //exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } else { + execution.setVariable("productFamilyId", productFamilyId) + } + String source = jsonUtil.getJsonValue(siRequest, "requestDetails.requestInfo.source") + execution.setVariable("source", source) + + //subscriberInfo + String globalSubscriberId = jsonUtil.getJsonValue(siRequest, "requestDetails.subscriberInfo.globalSubscriberId") + if (isBlank(globalSubscriberId)) { + msg = "Input globalSubscriberId' is null" + utils.log("DEBUG", msg, isDebugEnabled) + } else { + execution.setVariable("globalSubscriberId", globalSubscriberId) + } + + //requestParameters + String subscriptionServiceType = jsonUtil.getJsonValue(siRequest, "requestDetails.requestParameters.subscriptionServiceType") + if (isBlank(subscriptionServiceType)) { + msg = "Input subscriptionServiceType is null" + utils.log("DEBUG", msg, isDebugEnabled) + //exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } else { + execution.setVariable("subscriptionServiceType", subscriptionServiceType) + } + + } catch (BpmnError e) { + throw e; + } catch (Exception ex){ + msg = "Exception in preProcessRequest " + ex.getMessage() + utils.log("DEBUG", msg, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + utils.log("DEBUG"," ***** Exit preProcessRequest *****", isDebugEnabled) + } + + public void sendSyncResponse (Execution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + utils.log("DEBUG", " *** sendSyncResponse *** ", isDebugEnabled) + + try { + String requestId = execution.getVariable("msoRequestId") + String serviceInstanceId = execution.getVariable("serviceInstanceId") + + // RESTResponse (for API Handler (APIH) Reply Task) + String syncResponse = """{"requestReferences":{"instanceId":"${serviceInstanceId}","requestId":"${requestId}"}}""".trim() + utils.log("DEBUG", " sendSynchResponse: xmlSyncResponse - " + "\n" + syncResponse, isDebugEnabled) + sendWorkflowResponse(execution, 202, syncResponse) + + } catch (Exception ex) { + String msg = "Exception in sendSyncResponse: " + ex.getMessage() + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + } + utils.log("DEBUG"," ***** Exit sendSyncResopnse *****", isDebugEnabled) + } + + public void sendSyncError (Execution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + utils.log("DEBUG", " *** sendSyncError *** ", isDebugEnabled) + + try { + String errorMessage = "" + if (execution.getVariable("WorkflowException") instanceof WorkflowException) { + WorkflowException wfe = execution.getVariable("WorkflowException") + errorMessage = wfe.getErrorMessage() + } else { + errorMessage = "Sending Sync Error." + } + + String buildworkflowException = + """ + ${errorMessage} + 7000 + """ + + utils.logAudit(buildworkflowException) + sendWorkflowResponse(execution, 500, buildworkflowException) + + } catch (Exception ex) { + utils.log("DEBUG", " Sending Sync Error Activity Failed. " + "\n" + ex.getMessage(), isDebugEnabled) + } + + } + + public void prepareCompletionRequest (Execution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + utils.log("DEBUG", " *** prepareCompletion *** ", isDebugEnabled) + + try { + String requestId = execution.getVariable("msoRequestId") + String source = execution.getVariable("source") + String msoCompletionRequest = + """ + + ${requestId} + DELETE + ${source} + + Service Instance was deleted successfully. + DelServiceInstance + """ + + // Format Response + String xmlMsoCompletionRequest = utils.formatXml(msoCompletionRequest) + + execution.setVariable("completionRequest", xmlMsoCompletionRequest) + utils.log("DEBUG", " Overall SUCCESS Response going to CompleteMsoProcess - " + "\n" + xmlMsoCompletionRequest, isDebugEnabled) + + } catch (Exception ex) { + String msg = " Exception in prepareCompletion:" + ex.getMessage() + utils.log("DEBUG", msg, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + utils.log("DEBUG", "*** Exit prepareCompletionRequest ***", isDebugEnabled) + } + + public void prepareFalloutRequest(Execution execution){ + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + utils.log("DEBUG", " *** prepareFalloutRequest *** ", isDebugEnabled) + + try { + WorkflowException wfex = execution.getVariable("WorkflowException") + utils.log("DEBUG", " Input Workflow Exception: " + wfex.toString(), isDebugEnabled) + String requestId = execution.getVariable("msoRequestId") + String source = execution.getVariable("source") + String requestInfo = + """ + ${requestId} + DELETE + ${source} + """ + + String falloutRequest = exceptionUtil.processMainflowsBPMNException(execution, requestInfo) + execution.setVariable("falloutRequest", falloutRequest) + } catch (Exception ex) { + utils.log("DEBUG", "Exception prepareFalloutRequest:" + ex.getMessage(), isDebugEnabled) + String errorException = " Bpmn error encountered in CreateServiceInstance flow. FalloutHandlerRequest, buildErrorResponse() - " + ex.getMessage() + String requestId = execution.getVariable("msoRequestId") + String falloutRequest = + """ + + ${requestId} + DELETE + VID + + + ${errorException} + 7000 + + """ + + execution.setVariable("falloutRequest", falloutRequest) + } + utils.log("DEBUG", "*** Exit prepareFalloutRequest ***", isDebugEnabled) + } + + + // ******************************* + // Build DB request Section + // ******************************* + public void prepareDBRequest (Execution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix", Prefix) + + try { + utils.log("DEBUG", " ***** Inside prepareDBRequest of DeleteServiceInstance ***** ", isDebugEnabled) + + String requestId = execution.getVariable("DELSI_requestId") + String statusMessage = "Service Instance successfully deleted." + + //TODO - verify the format for Service Instance Delete, + String dbRequest = + """ + + + + ${requestId} + BPMN + ${statusMessage} + + COMPLETED + 100 + + + """ + + String buildDeleteDBRequestAsString = utils.formatXml(dbRequest) + execution.setVariable("DELSI_createDBRequest", buildDeleteDBRequestAsString) + utils.logAudit(buildDeleteDBRequestAsString) + + } catch (Exception ex) { + // try error in method block + String exceptionMessage = "Bpmn error encountered in DeleteServiceInstance flow. Unexpected Error from method prepareDBRequest() - " + ex.getMessage() + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + + } + + } + + // ******************************* + // Build Error Section + // ******************************* + public void prepareDBRequestError (Execution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix", Prefix) + + utils.log("DEBUG", " ***** Inside prepareDBRequestError of DeleteServiceInstanceInfra ***** ", isDebugEnabled) + + try { + String requestId = execution.getVariable("DELSI_requestId") + String statusMessage = "" + if (execution.getVariable("WorkflowException") instanceof WorkflowException) { + WorkflowException wfe = execution.getVariable("WorkflowException") + statusMessage = wfe.getErrorMessage() + + } else { + statusMessage = "Encountered Error during DeleteServiceInstanceInfra proccessing. " + } + + //TODO - verify the format for Service Instance Create, + String dbRequest = + """ + + + + ${requestId} + BPMN + ${statusMessage} + + FAILED + + + """ + + String buildDBRequestAsString = utils.formatXml(dbRequest) + execution.setVariable("DELSI_createDBInfraErrorRequest", buildDBRequestAsString) + utils.logAudit(buildDBRequestAsString) + + } catch (Exception ex) { + // try error in method block + String exceptionMessage = "Bpmn error encountered in DeleteServiceInstanceInfra flow. Unexpected Error from method prepareDBRequestError() - " + ex.getMessage() + exceptionUtil.buildWorkflowException(execution, 7000, exceptionMessage) + + } + + } +} diff --git a/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/DeleteGenericMacroServiceNetworkVnf.groovy b/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/DeleteGenericMacroServiceNetworkVnf.groovy index f1513c6b09..e49de0bc09 100644 --- a/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/DeleteGenericMacroServiceNetworkVnf.groovy +++ b/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/DeleteGenericMacroServiceNetworkVnf.groovy @@ -1,476 +1,468 @@ -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - MSO - * ================================================================================ - * 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.openecomp.mso.bpmn.infrastructure.scripts; - -import groovy.xml.XmlUtil -import groovy.json.* - -import org.openecomp.mso.bpmn.core.json.JsonUtils -import org.openecomp.mso.bpmn.common.scripts.AbstractServiceTaskProcessor -import org.openecomp.mso.bpmn.common.scripts.CatalogDbUtils -import org.openecomp.mso.bpmn.common.scripts.ExceptionUtil -import org.openecomp.mso.bpmn.common.scripts.NetworkUtils -import org.openecomp.mso.bpmn.common.scripts.VidUtils -import org.openecomp.mso.bpmn.core.WorkflowException -import org.openecomp.mso.rest.APIResponse; - - -import java.util.UUID; - -import org.camunda.bpm.engine.delegate.BpmnError -import org.camunda.bpm.engine.runtime.Execution -import org.json.JSONObject; -import org.json.JSONArray; -import org.apache.commons.lang3.* -import org.apache.commons.codec.binary.Base64; -import org.springframework.web.util.UriUtils; - -/** - * This groovy class supports the DeleteViprAtmService.bpmn process. - * - */ -public class DeleteGenericMacroServiceNetworkVnf extends AbstractServiceTaskProcessor { - - String Prefix="DELVAS_" - ExceptionUtil exceptionUtil = new ExceptionUtil() - JsonUtils jsonUtil = new JsonUtils() - VidUtils vidUtils = new VidUtils() - CatalogDbUtils catalogDbUtils = new CatalogDbUtils() - NetworkUtils networkUtils = new NetworkUtils() - - /** - * This method is executed during the preProcessRequest task of the DeleteViprAtmService.bpmn process. - * @param execution - */ - public InitializeProcessVariables(Execution execution){ - /* Initialize all the process variables in this block */ - - execution.setVariable("deleteViprAtmServiceRequest", "") - execution.setVariable("msoRequestId", "") - execution.setVariable("DELVAS_vnfsDeletedCount", 0) - execution.setVariable("DELVAS_vnfsCount", 0) - execution.setVariable("DELVAS_networksCount", 0) - execution.setVariable("DELVAS_networksDeletedCount", 0) - } - - // ************************************************** - // Pre or Prepare Request Section - // ************************************************** - /** - * This method is executed during the preProcessRequest task of the CreateServiceInstance.bpmn process. - * @param execution - */ - public void preProcessRequest (Execution execution) { - def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - execution.setVariable("prefix",Prefix) - - utils.log("DEBUG", " ***** Inside preProcessRequest DeleteViprAtmService Request ***** ", isDebugEnabled) - - try { - // initialize flow variables - InitializeProcessVariables(execution) - - // check for incoming json message/input - String deleteViprAtmServiceRequest = execution.getVariable("bpmnRequest") - utils.logAudit(deleteViprAtmServiceRequest) - execution.setVariable("deleteViprAtmServiceRequest", deleteViprAtmServiceRequest); - println 'deleteViprAtmServiceRequest - ' + deleteViprAtmServiceRequest - - // extract requestId - String requestId = execution.getVariable("mso-request-id") - execution.setVariable("msoRequestId", requestId) - - String serviceInstanceId = execution.getVariable("serviceInstanceId") - if ((serviceInstanceId == null) || (serviceInstanceId.isEmpty())) { - String dataErrorMessage = " Element 'serviceInstanceId' is missing. " - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) - } - - String requestAction = execution.getVariable("requestAction") - execution.setVariable("requestAction", requestAction) - - String source = jsonUtil.getJsonValue(deleteViprAtmServiceRequest, "requestDetails.requestInfo.source") - if ((source == null) || (source.isEmpty())) { - execution.setVariable("source", "VID") - } else { - execution.setVariable("source", source) - } - - // extract globalSubscriberId - String globalSubscriberId = jsonUtil.getJsonValue(deleteViprAtmServiceRequest, "requestDetails.subscriberInfo.globalSubscriberId") - - // global-customer-id is optional on Delete - - execution.setVariable("globalSubscriberId", globalSubscriberId) - execution.setVariable("globalCustomerId", globalSubscriberId) - - String suppressRollback = jsonUtil.getJsonValue(deleteViprAtmServiceRequest, "requestDetails.requestInfo.suppressRollback") - execution.setVariable("disableRollback", suppressRollback) - utils.log("DEBUG", "Incoming Suppress/Disable Rollback is: " + suppressRollback, isDebugEnabled) - - String productFamilyId = jsonUtil.getJsonValue(deleteViprAtmServiceRequest, "requestDetails.requestInfo.productFamilyId") - execution.setVariable("productFamilyId", productFamilyId) - utils.log("DEBUG", "Incoming productFamilyId is: " + productFamilyId, isDebugEnabled) - - // extract subscriptionServiceType - String subscriptionServiceType = jsonUtil.getJsonValue(deleteViprAtmServiceRequest, "requestDetails.requestParameters.subscriptionServiceType") - execution.setVariable("subscriptionServiceType", subscriptionServiceType) - utils.log("DEBUG", "Incoming subscriptionServiceType is: " + subscriptionServiceType, isDebugEnabled) - - // extract cloud configuration - String lcpCloudRegionId = jsonUtil.getJsonValue(deleteViprAtmServiceRequest, "requestDetails.cloudConfiguration.lcpCloudRegionId") - execution.setVariable("lcpCloudRegionId", lcpCloudRegionId) - utils.log("DEBUG","lcpCloudRegionId: "+ lcpCloudRegionId, isDebugEnabled) - String tenantId = jsonUtil.getJsonValue(deleteViprAtmServiceRequest, "requestDetails.cloudConfiguration.tenantId") - execution.setVariable("tenantId", tenantId) - utils.log("DEBUG","tenantId: "+ tenantId, isDebugEnabled) - - String sdncVersion = "1702" - execution.setVariable("sdncVersion", sdncVersion) - utils.log("DEBUG","sdncVersion: "+ sdncVersion, isDebugEnabled) - - //For Completion Handler & Fallout Handler - String requestInfo = - """ - ${requestId} - DELETE - ${source} - """ - - execution.setVariable("DELVAS_requestInfo", requestInfo) - - //Setting for Generic Sub Flows - execution.setVariable("GENGS_type", "service-instance") - - utils.log("DEBUG", " ***** Completed preProcessRequest DeleteViprAtmService Request ***** ", isDebugEnabled) - - } catch (BpmnError e) { - throw e; - } catch (Exception ex){ - String exceptionMessage = "Bpmn error encountered in DeleteViprAtmService flow. Unexpected from method preProcessRequest() - " + ex.getMessage() - exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) - } - } - - public void sendSyncResponse (Execution execution) { - def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - - utils.log("DEBUG", " ***** Inside sendSyncResponse of DeleteViprAtmService ***** ", isDebugEnabled) - - try { - String serviceInstanceId = execution.getVariable("serviceInstanceId") - String requestId = execution.getVariable("mso-request-id") - - // RESTResponse (for API Handler (APIH) Reply Task) - String syncResponse ="""{"requestReferences":{"instanceId":"${serviceInstanceId}","requestId":"${requestId}"}}""".trim() - - utils.log("DEBUG", " sendSynchResponse: xmlSyncResponse - " + "\n" + syncResponse, isDebugEnabled) - sendWorkflowResponse(execution, 202, syncResponse) - } catch (Exception ex) { - String exceptionMessage = "Bpmn error encountered in DeleteViprAtmService flow. Unexpected from method sendSyncResponse() - " + ex.getMessage() - exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) - } - } - - public void prepareServiceInstanceDelete (Execution execution) { - def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - utils.log("DEBUG", " ***** Inside prepareServiceInstanceDelete() of DeleteViprAtmService ***** ", isDebugEnabled) - - try { - - String serviceInstanceId = execution.getVariable("serviceInstanceId") - - // confirm if ServiceInstance was found - if ( !execution.getVariable("GENGS_FoundIndicator") ) - { - String exceptionMessage = "Bpmn error encountered in DeleteViprAtmService flow. Service Instance was not found in AAI by id: " + serviceInstanceId - exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) - } - - // get variable within incoming json - String deleteViprAtmServiceRequest = execution.getVariable("deleteViprAtmServiceRequest"); - - // get SI extracted by GenericGetService - String serviceInstanceAaiRecord = execution.getVariable("GENGS_service"); - - utils.log("DEBUG", "serviceInstanceAaiRecord: "+serviceInstanceAaiRecord, isDebugEnabled) - - String relationship = "" - try { - relationship = networkUtils.getFirstNodeXml(serviceInstanceAaiRecord, "relationship-list") - } catch (Exception ex) { - //no relationships found - } - utils.log("DEBUG", " relationship string - " + relationship, isDebugEnabled) - - int vnfsCount = 0 - int networksCount = 0 - - if (relationship != null && relationship.length() > 0){ - relationship = relationship.trim().replace("tag0:","").replace(":tag0","") - - // Check if Network TableREf is present, then build a List of network policy - List relatedVnfIdList = networkUtils.getRelatedVnfIdList(relationship) - vnfsCount = relatedVnfIdList.size() - execution.setVariable("DELVAS_vnfsCount", vnfsCount) - utils.log("DEBUG", " DELVAS_vnfsCount : " + vnfsCount, isDebugEnabled) - execution.setVariable("DELVAS_relatedVnfIdList", relatedVnfIdList) - - // Check if Network TableREf is present, then build a List of network policy - List relatedNetworkIdList = networkUtils.getRelatedNetworkIdList(relationship) - networksCount = relatedNetworkIdList.size() - execution.setVariable("DELVAS_networksCount", networksCount) - utils.log("DEBUG", " DELVAS_networksCount : " + networksCount, isDebugEnabled) - execution.setVariable("DELVAS_relatedNetworkIdList", relatedNetworkIdList) - execution.setVariable("relatedNetworkIdListString", relatedNetworkIdList.toString()) - } else { - execution.setVariable("DELVAS_vnfsCount", 0) - utils.log("DEBUG", " DELVAS_vnfsCount : " + vnfsCount, isDebugEnabled) - execution.setVariable("DELVAS_networksCount", 0) - utils.log("DEBUG", " DELVAS_networksCount : " + networksCount, isDebugEnabled) - } - - utils.log("DEBUG", " ***** Completed prepareServiceInstanceDelete() of DeleteViprAtmService ***** ", isDebugEnabled) - } catch (Exception ex) { - sendSyncError(execution) - String exceptionMessage = "Bpmn error encountered in DeleteViprAtmService flow. prepareServiceInstanceDelete() - " + ex.getMessage() - utils.log("DEBUG", exceptionMessage, isDebugEnabled) - exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) - } - } - - - // ******************************* - // - // ******************************* - public void prepareVnfAndModulesDelete (Execution execution) { - def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - - try { - utils.log("DEBUG", " ***** Inside prepareVnfAndModulesDelete of DeleteServiceInstanceMacro ***** ", isDebugEnabled) - - List vnfList = execution.getVariable("DELVAS_relatedVnfIdList") - Integer vnfsDeletedCount = execution.getVariable("DELVAS_vnfsDeletedCount") - String vnfModelInfoString = "" - String vnfId = "" - if (vnfList.size() > 0 ) { - vnfId = vnfList.get(vnfsDeletedCount.intValue()) - } - - execution.setVariable("vnfId", vnfId) - utils.log("DEBUG", "need to delete vnfId:" + vnfId, isDebugEnabled) - - utils.log("DEBUG", " ***** Completed prepareVnfAndModulesDelete of DeleteServiceInstanceMacro ***** ", isDebugEnabled) - } catch (Exception ex) { - // try error in method block - String exceptionMessage = "Bpmn error encountered in DeleteServiceInstanceMacro flow. Unexpected Error from method prepareVnfAndModulesDelete() - " + ex.getMessage() - exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) - } - } - - // ******************************* - // Validate Vnf request Section -> increment count - // ******************************* - public void validateVnfDelete (Execution execution) { - def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - - try { - utils.log("DEBUG", " ***** Inside validateVnfDelete of DeleteViprAtmService ***** ", isDebugEnabled) - - String vnfsDeletedCount = execution.getVariable("DELVAS_vnfsDeletedCount") - vnfsDeletedCount++ - - execution.setVariable("DELVAS_vnfsDeletedCount", vnfsDeletedCount) - - utils.log("DEBUG", " ***** Completed validateVnfDelete of DeleteViprAtmService ***** "+" vnf # "+vnfsDeletedCount, isDebugEnabled) - } catch (Exception ex) { - // try error in method block - String exceptionMessage = "Bpmn error encountered in DeleteViprAtmService flow. Unexpected Error from method validateVnfDelete() - " + ex.getMessage() - exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) - } - } - - // ******************************* - // Generate Network request Section - // ******************************* - public void prepareNetworkDelete (Execution execution) { - def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - - try { - utils.log("DEBUG", " ***** Inside prepareNetworkDelete of DeleteViprAtmService ***** ", isDebugEnabled) - - List networkList = execution.getVariable("DELVAS_relatedNetworkIdList") - utils.log("DEBUG", "array networkList from execution: "+ networkList, isDebugEnabled) - - if (networkList == null || networkList.size() < 1){ - networkList = Arrays.asList(execution.getVariable("relatedNetworkIdListString")) - utils.log("DEBUG", "array from string networkList: "+ networkList, isDebugEnabled) - } - - Integer networksDeletedCount = execution.getVariable("DELVAS_networksDeletedCount") - - String networkId = "" - if (networkList.size() > 0) { - networkId = (String) networkList.get(networksDeletedCount.intValue()) - } - - execution.setVariable("networkId", networkId) - utils.log("DEBUG", "need to delete networkId:" + networkId, isDebugEnabled) - - utils.log("DEBUG", " ***** Completed prepareNetworkDelete of DeleteViprAtmService ***** ", isDebugEnabled) - } catch (Exception ex) { - // try error in method block - String exceptionMessage = q"Bpmn error encountered in DeleteViprAtmService flow. Unexpected Error from method prepareNetworkDelete() - " + ex.getMessage() - exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) - } - } - - // ******************************* - // Validate Network request Section - // ******************************* - public void validateNetworkDelete (Execution execution) { - def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - - try { - utils.log("DEBUG", " ***** Inside validateNetworkDelete of DeleteViprAtmService ***** ", isDebugEnabled) - - Integer networksDeletedCount = execution.getVariable("DELVAS_networksDeletedCount") - networksDeletedCount++ - - execution.setVariable("DELVAS_networksDeletedCount", networksDeletedCount) - - utils.log("DEBUG", " ***** Completed validateNetworkDelete of DeleteViprAtmService ***** ", isDebugEnabled) - } catch (Exception ex) { - // try error in method block - String exceptionMessage = "Bpmn error encountered in DeleteViprAtmService flow. Unexpected Error from method validateNetworkDelete() - " + ex.getMessage() - exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) - } - } - - - // ***************************************** - // Prepare Completion request Section - // ***************************************** - public void postProcessResponse (Execution execution) { - def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - utils.log("DEBUG", " ***** Inside postProcessResponse of DeleteViprAtmService ***** ", isDebugEnabled) - - try { - String source = execution.getVariable("source") - String requestId = execution.getVariable("msoRequestId") - - String msoCompletionRequest = - """ - - ${requestId} - DELETE - ${source} - - vIPR ATM Service Instance has been deleted successfully. - BPMN Service Instance macro action: DELETE - """ - - // Format Response - String xmlMsoCompletionRequest = utils.formatXml(msoCompletionRequest) - - utils.logAudit(xmlMsoCompletionRequest) - execution.setVariable("DELVAS_Success", true) - execution.setVariable("DELVAS_CompleteMsoProcessRequest", xmlMsoCompletionRequest) - utils.log("DEBUG", " SUCCESS flow, going to CompleteMsoProcess - " + "\n" + xmlMsoCompletionRequest, isDebugEnabled) - } catch (BpmnError e) { - throw e; - - } catch (Exception ex) { - // try error in method block - String exceptionMessage = "Bpmn error encountered in DeleteServiceInstance flow. Unexpected Error from method postProcessResponse() - " + ex.getMessage() - exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) - } - } - - public void prepareFalloutRequest(Execution execution){ - def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - utils.log("DEBUG", " *** STARTED DeleteViprAtmService prepareFalloutRequest Process *** ", isDebugEnabled) - - try { - WorkflowException wfex = execution.getVariable("WorkflowException") - utils.log("DEBUG", " Incoming Workflow Exception: " + wfex.toString(), isDebugEnabled) - String requestInfo = execution.getVariable("DELVAS_requestInfo") - utils.log("DEBUG", " Incoming Request Info: " + requestInfo, isDebugEnabled) - - String falloutRequest = exceptionUtil.processMainflowsBPMNException(execution, requestInfo) - - execution.setVariable("DELVAS_falloutRequest", falloutRequest) - } catch (Exception ex) { - utils.log("DEBUG", "Error Occured in DeleteViprAtmService prepareFalloutRequest Process " + ex.getMessage(), isDebugEnabled) - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured in DeleteViprAtmService prepareFalloutRequest Process") - } - utils.log("DEBUG", "*** COMPLETED DeleteViprAtmService prepareFalloutRequest Process ***", isDebugEnabled) - } - - - public void sendSyncError (Execution execution) { - def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - utils.log("DEBUG", " ***** Inside sendSyncError() of DeleteServiceInstanceInfra ***** ", isDebugEnabled) - - try { - String errorMessage = "" - if (execution.getVariable("WorkflowException") instanceof WorkflowException) { - WorkflowException wfe = execution.getVariable("WorkflowException") - errorMessage = wfe.getErrorMessage() - } else { - errorMessage = "Sending Sync Error." - } - - String buildworkflowException = - """ - ${errorMessage} - 7000 - """ - - utils.logAudit(buildworkflowException) - sendWorkflowResponse(execution, 500, buildworkflowException) - } catch (Exception ex) { - utils.log("DEBUG", " Sending Sync Error Activity Failed. " + "\n" + ex.getMessage(), isDebugEnabled) - } - } - - public void processJavaException(Execution execution){ - def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - execution.setVariable("prefix",Prefix) - try{ - utils.log("DEBUG", "Caught a Java Exception", isDebugEnabled) - utils.log("DEBUG", "Started processJavaException Method", isDebugEnabled) - utils.log("DEBUG", "Variables List: " + execution.getVariables(), isDebugEnabled) - execution.setVariable("DELVAS_unexpectedError", "Caught a Java Lang Exception") // Adding this line temporarily until this flows error handling gets updated - exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Caught a Java Lang Exception") - }catch(BpmnError b){ - utils.log("ERROR", "Rethrowing MSOWorkflowException", isDebugEnabled) - throw b - }catch(Exception e){ - utils.log("DEBUG", "Caught Exception during processJavaException Method: " + e, isDebugEnabled) - execution.setVariable("DELVAS_unexpectedError", "Exception in processJavaException method") // Adding this line temporarily until this flows error handling gets updated - exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Exception in processJavaException method") - } - utils.log("DEBUG", "Completed processJavaException Method", isDebugEnabled) - } - - +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.bpmn.infrastructure.scripts; + +import groovy.xml.XmlUtil +import groovy.json.* + +import org.openecomp.mso.bpmn.core.json.JsonUtils +import org.openecomp.mso.bpmn.common.scripts.AbstractServiceTaskProcessor +import org.openecomp.mso.bpmn.common.scripts.CatalogDbUtils +import org.openecomp.mso.bpmn.common.scripts.ExceptionUtil +import org.openecomp.mso.bpmn.common.scripts.NetworkUtils +import org.openecomp.mso.bpmn.common.scripts.VidUtils +import org.openecomp.mso.bpmn.core.WorkflowException +import org.openecomp.mso.rest.APIResponse; + + +import java.util.UUID; + +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.runtime.Execution +import org.json.JSONObject; +import org.json.JSONArray; +import org.apache.commons.lang3.* +import org.apache.commons.codec.binary.Base64; +import org.springframework.web.util.UriUtils; + +/** + * This groovy class supports the DeleteViprAtmService.bpmn process. + * + */ +public class DeleteGenericMacroServiceNetworkVnf extends AbstractServiceTaskProcessor { + + String Prefix="DELVAS_" + ExceptionUtil exceptionUtil = new ExceptionUtil() + JsonUtils jsonUtil = new JsonUtils() + VidUtils vidUtils = new VidUtils() + CatalogDbUtils catalogDbUtils = new CatalogDbUtils() + NetworkUtils networkUtils = new NetworkUtils() + + /** + * This method is executed during the preProcessRequest task of the DeleteViprAtmService.bpmn process. + * @param execution + */ + public InitializeProcessVariables(Execution execution){ + /* Initialize all the process variables in this block */ + + execution.setVariable("deleteViprAtmServiceRequest", "") + execution.setVariable("msoRequestId", "") + execution.setVariable("DELVAS_vnfsDeletedCount", 0) + execution.setVariable("DELVAS_vnfsCount", 0) + execution.setVariable("DELVAS_networksCount", 0) + execution.setVariable("DELVAS_networksDeletedCount", 0) + } + + // ************************************************** + // Pre or Prepare Request Section + // ************************************************** + /** + * This method is executed during the preProcessRequest task of the CreateServiceInstance.bpmn process. + * @param execution + */ + public void preProcessRequest (Execution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix",Prefix) + + utils.log("DEBUG", " ***** Inside preProcessRequest DeleteViprAtmService Request ***** ", isDebugEnabled) + + try { + // initialize flow variables + InitializeProcessVariables(execution) + + // check for incoming json message/input + String deleteViprAtmServiceRequest = execution.getVariable("bpmnRequest") + utils.logAudit(deleteViprAtmServiceRequest) + execution.setVariable("deleteViprAtmServiceRequest", deleteViprAtmServiceRequest); + println 'deleteViprAtmServiceRequest - ' + deleteViprAtmServiceRequest + + // extract requestId + String requestId = execution.getVariable("mso-request-id") + execution.setVariable("msoRequestId", requestId) + + String serviceInstanceId = execution.getVariable("serviceInstanceId") + if ((serviceInstanceId == null) || (serviceInstanceId.isEmpty())) { + String dataErrorMessage = " Element 'serviceInstanceId' is missing. " + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) + } + + String requestAction = execution.getVariable("requestAction") + execution.setVariable("requestAction", requestAction) + + String source = jsonUtil.getJsonValue(deleteViprAtmServiceRequest, "requestDetails.requestInfo.source") + if ((source == null) || (source.isEmpty())) { + execution.setVariable("source", "VID") + } else { + execution.setVariable("source", source) + } + + // extract globalSubscriberId + String globalSubscriberId = jsonUtil.getJsonValue(deleteViprAtmServiceRequest, "requestDetails.subscriberInfo.globalSubscriberId") + + // global-customer-id is optional on Delete + + execution.setVariable("globalSubscriberId", globalSubscriberId) + execution.setVariable("globalCustomerId", globalSubscriberId) + + String suppressRollback = jsonUtil.getJsonValue(deleteViprAtmServiceRequest, "requestDetails.requestInfo.suppressRollback") + execution.setVariable("disableRollback", suppressRollback) + utils.log("DEBUG", "Incoming Suppress/Disable Rollback is: " + suppressRollback, isDebugEnabled) + + String productFamilyId = jsonUtil.getJsonValue(deleteViprAtmServiceRequest, "requestDetails.requestInfo.productFamilyId") + execution.setVariable("productFamilyId", productFamilyId) + utils.log("DEBUG", "Incoming productFamilyId is: " + productFamilyId, isDebugEnabled) + + // extract subscriptionServiceType + String subscriptionServiceType = jsonUtil.getJsonValue(deleteViprAtmServiceRequest, "requestDetails.requestParameters.subscriptionServiceType") + execution.setVariable("subscriptionServiceType", subscriptionServiceType) + utils.log("DEBUG", "Incoming subscriptionServiceType is: " + subscriptionServiceType, isDebugEnabled) + + // extract cloud configuration + String lcpCloudRegionId = jsonUtil.getJsonValue(deleteViprAtmServiceRequest, "requestDetails.cloudConfiguration.lcpCloudRegionId") + execution.setVariable("lcpCloudRegionId", lcpCloudRegionId) + utils.log("DEBUG","lcpCloudRegionId: "+ lcpCloudRegionId, isDebugEnabled) + String tenantId = jsonUtil.getJsonValue(deleteViprAtmServiceRequest, "requestDetails.cloudConfiguration.tenantId") + execution.setVariable("tenantId", tenantId) + utils.log("DEBUG","tenantId: "+ tenantId, isDebugEnabled) + + String sdncVersion = "1702" + execution.setVariable("sdncVersion", sdncVersion) + utils.log("DEBUG","sdncVersion: "+ sdncVersion, isDebugEnabled) + + //For Completion Handler & Fallout Handler + String requestInfo = + """ + ${requestId} + DELETE + ${source} + """ + + execution.setVariable("DELVAS_requestInfo", requestInfo) + + //Setting for Generic Sub Flows + execution.setVariable("GENGS_type", "service-instance") + + utils.log("DEBUG", " ***** Completed preProcessRequest DeleteViprAtmService Request ***** ", isDebugEnabled) + + } catch (BpmnError e) { + throw e; + } catch (Exception ex){ + String exceptionMessage = "Bpmn error encountered in DeleteViprAtmService flow. Unexpected from method preProcessRequest() - " + ex.getMessage() + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + } + } + + public void sendSyncResponse (Execution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + + utils.log("DEBUG", " ***** Inside sendSyncResponse of DeleteViprAtmService ***** ", isDebugEnabled) + + try { + String serviceInstanceId = execution.getVariable("serviceInstanceId") + String requestId = execution.getVariable("mso-request-id") + + // RESTResponse (for API Handler (APIH) Reply Task) + String syncResponse ="""{"requestReferences":{"instanceId":"${serviceInstanceId}","requestId":"${requestId}"}}""".trim() + + utils.log("DEBUG", " sendSynchResponse: xmlSyncResponse - " + "\n" + syncResponse, isDebugEnabled) + sendWorkflowResponse(execution, 202, syncResponse) + } catch (Exception ex) { + String exceptionMessage = "Bpmn error encountered in DeleteViprAtmService flow. Unexpected from method sendSyncResponse() - " + ex.getMessage() + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + } + } + + public void prepareServiceInstanceDelete (Execution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + utils.log("DEBUG", " ***** Inside prepareServiceInstanceDelete() of DeleteViprAtmService ***** ", isDebugEnabled) + + try { + + String serviceInstanceId = execution.getVariable("serviceInstanceId") + + // confirm if ServiceInstance was found + if ( !execution.getVariable("GENGS_FoundIndicator") ) + { + String exceptionMessage = "Bpmn error encountered in DeleteViprAtmService flow. Service Instance was not found in AAI by id: " + serviceInstanceId + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + } + + // get variable within incoming json + String deleteViprAtmServiceRequest = execution.getVariable("deleteViprAtmServiceRequest"); + + // get SI extracted by GenericGetService + String serviceInstanceAaiRecord = execution.getVariable("GENGS_service"); + + utils.log("DEBUG", "serviceInstanceAaiRecord: "+serviceInstanceAaiRecord, isDebugEnabled) + + String relationship = "" + try { + relationship = networkUtils.getFirstNodeXml(serviceInstanceAaiRecord, "relationship-list") + } catch (Exception ex) { + //no relationships found + } + utils.log("DEBUG", " relationship string - " + relationship, isDebugEnabled) + + int vnfsCount = 0 + int networksCount = 0 + + if (relationship != null && relationship.length() > 0){ + relationship = relationship.trim().replace("tag0:","").replace(":tag0","") + + // Check if Network TableREf is present, then build a List of network policy + List relatedVnfIdList = networkUtils.getRelatedVnfIdList(relationship) + vnfsCount = relatedVnfIdList.size() + execution.setVariable("DELVAS_vnfsCount", vnfsCount) + utils.log("DEBUG", " DELVAS_vnfsCount : " + vnfsCount, isDebugEnabled) + execution.setVariable("DELVAS_relatedVnfIdList", relatedVnfIdList) + + // Check if Network TableREf is present, then build a List of network policy + List relatedNetworkIdList = networkUtils.getRelatedNetworkIdList(relationship) + networksCount = relatedNetworkIdList.size() + execution.setVariable("DELVAS_networksCount", networksCount) + utils.log("DEBUG", " DELVAS_networksCount : " + networksCount, isDebugEnabled) + execution.setVariable("DELVAS_relatedNetworkIdList", relatedNetworkIdList) + } else { + execution.setVariable("DELVAS_vnfsCount", 0) + utils.log("DEBUG", " DELVAS_vnfsCount : " + vnfsCount, isDebugEnabled) + execution.setVariable("DELVAS_networksCount", 0) + utils.log("DEBUG", " DELVAS_networksCount : " + networksCount, isDebugEnabled) + } + + utils.log("DEBUG", " ***** Completed prepareServiceInstanceDelete() of DeleteViprAtmService ***** ", isDebugEnabled) + } catch (Exception ex) { + sendSyncError(execution) + String exceptionMessage = "Bpmn error encountered in DeleteViprAtmService flow. prepareServiceInstanceDelete() - " + ex.getMessage() + utils.log("DEBUG", exceptionMessage, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + } + } + + + // ******************************* + // + // ******************************* + public void prepareVnfAndModulesDelete (Execution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + + try { + utils.log("DEBUG", " ***** Inside prepareVnfAndModulesDelete of DeleteServiceInstanceMacro ***** ", isDebugEnabled) + + List vnfList = execution.getVariable("DELVAS_relatedVnfIdList") + Integer vnfsDeletedCount = execution.getVariable("DELVAS_vnfsDeletedCount") + String vnfModelInfoString = "" + String vnfId = "" + if (vnfList.size() > 0 ) { + vnfId = vnfList.get(vnfsDeletedCount.intValue()) + } + + execution.setVariable("vnfId", vnfId) + utils.log("DEBUG", "need to delete vnfId:" + vnfId, isDebugEnabled) + + utils.log("DEBUG", " ***** Completed prepareVnfAndModulesDelete of DeleteServiceInstanceMacro ***** ", isDebugEnabled) + } catch (Exception ex) { + // try error in method block + String exceptionMessage = "Bpmn error encountered in DeleteServiceInstanceMacro flow. Unexpected Error from method prepareVnfAndModulesDelete() - " + ex.getMessage() + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + } + } + + // ******************************* + // Validate Vnf request Section -> increment count + // ******************************* + public void validateVnfDelete (Execution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + + try { + utils.log("DEBUG", " ***** Inside validateVnfDelete of DeleteViprAtmService ***** ", isDebugEnabled) + + String vnfsDeletedCount = execution.getVariable("DELVAS_vnfsDeletedCount") + vnfsDeletedCount++ + + execution.setVariable("DELVAS_vnfsDeletedCount", vnfsDeletedCount) + + utils.log("DEBUG", " ***** Completed validateVnfDelete of DeleteViprAtmService ***** "+" vnf # "+vnfsDeletedCount, isDebugEnabled) + } catch (Exception ex) { + // try error in method block + String exceptionMessage = "Bpmn error encountered in DeleteViprAtmService flow. Unexpected Error from method validateVnfDelete() - " + ex.getMessage() + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + } + } + + // ******************************* + // Generate Network request Section + // ******************************* + public void prepareNetworkDelete (Execution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + + try { + utils.log("DEBUG", " ***** Inside prepareNetworkDelete of DeleteViprAtmService ***** ", isDebugEnabled) + + List networkList = execution.getVariable("DELVAS_relatedNetworkIdList") + Integer networksDeletedCount = execution.getVariable("DELVAS_networksDeletedCount") + + String networkId = "" + if (networkList.size() > 0) { + networkId = networkList.get(networksDeletedCount.intValue()) + } + + execution.setVariable("networkId", networkId) + utils.log("DEBUG", "need to delete networkId:" + networkId, isDebugEnabled) + + utils.log("DEBUG", " ***** Completed prepareNetworkDelete of DeleteViprAtmService ***** ", isDebugEnabled) + } catch (Exception ex) { + // try error in method block + String exceptionMessage = q"Bpmn error encountered in DeleteViprAtmService flow. Unexpected Error from method prepareNetworkDelete() - " + ex.getMessage() + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + } + } + + // ******************************* + // Validate Network request Section + // ******************************* + public void validateNetworkDelete (Execution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + + try { + utils.log("DEBUG", " ***** Inside validateNetworkDelete of DeleteViprAtmService ***** ", isDebugEnabled) + + Integer networksDeletedCount = execution.getVariable("DELVAS_networksDeletedCount") + networksDeletedCount++ + + execution.setVariable("DELVAS_networksDeletedCount", networksDeletedCount) + + utils.log("DEBUG", " ***** Completed validateNetworkDelete of DeleteViprAtmService ***** ", isDebugEnabled) + } catch (Exception ex) { + // try error in method block + String exceptionMessage = "Bpmn error encountered in DeleteViprAtmService flow. Unexpected Error from method validateNetworkDelete() - " + ex.getMessage() + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + } + } + + + // ***************************************** + // Prepare Completion request Section + // ***************************************** + public void postProcessResponse (Execution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + utils.log("DEBUG", " ***** Inside postProcessResponse of DeleteViprAtmService ***** ", isDebugEnabled) + + try { + String source = execution.getVariable("source") + String requestId = execution.getVariable("msoRequestId") + + String msoCompletionRequest = + """ + + ${requestId} + DELETE + ${source} + + vIPR ATM Service Instance has been deleted successfully. + BPMN Service Instance macro action: DELETE + """ + + // Format Response + String xmlMsoCompletionRequest = utils.formatXml(msoCompletionRequest) + + utils.logAudit(xmlMsoCompletionRequest) + execution.setVariable("DELVAS_Success", true) + execution.setVariable("DELVAS_CompleteMsoProcessRequest", xmlMsoCompletionRequest) + utils.log("DEBUG", " SUCCESS flow, going to CompleteMsoProcess - " + "\n" + xmlMsoCompletionRequest, isDebugEnabled) + } catch (BpmnError e) { + throw e; + + } catch (Exception ex) { + // try error in method block + String exceptionMessage = "Bpmn error encountered in DeleteServiceInstance flow. Unexpected Error from method postProcessResponse() - " + ex.getMessage() + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + } + } + + public void prepareFalloutRequest(Execution execution){ + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + utils.log("DEBUG", " *** STARTED DeleteViprAtmService prepareFalloutRequest Process *** ", isDebugEnabled) + + try { + WorkflowException wfex = execution.getVariable("WorkflowException") + utils.log("DEBUG", " Incoming Workflow Exception: " + wfex.toString(), isDebugEnabled) + String requestInfo = execution.getVariable("DELVAS_requestInfo") + utils.log("DEBUG", " Incoming Request Info: " + requestInfo, isDebugEnabled) + + String falloutRequest = exceptionUtil.processMainflowsBPMNException(execution, requestInfo) + + execution.setVariable("DELVAS_falloutRequest", falloutRequest) + } catch (Exception ex) { + utils.log("DEBUG", "Error Occured in DeleteViprAtmService prepareFalloutRequest Process " + ex.getMessage(), isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured in DeleteViprAtmService prepareFalloutRequest Process") + } + utils.log("DEBUG", "*** COMPLETED DeleteViprAtmService prepareFalloutRequest Process ***", isDebugEnabled) + } + + + public void sendSyncError (Execution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + utils.log("DEBUG", " ***** Inside sendSyncError() of DeleteServiceInstanceInfra ***** ", isDebugEnabled) + + try { + String errorMessage = "" + if (execution.getVariable("WorkflowException") instanceof WorkflowException) { + WorkflowException wfe = execution.getVariable("WorkflowException") + errorMessage = wfe.getErrorMessage() + } else { + errorMessage = "Sending Sync Error." + } + + String buildworkflowException = + """ + ${errorMessage} + 7000 + """ + + utils.logAudit(buildworkflowException) + sendWorkflowResponse(execution, 500, buildworkflowException) + } catch (Exception ex) { + utils.log("DEBUG", " Sending Sync Error Activity Failed. " + "\n" + ex.getMessage(), isDebugEnabled) + } + } + + public void processJavaException(Execution execution){ + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix",Prefix) + try{ + utils.log("DEBUG", "Caught a Java Exception", isDebugEnabled) + utils.log("DEBUG", "Started processJavaException Method", isDebugEnabled) + utils.log("DEBUG", "Variables List: " + execution.getVariables(), isDebugEnabled) + execution.setVariable("DELVAS_unexpectedError", "Caught a Java Lang Exception") // Adding this line temporarily until this flows error handling gets updated + exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Caught a Java Lang Exception") + }catch(BpmnError b){ + utils.log("ERROR", "Rethrowing MSOWorkflowException", isDebugEnabled) + throw b + }catch(Exception e){ + utils.log("DEBUG", "Caught Exception during processJavaException Method: " + e, isDebugEnabled) + execution.setVariable("DELVAS_unexpectedError", "Exception in processJavaException method") // Adding this line temporarily until this flows error handling gets updated + exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Exception in processJavaException method") + } + utils.log("DEBUG", "Completed processJavaException Method", isDebugEnabled) + } + + } \ No newline at end of file diff --git a/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/DeleteNetworkInstance.groovy b/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/DeleteNetworkInstance.groovy index e18af172de..9e341dafbc 100644 --- a/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/DeleteNetworkInstance.groovy +++ b/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/DeleteNetworkInstance.groovy @@ -1,417 +1,417 @@ -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - MSO - * ================================================================================ - * 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.openecomp.mso.bpmn.infrastructure.scripts; - -import org.openecomp.mso.bpmn.common.scripts.AbstractServiceTaskProcessor -import org.openecomp.mso.bpmn.common.scripts.ExceptionUtil -import org.openecomp.mso.bpmn.common.scripts.NetworkUtils -import org.openecomp.mso.bpmn.common.scripts.VidUtils -import org.openecomp.mso.bpmn.core.WorkflowException -import org.openecomp.mso.bpmn.core.json.JsonUtils; -import org.openecomp.mso.rest.APIResponse -import java.util.UUID; -import org.camunda.bpm.engine.delegate.BpmnError -import org.camunda.bpm.engine.runtime.Execution -import org.apache.commons.lang3.* -import org.apache.commons.codec.binary.Base64; -import org.springframework.web.util.UriUtils -import groovy.xml.XmlUtil -import groovy.json.* - -public class DeleteNetworkInstance extends AbstractServiceTaskProcessor { - String Prefix="DELNI_" - String groovyClassName = "DeleteNetworkInstance" - ExceptionUtil exceptionUtil = new ExceptionUtil() - JsonUtils jsonUtil = new JsonUtils() - VidUtils vidUtils = new VidUtils(this) - NetworkUtils networkUtils = new NetworkUtils() - - - public InitializeProcessVariables(Execution execution){ - - execution.setVariable(Prefix + "Success", false) - - execution.setVariable(Prefix + "CompleteMsoProcessRequest", "") - execution.setVariable(Prefix + "FalloutHandlerRequest", "") - execution.setVariable(Prefix + "isSilentSuccess", false) - - } - - // ************************************************** - // Pre or Prepare Request Section - // ************************************************** - - public void preProcessRequest (Execution execution) { - def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - execution.setVariable("prefix",Prefix) - - utils.log("DEBUG", " ***** Inside preProcessRequest() of " + groovyClassName + " ***** ", isDebugEnabled) - - try { - // initialize flow variables - InitializeProcessVariables(execution) - - String sdncVersion = execution.getVariable("sdncVersion") - if (sdncVersion == null || sdncVersion == '1610') { - // 'a-la-cart' default, sdncVersion = '1610' - execution.setVariable("sdncVersion", "1610") - String bpmnRequest = execution.getVariable("bpmnRequest") - // set 'disableRollback' - if (bpmnRequest != null) { - String disableRollback = jsonUtil.getJsonValue(bpmnRequest, "requestDetails.requestInfo.suppressRollback") - if (disableRollback != null) { - execution.setVariable("disableRollback", disableRollback) - utils.log("DEBUG", "Received 'suppressRollback': " + disableRollback , isDebugEnabled) - } else { - execution.setVariable("disableRollback", false) - } - utils.log("DEBUG", " Set 'disableRollback' : " + execution.getVariable("disableRollback") , isDebugEnabled) - } else { - String dataErrorMessage = " Invalid 'bpmnRequest' request." - utils.log("DEBUG", dataErrorMessage, isDebugEnabled) - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) - } - - } else { - // 'macro' test ONLY, sdncVersion = '1702' - utils.log("DEBUG", " 'disableRollback' : " + execution.getVariable("disableRollback") , isDebugEnabled) - } - - // get/set 'msoRequestId' and 'mso-request-id' - String requestId = execution.getVariable("msoRequestId") - if (requestId != null) { - execution.setVariable("mso-request-id", requestId) - } else { - requestId = execution.getVariable("mso-request-id") - } - execution.setVariable(Prefix + "requestId", requestId) - - // get/set 'requestId' - if (execution.getVariable("requestId") == null) { - execution.setVariable("requestId", requestId) - } - - // set action to "DELETE" - execution.setVariable("action", "DELETE") - - //Place holder for additional code. - - // TODO ??? - // userParams??? 1) pre-loads indicator, 2) 'auto-activation' - // Tag/Value parameters - // - // Map: 'networkInputParams': 'auto-activation'' - // Sample format? - // "requestParameters": { - // "userParams": [ - // { - // "name": "someUserParam1", - // "value": "someValue1" - // } - // ] - // } - // - // String userParams = //use json util to extract "userParams"// - // execution.setVariable("networkInputParams", userParams) - // else: execution.setVariable("networkInputParams", null) - // - - - } catch (Exception ex){ - sendSyncError(execution) - String exceptionMessage = "Exception Encountered in " + groovyClassName + ", PreProcessRequest() - " + ex.getMessage() - utils.log("DEBUG", exceptionMessage, isDebugEnabled) - exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) - - } - - } - - public void getNetworkModelInfo (Execution execution) { - def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - execution.setVariable("prefix", Prefix) - - utils.log("DEBUG", " ***** Inside getNetworkModelInfo() of DeleteNetworkInstance ***** ", isDebugEnabled) - - try { - - // "networkModelInfo" is expected to be sent - String networkModelInfo = execution.getVariable("networkModelInfo") - utils.log("DEBUG", " networkModelInfo - " + networkModelInfo, isDebugEnabled) - - - } catch (Exception ex) { - sendSyncError(execution) - String exceptionMessage = "Bpmn error encountered in DeleteNetworkInstance flow. getNetworkModelInfo() - " + ex.getMessage() - utils.log("DEBUG", exceptionMessage, isDebugEnabled) - exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) - - } - - } - - public void sendSyncResponse (Execution execution) { - def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - execution.setVariable("prefix",Prefix) - - utils.log("DEBUG", " ***** Inside sendSyncResponse() of DeleteNetworkInstance ***** ", isDebugEnabled) - - try { - String requestId = execution.getVariable("mso-request-id") - String serviceInstanceId = execution.getVariable("serviceInstanceId") - - // RESTResponse (for API Handler (APIH) Reply Task) - String deleteNetworkRestRequest = """{"requestReferences":{"instanceId":"${serviceInstanceId}","requestId":"${requestId}"}}""".trim() - - utils.log("DEBUG", " sendSyncResponse to APIH - " + "\n" + deleteNetworkRestRequest, isDebugEnabled) - - sendWorkflowResponse(execution, 202, deleteNetworkRestRequest) - - } catch (Exception ex) { - // caught exception - String exceptionMessage = "Exception Encountered in DeleteNetworkInstance, sendSyncResponse() - " + ex.getMessage() - utils.log("DEBUG", exceptionMessage, isDebugEnabled) - exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) - - } - - } - - public void prepareCompletion (Execution execution) { - def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - execution.setVariable("prefix",Prefix) - - utils.log("DEBUG", " ***** Inside prepareCompletion() of CreateNetworkInstance ***** ", isDebugEnabled) - - try { - - String requestId = execution.getVariable("mso-request-id") - String source = execution.getVariable(Prefix + "source") - - String msoCompletionRequest = - """ - - ${requestId} - DELETE - VID - - Network has been deleted successfully. - BPMN Network action: DELETE - """ - - // Format Response - String xmlMsoCompletionRequest = utils.formatXml(msoCompletionRequest) - - // normal path - execution.setVariable(Prefix + "CompleteMsoProcessRequest", xmlMsoCompletionRequest) - utils.log("DEBUG", " Overall SUCCESS Response going to CompleteMsoProcess - " + "\n" + xmlMsoCompletionRequest, isDebugEnabled) - - } catch (Exception ex) { - String exceptionMessage = " Bpmn error encountered in CreateNetworkInstance flow. prepareCompletion() - " + ex.getMessage() - utils.log("DEBUG", exceptionMessage, isDebugEnabled) - exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) - - } - - - } - - public void prepareDBRequestError (Execution execution) { - def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - execution.setVariable("prefix", Prefix) - - try { - utils.log("DEBUG", " ***** Inside prepareDBRequestError of DeleteNetworkInstance ***** ", isDebugEnabled) - - WorkflowException wfe = execution.getVariable("WorkflowException") - String statusMessage = wfe.getErrorMessage() - String requestId = execution.getVariable(Prefix +"requestId") - - String dbRequest = - """ - - - - ${requestId} - BPMN - ${statusMessage} - - FAILED - - <network-outputs xmlns="http://org.openecomp/mso/infra/vnf-request/v1" xmlns:aetgt="http://org.openecomp/mso/infra/vnf-request/v1" xmlns:rest="http://schemas.activebpel.org/REST/2007/12/01/aeREST.xsd"/> - - - """ - - execution.setVariable(Prefix + "deleteDBRequest", dbRequest) - utils.log("DEBUG", " DB Adapter Request - " + "\n" + dbRequest, isDebugEnabled) - - } catch (Exception ex) { - // caught exception - String exceptionMessage = "Bpmn error encountered in DeleteNetworkInstance, prepareDBRequestError() - " + ex.getMessage() - logError(exceptionMessage) - utils.log("DEBUG", exceptionMessage, isDebugEnabled) - exceptionUtil.buildWorkflowException(execution, 7000, exceptionMessage) - - } - - } - - // ************************************************** - // Post or Validate Response Section - // ************************************************** - - public void postProcessResponse (Execution execution) { - def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - execution.setVariable("prefix", Prefix) - - utils.log("DEBUG", " ***** Inside postProcessResponse() of DeleteNetworkInstance ***** ", isDebugEnabled) - - try { - if (execution.getVariable("CMSO_ResponseCode") == "200") { - execution.setVariable(Prefix + "Success", true) - utils.log("DEBUG", " ***** DeleteNetworkInstance Success ***** ", isDebugEnabled) - // Place holder for additional code. - - } else { - execution.setVariable(Prefix + "Success", false) - utils.log("DEBUG", " ***** DeleteNetworkInstance Failed in CompletionMsoProces flow!. ***** ", isDebugEnabled) - - } - - - } catch (Exception ex) { - String exceptionMessage = " Bpmn error encountered in DeleteNetworkInstance flow. postProcessResponse() - " + ex.getMessage() - utils.log("DEBUG", exceptionMessage, isDebugEnabled) - exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) - - } - - } - - - // ******************************* - // Build Error Section - // ******************************* - - // Prepare for FalloutHandler - public void buildErrorResponse (Execution execution) { - def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - execution.setVariable("prefix", Prefix) - - utils.log("DEBUG", " ***** Prepare for FalloutHandler. FAILURE - prepare request for sub-process FalloutHandler. *****", isDebugEnabled) - - String dbReturnCode = execution.getVariable(Prefix + "dbReturnCode") - utils.log("DEBUG", " ***** DB Update Response Code : " + dbReturnCode, isDebugEnabled) - utils.log("DEBUG", " ***** DB Update Response String: " + '\n' + execution.getVariable(Prefix + "deleteDBResponse"), isDebugEnabled) - - String falloutHandlerRequest = "" - String requestId = execution.getVariable("mso-request-id") - String source = execution.getVariable(Prefix + "source") - execution.setVariable(Prefix + "Success", false) - try { - WorkflowException wfe = execution.getVariable("WorkflowException") - String errorCode = String.valueOf(wfe.getErrorCode()) - String errorMessage = wfe.getErrorMessage() - - falloutHandlerRequest = - """ - - ${requestId} - DELETE - ${source} - - - ${errorMessage} - ${errorCode} - - """ - - utils.logAudit(falloutHandlerRequest) - execution.setVariable(Prefix + "FalloutHandlerRequest", falloutHandlerRequest) - utils.log("ERROR", " Overall Error Response going to FalloutHandler: " + "\n" + falloutHandlerRequest, isDebugEnabled) - - } catch (Exception ex) { - // caught exception - String exceptionMessage = "Bpmn error encountered in DeleteNetworkInstance, buildErrorResponse() - " + ex.getMessage() - utils.log("DEBUG", exceptionMessage, isDebugEnabled) - falloutHandlerRequest = - """ - - ${requestId} - DELEtE - ${source} - - - ${exceptionMessage} - 9999 - - """ - execution.setVariable(Prefix + "FalloutHandlerRequest", falloutHandlerRequest) - utils.log("DEBUG", " Overall Error Response going to FalloutHandler: " + "\n" + falloutHandlerRequest, isDebugEnabled) - } - } - - - public void sendSyncError (Execution execution) { - def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - execution.setVariable("prefix", Prefix) - - try { - String requestId = execution.getVariable("mso-request-id") - String serviceInstanceId = execution.getVariable("serviceInstanceId") - - // RESTResponse (for API Handler (APIH) Reply Task) - String deleteNetworkRestError = """{"requestReferences":{"instanceId":"${serviceInstanceId}","requestId":"${requestId}"}}""".trim() - - utils.log("DEBUG", " sendSyncResponse to APIH - " + "\n" + deleteNetworkRestError, isDebugEnabled) - - sendWorkflowResponse(execution, 500, deleteNetworkRestError) - - } catch (Exception ex) { - utils.log("DEBUG", " Sending Sync Error Activity Failed - DeleteNetworkInstance, sendSyncError(): " + "\n" + ex.getMessage(), isDebugEnabled) - } - } - - public void processJavaException(Execution execution){ - def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - execution.setVariable("prefix",Prefix) - try{ - utils.log("DEBUG", "Caught a Java Exception", isDebugEnabled) - utils.log("DEBUG", "Started processJavaException Method", isDebugEnabled) - utils.log("DEBUG", "Variables List: " + execution.getVariables(), isDebugEnabled) - execution.setVariable("UnexpectedError", "Caught a Java Lang Exception") // Adding this line temporarily until this flows error handling gets updated - exceptionUtil.buildWorkflowException(execution, 500, "Caught a Java Lang Exception") - - }catch(Exception e){ - utils.log("DEBUG", "Caught Exception during processJavaException Method: " + e, isDebugEnabled) - execution.setVariable("UnexpectedError", "Exception in processJavaException method") // Adding this line temporarily until this flows error handling gets updated - exceptionUtil.buildWorkflowException(execution, 500, "Exception in processJavaException method") - } - utils.log("DEBUG", "Completed processJavaException Method of " + Prefix, isDebugEnabled) - } - -} +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.bpmn.infrastructure.scripts; + +import org.openecomp.mso.bpmn.common.scripts.AbstractServiceTaskProcessor +import org.openecomp.mso.bpmn.common.scripts.ExceptionUtil +import org.openecomp.mso.bpmn.common.scripts.NetworkUtils +import org.openecomp.mso.bpmn.common.scripts.VidUtils +import org.openecomp.mso.bpmn.core.WorkflowException +import org.openecomp.mso.bpmn.core.json.JsonUtils; +import org.openecomp.mso.rest.APIResponse +import java.util.UUID; +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.runtime.Execution +import org.apache.commons.lang3.* +import org.apache.commons.codec.binary.Base64; +import org.springframework.web.util.UriUtils +import groovy.xml.XmlUtil +import groovy.json.* + +public class DeleteNetworkInstance extends AbstractServiceTaskProcessor { + String Prefix="DELNI_" + String groovyClassName = "DeleteNetworkInstance" + ExceptionUtil exceptionUtil = new ExceptionUtil() + JsonUtils jsonUtil = new JsonUtils() + VidUtils vidUtils = new VidUtils(this) + NetworkUtils networkUtils = new NetworkUtils() + + + public InitializeProcessVariables(Execution execution){ + + execution.setVariable(Prefix + "Success", false) + + execution.setVariable(Prefix + "CompleteMsoProcessRequest", "") + execution.setVariable(Prefix + "FalloutHandlerRequest", "") + execution.setVariable(Prefix + "isSilentSuccess", false) + + } + + // ************************************************** + // Pre or Prepare Request Section + // ************************************************** + + public void preProcessRequest (Execution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix",Prefix) + + utils.log("DEBUG", " ***** Inside preProcessRequest() of " + groovyClassName + " ***** ", isDebugEnabled) + + try { + // initialize flow variables + InitializeProcessVariables(execution) + + String sdncVersion = execution.getVariable("sdncVersion") + if (sdncVersion == null || sdncVersion == '1610') { + // 'a-la-cart' default, sdncVersion = '1610' + execution.setVariable("sdncVersion", "1610") + String bpmnRequest = execution.getVariable("bpmnRequest") + // set 'disableRollback' + if (bpmnRequest != null) { + String disableRollback = jsonUtil.getJsonValue(bpmnRequest, "requestDetails.requestInfo.suppressRollback") + if (disableRollback != null) { + execution.setVariable("disableRollback", disableRollback) + utils.log("DEBUG", "Received 'suppressRollback': " + disableRollback , isDebugEnabled) + } else { + execution.setVariable("disableRollback", false) + } + utils.log("DEBUG", " Set 'disableRollback' : " + execution.getVariable("disableRollback") , isDebugEnabled) + } else { + String dataErrorMessage = " Invalid 'bpmnRequest' request." + utils.log("DEBUG", dataErrorMessage, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) + } + + } else { + // 'macro' test ONLY, sdncVersion = '1702' + utils.log("DEBUG", " 'disableRollback' : " + execution.getVariable("disableRollback") , isDebugEnabled) + } + + // get/set 'msoRequestId' and 'mso-request-id' + String requestId = execution.getVariable("msoRequestId") + if (requestId != null) { + execution.setVariable("mso-request-id", requestId) + } else { + requestId = execution.getVariable("mso-request-id") + } + execution.setVariable(Prefix + "requestId", requestId) + + // get/set 'requestId' + if (execution.getVariable("requestId") == null) { + execution.setVariable("requestId", requestId) + } + + // set action to "DELETE" + execution.setVariable("action", "DELETE") + + //Place holder for additional code. + + // TODO ??? + // userParams??? 1) pre-loads indicator, 2) 'auto-activation' + // Tag/Value parameters + // + // Map: 'networkInputParams': 'auto-activation'' + // Sample format? + // "requestParameters": { + // "userParams": [ + // { + // "name": "someUserParam1", + // "value": "someValue1" + // } + // ] + // } + // + // String userParams = //use json util to extract "userParams"// + // execution.setVariable("networkInputParams", userParams) + // else: execution.setVariable("networkInputParams", null) + // + + + } catch (Exception ex){ + sendSyncError(execution) + String exceptionMessage = "Exception Encountered in " + groovyClassName + ", PreProcessRequest() - " + ex.getMessage() + utils.log("DEBUG", exceptionMessage, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + + } + + } + + public void getNetworkModelInfo (Execution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix", Prefix) + + utils.log("DEBUG", " ***** Inside getNetworkModelInfo() of DeleteNetworkInstance ***** ", isDebugEnabled) + + try { + + // "networkModelInfo" is expected to be sent + String networkModelInfo = execution.getVariable("networkModelInfo") + utils.log("DEBUG", " networkModelInfo - " + networkModelInfo, isDebugEnabled) + + + } catch (Exception ex) { + sendSyncError(execution) + String exceptionMessage = "Bpmn error encountered in DeleteNetworkInstance flow. getNetworkModelInfo() - " + ex.getMessage() + utils.log("DEBUG", exceptionMessage, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + + } + + } + + public void sendSyncResponse (Execution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix",Prefix) + + utils.log("DEBUG", " ***** Inside sendSyncResponse() of DeleteNetworkInstance ***** ", isDebugEnabled) + + try { + String requestId = execution.getVariable("mso-request-id") + String serviceInstanceId = execution.getVariable("serviceInstanceId") + + // RESTResponse (for API Handler (APIH) Reply Task) + String deleteNetworkRestRequest = """{"requestReferences":{"instanceId":"${serviceInstanceId}","requestId":"${requestId}"}}""".trim() + + utils.log("DEBUG", " sendSyncResponse to APIH - " + "\n" + deleteNetworkRestRequest, isDebugEnabled) + + sendWorkflowResponse(execution, 202, deleteNetworkRestRequest) + + } catch (Exception ex) { + // caught exception + String exceptionMessage = "Exception Encountered in DeleteNetworkInstance, sendSyncResponse() - " + ex.getMessage() + utils.log("DEBUG", exceptionMessage, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + + } + + } + + public void prepareCompletion (Execution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix",Prefix) + + utils.log("DEBUG", " ***** Inside prepareCompletion() of CreateNetworkInstance ***** ", isDebugEnabled) + + try { + + String requestId = execution.getVariable("mso-request-id") + String source = execution.getVariable(Prefix + "source") + + String msoCompletionRequest = + """ + + ${requestId} + DELETE + VID + + Network has been deleted successfully. + BPMN Network action: DELETE + """ + + // Format Response + String xmlMsoCompletionRequest = utils.formatXml(msoCompletionRequest) + + // normal path + execution.setVariable(Prefix + "CompleteMsoProcessRequest", xmlMsoCompletionRequest) + utils.log("DEBUG", " Overall SUCCESS Response going to CompleteMsoProcess - " + "\n" + xmlMsoCompletionRequest, isDebugEnabled) + + } catch (Exception ex) { + String exceptionMessage = " Bpmn error encountered in CreateNetworkInstance flow. prepareCompletion() - " + ex.getMessage() + utils.log("DEBUG", exceptionMessage, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + + } + + + } + + public void prepareDBRequestError (Execution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix", Prefix) + + try { + utils.log("DEBUG", " ***** Inside prepareDBRequestError of DeleteNetworkInstance ***** ", isDebugEnabled) + + WorkflowException wfe = execution.getVariable("WorkflowException") + String statusMessage = wfe.getErrorMessage() + String requestId = execution.getVariable(Prefix +"requestId") + + String dbRequest = + """ + + + + ${requestId} + BPMN + ${statusMessage} + + FAILED + + <network-outputs xmlns="http://org.openecomp/mso/infra/vnf-request/v1" xmlns:aetgt="http://org.openecomp/mso/infra/vnf-request/v1" xmlns:rest="http://schemas.activebpel.org/REST/2007/12/01/aeREST.xsd"/> + + + """ + + execution.setVariable(Prefix + "deleteDBRequest", dbRequest) + utils.log("DEBUG", " DB Adapter Request - " + "\n" + dbRequest, isDebugEnabled) + + } catch (Exception ex) { + // caught exception + String exceptionMessage = "Bpmn error encountered in DeleteNetworkInstance, prepareDBRequestError() - " + ex.getMessage() + logError(exceptionMessage) + utils.log("DEBUG", exceptionMessage, isDebugEnabled) + exceptionUtil.buildWorkflowException(execution, 7000, exceptionMessage) + + } + + } + + // ************************************************** + // Post or Validate Response Section + // ************************************************** + + public void postProcessResponse (Execution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix", Prefix) + + utils.log("DEBUG", " ***** Inside postProcessResponse() of DeleteNetworkInstance ***** ", isDebugEnabled) + + try { + if (execution.getVariable("CMSO_ResponseCode") == "200") { + execution.setVariable(Prefix + "Success", true) + utils.log("DEBUG", " ***** DeleteNetworkInstance Success ***** ", isDebugEnabled) + // Place holder for additional code. + + } else { + execution.setVariable(Prefix + "Success", false) + utils.log("DEBUG", " ***** DeleteNetworkInstance Failed in CompletionMsoProces flow!. ***** ", isDebugEnabled) + + } + + + } catch (Exception ex) { + String exceptionMessage = " Bpmn error encountered in DeleteNetworkInstance flow. postProcessResponse() - " + ex.getMessage() + utils.log("DEBUG", exceptionMessage, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + + } + + } + + + // ******************************* + // Build Error Section + // ******************************* + + // Prepare for FalloutHandler + public void buildErrorResponse (Execution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix", Prefix) + + utils.log("DEBUG", " ***** Prepare for FalloutHandler. FAILURE - prepare request for sub-process FalloutHandler. *****", isDebugEnabled) + + String dbReturnCode = execution.getVariable(Prefix + "dbReturnCode") + utils.log("DEBUG", " ***** DB Update Response Code : " + dbReturnCode, isDebugEnabled) + utils.log("DEBUG", " ***** DB Update Response String: " + '\n' + execution.getVariable(Prefix + "deleteDBResponse"), isDebugEnabled) + + String falloutHandlerRequest = "" + String requestId = execution.getVariable("mso-request-id") + String source = execution.getVariable(Prefix + "source") + execution.setVariable(Prefix + "Success", false) + try { + WorkflowException wfe = execution.getVariable("WorkflowException") + String errorCode = String.valueOf(wfe.getErrorCode()) + String errorMessage = wfe.getErrorMessage() + + falloutHandlerRequest = + """ + + ${requestId} + DELETE + ${source} + + + ${errorMessage} + ${errorCode} + + """ + + utils.logAudit(falloutHandlerRequest) + execution.setVariable(Prefix + "FalloutHandlerRequest", falloutHandlerRequest) + utils.log("ERROR", " Overall Error Response going to FalloutHandler: " + "\n" + falloutHandlerRequest, isDebugEnabled) + + } catch (Exception ex) { + // caught exception + String exceptionMessage = "Bpmn error encountered in DeleteNetworkInstance, buildErrorResponse() - " + ex.getMessage() + utils.log("DEBUG", exceptionMessage, isDebugEnabled) + falloutHandlerRequest = + """ + + ${requestId} + DELEtE + ${source} + + + ${exceptionMessage} + 9999 + + """ + execution.setVariable(Prefix + "FalloutHandlerRequest", falloutHandlerRequest) + utils.log("DEBUG", " Overall Error Response going to FalloutHandler: " + "\n" + falloutHandlerRequest, isDebugEnabled) + } + } + + + public void sendSyncError (Execution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix", Prefix) + + try { + String requestId = execution.getVariable("mso-request-id") + String serviceInstanceId = execution.getVariable("serviceInstanceId") + + // RESTResponse (for API Handler (APIH) Reply Task) + String deleteNetworkRestError = """{"requestReferences":{"instanceId":"${serviceInstanceId}","requestId":"${requestId}"}}""".trim() + + utils.log("DEBUG", " sendSyncResponse to APIH - " + "\n" + deleteNetworkRestError, isDebugEnabled) + + sendWorkflowResponse(execution, 500, deleteNetworkRestError) + + } catch (Exception ex) { + utils.log("DEBUG", " Sending Sync Error Activity Failed - DeleteNetworkInstance, sendSyncError(): " + "\n" + ex.getMessage(), isDebugEnabled) + } + } + + public void processJavaException(Execution execution){ + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix",Prefix) + try{ + utils.log("DEBUG", "Caught a Java Exception", isDebugEnabled) + utils.log("DEBUG", "Started processJavaException Method", isDebugEnabled) + utils.log("DEBUG", "Variables List: " + execution.getVariables(), isDebugEnabled) + execution.setVariable("UnexpectedError", "Caught a Java Lang Exception") // Adding this line temporarily until this flows error handling gets updated + exceptionUtil.buildWorkflowException(execution, 500, "Caught a Java Lang Exception") + + }catch(Exception e){ + utils.log("DEBUG", "Caught Exception during processJavaException Method: " + e, isDebugEnabled) + execution.setVariable("UnexpectedError", "Exception in processJavaException method") // Adding this line temporarily until this flows error handling gets updated + exceptionUtil.buildWorkflowException(execution, 500, "Exception in processJavaException method") + } + utils.log("DEBUG", "Completed processJavaException Method of " + Prefix, isDebugEnabled) + } + +} diff --git a/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/DeleteVfModuleInfra.groovy b/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/DeleteVfModuleInfra.groovy index 93890be2af..f8b3b4739f 100644 --- a/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/DeleteVfModuleInfra.groovy +++ b/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/DeleteVfModuleInfra.groovy @@ -41,7 +41,7 @@ import org.openecomp.mso.bpmn.core.json.JsonUtils; public class DeleteVfModuleInfra extends AbstractServiceTaskProcessor { - + ExceptionUtil exceptionUtil = new ExceptionUtil() JsonUtils jsonUtil = new JsonUtils() /** @@ -78,20 +78,20 @@ public class DeleteVfModuleInfra extends AbstractServiceTaskProcessor { logDebug('Entered ' + method, isDebugLogEnabled) execution.setVariable("isVidRequest", "false") initProcessVariables(execution) - + def prefix = execution.getVariable('prefix') - + def incomingRequest = execution.getVariable('bpmnRequest') - + utils.log("DEBUG", "Incoming Infra Request: " + incomingRequest, isDebugLogEnabled) utils.logAudit("DeleteVfModule Infra incoming Request: " + incomingRequest) - + // check if request is xml or json try { def jsonSlurper = new JsonSlurper() Map reqMap = jsonSlurper.parseText(incomingRequest) utils.log("DEBUG", " Request is in JSON format.", isDebugLogEnabled) - + def serviceInstanceId = execution.getVariable('serviceInstanceId') utils.log("DEBUG", "serviceInstanceId is: " + serviceInstanceId, isDebugLogEnabled) def vnfId = execution.getVariable('vnfId') @@ -100,16 +100,16 @@ public class DeleteVfModuleInfra extends AbstractServiceTaskProcessor { execution.setVariable("cloudConfiguration", cloudConfiguration) utils.log("DEBUG", "CloudConfiguration is: " + cloudConfiguration, isDebugLogEnabled) def vfModuleModelInfo = jsonUtil.getJsonValue(incomingRequest, "requestDetails.modelInfo") - + execution.setVariable("vfModuleModelInfo", vfModuleModelInfo) utils.log("DEBUG", "VfModuleModelInfo is: " + vfModuleModelInfo, isDebugLogEnabled) - + def vidUtils = new VidUtils(this) - + String requestInXmlFormat = vidUtils.createXmlVfModuleRequest(execution, reqMap, 'DELETE_VF_MODULE', serviceInstanceId) - + utils.log("DEBUG", " Request in XML format: " + requestInXmlFormat, isDebugLogEnabled) - + try { // Catalog DB headers Authorization String basicAuthValueDB = execution.getVariable("URN_mso_adapters_db_auth") @@ -126,31 +126,31 @@ public class DeleteVfModuleInfra extends AbstractServiceTaskProcessor { execution.setVariable(prefix + 'Request', requestInXmlFormat) execution.setVariable(prefix+'vnfId', vnfId) execution.setVariable("isVidRequest", "true") - + } catch(groovy.json.JsonException je) { utils.log("DEBUG", " Request is not in JSON format.", isDebugLogEnabled) - workflowException(execution, "Invalid request format", 400) - + exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Internal Error - During PreProcess Request") + } catch(Exception e) { String restFaultMessage = e.getMessage() utils.log("ERROR", " Exception Encountered - " + "\n" + restFaultMessage, isDebugLogEnabled) - workflowException(execution, restFaultMessage, 400) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Internal Error - During PreProcess Request") } - - + + try { - + String request = validateRequest(execution) execution.setVariable('DeleteVfModuleRequest', request) utils.logAudit("DeleteVfModuleInfra Request: " + request) - + def requestInfo = getRequiredNodeXml(execution, request, 'request-info') execution.setVariable('DELVfModI_requestInfo', requestInfo) execution.setVariable('DELVfModI_requestId', getRequiredNodeText(execution, requestInfo, 'request-id')) execution.setVariable('DELVfModI_source', getNodeTextForce(requestInfo, 'source')) - + def vnfInputs = getRequiredNodeXml(execution, request, 'vnf-inputs') execution.setVariable('DELVfModI_vnfInputs', vnfInputs) execution.setVariable('DELVfModI_vnfId', getRequiredNodeText(execution, vnfInputs, 'vnf-id')) @@ -158,16 +158,16 @@ public class DeleteVfModuleInfra extends AbstractServiceTaskProcessor { execution.setVariable('DELVfModI_vfModuleName', getNodeTextForce(vnfInputs, 'vf-module-name')) execution.setVariable('DELVfModI_tenantId', getRequiredNodeText(execution, vnfInputs, 'tenant-id')) execution.setVariable('DELVfModI_volumeGroupId', getNodeTextForce(vnfInputs, 'volume-group-id')) - + def vnfParams = utils.getNodeXml(request, 'vnf-params') execution.setVariable('DELVfModI_vnfParams', vnfParams) - + logDebug('Exited ' + method, isDebugLogEnabled) } catch (BpmnError e) { throw e; } catch (Exception e) { logError('Caught exception in ' + method, e) - createWorkflowException(execution, 1002, 'Error in preProcessRequest(): ' + e.getMessage()) + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in preProcessRequest(): ' + e.getMessage()) } } @@ -182,7 +182,7 @@ public class DeleteVfModuleInfra extends AbstractServiceTaskProcessor { ')' def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') logDebug('Entered ' + method, isDebugLogEnabled) - + try { def requestInfo = execution.getVariable('DELVfModI_requestInfo') def requestId = execution.getVariable('DELVfModI_requestId') @@ -195,11 +195,11 @@ public class DeleteVfModuleInfra extends AbstractServiceTaskProcessor { if (startTime.isEmpty()) { startTime = System.currentTimeMillis() } - + // RESTResponse (for API Handler (APIH) Reply Task) def vfModuleId = execution.getVariable('DELVfModI_vfModuleId') String synchResponse = """{"requestReferences":{"instanceId":"${vfModuleId}","requestId":"${requestId}"}}""".trim() - + utils.logAudit("DeleteVfModuleInfra Synch Response: " + synchResponse) sendWorkflowResponse(execution, 200, synchResponse) @@ -208,10 +208,10 @@ public class DeleteVfModuleInfra extends AbstractServiceTaskProcessor { throw e; } catch (Exception e) { logError('Caught exception in ' + method, e) - createWorkflowException(execution, 1002, 'Error in sendResponse(): ' + e.getMessage()) + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in sendResponse(): ' + e.getMessage()) } } - + /** * Currently passing the entire DELETE_VF_MODULE vnf-request to DoDeleteVfModule. * 'DeleteVfModuleRequest' is now being set in preProcessRequest(). @@ -233,10 +233,10 @@ public class DeleteVfModuleInfra extends AbstractServiceTaskProcessor { throw e; } catch (Exception e) { logError('Caught exception in ' + method, e) - createWorkflowException(execution, 1002, 'Error in prepDoDeleteVfModule(): ' + e.getMessage()) + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in prepDoDeleteVfModule(): ' + e.getMessage()) } } - + /** * Prepare the DB update to add an entry for the Vf Module request. * @@ -257,19 +257,19 @@ public class DeleteVfModuleInfra extends AbstractServiceTaskProcessor { def volumeGroupId = execution.getVariable('DELVfModI_volumeGroupId') String updateInfraRequest = """ - - - - - ${requestId} - BPMN - COMPLETED - 100 - - - - """ + + + + ${requestId} + BPMN + COMPLETED + 100 + + + + """ updateInfraRequest = utils.formatXml(updateInfraRequest) execution.setVariable('DELVfModI_updateInfraRequest', updateInfraRequest) @@ -281,7 +281,7 @@ public class DeleteVfModuleInfra extends AbstractServiceTaskProcessor { throw e; } catch (Exception e) { logError('Caught exception in ' + method, e) - createWorkflowException(execution, 1002, 'Error in prepInfraRequest(): ' + e.getMessage()) + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in prepInfraRequest(): ' + e.getMessage()) } } @@ -303,18 +303,18 @@ public class DeleteVfModuleInfra extends AbstractServiceTaskProcessor { def request = execution.getVariable("DeleteVfModuleRequest") def requestInfo = utils.getNodeXml(request, 'request-info', false) def action = utils.getNodeText1(requestInfo, "action") - + String content = """ - ${requestInfo} - - Vf Module has been deleted successfully. - BPMN - """ - + ${requestInfo} + + Vf Module has been deleted successfully. + BPMN + """ + content = utils.formatXml(content) logDebug(resultVar + ' = ' + System.lineSeparator() + content, isDebugLogEnabled) utils.logAudit("DeleteVfModule Infra Completion Handler Request: " + content) @@ -325,7 +325,7 @@ public class DeleteVfModuleInfra extends AbstractServiceTaskProcessor { throw e; } catch (Exception e) { logError('Caught exception in ' + method, e) - createWorkflowException(execution, 2000, 'Internal Error') + exceptionUtil.buildAndThrowWorkflowException(execution, 2000, 'Internal Error') } } @@ -342,7 +342,7 @@ public class DeleteVfModuleInfra extends AbstractServiceTaskProcessor { ')' def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') logDebug('Entered ' + method, isDebugLogEnabled) - + try { def prefix = execution.getVariable('prefix') def request = execution.getVariable("DeleteVfModuleRequest") @@ -360,13 +360,13 @@ public class DeleteVfModuleInfra extends AbstractServiceTaskProcessor { xmlns:reqtype="http://org.openecomp/mso/request/types/v1" xmlns:msoservtypes="http://org.openecomp/mso/request/types/v1" xmlns:structuredtypes="http://org.openecomp/mso/structured/types/v1"> - ${requestInfo} - - ${encErrorResponseMsg} - ${errorResponseCode} - - - """ + ${requestInfo} + + ${encErrorResponseMsg} + ${errorResponseCode} + + + """ content = utils.formatXml(content) utils.logAudit("DeleteVfModuleInfra Fallout Handler Request: " + content) logDebug(resultVar + ' = ' + System.lineSeparator() + content, isDebugLogEnabled) @@ -377,7 +377,7 @@ public class DeleteVfModuleInfra extends AbstractServiceTaskProcessor { throw e; } catch (Exception e) { logError('Caught exception in ' + method, e) - createWorkflowException(execution, 2000, 'Internal Error') + exceptionUtil.buildWorkflowException(execution, 2000, 'Internal Error') } } -} \ No newline at end of file +} diff --git a/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/DeleteVfModuleVolumeInfraV1.groovy b/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/DeleteVfModuleVolumeInfraV1.groovy index 0a3af33d49..7bda7b4fe3 100644 --- a/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/DeleteVfModuleVolumeInfraV1.groovy +++ b/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/DeleteVfModuleVolumeInfraV1.groovy @@ -1,560 +1,560 @@ -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - MSO - * ================================================================================ - * 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.openecomp.mso.bpmn.infrastructure.scripts; - -import groovy.json.JsonSlurper - -import java.util.concurrent.ExecutionException; - -import org.springframework.web.util.UriUtils -import org.camunda.bpm.engine.delegate.BpmnError -import org.camunda.bpm.engine.runtime.Execution -import org.apache.commons.lang3.* -import org.openecomp.mso.bpmn.common.scripts.AaiUtil; -import org.openecomp.mso.bpmn.common.scripts.AbstractServiceTaskProcessor; -import org.openecomp.mso.bpmn.common.scripts.ExceptionUtil; -import org.openecomp.mso.bpmn.common.scripts.VidUtils; -import org.openecomp.mso.bpmn.core.WorkflowException -import org.openecomp.mso.rest.APIResponse - -/** - * This groovy class supports the DeleteVfModuleVolume.bpmn process. - */ -public class DeleteVfModuleVolumeInfraV1 extends AbstractServiceTaskProcessor { - - private XmlParser xmlParser = new XmlParser() - /** - * This method is executed during the preProcessRequest task of the DeleteVfModuleVolume.bpmn process. - * @param execution - */ - public InitializeProcessVariables(Execution execution){ - execution.setVariable('prefix', 'DELVfModVol_') - execution.setVariable("DELVfModVol_volumeRequest", null) - execution.setVariable('DELVfModVol_requestInfo', null) - execution.setVariable('DELVfModVol_requestId', null) - execution.setVariable('DELVfModVol_source', null) - execution.setVariable('DELVfModVol_volumeInputs', null) - execution.setVariable('DELVfModVol_volumeOutputs', null) - execution.setVariable('DELVfModVol_volumeGroupId', null) - execution.setVariable('DELVfModVol_vnfType', null) - execution.setVariable('DELVfModVol_serviceId', null) - execution.setVariable('DELVfModVol_cloudRegion', null) - execution.setVariable('DELVfModVol_tenantId', null) - execution.setVariable('DELVfModVol_volumeParams', null) - execution.setVariable('DELVfModVol_volumeGroupHeatStackId', null) - execution.setVariable('DELVfModVol_volumeGroupTenantId', null) - execution.setVariable("DELVfModVol_queryAAIVolGrpResponse", null) - execution.setVariable('DELVfModVol_messageId', null) - execution.setVariable('DELVfModVol_deleteVnfARequest', null) - execution.setVariable('DELVfModVol_updateInfraRequest', null) - execution.setVariable('DELVfModVol_CompleteMsoProcessRequest', null) - execution.setVariable('DELVfModVol_WorkflowException', null) - execution.setVariable('DELVfModVol_TransactionSuccessIndicator', false) - execution.setVariable("DELVfModVol_isErrorMessageException", false) - execution.setVariable('DELVfModVol_syncResponseSent', false) - } - - /** - * Perform initial processing, such as request validation, initialization of variables, etc. - * * @param execution - */ - public void preProcessRequest (Execution execution) { - def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - preProcessRequest(execution, isDebugEnabled) - } - - /** - * This method is executed during the preProcessRequest task of the DeleteVfModuleVolume.bpmn process. - * @param execution - */ - public void preProcessRequest (Execution execution, isDebugLogEnabled) { - - InitializeProcessVariables(execution) - - String createVolumeIncoming = validateRequest(execution) - utils.logAudit(createVolumeIncoming) - - // check if request is xml or json - try { - def jsonSlurper = new JsonSlurper() - Map reqMap = jsonSlurper.parseText(createVolumeIncoming) - utils.log("DEBUG", " Request is in JSON format.", isDebugLogEnabled) - - def serviceInstanceId = execution.getVariable('serviceInstanceId') - def volumeGroupId = execution.getVariable('volumeGroupId') - def vidUtils = new VidUtils(this) - createVolumeIncoming = vidUtils.createXmlVolumeRequest(reqMap, 'DELETE_VF_MODULE_VOL', serviceInstanceId, volumeGroupId) - execution.setVariable("DELVfModVol_isVidRequest", true) - } - catch(groovy.json.JsonException je) { - utils.log("DEBUG", " Request is in XML format.", isDebugLogEnabled) - // assume request is in XML format - proceed as usual to process XML request - } - - String request = utils.getNodeXml(createVolumeIncoming, "volume-request").drop(38).trim().replace("tag0:","").replace(":tag0","") - execution.setVariable("DELVfModVol_volumeRequest", request) - - def requestInfo = getRequiredNodeXml(execution, request, 'request-info') - execution.setVariable('DELVfModVol_requestInfo', requestInfo) - String requestId = execution.getVariable("mso-request-id") - if (requestId == null || requestId == "") { - requestId = getRequiredNodeText(execution, requestInfo, 'request-id') - } - execution.setVariable('DELVfModVol_requestId', requestId) - execution.setVariable('DELVfModVol_source', getNodeTextForce(requestInfo, 'source')) - - def volumeInputs = getRequiredNodeXml(execution, request, 'volume-inputs') - execution.setVariable('DELVfModVol_volumeInputs', volumeInputs) - execution.setVariable('DELVfModVol_volumeGroupId', getRequiredNodeText(execution, volumeInputs, 'volume-group-id')) - execution.setVariable('DELVfModVol_vnfType', getRequiredNodeText(execution, volumeInputs, 'vnf-type')) - execution.setVariable('DELVfModVol_serviceId', getRequiredNodeText(execution, volumeInputs, 'service-id')) - execution.setVariable('DELVfModVol_tenantId', getRequiredNodeText(execution, volumeInputs, 'tenant-id')) - execution.setVariable('DELVfModVol_messageId', UUID.randomUUID().toString()) - execution.setVariable('DELVfModVol_volumeOutputs', utils.getNodeXml(request, 'volume-outputs', false)) - execution.setVariable('DELVfModVol_volumeParams', utils.getNodeXml(request, 'volume-params')) - execution.setVariable('DELVfModVol_cloudRegion', utils.getNodeText1(request, 'aic-cloud-region')) - - try { - // Catalog DB headers Authorization - String basicAuthValueDB = execution.getVariable("URN_mso_adapters_db_auth") - utils.log("DEBUG", " Obtained BasicAuth userid password for Catalog DB adapter: " + basicAuthValueDB, isDebugLogEnabled) - - def encodedString = utils.getBasicAuth(basicAuthValueDB, execution.getVariable("URN_mso_msoKey")) - execution.setVariable("BasicAuthHeaderValueDB",encodedString) - } catch (IOException ex) { - String dataErrorMessage = " Unable to encode Catalog DB user/password string - " + ex.getMessage() - utils.log("DEBUG", dataErrorMessage, isDebugLogEnabled) - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) - } - - logDebug('Request: ' + createVolumeIncoming, isDebugLogEnabled) - } - - public void sendSyncResponse (Execution execution, isDebugEnabled) { - - String volumeRequest = execution.getVariable("DELVfModVol_volumeRequest") - utils.log("DEBUG", " DELVfModVol_volumeRequest - " + "\n" + volumeRequest, isDebugEnabled) - // RESTResponse (for API Handler (APIH) Reply Task) - String deleteVolumeRequest = - """ - - ${volumeRequest} - - """.trim() - - def isVidRequest = execution.getVariable('DELVfModVol_isVidRequest') - def syncResponse = '' - - if(isVidRequest) { - def serviceInstanceId = execution.getVariable('serviceInstanceId') - def volumeGroupId = execution.getVariable('volumeGroupId') - def requestId = execution.getVariable('DELVfModVol_requestId') - syncResponse = """{"requestReferences":{"instanceId":"${volumeGroupId}","requestId":"${requestId}"}}""".trim() - } - else { - syncResponse = utils.formatXml(deleteVolumeRequest) - } - - execution.setVariable('DELVfModVol_syncResponseSent', true) - - sendWorkflowResponse(execution, 200, syncResponse) - } - - - public void sendSyncError (Execution execution, isDebugEnabled) { - WorkflowException we = execution.getVariable('WorkflowException') - def errorCode = we?.getErrorCode() - def errorMessage = we?.getErrorMessage() - //default to 400 since only invalid request will trigger this method - sendWorkflowResponse(execution, 400, errorMessage) - } - - - public void callRESTQueryAAICloudRegion (Execution execution, isDebugEnabled) { - - String cloudRegion = execution.getVariable('DELVfModVol_cloudRegion') - - String aai_endpoint = execution.getVariable("URN_aai_endpoint") - AaiUtil aaiUtil = new AaiUtil(this) - String aai_uri = aaiUtil.getCloudInfrastructureCloudRegionUri(execution) - String queryCloudRegionRequest = "${aai_endpoint}${aai_uri}/" + cloudRegion - utils.logAudit(queryCloudRegionRequest) - execution.setVariable("DELVfModVol_queryCloudRegionRequest", queryCloudRegionRequest) - utils.log("DEBUG", " DELVfModVol_queryCloudRegionRequest - " + "\n" + queryCloudRegionRequest, isDebugEnabled) - - cloudRegion = aaiUtil.getAAICloudReqion(execution, queryCloudRegionRequest, "PO", cloudRegion) - - ExceptionUtil exceptionUtil = new ExceptionUtil() - - if ((cloudRegion != "ERROR")) { - if(execution.getVariable("DELVfModVol_queryCloudRegionReturnCode") == "404"){ - execution.setVariable("DELVfModVol_aicCloudRegion", "AAIAIC25") - }else{ - execution.setVariable("DELVfModVol_aicCloudRegion", cloudRegion) - } - execution.setVariable("DELVfModVol_cloudRegion", cloudRegion) - execution.setVariable("DELVfModVol_isCloudRegionGood", true) - - } else { - utils.log("DEBUG", "AAI Query Cloud Region Unsuccessful.", isDebugEnabled) - execution.setVariable("DELVfModVol_isCloudRegionGood", false) - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "AAI Query Cloud Region Unsuccessful. Return Code: " + execution.getVariable("DELVfModVol_queryCloudRegionReturnCode")) - } - - utils.log("DEBUG", " is Cloud Region Good: " + execution.getVariable("DELVfModVol_isCloudRegionGood"), isDebugEnabled) - } - - /** - * Query volume group by id - * @param execution - */ - public void queryAAIForVolumeGroup(Execution execution, isDebugLogEnabled) { - - ExceptionUtil exceptionUtil = new ExceptionUtil() - - def volumeGroupId = execution.getVariable('DELVfModVol_volumeGroupId') - if(volumeGroupId == null) { - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, 'volume-group-id is not provided in the request') - throw new Exception('volume-group-id is not provided in the request') - } - String cloudRegion = execution.getVariable('DELVfModVol_aicCloudRegion') - - AaiUtil aaiUtil = new AaiUtil(this) - String aaiEndpoint = aaiUtil.getCloudInfrastructureCloudRegionEndpoint(execution) - String queryAAIVolumeGroupRequest = aaiEndpoint + '/' + URLEncoder.encode(cloudRegion, "UTF-8") + "/volume-groups/volume-group/" + UriUtils.encode(volumeGroupId, "UTF-8") - - utils.logAudit('Query AAI volume group by ID: ' + queryAAIVolumeGroupRequest) - logDebug('Query AAI volume group by ID: ' + queryAAIVolumeGroupRequest, isDebugLogEnabled) - - APIResponse response = aaiUtil.executeAAIGetCall(execution, queryAAIVolumeGroupRequest) - - String returnCode = response.getStatusCode() - String aaiResponseAsString = response.getResponseBodyAsString() - aaiResponseAsString = StringEscapeUtils.unescapeXml(aaiResponseAsString) - - utils.logAudit("AAI query volume group by id return code: " + returnCode) - utils.logAudit("AAI query volume group by id response: " + aaiResponseAsString) - - execution.setVariable("DELVfModVol_queryAAIVolGrpResponse", aaiResponseAsString) - - if (returnCode=='200' || returnCode == '204') { - - def heatStackId = getNodeTextForce(aaiResponseAsString, 'heat-stack-id') - execution.setVariable('DELVfModVol_volumeGroupHeatStackId', heatStackId) - - if(hasVfModuleRelationship(aaiResponseAsString)){ - utils.log("DEBUG", 'Volume Group ' + volumeGroupId + ' currently in use', isDebugLogEnabled) - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Volume Group ${volumeGroupId} currently in use - found vf-module relationship.") - } - - def volumeGroupTenantId = getTenantIdFromVolumeGroup(aaiResponseAsString) - if (volumeGroupTenantId == null) { - utils.log("DEBUG", "Could not find Tenant Id element in Volume Group with Volume Group Id ${volumeGroupId}", isDebugLogEnabled) - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Could not find Tenant Id element in Volume Group with Volume Group Id ${volumeGroupId}") - } - - execution.setVariable('DELVfModVol_volumeGroupTenantId', volumeGroupTenantId) - logDebug('Received Tenant Id ' + volumeGroupTenantId + ' from AAI for Volume Group with Volume Group Id ' + volumeGroupId , isDebugLogEnabled) - } - else { - if (returnCode=='404') { - utils.log("DEBUG", "Volume Group ${volumeGroupId} not found in AAI", isDebugLogEnabled) - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Volume Group ${volumeGroupId} not found in AAI. Response code: 404") - } - else { - WorkflowException aWorkflowException = exceptionUtil.MapAAIExceptionToWorkflowException(aaiResponseAsString, execution) - throw new BpmnError("MSOWorkflowException") - } - } - } - - /** - * Extract the Tenant Id from the Volume Group information returned by AAI. - * - * @param volumeGroupXml Volume Group XML returned by AAI. - * @return the Tenant Id extracted from the Volume Group information. 'null' is returned if - * the Tenant Id is missing or could not otherwise be extracted. - */ - private String getTenantIdFromVolumeGroup(String volumeGroupXml) { - def Node volumeGroupNode = xmlParser.parseText(volumeGroupXml) - def Node relationshipList = utils.getChildNode(volumeGroupNode, 'relationship-list') - if (relationshipList != null) { - def NodeList relationships = utils.getIdenticalChildren(relationshipList, 'relationship') - for (Node relationship in relationships) { - def Node relatedTo = utils.getChildNode(relationship, 'related-to') - if ((relatedTo != null) && (relatedTo.text().equals('tenant'))) { - def NodeList relationshipDataList = utils.getIdenticalChildren(relationship, 'relationship-data') - for (Node relationshipData in relationshipDataList) { - def Node relationshipKey = utils.getChildNode(relationshipData, 'relationship-key') - if ((relationshipKey != null) && (relationshipKey.text().equals('tenant.tenant-id'))) { - def Node relationshipValue = utils.getChildNode(relationshipData, 'relationship-value') - if (relationshipValue != null) { - return relationshipValue.text() - } - } - } - } - } - } - return null - } - - private boolean hasVnfRelationship(String volumeGroupXml) { - def Node volumeGroupNode = xmlParser.parseText(volumeGroupXml) - def Node relationshipList = utils.getChildNode(volumeGroupNode, 'relationship-list') - if (relationshipList != null) { - def NodeList relationships = utils.getIdenticalChildren(relationshipList, 'relationship') - for (Node relationship in relationships) { - def Node relatedTo = utils.getChildNode(relationship, 'related-to') - if ((relatedTo != null) && (relatedTo.text().equals('generic-vnf'))) { - def Node relatedLink = utils.getChildNode(relationship, 'related-link') - if (relatedLink !=null && relatedLink.text() != null){ - return true - } - } - } - } - return false - } - - private boolean hasVfModuleRelationship(String volumeGroupXml) { - def Node volumeGroupNode = xmlParser.parseText(volumeGroupXml) - def Node relationshipList = utils.getChildNode(volumeGroupNode, 'relationship-list') - if (relationshipList != null) { - def NodeList relationships = utils.getIdenticalChildren(relationshipList, 'relationship') - for (Node relationship in relationships) { - def Node relatedTo = utils.getChildNode(relationship, 'related-to') - if ((relatedTo != null) && (relatedTo.text().equals('vf-module'))) { - def Node relatedLink = utils.getChildNode(relationship, 'related-link') - if (relatedLink !=null && relatedLink.text() != null){ - return true - } - } - } - } - return false - } - - public void prepareVnfAdapterDeleteRequest(Execution execution, isDebugLogEnabled) { - def cloudRegion = execution.getVariable('DELVfModVol_cloudRegion') - def tenantId = execution.getVariable('DELVfModVol_tenantId') - def volumeGroupId = execution.getVariable('DELVfModVol_volumeGroupId') - def volumeGroupHeatStackId = execution.getVariable('DELVfModVol_volumeGroupHeatStackId') - def requestId = execution.getVariable('DELVfModVol_requestId') - def serviceId = execution.getVariable('DELVfModVol_serviceId') - - def messageId = execution.getVariable('DELVfModVol_messageId') - def notificationUrl = createCallbackURL(execution, "VNFAResponse", messageId) - def useQualifiedHostName = execution.getVariable("URN_mso_use_qualified_host") - if ('true'.equals(useQualifiedHostName)) { - notificationUrl = utils.getQualifiedHostNameForCallback(notificationUrl) - } - - String vnfAdapterRestRequest = """ - - ${cloudRegion} - ${tenantId} - ${volumeGroupId} - ${volumeGroupHeatStackId} - true - - ${requestId} - ${serviceId} - - ${messageId} - ${notificationUrl} - - """ - vnfAdapterRestRequest = utils.formatXml(vnfAdapterRestRequest) - execution.setVariable('DELVfModVol_deleteVnfARequest', vnfAdapterRestRequest) - logDebug('Request for VNFAdapter Rest:\n' + vnfAdapterRestRequest, isDebugLogEnabled) - } - - - public void deleteVolGrpId(Execution execution, isDebugEnabled) { - - // get variables - String queryAAIVolGrpIdResponse = execution.getVariable("DELVfModVol_queryAAIVolGrpResponse") - String groupId = utils.getNodeText(queryAAIVolGrpIdResponse, "volume-group-id") - String resourceVersion = utils.getNodeText(queryAAIVolGrpIdResponse, "resource-version") - String messageId = execution.getVariable('DELVfModVol_messageId') - String cloudRegion = execution.getVariable('DELVfModVol_aicCloudRegion') - - AaiUtil aaiUtil = new AaiUtil(this) - String aaiEndpoint = aaiUtil.getCloudInfrastructureCloudRegionEndpoint(execution) - String deleteAAIVolumeGrpIdRequest = aaiEndpoint + '/' + URLEncoder.encode(cloudRegion, "UTF-8") + "/volume-groups/volume-group/" + UriUtils.encode(groupId, "UTF-8") - - if(resourceVersion !=null){ - deleteAAIVolumeGrpIdRequest = deleteAAIVolumeGrpIdRequest +'?resource-version=' + UriUtils.encode(resourceVersion, 'UTF-8') - } - - utils.logAudit('Delete AAI volume group : ' + deleteAAIVolumeGrpIdRequest) - utils.log("DEBUG", "Delete AAI volume group : " + deleteAAIVolumeGrpIdRequest, isDebugEnabled) - - APIResponse response = aaiUtil.executeAAIDeleteCall(execution, deleteAAIVolumeGrpIdRequest) - - String returnCode = response.getStatusCode() - String aaiResponseAsString = response.getResponseBodyAsString() - aaiResponseAsString = StringEscapeUtils.unescapeXml(aaiResponseAsString) - - utils.logAudit("AAI delete volume group return code: " + returnCode) - utils.logAudit("AAI delete volume group response: " + aaiResponseAsString) - - ExceptionUtil exceptionUtil = new ExceptionUtil() - if (returnCode=='200' || (returnCode == '204')) { - utils.log("DEBUG", "Volume group $groupId deleted.", isDebugEnabled) - } else { - if (returnCode=='404') { - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Volume group $groupId not found for delete in AAI Response code: 404") - } else { - WorkflowException aWorkflowException = exceptionUtil.MapAAIExceptionToWorkflowException(aaiResponseAsString, execution) - throw new BpmnError("MSOWorkflowException") - } - } - } - - - public void prepareDBRequest (Execution execution, isDebugLogEnabled) { - - WorkflowException workflowExceptionObj = execution.getVariable("WorkflowException") - - def requestId = execution.getVariable('DELVfModVol_requestId') - def volOutputs = execution.getVariable('DELVfModVol_volumeOutputs') - def statusMessage = "VolumeGroup successfully deleted" - def progress = "100" - def requestStatus = "COMPLETE" - - if (workflowExceptionObj != null) { - statusMessage = (workflowExceptionObj.getErrorMessage()).replace("&", "&").replace("<", "<").replace(">", ">") - execution.setVariable("DELVfModVol_WorkflowExceptionMessage", statusMessage) - execution.setVariable("DELVfModVol_WorkflowExceptionCode", workflowExceptionObj.getErrorCode()) - requestStatus = "FAILURE" - progress = "" - } - - String updateInfraRequest = """ - - - - - ${requestId} - BPMN - ${statusMessage} - ${requestStatus} - ${progress} - ${volOutputs} - - - - """ - - updateInfraRequest = utils.formatXml(updateInfraRequest) - execution.setVariable('DELVfModVol_updateInfraRequest', updateInfraRequest) - logDebug('Request for Update Infra Request:\n' + updateInfraRequest, isDebugLogEnabled) - - } - - - public void prepareCompletionHandlerRequest (Execution execution, isDebugLogEnabled) { - def requestId = execution.getVariable("mso-request-id") - def source = execution.getVariable("DELVfModVol_source") - - String msoCompletionRequest = - """ - - ${requestId} - DELETE - ${source} - - Volume Group has been deleted successfully. - BPMN VF Module Volume action: DELETE - """ - - String xmlMsoCompletionRequest = utils.formatXml(msoCompletionRequest) - execution.setVariable('DELVfModVol_CompleteMsoProcessRequest', xmlMsoCompletionRequest) - utils.log("DEBUG", " Overall SUCCESS Response going to CompleteMsoProcess - " + "\n" + xmlMsoCompletionRequest, isDebugLogEnabled) - - } - - - - public void prepareFalloutHandler (Execution execution, isDebugEnabled) { - - execution.setVariable("DELVfModVol_Success", false) - String requestId = execution.getVariable("DELVfModVol_requestId") - String source = execution.getVariable("DELVfModVol_source") - - WorkflowException workflowExceptionObj = execution.getVariable("WorkflowException") - def errorMessage = workflowExceptionObj.getErrorMessage() - def errorCode = workflowExceptionObj.getErrorCode() - - String falloutHandlerRequest = - """ - - ${requestId} - DELETE - ${source} - - - ${errorMessage} - ${errorCode} - - """ - - // Format Response - String xmlHandlerRequest = utils.formatXml(falloutHandlerRequest) - utils.logAudit(xmlHandlerRequest) - - execution.setVariable("DELVfModVol_FalloutHandlerRequest", xmlHandlerRequest) - utils.log("ERROR", " Overall Error Response going to FalloutHandler: " + "\n" + xmlHandlerRequest, isDebugEnabled) - - } - - - /** - * Create a WorkflowException for the error case where the Tenant Id from - * AAI did not match the Tenant Id in the incoming request. - * - * @param execution The flow's execution instance. - */ - public void handleTenantIdMismatch(Execution execution, isDebugLogEnabled) { - - def volumeGroupId = execution.getVariable('DELVfModVol_volumeGroupId') - def aicCloudRegion = execution.getVariable('DELVfModVol_aicCloudRegion') - def tenantId = execution.getVariable('DELVfModVol_tenantId') - def volumeGroupTenantId = execution.getVariable('DELVfModVol_volumeGroupTenantId') - - def String errorMessage = 'TenantId ' + tenantId + ' in incoming request does not match Tenant Id ' + volumeGroupTenantId + - ' retrieved from AAI for Volume Group Id ' + volumeGroupId - - logError('Error in DeleteVfModuleVolume: ' + errorMessage) - - ExceptionUtil exceptionUtil = new ExceptionUtil() - exceptionUtil.buildWorkflowException(execution, 5000, errorMessage) - - } - -} +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.bpmn.infrastructure.scripts; + +import groovy.json.JsonSlurper + +import java.util.concurrent.ExecutionException; + +import org.springframework.web.util.UriUtils +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.runtime.Execution +import org.apache.commons.lang3.* +import org.openecomp.mso.bpmn.common.scripts.AaiUtil; +import org.openecomp.mso.bpmn.common.scripts.AbstractServiceTaskProcessor; +import org.openecomp.mso.bpmn.common.scripts.ExceptionUtil; +import org.openecomp.mso.bpmn.common.scripts.VidUtils; +import org.openecomp.mso.bpmn.core.WorkflowException +import org.openecomp.mso.rest.APIResponse + +/** + * This groovy class supports the DeleteVfModuleVolume.bpmn process. + */ +public class DeleteVfModuleVolumeInfraV1 extends AbstractServiceTaskProcessor { + + private XmlParser xmlParser = new XmlParser() + /** + * This method is executed during the preProcessRequest task of the DeleteVfModuleVolume.bpmn process. + * @param execution + */ + public InitializeProcessVariables(Execution execution){ + execution.setVariable('prefix', 'DELVfModVol_') + execution.setVariable("DELVfModVol_volumeRequest", null) + execution.setVariable('DELVfModVol_requestInfo', null) + execution.setVariable('DELVfModVol_requestId', null) + execution.setVariable('DELVfModVol_source', null) + execution.setVariable('DELVfModVol_volumeInputs', null) + execution.setVariable('DELVfModVol_volumeOutputs', null) + execution.setVariable('DELVfModVol_volumeGroupId', null) + execution.setVariable('DELVfModVol_vnfType', null) + execution.setVariable('DELVfModVol_serviceId', null) + execution.setVariable('DELVfModVol_cloudRegion', null) + execution.setVariable('DELVfModVol_tenantId', null) + execution.setVariable('DELVfModVol_volumeParams', null) + execution.setVariable('DELVfModVol_volumeGroupHeatStackId', null) + execution.setVariable('DELVfModVol_volumeGroupTenantId', null) + execution.setVariable("DELVfModVol_queryAAIVolGrpResponse", null) + execution.setVariable('DELVfModVol_messageId', null) + execution.setVariable('DELVfModVol_deleteVnfARequest', null) + execution.setVariable('DELVfModVol_updateInfraRequest', null) + execution.setVariable('DELVfModVol_CompleteMsoProcessRequest', null) + execution.setVariable('DELVfModVol_WorkflowException', null) + execution.setVariable('DELVfModVol_TransactionSuccessIndicator', false) + execution.setVariable("DELVfModVol_isErrorMessageException", false) + execution.setVariable('DELVfModVol_syncResponseSent', false) + } + + /** + * Perform initial processing, such as request validation, initialization of variables, etc. + * * @param execution + */ + public void preProcessRequest (Execution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + preProcessRequest(execution, isDebugEnabled) + } + + /** + * This method is executed during the preProcessRequest task of the DeleteVfModuleVolume.bpmn process. + * @param execution + */ + public void preProcessRequest (Execution execution, isDebugLogEnabled) { + + InitializeProcessVariables(execution) + + String createVolumeIncoming = validateRequest(execution) + utils.logAudit(createVolumeIncoming) + + // check if request is xml or json + try { + def jsonSlurper = new JsonSlurper() + Map reqMap = jsonSlurper.parseText(createVolumeIncoming) + utils.log("DEBUG", " Request is in JSON format.", isDebugLogEnabled) + + def serviceInstanceId = execution.getVariable('serviceInstanceId') + def volumeGroupId = execution.getVariable('volumeGroupId') + def vidUtils = new VidUtils(this) + createVolumeIncoming = vidUtils.createXmlVolumeRequest(reqMap, 'DELETE_VF_MODULE_VOL', serviceInstanceId, volumeGroupId) + execution.setVariable("DELVfModVol_isVidRequest", true) + } + catch(groovy.json.JsonException je) { + utils.log("DEBUG", " Request is in XML format.", isDebugLogEnabled) + // assume request is in XML format - proceed as usual to process XML request + } + + String request = utils.getNodeXml(createVolumeIncoming, "volume-request").drop(38).trim().replace("tag0:","").replace(":tag0","") + execution.setVariable("DELVfModVol_volumeRequest", request) + + def requestInfo = getRequiredNodeXml(execution, request, 'request-info') + execution.setVariable('DELVfModVol_requestInfo', requestInfo) + String requestId = execution.getVariable("mso-request-id") + if (requestId == null || requestId == "") { + requestId = getRequiredNodeText(execution, requestInfo, 'request-id') + } + execution.setVariable('DELVfModVol_requestId', requestId) + execution.setVariable('DELVfModVol_source', getNodeTextForce(requestInfo, 'source')) + + def volumeInputs = getRequiredNodeXml(execution, request, 'volume-inputs') + execution.setVariable('DELVfModVol_volumeInputs', volumeInputs) + execution.setVariable('DELVfModVol_volumeGroupId', getRequiredNodeText(execution, volumeInputs, 'volume-group-id')) + execution.setVariable('DELVfModVol_vnfType', getRequiredNodeText(execution, volumeInputs, 'vnf-type')) + execution.setVariable('DELVfModVol_serviceId', utils.getNodeText1(volumeInputs, 'service-id')) + execution.setVariable('DELVfModVol_tenantId', getRequiredNodeText(execution, volumeInputs, 'tenant-id')) + execution.setVariable('DELVfModVol_messageId', UUID.randomUUID().toString()) + execution.setVariable('DELVfModVol_volumeOutputs', utils.getNodeXml(request, 'volume-outputs', false)) + execution.setVariable('DELVfModVol_volumeParams', utils.getNodeXml(request, 'volume-params')) + execution.setVariable('DELVfModVol_cloudRegion', utils.getNodeText1(request, 'aic-cloud-region')) + + try { + // Catalog DB headers Authorization + String basicAuthValueDB = execution.getVariable("URN_mso_adapters_db_auth") + utils.log("DEBUG", " Obtained BasicAuth userid password for Catalog DB adapter: " + basicAuthValueDB, isDebugLogEnabled) + + def encodedString = utils.getBasicAuth(basicAuthValueDB, execution.getVariable("URN_mso_msoKey")) + execution.setVariable("BasicAuthHeaderValueDB",encodedString) + } catch (IOException ex) { + String dataErrorMessage = " Unable to encode Catalog DB user/password string - " + ex.getMessage() + utils.log("DEBUG", dataErrorMessage, isDebugLogEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) + } + + logDebug('Request: ' + createVolumeIncoming, isDebugLogEnabled) + } + + public void sendSyncResponse (Execution execution, isDebugEnabled) { + + String volumeRequest = execution.getVariable("DELVfModVol_volumeRequest") + utils.log("DEBUG", " DELVfModVol_volumeRequest - " + "\n" + volumeRequest, isDebugEnabled) + // RESTResponse (for API Handler (APIH) Reply Task) + String deleteVolumeRequest = + """ + + ${volumeRequest} + + """.trim() + + def isVidRequest = execution.getVariable('DELVfModVol_isVidRequest') + def syncResponse = '' + + if(isVidRequest) { + def serviceInstanceId = execution.getVariable('serviceInstanceId') + def volumeGroupId = execution.getVariable('volumeGroupId') + def requestId = execution.getVariable('DELVfModVol_requestId') + syncResponse = """{"requestReferences":{"instanceId":"${volumeGroupId}","requestId":"${requestId}"}}""".trim() + } + else { + syncResponse = utils.formatXml(deleteVolumeRequest) + } + + execution.setVariable('DELVfModVol_syncResponseSent', true) + + sendWorkflowResponse(execution, 200, syncResponse) + } + + + public void sendSyncError (Execution execution, isDebugEnabled) { + WorkflowException we = execution.getVariable('WorkflowException') + def errorCode = we?.getErrorCode() + def errorMessage = we?.getErrorMessage() + //default to 400 since only invalid request will trigger this method + sendWorkflowResponse(execution, 400, errorMessage) + } + + + public void callRESTQueryAAICloudRegion (Execution execution, isDebugEnabled) { + + String cloudRegion = execution.getVariable('DELVfModVol_cloudRegion') + + String aai_endpoint = execution.getVariable("URN_aai_endpoint") + AaiUtil aaiUtil = new AaiUtil(this) + String aai_uri = aaiUtil.getCloudInfrastructureCloudRegionUri(execution) + String queryCloudRegionRequest = "${aai_endpoint}${aai_uri}/" + cloudRegion + utils.logAudit(queryCloudRegionRequest) + execution.setVariable("DELVfModVol_queryCloudRegionRequest", queryCloudRegionRequest) + utils.log("DEBUG", " DELVfModVol_queryCloudRegionRequest - " + "\n" + queryCloudRegionRequest, isDebugEnabled) + + cloudRegion = aaiUtil.getAAICloudReqion(execution, queryCloudRegionRequest, "PO", cloudRegion) + + ExceptionUtil exceptionUtil = new ExceptionUtil() + + if ((cloudRegion != "ERROR")) { + if(execution.getVariable("DELVfModVol_queryCloudRegionReturnCode") == "404"){ + execution.setVariable("DELVfModVol_aicCloudRegion", "AAIAIC25") + }else{ + execution.setVariable("DELVfModVol_aicCloudRegion", cloudRegion) + } + execution.setVariable("DELVfModVol_cloudRegion", cloudRegion) + execution.setVariable("DELVfModVol_isCloudRegionGood", true) + + } else { + utils.log("DEBUG", "AAI Query Cloud Region Unsuccessful.", isDebugEnabled) + execution.setVariable("DELVfModVol_isCloudRegionGood", false) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "AAI Query Cloud Region Unsuccessful. Return Code: " + execution.getVariable("DELVfModVol_queryCloudRegionReturnCode")) + } + + utils.log("DEBUG", " is Cloud Region Good: " + execution.getVariable("DELVfModVol_isCloudRegionGood"), isDebugEnabled) + } + + /** + * Query volume group by id + * @param execution + */ + public void queryAAIForVolumeGroup(Execution execution, isDebugLogEnabled) { + + ExceptionUtil exceptionUtil = new ExceptionUtil() + + def volumeGroupId = execution.getVariable('DELVfModVol_volumeGroupId') + if(volumeGroupId == null) { + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, 'volume-group-id is not provided in the request') + throw new Exception('volume-group-id is not provided in the request') + } + String cloudRegion = execution.getVariable('DELVfModVol_aicCloudRegion') + + AaiUtil aaiUtil = new AaiUtil(this) + String aaiEndpoint = aaiUtil.getCloudInfrastructureCloudRegionEndpoint(execution) + String queryAAIVolumeGroupRequest = aaiEndpoint + '/' + URLEncoder.encode(cloudRegion, "UTF-8") + "/volume-groups/volume-group/" + UriUtils.encode(volumeGroupId, "UTF-8") + + utils.logAudit('Query AAI volume group by ID: ' + queryAAIVolumeGroupRequest) + logDebug('Query AAI volume group by ID: ' + queryAAIVolumeGroupRequest, isDebugLogEnabled) + + APIResponse response = aaiUtil.executeAAIGetCall(execution, queryAAIVolumeGroupRequest) + + String returnCode = response.getStatusCode() + String aaiResponseAsString = response.getResponseBodyAsString() + aaiResponseAsString = StringEscapeUtils.unescapeXml(aaiResponseAsString) + + utils.logAudit("AAI query volume group by id return code: " + returnCode) + utils.logAudit("AAI query volume group by id response: " + aaiResponseAsString) + + execution.setVariable("DELVfModVol_queryAAIVolGrpResponse", aaiResponseAsString) + + if (returnCode=='200' || returnCode == '204') { + + def heatStackId = getNodeTextForce(aaiResponseAsString, 'heat-stack-id') + execution.setVariable('DELVfModVol_volumeGroupHeatStackId', heatStackId) + + if(hasVfModuleRelationship(aaiResponseAsString)){ + utils.log("DEBUG", 'Volume Group ' + volumeGroupId + ' currently in use', isDebugLogEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Volume Group ${volumeGroupId} currently in use - found vf-module relationship.") + } + + def volumeGroupTenantId = getTenantIdFromVolumeGroup(aaiResponseAsString) + if (volumeGroupTenantId == null) { + utils.log("DEBUG", "Could not find Tenant Id element in Volume Group with Volume Group Id ${volumeGroupId}", isDebugLogEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Could not find Tenant Id element in Volume Group with Volume Group Id ${volumeGroupId}") + } + + execution.setVariable('DELVfModVol_volumeGroupTenantId', volumeGroupTenantId) + logDebug('Received Tenant Id ' + volumeGroupTenantId + ' from AAI for Volume Group with Volume Group Id ' + volumeGroupId , isDebugLogEnabled) + } + else { + if (returnCode=='404') { + utils.log("DEBUG", "Volume Group ${volumeGroupId} not found in AAI", isDebugLogEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Volume Group ${volumeGroupId} not found in AAI. Response code: 404") + } + else { + WorkflowException aWorkflowException = exceptionUtil.MapAAIExceptionToWorkflowException(aaiResponseAsString, execution) + throw new BpmnError("MSOWorkflowException") + } + } + } + + /** + * Extract the Tenant Id from the Volume Group information returned by AAI. + * + * @param volumeGroupXml Volume Group XML returned by AAI. + * @return the Tenant Id extracted from the Volume Group information. 'null' is returned if + * the Tenant Id is missing or could not otherwise be extracted. + */ + private String getTenantIdFromVolumeGroup(String volumeGroupXml) { + def Node volumeGroupNode = xmlParser.parseText(volumeGroupXml) + def Node relationshipList = utils.getChildNode(volumeGroupNode, 'relationship-list') + if (relationshipList != null) { + def NodeList relationships = utils.getIdenticalChildren(relationshipList, 'relationship') + for (Node relationship in relationships) { + def Node relatedTo = utils.getChildNode(relationship, 'related-to') + if ((relatedTo != null) && (relatedTo.text().equals('tenant'))) { + def NodeList relationshipDataList = utils.getIdenticalChildren(relationship, 'relationship-data') + for (Node relationshipData in relationshipDataList) { + def Node relationshipKey = utils.getChildNode(relationshipData, 'relationship-key') + if ((relationshipKey != null) && (relationshipKey.text().equals('tenant.tenant-id'))) { + def Node relationshipValue = utils.getChildNode(relationshipData, 'relationship-value') + if (relationshipValue != null) { + return relationshipValue.text() + } + } + } + } + } + } + return null + } + + private boolean hasVnfRelationship(String volumeGroupXml) { + def Node volumeGroupNode = xmlParser.parseText(volumeGroupXml) + def Node relationshipList = utils.getChildNode(volumeGroupNode, 'relationship-list') + if (relationshipList != null) { + def NodeList relationships = utils.getIdenticalChildren(relationshipList, 'relationship') + for (Node relationship in relationships) { + def Node relatedTo = utils.getChildNode(relationship, 'related-to') + if ((relatedTo != null) && (relatedTo.text().equals('generic-vnf'))) { + def Node relatedLink = utils.getChildNode(relationship, 'related-link') + if (relatedLink !=null && relatedLink.text() != null){ + return true + } + } + } + } + return false + } + + private boolean hasVfModuleRelationship(String volumeGroupXml) { + def Node volumeGroupNode = xmlParser.parseText(volumeGroupXml) + def Node relationshipList = utils.getChildNode(volumeGroupNode, 'relationship-list') + if (relationshipList != null) { + def NodeList relationships = utils.getIdenticalChildren(relationshipList, 'relationship') + for (Node relationship in relationships) { + def Node relatedTo = utils.getChildNode(relationship, 'related-to') + if ((relatedTo != null) && (relatedTo.text().equals('vf-module'))) { + def Node relatedLink = utils.getChildNode(relationship, 'related-link') + if (relatedLink !=null && relatedLink.text() != null){ + return true + } + } + } + } + return false + } + + public void prepareVnfAdapterDeleteRequest(Execution execution, isDebugLogEnabled) { + def cloudRegion = execution.getVariable('DELVfModVol_cloudRegion') + def tenantId = execution.getVariable('DELVfModVol_tenantId') + def volumeGroupId = execution.getVariable('DELVfModVol_volumeGroupId') + def volumeGroupHeatStackId = execution.getVariable('DELVfModVol_volumeGroupHeatStackId') + def requestId = execution.getVariable('DELVfModVol_requestId') + def serviceId = execution.getVariable('DELVfModVol_serviceId') + + def messageId = execution.getVariable('DELVfModVol_messageId') + def notificationUrl = createCallbackURL(execution, "VNFAResponse", messageId) + def useQualifiedHostName = execution.getVariable("URN_mso_use_qualified_host") + if ('true'.equals(useQualifiedHostName)) { + notificationUrl = utils.getQualifiedHostNameForCallback(notificationUrl) + } + + String vnfAdapterRestRequest = """ + + ${cloudRegion} + ${tenantId} + ${volumeGroupId} + ${volumeGroupHeatStackId} + true + + ${requestId} + ${serviceId} + + ${messageId} + ${notificationUrl} + + """ + vnfAdapterRestRequest = utils.formatXml(vnfAdapterRestRequest) + execution.setVariable('DELVfModVol_deleteVnfARequest', vnfAdapterRestRequest) + logDebug('Request for VNFAdapter Rest:\n' + vnfAdapterRestRequest, isDebugLogEnabled) + } + + + public void deleteVolGrpId(Execution execution, isDebugEnabled) { + + // get variables + String queryAAIVolGrpIdResponse = execution.getVariable("DELVfModVol_queryAAIVolGrpResponse") + String groupId = utils.getNodeText(queryAAIVolGrpIdResponse, "volume-group-id") + String resourceVersion = utils.getNodeText(queryAAIVolGrpIdResponse, "resource-version") + String messageId = execution.getVariable('DELVfModVol_messageId') + String cloudRegion = execution.getVariable('DELVfModVol_aicCloudRegion') + + AaiUtil aaiUtil = new AaiUtil(this) + String aaiEndpoint = aaiUtil.getCloudInfrastructureCloudRegionEndpoint(execution) + String deleteAAIVolumeGrpIdRequest = aaiEndpoint + '/' + URLEncoder.encode(cloudRegion, "UTF-8") + "/volume-groups/volume-group/" + UriUtils.encode(groupId, "UTF-8") + + if(resourceVersion !=null){ + deleteAAIVolumeGrpIdRequest = deleteAAIVolumeGrpIdRequest +'?resource-version=' + UriUtils.encode(resourceVersion, 'UTF-8') + } + + utils.logAudit('Delete AAI volume group : ' + deleteAAIVolumeGrpIdRequest) + utils.log("DEBUG", "Delete AAI volume group : " + deleteAAIVolumeGrpIdRequest, isDebugEnabled) + + APIResponse response = aaiUtil.executeAAIDeleteCall(execution, deleteAAIVolumeGrpIdRequest) + + String returnCode = response.getStatusCode() + String aaiResponseAsString = response.getResponseBodyAsString() + aaiResponseAsString = StringEscapeUtils.unescapeXml(aaiResponseAsString) + + utils.logAudit("AAI delete volume group return code: " + returnCode) + utils.logAudit("AAI delete volume group response: " + aaiResponseAsString) + + ExceptionUtil exceptionUtil = new ExceptionUtil() + if (returnCode=='200' || (returnCode == '204')) { + utils.log("DEBUG", "Volume group $groupId deleted.", isDebugEnabled) + } else { + if (returnCode=='404') { + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Volume group $groupId not found for delete in AAI Response code: 404") + } else { + WorkflowException aWorkflowException = exceptionUtil.MapAAIExceptionToWorkflowException(aaiResponseAsString, execution) + throw new BpmnError("MSOWorkflowException") + } + } + } + + + public void prepareDBRequest (Execution execution, isDebugLogEnabled) { + + WorkflowException workflowExceptionObj = execution.getVariable("WorkflowException") + + def requestId = execution.getVariable('DELVfModVol_requestId') + def volOutputs = execution.getVariable('DELVfModVol_volumeOutputs') + def statusMessage = "VolumeGroup successfully deleted" + def progress = "100" + def requestStatus = "COMPLETE" + + if (workflowExceptionObj != null) { + statusMessage = (workflowExceptionObj.getErrorMessage()).replace("&", "&").replace("<", "<").replace(">", ">") + execution.setVariable("DELVfModVol_WorkflowExceptionMessage", statusMessage) + execution.setVariable("DELVfModVol_WorkflowExceptionCode", workflowExceptionObj.getErrorCode()) + requestStatus = "FAILURE" + progress = "" + } + + String updateInfraRequest = """ + + + + + ${requestId} + BPMN + ${statusMessage} + ${requestStatus} + ${progress} + ${volOutputs} + + + + """ + + updateInfraRequest = utils.formatXml(updateInfraRequest) + execution.setVariable('DELVfModVol_updateInfraRequest', updateInfraRequest) + logDebug('Request for Update Infra Request:\n' + updateInfraRequest, isDebugLogEnabled) + + } + + + public void prepareCompletionHandlerRequest (Execution execution, isDebugLogEnabled) { + def requestId = execution.getVariable("mso-request-id") + def source = execution.getVariable("DELVfModVol_source") + + String msoCompletionRequest = + """ + + ${requestId} + DELETE + ${source} + + Volume Group has been deleted successfully. + BPMN VF Module Volume action: DELETE + """ + + String xmlMsoCompletionRequest = utils.formatXml(msoCompletionRequest) + execution.setVariable('DELVfModVol_CompleteMsoProcessRequest', xmlMsoCompletionRequest) + utils.log("DEBUG", " Overall SUCCESS Response going to CompleteMsoProcess - " + "\n" + xmlMsoCompletionRequest, isDebugLogEnabled) + + } + + + + public void prepareFalloutHandler (Execution execution, isDebugEnabled) { + + execution.setVariable("DELVfModVol_Success", false) + String requestId = execution.getVariable("DELVfModVol_requestId") + String source = execution.getVariable("DELVfModVol_source") + + WorkflowException workflowExceptionObj = execution.getVariable("WorkflowException") + def errorMessage = workflowExceptionObj.getErrorMessage() + def errorCode = workflowExceptionObj.getErrorCode() + + String falloutHandlerRequest = + """ + + ${requestId} + DELETE + ${source} + + + ${errorMessage} + ${errorCode} + + """ + + // Format Response + String xmlHandlerRequest = utils.formatXml(falloutHandlerRequest) + utils.logAudit(xmlHandlerRequest) + + execution.setVariable("DELVfModVol_FalloutHandlerRequest", xmlHandlerRequest) + utils.log("ERROR", " Overall Error Response going to FalloutHandler: " + "\n" + xmlHandlerRequest, isDebugEnabled) + + } + + + /** + * Create a WorkflowException for the error case where the Tenant Id from + * AAI did not match the Tenant Id in the incoming request. + * + * @param execution The flow's execution instance. + */ + public void handleTenantIdMismatch(Execution execution, isDebugLogEnabled) { + + def volumeGroupId = execution.getVariable('DELVfModVol_volumeGroupId') + def aicCloudRegion = execution.getVariable('DELVfModVol_aicCloudRegion') + def tenantId = execution.getVariable('DELVfModVol_tenantId') + def volumeGroupTenantId = execution.getVariable('DELVfModVol_volumeGroupTenantId') + + def String errorMessage = 'TenantId ' + tenantId + ' in incoming request does not match Tenant Id ' + volumeGroupTenantId + + ' retrieved from AAI for Volume Group Id ' + volumeGroupId + + logError('Error in DeleteVfModuleVolume: ' + errorMessage) + + ExceptionUtil exceptionUtil = new ExceptionUtil() + exceptionUtil.buildWorkflowException(execution, 5000, errorMessage) + + } + +} diff --git a/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/DoCreateNetworkInstance.groovy b/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/DoCreateNetworkInstance.groovy index ed65dbc79b..2d5ddf0d0c 100644 --- a/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/DoCreateNetworkInstance.groovy +++ b/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/DoCreateNetworkInstance.groovy @@ -1,37 +1,37 @@ -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - MSO - * ================================================================================ - * 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========================================================= +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.bpmn.infrastructure.scripts; +package org.openecomp.mso.bpmn.infrastructure.scripts; import groovy.xml.XmlUtil import groovy.json.* -import org.openecomp.mso.bpmn.core.json.JsonUtils -import org.openecomp.mso.bpmn.common.scripts.AaiUtil -import org.openecomp.mso.bpmn.common.scripts.AbstractServiceTaskProcessor -import org.openecomp.mso.bpmn.common.scripts.ExceptionUtil -import org.openecomp.mso.bpmn.common.scripts.NetworkUtils -import org.openecomp.mso.bpmn.common.scripts.SDNCAdapterUtils -import org.openecomp.mso.bpmn.common.scripts.VidUtils -import org.openecomp.mso.bpmn.core.WorkflowException -import org.openecomp.mso.rest.APIResponse; -import org.openecomp.mso.rest.RESTClient -import org.openecomp.mso.rest.RESTConfig +import org.openecomp.mso.bpmn.core.json.JsonUtils +import org.openecomp.mso.bpmn.common.scripts.AaiUtil +import org.openecomp.mso.bpmn.common.scripts.AbstractServiceTaskProcessor +import org.openecomp.mso.bpmn.common.scripts.ExceptionUtil +import org.openecomp.mso.bpmn.common.scripts.NetworkUtils +import org.openecomp.mso.bpmn.common.scripts.SDNCAdapterUtils +import org.openecomp.mso.bpmn.common.scripts.VidUtils +import org.openecomp.mso.bpmn.core.WorkflowException +import org.openecomp.mso.rest.APIResponse; +import org.openecomp.mso.rest.RESTClient +import org.openecomp.mso.rest.RESTConfig import java.util.HashMap; import java.util.Map; @@ -223,8 +223,6 @@ public class DoCreateNetworkInstance extends AbstractServiceTaskProcessor { execution.setVariable(Prefix + "networkInputs", networkInputs) utils.log("DEBUG", Prefix + "networkInputs - " + '\n' + networkInputs, isDebugEnabled) - - // prepare messageId String messageId = execution.getVariable("testMessageId") // for testing if (messageId == null || messageId == "") { @@ -491,7 +489,7 @@ public class DoCreateNetworkInstance extends AbstractServiceTaskProcessor { String aai_endpoint = execution.getVariable("URN_aai_endpoint") AaiUtil aaiUriUtil = new AaiUtil(this) String aai_uri = aaiUriUtil.getNetworkL3NetworkUri(execution) - String queryIdAAIRequest = "${aai_endpoint}${aai_uri}/" + networkId + String queryIdAAIRequest = "${aai_endpoint}${aai_uri}/" + networkId + "?depth=1" utils.logAudit(queryIdAAIRequest) execution.setVariable(Prefix + "queryIdAAIRequest", queryIdAAIRequest) utils.log("DEBUG", Prefix + "queryIdAAIRequest - " + "\n" + queryIdAAIRequest, isDebugEnabled) @@ -570,7 +568,7 @@ public class DoCreateNetworkInstance extends AbstractServiceTaskProcessor { String aai_endpoint = execution.getVariable("URN_aai_endpoint") AaiUtil aaiUriUtil = new AaiUtil(this) String aai_uri = aaiUriUtil.getNetworkL3NetworkUri(execution) - String requeryIdAAIRequest = "${aai_endpoint}${aai_uri}/" + networkId + String requeryIdAAIRequest = "${aai_endpoint}${aai_uri}/" + networkId + "?depth=1" utils.logAudit(requeryIdAAIRequest) execution.setVariable(Prefix + "requeryIdAAIRequest", requeryIdAAIRequest) utils.log("DEBUG", Prefix + "requeryIdAAIRequest - " + "\n" + requeryIdAAIRequest, isDebugEnabled) @@ -1078,7 +1076,7 @@ public class DoCreateNetworkInstance extends AbstractServiceTaskProcessor { String aai_endpoint = execution.getVariable("URN_aai_endpoint") AaiUtil aaiUriUtil = new AaiUtil(this) String aai_uri = aaiUriUtil.getNetworkL3NetworkUri(execution) - String updateContrailAAIUrlRequest = "${aai_endpoint}${aai_uri}/" + networkId + String updateContrailAAIUrlRequest = "${aai_endpoint}${aai_uri}/" + networkId + "?depth=1" utils.logAudit(updateContrailAAIUrlRequest) execution.setVariable(Prefix + "updateContrailAAIUrlRequest", updateContrailAAIUrlRequest) @@ -1092,18 +1090,11 @@ public class DoCreateNetworkInstance extends AbstractServiceTaskProcessor { execution.setVariable(Prefix + "updateContrailAAIPayloadRequest", payloadXml) utils.log("DEBUG", " 'payload' to Update Contrail - " + "\n" + payloadXml, isDebugEnabled) - RESTConfig config = new RESTConfig(updateContrailAAIUrlRequest); - RESTClient client = new RESTClient(config).addHeader("X-TransactionId", messageId) - .addHeader("X-FromAppId", "MSO") - .addHeader("Content-Type", "application/xml") - .addHeader("Accept","application/xml"); - - APIResponse response = client.httpPut(payload) + APIResponse response = aaiUriUtil.executeAAIPutCall(execution, updateContrailAAIUrlRequest, payloadXml) + String returnCode = response.getStatusCode() execution.setVariable(Prefix + "aaiUpdateContrailReturnCode", returnCode) - utils.log("DEBUG", " ***** AAI Update Contrail Response Code : " + returnCode, isDebugEnabled) - String aaiUpdateContrailResponseAsString = response.getResponseBodyAsString() if (returnCode=='200') { @@ -1117,7 +1108,7 @@ public class DoCreateNetworkInstance extends AbstractServiceTaskProcessor { } else { execution.setVariable(Prefix + "isPONR", true) } - + utils.log("DEBUG", Prefix + "isPONR" + ": " + execution.getVariable(Prefix + "isPONR"), isDebugEnabled) } else { if (returnCode=='404') { String dataErrorMessage = " Response Error from UpdateContrailAAINetwork is 404 (Not Found)." @@ -1162,7 +1153,7 @@ public class DoCreateNetworkInstance extends AbstractServiceTaskProcessor { // get variables String requestId = execution.getVariable("msoRequestId") if (requestId == null) { - requestId = execution.getVariable("mso-request-id") + requestId = execution.getVariable("mso-request-id") } String messageId = execution.getVariable(Prefix + "messageId") String source = execution.getVariable(Prefix + "source") @@ -1209,12 +1200,12 @@ public class DoCreateNetworkInstance extends AbstractServiceTaskProcessor { String networkId = execution.getVariable(Prefix + "networkId") String serviceInstanceId = execution.getVariable(Prefix + "serviceInstanceId") - // get/set 'msoRequestId' and 'mso-request-id' + // get/set 'msoRequestId' and 'mso-request-id' String requestId = execution.getVariable("msoRequestId") if (requestId != null) { - execution.setVariable("mso-request-id", requestId) + execution.setVariable("mso-request-id", requestId) } else { - requestId = execution.getVariable("mso-request-id") + requestId = execution.getVariable("mso-request-id") } execution.setVariable(Prefix + "requestId", requestId) diff --git a/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/DoCreateNetworkInstanceRollback.groovy b/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/DoCreateNetworkInstanceRollback.groovy index 0ad42f9da4..5b9cebc46b 100644 --- a/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/DoCreateNetworkInstanceRollback.groovy +++ b/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/DoCreateNetworkInstanceRollback.groovy @@ -1,387 +1,387 @@ -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - MSO - * ================================================================================ - * 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.openecomp.mso.bpmn.infrastructure.scripts; - -import groovy.xml.XmlUtil -import groovy.json.* - -import org.openecomp.mso.bpmn.core.json.JsonUtils -import org.openecomp.mso.bpmn.common.scripts.AbstractServiceTaskProcessor -import org.openecomp.mso.bpmn.common.scripts.ExceptionUtil -import org.openecomp.mso.bpmn.common.scripts.NetworkUtils -import org.openecomp.mso.bpmn.common.scripts.SDNCAdapterUtils -import org.openecomp.mso.bpmn.common.scripts.VidUtils -import org.openecomp.mso.bpmn.core.WorkflowException -import org.openecomp.mso.rest.APIResponse; -import org.openecomp.mso.rest.RESTClient -import org.openecomp.mso.rest.RESTConfig - -import java.util.UUID; - -import org.camunda.bpm.engine.delegate.BpmnError -import org.camunda.bpm.engine.runtime.Execution -import org.apache.commons.lang3.* -import org.apache.commons.codec.binary.Base64; -import org.springframework.web.util.UriUtils - -/** - * This groovy class supports the DoCreateNetworkInstance.bpmn process. - * - */ -public class DoCreateNetworkInstanceRollback extends AbstractServiceTaskProcessor { - String Prefix="CRENWKIR_" - ExceptionUtil exceptionUtil = new ExceptionUtil() - JsonUtils jsonUtil = new JsonUtils() - VidUtils vidUtils = new VidUtils(this) - NetworkUtils networkUtils = new NetworkUtils() - SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils() - - def className = getClass().getSimpleName() - - /** - * This method is executed during the preProcessRequest task of the DoCreateNetworkInstanceRollback.bpmn process. - * @param execution - */ - public InitializeProcessVariables(Execution execution){ - /* Initialize all the process variables in this block */ - - execution.setVariable(Prefix + "rollbackNetworkRequest", null) - execution.setVariable(Prefix + "rollbackSDNCRequest", null) - execution.setVariable(Prefix + "rollbackActivateSDNCRequest", null) - execution.setVariable(Prefix + "WorkflowException", null) - - execution.setVariable(Prefix + "rollbackNetworkRequest", "") - execution.setVariable(Prefix + "rollbackNetworkResponse", "") - execution.setVariable(Prefix + "rollbackNetworkReturnCode", "") - - execution.setVariable(Prefix + "rollbackSDNCRequest", "") - execution.setVariable(Prefix + "rollbackSDNCResponse", "") - execution.setVariable(Prefix + "rollbackSDNCReturnCode", "") - - execution.setVariable(Prefix + "rollbackActivateSDNCRequest", "") - execution.setVariable(Prefix + "rollbackActivateSDNCResponse", "") - execution.setVariable(Prefix + "rollbackActivateSDNCReturnCode", "") - - execution.setVariable(Prefix + "Success", false) - execution.setVariable(Prefix + "fullRollback", false) - execution.setVariable(Prefix + "networkId", "") - execution.setVariable(Prefix + "urlRollbackPoNetwork", "") - - } - - // ************************************************** - // Pre or Prepare Request Section - // ************************************************** - /** - * This method is executed during the preProcessRequest task of the DoCreateNetworkInstanceRollback.bpmn process. - * @param execution - */ - public void preProcessRequest (Execution execution) { - def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - execution.setVariable("prefix",Prefix) - - utils.log("DEBUG", " ***** Inside preProcessRequest() of " + className + ".groovy ***** ", isDebugEnabled) - - try { - // initialize flow variables - InitializeProcessVariables(execution) - - // GET Incoming request/variables - String rollbackNetworkRequest = null - String rollbackSDNCRequest = null - String rollbackActivateSDNCRequest = null - - // Partial Rollback - Map rollbackData = execution.getVariable("rollbackData") - if (rollbackData != null && rollbackData instanceof Map) { - - if(rollbackData.containsKey("rollbackSDNCRequest")) { - rollbackSDNCRequest = rollbackData["rollbackSDNCRequest"] - } - - if(rollbackData.containsKey("rollbackNetworkRequest")) { - rollbackNetworkRequest = rollbackData["rollbackNetworkRequest"] - } - - if(rollbackData.containsKey("rollbackActivateSDNCRequest")) { - rollbackActivateSDNCRequest = rollbackData["rollbackActivateSDNCRequest"] - } - - } - - execution.setVariable(Prefix + "rollbackNetworkRequest", rollbackNetworkRequest) - execution.setVariable(Prefix + "rollbackSDNCRequest", rollbackSDNCRequest) - execution.setVariable(Prefix + "rollbackActivateSDNCRequest", rollbackActivateSDNCRequest) - utils.log("DEBUG", "'rollbackData': " + '\n' + execution.getVariable("rollbackData"), isDebugEnabled) - - String sdncVersion = execution.getVariable("sdncVersion") - utils.log("DEBUG", "sdncVersion? : " + sdncVersion, isDebugEnabled) - - // PO Authorization Info / headers Authorization= - String basicAuthValuePO = execution.getVariable("URN_mso_adapters_po_auth") - utils.log("DEBUG", " Obtained BasicAuth userid password for PO/SDNC adapter: " + basicAuthValuePO, isDebugEnabled) - try { - def encodedString = utils.getBasicAuth(basicAuthValuePO, execution.getVariable("URN_mso_msoKey")) - execution.setVariable("BasicAuthHeaderValuePO",encodedString) - execution.setVariable("BasicAuthHeaderValueSDNC", encodedString) - - } catch (IOException ex) { - String exceptionMessage = "Exception Encountered in DoCreateNetworkInstance, PreProcessRequest() - " - String dataErrorMessage = exceptionMessage + " Unable to encode PO/SDNC user/password string - " + ex.getMessage() - utils.log("DEBUG", dataErrorMessage , isDebugEnabled) - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) - } - - if (execution.getVariable("SavedWorkflowException1") != null) { - execution.setVariable(Prefix + "WorkflowException", execution.getVariable("SavedWorkflowException1")) - } else { - execution.setVariable(Prefix + "WorkflowException", execution.getVariable("WorkflowException")) - } - utils.log("DEBUG", "*** WorkflowException : " + execution.getVariable(Prefix + "WorkflowException"), isDebugEnabled) - if(execution.getVariable(Prefix + "WorkflowException") != null) { - // called by: DoCreateNetworkInstance, partial rollback - execution.setVariable(Prefix + "fullRollback", false) - - } else { - // called by: Macro - Full Rollback, WorkflowException = null - execution.setVariable(Prefix + "fullRollback", true) - - } - utils.log("DEBUG", "*** fullRollback? : " + execution.getVariable(Prefix + "fullRollback"), isDebugEnabled) - - - } catch (BpmnError e) { - throw e; - - } catch (Exception ex) { - // caught exception - String exceptionMessage = "Exception Encountered in PreProcessRequest() of " + className + ".groovy ***** : " + ex.getMessage() - utils.log("DEBUG", exceptionMessage, isDebugEnabled) - exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) - - } - - } - - public void callPONetworkAdapter (Execution execution) { - def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - execution.setVariable("prefix",Prefix) - - utils.log("DEBUG", " ***** Inside callPONetworkAdapter() of " + className + " ***** ", isDebugEnabled) - - try { - String poUrl = execution.getVariable("URN_mso_adapters_network_rest_endpoint") - String rollbackSDNCRequest = execution.getVariable(Prefix + "rollbackSDNCRequest") - String networkId = utils.getNodeText1(rollbackSDNCRequest, "network-id") - - String rollbackNetworkRequest = execution.getVariable(Prefix + "rollbackNetworkRequest") - - String urlRollbackPoNetwork = poUrl+ "/" + networkId + "/rollback" - utils.log("DEBUG", "'urlRollbackPoNetwork': " + urlRollbackPoNetwork, isDebugEnabled) - execution.setVariable(Prefix + "urlRollbackPoNetwork", urlRollbackPoNetwork) - - RESTConfig config = new RESTConfig(urlRollbackPoNetwork) - RESTClient client = new RESTClient(config). - addHeader("Content-Type", "application/xml"). - addAuthorizationHeader(execution.getVariable("BasicAuthHeaderValuePO")); - - APIResponse response = client.httpDelete(rollbackNetworkRequest) - String responseCode = response.getStatusCode() - String responseBody = response.getResponseBodyAsString() - - execution.setVariable(Prefix + "rollbackNetworkReturnCode", responseCode) - execution.setVariable(Prefix + "rollbackNetworkResponse", responseBody) - - utils.log("DEBUG", " Network Adapter rollback responseCode: " + responseCode, isDebugEnabled) - utils.log("DEBUG", " Network Adapter rollback responseBody: " + responseBody, isDebugEnabled) - - - } catch (Exception ex) { - String exceptionMessage = "Exception Encountered in callPONetworkAdapter() of DoCreateNetworkInstanceRollback flow - " + ex.getMessage() - utils.log("DEBUG", exceptionMessage, isDebugEnabled) - exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) - } - - } - - - public void validateRollbackResponses (Execution execution) { - def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - execution.setVariable("prefix",Prefix) - - utils.log("DEBUG", " ***** Inside validateRollbackResponses() of DoCreateNetworkInstanceRollback ***** ", isDebugEnabled) - - try { - // validate PO network rollback response - String rollbackNetworkErrorMessages = "" - String rollbackNetworkReturnCode = "200" - if (execution.getVariable(Prefix + "rollbackNetworkRequest") != null) { - rollbackNetworkReturnCode = execution.getVariable(Prefix + "rollbackNetworkReturnCode") - String rollbackNetworkResponse = execution.getVariable(Prefix + "rollbackNetworkResponse") - utils.log("DEBUG", " NetworkRollback Code - " + rollbackNetworkReturnCode, isDebugEnabled) - utils.log("DEBUG", " NetworkRollback Response - " + rollbackNetworkResponse, isDebugEnabled) - if (rollbackNetworkReturnCode != "200") { - rollbackNetworkErrorMessages = " + PO Network rollback failed. " - } else { - rollbackNetworkErrorMessages = " + PO Network rollback completed." - } - } - - // validate SDNC rollback response - String rollbackSdncErrorMessages = "" - String rollbackSDNCReturnCode = "200" - if (execution.getVariable(Prefix + "rollbackSDNCRequest") != null) { - rollbackSDNCReturnCode = execution.getVariable(Prefix + "rollbackSDNCReturnCode") - String rollbackSDNCResponse = execution.getVariable(Prefix + "rollbackSDNCResponse") - String rollbackSDNCReturnInnerCode = "" - SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils(this) - rollbackSDNCResponse = sdncAdapterUtils.decodeXML(rollbackSDNCResponse) - rollbackSDNCResponse = rollbackSDNCResponse.replace("&", "&").replace('$', '').replace('', "") - if (rollbackSDNCReturnCode == "200") { - if (utils.nodeExists(rollbackSDNCResponse, "response-code")) { - rollbackSDNCReturnInnerCode = utils.getNodeText1(rollbackSDNCResponse, "response-code") - if (rollbackSDNCReturnInnerCode == "200" || rollbackSDNCReturnInnerCode == "" || rollbackSDNCReturnInnerCode == "0") { - rollbackSdncErrorMessages = " + SNDC assign rollback completed." - } else { - rollbackSdncErrorMessages = " + SDNC assign rollback failed. " - } - } else { - rollbackSdncErrorMessages = " + SNDC assign rollback completed." - } - } else { - rollbackSdncErrorMessages = " + SDNC assign rollback failed. " - } - utils.log("DEBUG", " SDNC assign rollback Code - " + rollbackSDNCReturnCode, isDebugEnabled) - utils.log("DEBUG", " SDNC assign rollback Response - " + rollbackSDNCResponse, isDebugEnabled) - } - - // validate SDNC activate rollback response - String rollbackActivateSdncErrorMessages = "" - String rollbackActivateSDNCReturnCode = "200" - if (execution.getVariable(Prefix + "rollbackActivateSDNCRequest") != null) { - rollbackActivateSDNCReturnCode = execution.getVariable(Prefix + "rollbackActivateSDNCReturnCode") - String rollbackActivateSDNCResponse = execution.getVariable(Prefix + "rollbackActivateSDNCResponse") - String rollbackActivateSDNCReturnInnerCode = "" - rollbackActivateSDNCResponse = sdncAdapterUtils.decodeXML(rollbackActivateSDNCResponse) - rollbackActivateSDNCResponse = rollbackActivateSDNCResponse.replace("&", "&").replace('$', '').replace('', "") - if (rollbackActivateSDNCReturnCode == "200") { - if (utils.nodeExists(rollbackActivateSDNCResponse, "response-code")) { - rollbackActivateSDNCReturnInnerCode = utils.getNodeText1(rollbackActivateSDNCResponse, "response-code") - if (rollbackActivateSDNCReturnInnerCode == "200" || rollbackActivateSDNCReturnInnerCode == "" || rollbackActivateSDNCReturnInnerCode == "0") { - rollbackActivateSdncErrorMessages = " + SNDC activate rollback completed." - } else { - rollbackActivateSdncErrorMessages = " + SDNC activate rollback failed. " - } - } else { - rollbackActivateSdncErrorMessages = " + SNDC activate rollback completed." - } - } else { - rollbackActivateSdncErrorMessages = " + SDNC activate rollback failed. " - } - utils.log("DEBUG", " SDNC activate rollback Code - " + rollbackActivateSDNCReturnCode, isDebugEnabled) - utils.log("DEBUG", " SDNC activate rollback Response - " + rollbackActivateSDNCResponse, isDebugEnabled) - } - - - String statusMessage = "" - int errorCode = 7000 - utils.log("DEBUG", "*** fullRollback? : " + execution.getVariable(Prefix + "fullRollback"), isDebugEnabled) - if (execution.getVariable(Prefix + "fullRollback") == false) { - // original WorkflowException, - WorkflowException wfe = execution.getVariable(Prefix + "WorkflowException") - if (wfe != null) { - // rollback due to failure in DoCreate - Partial rollback - statusMessage = wfe.getErrorMessage() - errorCode = wfe.getErrorCode() - } else { - statusMessage = "See Previous Camunda flows for cause of Error: Undetermined Exception." - errorCode = '7000' - } - - // set if all rolledbacks are successful - if (rollbackNetworkReturnCode == "200" && rollbackSDNCReturnCode == "200" && rollbackActivateSDNCReturnCode == "200") { - execution.setVariable("rolledBack", true) - execution.setVariable("wasDeleted", true) - - } else { - execution.setVariable("rolledBack", false) - execution.setVariable("wasDeleted", true) - } - - statusMessage = statusMessage + rollbackActivateSdncErrorMessages + rollbackNetworkErrorMessages + rollbackSdncErrorMessages - utils.log("DEBUG", "Final DoCreateNetworkInstanceRollback status message: " + statusMessage, isDebugEnabled) - String processKey = getProcessKey(execution); - WorkflowException exception = new WorkflowException(processKey, errorCode, statusMessage); - execution.setVariable("workflowException", exception); - - } else { - // rollback due to failures in Main flow (Macro) - Full rollback - // WorkflowException = null - if (rollbackNetworkReturnCode == "200" && rollbackSDNCReturnCode == "200" && rollbackActivateSDNCReturnCode == "200") { - execution.setVariable("rollbackSuccessful", true) - execution.setVariable("rollbackError", false) - } else { - String exceptionMessage = "Network Create Rollback was not Successful. " - utils.log("DEBUG", exceptionMessage, isDebugEnabled) - execution.setVariable("rollbackSuccessful", false) - execution.setVariable("rollbackError", true) - exceptionUtil.buildWorkflowException(execution, 7000, exceptionMessage) - throw new BpmnError("MSOWorkflowException") - } - - } - - - } catch (Exception ex) { - String errorMessage = "See Previous Camunda flows for cause of Error: Undetermined Exception." - String exceptionMessage = " Bpmn error encountered in DoCreateNetworkInstanceRollback flow. validateRollbackResponses() - " + errorMessage + ": " + ex.getMessage() - utils.log("DEBUG", exceptionMessage, isDebugEnabled) - exceptionUtil.buildWorkflowException(execution, 7000, exceptionMessage) - - } - - } - - // ******************************* - // Build Error Section - // ******************************* - - - - public void processJavaException(Execution execution){ - def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - execution.setVariable("prefix",Prefix) - - try{ - utils.log("DEBUG", "Caught a Java Exception in " + Prefix, isDebugEnabled) - utils.log("DEBUG", "Started processJavaException Method", isDebugEnabled) - utils.log("DEBUG", "Variables List: " + execution.getVariables(), isDebugEnabled) - execution.setVariable("UnexpectedError", "Caught a Java Lang Exception - " + Prefix) // Adding this line temporarily until this flows error handling gets updated - exceptionUtil.buildWorkflowException(execution, 500, "Caught a Java Lang Exception") - - }catch(Exception e){ - utils.log("DEBUG", "Caught Exception during processJavaException Method: " + e, isDebugEnabled) - execution.setVariable("UnexpectedError", "Exception in processJavaException method - " + Prefix) // Adding this line temporarily until this flows error handling gets updated - exceptionUtil.buildWorkflowException(execution, 500, "Exception in processJavaException method" + Prefix) - } - utils.log("DEBUG", "Completed processJavaException Method in " + Prefix, isDebugEnabled) - } - -} +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.bpmn.infrastructure.scripts; + +import groovy.xml.XmlUtil +import groovy.json.* + +import org.openecomp.mso.bpmn.core.json.JsonUtils +import org.openecomp.mso.bpmn.common.scripts.AbstractServiceTaskProcessor +import org.openecomp.mso.bpmn.common.scripts.ExceptionUtil +import org.openecomp.mso.bpmn.common.scripts.NetworkUtils +import org.openecomp.mso.bpmn.common.scripts.SDNCAdapterUtils +import org.openecomp.mso.bpmn.common.scripts.VidUtils +import org.openecomp.mso.bpmn.core.WorkflowException +import org.openecomp.mso.rest.APIResponse; +import org.openecomp.mso.rest.RESTClient +import org.openecomp.mso.rest.RESTConfig + +import java.util.UUID; + +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.runtime.Execution +import org.apache.commons.lang3.* +import org.apache.commons.codec.binary.Base64; +import org.springframework.web.util.UriUtils + +/** + * This groovy class supports the DoCreateNetworkInstance.bpmn process. + * + */ +public class DoCreateNetworkInstanceRollback extends AbstractServiceTaskProcessor { + String Prefix="CRENWKIR_" + ExceptionUtil exceptionUtil = new ExceptionUtil() + JsonUtils jsonUtil = new JsonUtils() + VidUtils vidUtils = new VidUtils(this) + NetworkUtils networkUtils = new NetworkUtils() + SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils() + + def className = getClass().getSimpleName() + + /** + * This method is executed during the preProcessRequest task of the DoCreateNetworkInstanceRollback.bpmn process. + * @param execution + */ + public InitializeProcessVariables(Execution execution){ + /* Initialize all the process variables in this block */ + + execution.setVariable(Prefix + "rollbackNetworkRequest", null) + execution.setVariable(Prefix + "rollbackSDNCRequest", null) + execution.setVariable(Prefix + "rollbackActivateSDNCRequest", null) + execution.setVariable(Prefix + "WorkflowException", null) + + execution.setVariable(Prefix + "rollbackNetworkRequest", "") + execution.setVariable(Prefix + "rollbackNetworkResponse", "") + execution.setVariable(Prefix + "rollbackNetworkReturnCode", "") + + execution.setVariable(Prefix + "rollbackSDNCRequest", "") + execution.setVariable(Prefix + "rollbackSDNCResponse", "") + execution.setVariable(Prefix + "rollbackSDNCReturnCode", "") + + execution.setVariable(Prefix + "rollbackActivateSDNCRequest", "") + execution.setVariable(Prefix + "rollbackActivateSDNCResponse", "") + execution.setVariable(Prefix + "rollbackActivateSDNCReturnCode", "") + + execution.setVariable(Prefix + "Success", false) + execution.setVariable(Prefix + "fullRollback", false) + execution.setVariable(Prefix + "networkId", "") + execution.setVariable(Prefix + "urlRollbackPoNetwork", "") + + } + + // ************************************************** + // Pre or Prepare Request Section + // ************************************************** + /** + * This method is executed during the preProcessRequest task of the DoCreateNetworkInstanceRollback.bpmn process. + * @param execution + */ + public void preProcessRequest (Execution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix",Prefix) + + utils.log("DEBUG", " ***** Inside preProcessRequest() of " + className + ".groovy ***** ", isDebugEnabled) + + try { + // initialize flow variables + InitializeProcessVariables(execution) + + // GET Incoming request/variables + String rollbackNetworkRequest = null + String rollbackSDNCRequest = null + String rollbackActivateSDNCRequest = null + + // Partial Rollback + Map rollbackData = execution.getVariable("rollbackData") + if (rollbackData != null && rollbackData instanceof Map) { + + if(rollbackData.containsKey("rollbackSDNCRequest")) { + rollbackSDNCRequest = rollbackData["rollbackSDNCRequest"] + } + + if(rollbackData.containsKey("rollbackNetworkRequest")) { + rollbackNetworkRequest = rollbackData["rollbackNetworkRequest"] + } + + if(rollbackData.containsKey("rollbackActivateSDNCRequest")) { + rollbackActivateSDNCRequest = rollbackData["rollbackActivateSDNCRequest"] + } + + } + + execution.setVariable(Prefix + "rollbackNetworkRequest", rollbackNetworkRequest) + execution.setVariable(Prefix + "rollbackSDNCRequest", rollbackSDNCRequest) + execution.setVariable(Prefix + "rollbackActivateSDNCRequest", rollbackActivateSDNCRequest) + utils.log("DEBUG", "'rollbackData': " + '\n' + execution.getVariable("rollbackData"), isDebugEnabled) + + String sdncVersion = execution.getVariable("sdncVersion") + utils.log("DEBUG", "sdncVersion? : " + sdncVersion, isDebugEnabled) + + // PO Authorization Info / headers Authorization= + String basicAuthValuePO = execution.getVariable("URN_mso_adapters_po_auth") + utils.log("DEBUG", " Obtained BasicAuth userid password for PO/SDNC adapter: " + basicAuthValuePO, isDebugEnabled) + try { + def encodedString = utils.getBasicAuth(basicAuthValuePO, execution.getVariable("URN_mso_msoKey")) + execution.setVariable("BasicAuthHeaderValuePO",encodedString) + execution.setVariable("BasicAuthHeaderValueSDNC", encodedString) + + } catch (IOException ex) { + String exceptionMessage = "Exception Encountered in DoCreateNetworkInstance, PreProcessRequest() - " + String dataErrorMessage = exceptionMessage + " Unable to encode PO/SDNC user/password string - " + ex.getMessage() + utils.log("DEBUG", dataErrorMessage , isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) + } + + if (execution.getVariable("SavedWorkflowException1") != null) { + execution.setVariable(Prefix + "WorkflowException", execution.getVariable("SavedWorkflowException1")) + } else { + execution.setVariable(Prefix + "WorkflowException", execution.getVariable("WorkflowException")) + } + utils.log("DEBUG", "*** WorkflowException : " + execution.getVariable(Prefix + "WorkflowException"), isDebugEnabled) + if(execution.getVariable(Prefix + "WorkflowException") != null) { + // called by: DoCreateNetworkInstance, partial rollback + execution.setVariable(Prefix + "fullRollback", false) + + } else { + // called by: Macro - Full Rollback, WorkflowException = null + execution.setVariable(Prefix + "fullRollback", true) + + } + utils.log("DEBUG", "*** fullRollback? : " + execution.getVariable(Prefix + "fullRollback"), isDebugEnabled) + + + } catch (BpmnError e) { + throw e; + + } catch (Exception ex) { + // caught exception + String exceptionMessage = "Exception Encountered in PreProcessRequest() of " + className + ".groovy ***** : " + ex.getMessage() + utils.log("DEBUG", exceptionMessage, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + + } + + } + + public void callPONetworkAdapter (Execution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix",Prefix) + + utils.log("DEBUG", " ***** Inside callPONetworkAdapter() of " + className + " ***** ", isDebugEnabled) + + try { + String poUrl = execution.getVariable("URN_mso_adapters_network_rest_endpoint") + String rollbackSDNCRequest = execution.getVariable(Prefix + "rollbackSDNCRequest") + String networkId = utils.getNodeText1(rollbackSDNCRequest, "network-id") + + String rollbackNetworkRequest = execution.getVariable(Prefix + "rollbackNetworkRequest") + + String urlRollbackPoNetwork = poUrl+ "/" + networkId + "/rollback" + utils.log("DEBUG", "'urlRollbackPoNetwork': " + urlRollbackPoNetwork, isDebugEnabled) + execution.setVariable(Prefix + "urlRollbackPoNetwork", urlRollbackPoNetwork) + + RESTConfig config = new RESTConfig(urlRollbackPoNetwork) + RESTClient client = new RESTClient(config). + addHeader("Content-Type", "application/xml"). + addAuthorizationHeader(execution.getVariable("BasicAuthHeaderValuePO")); + + APIResponse response = client.httpDelete(rollbackNetworkRequest) + String responseCode = response.getStatusCode() + String responseBody = response.getResponseBodyAsString() + + execution.setVariable(Prefix + "rollbackNetworkReturnCode", responseCode) + execution.setVariable(Prefix + "rollbackNetworkResponse", responseBody) + + utils.log("DEBUG", " Network Adapter rollback responseCode: " + responseCode, isDebugEnabled) + utils.log("DEBUG", " Network Adapter rollback responseBody: " + responseBody, isDebugEnabled) + + + } catch (Exception ex) { + String exceptionMessage = "Exception Encountered in callPONetworkAdapter() of DoCreateNetworkInstanceRollback flow - " + ex.getMessage() + utils.log("DEBUG", exceptionMessage, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + } + + } + + + public void validateRollbackResponses (Execution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix",Prefix) + + utils.log("DEBUG", " ***** Inside validateRollbackResponses() of DoCreateNetworkInstanceRollback ***** ", isDebugEnabled) + + try { + // validate PO network rollback response + String rollbackNetworkErrorMessages = "" + String rollbackNetworkReturnCode = "200" + if (execution.getVariable(Prefix + "rollbackNetworkRequest") != null) { + rollbackNetworkReturnCode = execution.getVariable(Prefix + "rollbackNetworkReturnCode") + String rollbackNetworkResponse = execution.getVariable(Prefix + "rollbackNetworkResponse") + utils.log("DEBUG", " NetworkRollback Code - " + rollbackNetworkReturnCode, isDebugEnabled) + utils.log("DEBUG", " NetworkRollback Response - " + rollbackNetworkResponse, isDebugEnabled) + if (rollbackNetworkReturnCode != "200") { + rollbackNetworkErrorMessages = " + PO Network rollback failed. " + } else { + rollbackNetworkErrorMessages = " + PO Network rollback completed." + } + } + + // validate SDNC rollback response + String rollbackSdncErrorMessages = "" + String rollbackSDNCReturnCode = "200" + if (execution.getVariable(Prefix + "rollbackSDNCRequest") != null) { + rollbackSDNCReturnCode = execution.getVariable(Prefix + "rollbackSDNCReturnCode") + String rollbackSDNCResponse = execution.getVariable(Prefix + "rollbackSDNCResponse") + String rollbackSDNCReturnInnerCode = "" + SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils(this) + rollbackSDNCResponse = sdncAdapterUtils.decodeXML(rollbackSDNCResponse) + rollbackSDNCResponse = rollbackSDNCResponse.replace("&", "&").replace('$', '').replace('', "") + if (rollbackSDNCReturnCode == "200") { + if (utils.nodeExists(rollbackSDNCResponse, "response-code")) { + rollbackSDNCReturnInnerCode = utils.getNodeText1(rollbackSDNCResponse, "response-code") + if (rollbackSDNCReturnInnerCode == "200" || rollbackSDNCReturnInnerCode == "" || rollbackSDNCReturnInnerCode == "0") { + rollbackSdncErrorMessages = " + SNDC assign rollback completed." + } else { + rollbackSdncErrorMessages = " + SDNC assign rollback failed. " + } + } else { + rollbackSdncErrorMessages = " + SNDC assign rollback completed." + } + } else { + rollbackSdncErrorMessages = " + SDNC assign rollback failed. " + } + utils.log("DEBUG", " SDNC assign rollback Code - " + rollbackSDNCReturnCode, isDebugEnabled) + utils.log("DEBUG", " SDNC assign rollback Response - " + rollbackSDNCResponse, isDebugEnabled) + } + + // validate SDNC activate rollback response + String rollbackActivateSdncErrorMessages = "" + String rollbackActivateSDNCReturnCode = "200" + if (execution.getVariable(Prefix + "rollbackActivateSDNCRequest") != null) { + rollbackActivateSDNCReturnCode = execution.getVariable(Prefix + "rollbackActivateSDNCReturnCode") + String rollbackActivateSDNCResponse = execution.getVariable(Prefix + "rollbackActivateSDNCResponse") + String rollbackActivateSDNCReturnInnerCode = "" + rollbackActivateSDNCResponse = sdncAdapterUtils.decodeXML(rollbackActivateSDNCResponse) + rollbackActivateSDNCResponse = rollbackActivateSDNCResponse.replace("&", "&").replace('$', '').replace('', "") + if (rollbackActivateSDNCReturnCode == "200") { + if (utils.nodeExists(rollbackActivateSDNCResponse, "response-code")) { + rollbackActivateSDNCReturnInnerCode = utils.getNodeText1(rollbackActivateSDNCResponse, "response-code") + if (rollbackActivateSDNCReturnInnerCode == "200" || rollbackActivateSDNCReturnInnerCode == "" || rollbackActivateSDNCReturnInnerCode == "0") { + rollbackActivateSdncErrorMessages = " + SNDC activate rollback completed." + } else { + rollbackActivateSdncErrorMessages = " + SDNC activate rollback failed. " + } + } else { + rollbackActivateSdncErrorMessages = " + SNDC activate rollback completed." + } + } else { + rollbackActivateSdncErrorMessages = " + SDNC activate rollback failed. " + } + utils.log("DEBUG", " SDNC activate rollback Code - " + rollbackActivateSDNCReturnCode, isDebugEnabled) + utils.log("DEBUG", " SDNC activate rollback Response - " + rollbackActivateSDNCResponse, isDebugEnabled) + } + + + String statusMessage = "" + int errorCode = 7000 + utils.log("DEBUG", "*** fullRollback? : " + execution.getVariable(Prefix + "fullRollback"), isDebugEnabled) + if (execution.getVariable(Prefix + "fullRollback") == false) { + // original WorkflowException, + WorkflowException wfe = execution.getVariable(Prefix + "WorkflowException") + if (wfe != null) { + // rollback due to failure in DoCreate - Partial rollback + statusMessage = wfe.getErrorMessage() + errorCode = wfe.getErrorCode() + } else { + statusMessage = "See Previous Camunda flows for cause of Error: Undetermined Exception." + errorCode = '7000' + } + + // set if all rolledbacks are successful + if (rollbackNetworkReturnCode == "200" && rollbackSDNCReturnCode == "200" && rollbackActivateSDNCReturnCode == "200") { + execution.setVariable("rolledBack", true) + execution.setVariable("wasDeleted", true) + + } else { + execution.setVariable("rolledBack", false) + execution.setVariable("wasDeleted", true) + } + + statusMessage = statusMessage + rollbackActivateSdncErrorMessages + rollbackNetworkErrorMessages + rollbackSdncErrorMessages + utils.log("DEBUG", "Final DoCreateNetworkInstanceRollback status message: " + statusMessage, isDebugEnabled) + String processKey = getProcessKey(execution); + WorkflowException exception = new WorkflowException(processKey, errorCode, statusMessage); + execution.setVariable("workflowException", exception); + + } else { + // rollback due to failures in Main flow (Macro) - Full rollback + // WorkflowException = null + if (rollbackNetworkReturnCode == "200" && rollbackSDNCReturnCode == "200" && rollbackActivateSDNCReturnCode == "200") { + execution.setVariable("rollbackSuccessful", true) + execution.setVariable("rollbackError", false) + } else { + String exceptionMessage = "Network Create Rollback was not Successful. " + utils.log("DEBUG", exceptionMessage, isDebugEnabled) + execution.setVariable("rollbackSuccessful", false) + execution.setVariable("rollbackError", true) + exceptionUtil.buildWorkflowException(execution, 7000, exceptionMessage) + throw new BpmnError("MSOWorkflowException") + } + + } + + + } catch (Exception ex) { + String errorMessage = "See Previous Camunda flows for cause of Error: Undetermined Exception." + String exceptionMessage = " Bpmn error encountered in DoCreateNetworkInstanceRollback flow. validateRollbackResponses() - " + errorMessage + ": " + ex.getMessage() + utils.log("DEBUG", exceptionMessage, isDebugEnabled) + exceptionUtil.buildWorkflowException(execution, 7000, exceptionMessage) + + } + + } + + // ******************************* + // Build Error Section + // ******************************* + + + + public void processJavaException(Execution execution){ + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix",Prefix) + + try{ + utils.log("DEBUG", "Caught a Java Exception in " + Prefix, isDebugEnabled) + utils.log("DEBUG", "Started processJavaException Method", isDebugEnabled) + utils.log("DEBUG", "Variables List: " + execution.getVariables(), isDebugEnabled) + execution.setVariable("UnexpectedError", "Caught a Java Lang Exception - " + Prefix) // Adding this line temporarily until this flows error handling gets updated + exceptionUtil.buildWorkflowException(execution, 500, "Caught a Java Lang Exception") + + }catch(Exception e){ + utils.log("DEBUG", "Caught Exception during processJavaException Method: " + e, isDebugEnabled) + execution.setVariable("UnexpectedError", "Exception in processJavaException method - " + Prefix) // Adding this line temporarily until this flows error handling gets updated + exceptionUtil.buildWorkflowException(execution, 500, "Exception in processJavaException method" + Prefix) + } + utils.log("DEBUG", "Completed processJavaException Method in " + Prefix, isDebugEnabled) + } + +} diff --git a/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/DoCreateServiceInstance.groovy b/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/DoCreateServiceInstance.groovy index be26247416..e6276a8852 100644 --- a/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/DoCreateServiceInstance.groovy +++ b/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/DoCreateServiceInstance.groovy @@ -1,39 +1,39 @@ -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - MSO - * ================================================================================ - * 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========================================================= +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.bpmn.infrastructure.scripts; +package org.openecomp.mso.bpmn.infrastructure.scripts; import static org.apache.commons.lang3.StringUtils.*; import groovy.xml.XmlUtil import groovy.json.* -import org.openecomp.mso.bpmn.core.json.JsonUtils -import org.openecomp.mso.bpmn.common.scripts.AaiUtil -import org.openecomp.mso.bpmn.common.scripts.AbstractServiceTaskProcessor -import org.openecomp.mso.bpmn.common.scripts.ExceptionUtil -import org.openecomp.mso.bpmn.common.scripts.SDNCAdapterUtils -import org.openecomp.mso.bpmn.common.scripts.VidUtils -import org.openecomp.mso.bpmn.core.RollbackData -import org.openecomp.mso.bpmn.core.WorkflowException -import org.openecomp.mso.rest.APIResponse; -import org.openecomp.mso.rest.RESTClient -import org.openecomp.mso.rest.RESTConfig +import org.openecomp.mso.bpmn.core.json.JsonUtils +import org.openecomp.mso.bpmn.common.scripts.AaiUtil +import org.openecomp.mso.bpmn.common.scripts.AbstractServiceTaskProcessor +import org.openecomp.mso.bpmn.common.scripts.ExceptionUtil +import org.openecomp.mso.bpmn.common.scripts.SDNCAdapterUtils +import org.openecomp.mso.bpmn.common.scripts.VidUtils +import org.openecomp.mso.bpmn.core.RollbackData +import org.openecomp.mso.bpmn.core.WorkflowException +import org.openecomp.mso.rest.APIResponse; +import org.openecomp.mso.rest.RESTClient +import org.openecomp.mso.rest.RESTConfig import java.util.UUID; @@ -46,7 +46,7 @@ import org.springframework.web.util.UriUtils; /** * This groovy class supports the DoCreateServiceInstance.bpmn process. - * + * * Inputs: * @param - msoRequestId * @param - globalSubscriberId @@ -64,7 +64,7 @@ import org.springframework.web.util.UriUtils; * @param - rollbackData (localRB->null) * @param - rolledBack (no localRB->null, localRB F->false, localRB S->true) * @param - WorkflowException - * @param - serviceInstanceName - TODO (GET from AAI if null in input) + * @param - serviceInstanceName - (GET from AAI if null in input) * */ public class DoCreateServiceInstance extends AbstractServiceTaskProcessor { @@ -362,9 +362,9 @@ public class DoCreateServiceInstance extends AbstractServiceTaskProcessor { } String sdncAssignRequest = - """ + """ ${sdncRequestId} ${serviceInstanceId} @@ -423,7 +423,7 @@ public class DoCreateServiceInstance extends AbstractServiceTaskProcessor { } utils.log("DEBUG"," *****Exit preProcessSDNCAssignRequest *****", isDebugEnabled) } - + public void postProcessSDNCAssign (Execution execution) { def isDebugEnabled=execution.getVariable("isDebugLogEnabled") utils.log("DEBUG"," ***** postProcessSDNCAssign ***** ", isDebugEnabled) @@ -460,6 +460,49 @@ public class DoCreateServiceInstance extends AbstractServiceTaskProcessor { } utils.log("DEBUG"," *** Exit postProcessSDNCAssign *** ", isDebugEnabled) } + + public void postProcessAAIGET2(Execution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + utils.log("DEBUG"," ***** postProcessAAIGET2 ***** ", isDebugEnabled) + String msg = "" + + try { + String serviceInstanceName = execution.getVariable("serviceInstanceName") + boolean succInAAI = execution.getVariable("GENGS_SuccessIndicator") + if(succInAAI != true){ + utils.log("DEBUG","Error getting Service-instance from AAI in postProcessAAIGET2", + serviceInstanceName, isDebugEnabled) + WorkflowException workflowException = execution.getVariable("WorkflowException") + utils.logAudit("workflowException: " + workflowException) + if(workflowException != null){ + exceptionUtil.buildAndThrowWorkflowException(execution, workflowException.getErrorCode(), workflowException.getErrorMessage()) + } + else + { + msg = "Failure in postProcessAAIGET2 GENGS_SuccessIndicator:" + succInAAI + utils.log("DEBUG", msg, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg) + } + } + else + { + boolean foundInAAI = execution.getVariable("GENGS_FoundIndicator") + if(foundInAAI == true){ + String aaiService = execution.getVariable("GENGS_service") + if (!isBlank(aaiService) && (utils.nodeExists(aaiService, "service-instance-name"))) { + execution.setVariable("serviceInstanceName", utils.getNodeText1(aaiService, "service-instance-name")) + utils.log("DEBUG","Found Service-instance in AAI.serviceInstanceName:" + execution.getVariable("serviceInstanceName"), isDebugEnabled) + } + } + } + } catch (BpmnError e) { + throw e; + } catch (Exception ex) { + msg = "Exception in DoCreateServiceInstance.postProcessAAIGET2 " + ex.getMessage() + utils.log("DEBUG", msg, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + utils.log("DEBUG"," *** Exit postProcessAAIGET2 *** ", isDebugEnabled) + } public void preProcessRollback (Execution execution) { def isDebugEnabled=execution.getVariable("isDebugLogEnabled") diff --git a/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/DoCreateServiceInstanceRollback.groovy b/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/DoCreateServiceInstanceRollback.groovy index bc34987cec..1e6541e226 100644 --- a/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/DoCreateServiceInstanceRollback.groovy +++ b/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/DoCreateServiceInstanceRollback.groovy @@ -1,231 +1,231 @@ -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - MSO - * ================================================================================ - * 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.openecomp.mso.bpmn.infrastructure.scripts - - -import static org.apache.commons.lang3.StringUtils.*; -import groovy.xml.XmlUtil -import groovy.json.* - -import org.openecomp.mso.bpmn.core.json.JsonUtils -import org.openecomp.mso.bpmn.common.scripts.AbstractServiceTaskProcessor -import org.openecomp.mso.bpmn.common.scripts.SDNCAdapterUtils -import org.openecomp.mso.bpmn.core.RollbackData -import org.openecomp.mso.bpmn.core.WorkflowException -import org.openecomp.mso.rest.APIResponse; -import org.openecomp.mso.rest.RESTClient -import org.openecomp.mso.rest.RESTConfig - -import java.util.UUID; - -import org.camunda.bpm.engine.delegate.BpmnError -import org.camunda.bpm.engine.runtime.Execution -import org.json.JSONObject; -import org.apache.commons.lang3.* -import org.apache.commons.codec.binary.Base64; -import org.springframework.web.util.UriUtils; -/** - * This groovy class supports the DoCreateServiceInstanceRollback.bpmn process. - * - * Inputs: - * @param - msoRequestId - * @param - rollbackData with - * globalCustomerId - * subscriptionServiceType - * serviceInstanceId - * disableRollback - * rollbackAAI - * rollbackSDNC - * sdncRollbackRequest - * - * - * Outputs: - * @param - rollbackError - * @param - rolledBack (no localRB->null, localRB F->false, localRB S->true) - * - */ -public class DoCreateServiceInstanceRollback extends AbstractServiceTaskProcessor{ - - String Prefix="DCRESIRB_" - - public void preProcessRequest(Execution execution) { - def isDebugEnabled = execution.getVariable("isDebugLogEnabled") - execution.setVariable("prefix",Prefix) - String msg = "" - utils.log("DEBUG"," ***** preProcessRequest *****", isDebugEnabled) - execution.setVariable("rollbackAAI",false) - execution.setVariable("rollbackSDNC",false) - - try { - def rollbackData = execution.getVariable("rollbackData") - utils.log("DEBUG", "RollbackData:" + rollbackData, isDebugEnabled) - - if (rollbackData != null) { - if (rollbackData.hasType("SERVICEINSTANCE")) { - - def serviceInstanceId = rollbackData.get("SERVICEINSTANCE", "serviceInstanceId") - execution.setVariable("serviceInstanceId", serviceInstanceId) - - def subscriptionServiceType = rollbackData.get("SERVICEINSTANCE", "subscriptionServiceType") - execution.setVariable("subscriptionServiceType", subscriptionServiceType) - - def globalSubscriberId = rollbackData.get("SERVICEINSTANCE", "globalSubscriberId") - execution.setVariable("globalSubscriberId", globalSubscriberId) - - def rollbackAAI = rollbackData.get("SERVICEINSTANCE", "rollbackAAI") - if ("true".equals(rollbackAAI)) - { - execution.setVariable("rollbackAAI",true) - } - - def rollbackSDNC = rollbackData.get("SERVICEINSTANCE", "rollbackSDNC") - if ("true".equals(rollbackSDNC)) - { - execution.setVariable("rollbackSDNC", true) - } - - if (execution.getVariable("rollbackAAI") != true && execution.getVariable("rollbackSDNC") != true) - { - execution.setVariable("skipRollback", true) - } - - def sdncRollbackRequest = rollbackData.get("SERVICEINSTANCE", "sdncRollbackRequest") - execution.setVariable("sdncRollbackRequest", sdncRollbackRequest) - } - else { - execution.setVariable("skipRollback", true) - } - } - else { - execution.setVariable("skipRollback", true) - } - if (execution.getVariable("disableRollback").equals("true" )) - { - execution.setVariable("skipRollback", true) - } - - } catch (BpmnError e) { - throw e; - } catch (Exception ex){ - msg = "Exception in Create ServiceInstance Rollback preProcessRequest " + ex.getMessage() - utils.log("DEBUG", msg, isDebugEnabled) - exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) - } - utils.log("DEBUG"," ***** Exit preProcessRequest *****", isDebugEnabled) - } - - public void validateSDNCResponse(Execution execution) { - def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - utils.log("DEBUG"," ***** validateSDNCResponse ***** ", isDebugEnabled) - String msg = "" - try { - WorkflowException workflowException = execution.getVariable("WorkflowException") - - boolean successIndicator = execution.getVariable("SDNCA_SuccessIndicator") - String response = execution.getVariable("sdncAdapterResponse") - - SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils(this) - sdncAdapterUtils.validateSDNCResponse(execution, response, workflowException, successIndicator) - - if(execution.getVariable(Prefix + 'sdncResponseSuccess') == true){ - utils.log("DEBUG", "SDNC Adapter for service-instance delete for rollback successful. response", isDebugEnabled) - }else{ - execution.setVariable("rolledBack", false) - execution.setVariable("rollbackError", "Error Response from SDNC Adapter for service-instance delete for rollback") - utils.log("DEBUG","Error Response from SDNC Adapter for service-instance delete for rollback", isDebugEnabled) - throw new BpmnError("MSOWorkflowException") - } - } catch (BpmnError e) { - throw e; - } catch (Exception ex){ - msg = "Exception in Create ServiceInstance Rollback validateSDNCResponse " + ex.getMessage() - utils.log("DEBUG", msg, isDebugEnabled) - exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) - } - utils.log("DEBUG"," ***** Exit validateSDNCResponse ***** ", isDebugEnabled) - } - - public void postProcessRequest(Execution execution) { - def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - utils.log("DEBUG"," ***** postProcessRequest ***** ", isDebugEnabled) - String msg = "" - try { - execution.setVariable("rollbackData", null) - String serviceInstanceId = execution.getVariable("serviceInstanceId") - boolean rollbackAAI = execution.getVariable("rollbackAAI") - boolean rollbackSDNC = execution.getVariable("rollbackSDNC") - if (rollbackAAI == true || rollbackSDNC == true) - { - execution.setVariable("rolledBack", true) - } - if (rollbackAAI == true) - { - boolean succInAAI = execution.getVariable("GENDS_SuccessIndicator") - if(succInAAI != true){ - execution.setVariable("rolledBack", false) //both sdnc and aai must be successful to declare rollback Succesful - execution.setVariable("rollbackError", "Error deleting service-instance in AAI for rollback") - utils.log("DEBUG","Error deleting service-instance in AAI for rollback", + serviceInstanceId, isDebugEnabled) - } - } - utils.log("DEBUG","*** Exit postProcessRequest ***", isDebugEnabled) - - } catch (BpmnError e) { - msg = "Exception in Create ServiceInstance Rollback postProcessRequest. " + ex.getMessage() - utils.log("DEBUG", msg, isDebugEnabled) - } catch (Exception ex) { - msg = "Exception in Create ServiceInstance Rollback postProcessRequest. " + ex.getMessage() - utils.log("DEBUG", msg, isDebugEnabled) - } - - } - - public void processRollbackException(Execution execution){ - def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - utils.log("DEBUG"," ***** processRollbackException ***** ", isDebugEnabled) - try{ - utils.log("DEBUG", "Caught an Exception in DoCreateServiceInstanceRollback", isDebugEnabled) - execution.setVariable("rollbackData", null) - execution.setVariable("rollbackError", "Caught exception in ServiceInstance Create Rollback") - execution.setVariable("WorkflowException", null) - - }catch(BpmnError b){ - utils.log("DEBUG", "BPMN Error during processRollbackExceptions Method: ", isDebugEnabled) - }catch(Exception e){ - utils.log("DEBUG", "Caught Exception during processRollbackExceptions Method: " + e.getMessage(), isDebugEnabled) - } - - utils.log("DEBUG", " Exit processRollbackException", isDebugEnabled) - } - - public void processRollbackJavaException(Execution execution){ - def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - utils.log("DEBUG"," ***** processRollbackJavaException ***** ", isDebugEnabled) - try{ - execution.setVariable("rollbackData", null) - execution.setVariable("rollbackError", "Caught Java exception in ServiceInstance Create Rollback") - utils.log("DEBUG", "Caught Exception in processRollbackJavaException", isDebugEnabled) - - }catch(Exception e){ - utils.log("DEBUG", "Caught Exception in processRollbackJavaException " + e.getMessage(), isDebugEnabled) - } - utils.log("DEBUG", "***** Exit processRollbackJavaException *****", isDebugEnabled) - } - -} +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.bpmn.infrastructure.scripts + + +import static org.apache.commons.lang3.StringUtils.*; +import groovy.xml.XmlUtil +import groovy.json.* + +import org.openecomp.mso.bpmn.core.json.JsonUtils +import org.openecomp.mso.bpmn.common.scripts.AbstractServiceTaskProcessor +import org.openecomp.mso.bpmn.common.scripts.SDNCAdapterUtils +import org.openecomp.mso.bpmn.core.RollbackData +import org.openecomp.mso.bpmn.core.WorkflowException +import org.openecomp.mso.rest.APIResponse; +import org.openecomp.mso.rest.RESTClient +import org.openecomp.mso.rest.RESTConfig + +import java.util.UUID; + +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.runtime.Execution +import org.json.JSONObject; +import org.apache.commons.lang3.* +import org.apache.commons.codec.binary.Base64; +import org.springframework.web.util.UriUtils; +/** + * This groovy class supports the DoCreateServiceInstanceRollback.bpmn process. + * + * Inputs: + * @param - msoRequestId + * @param - rollbackData with + * globalCustomerId + * subscriptionServiceType + * serviceInstanceId + * disableRollback + * rollbackAAI + * rollbackSDNC + * sdncRollbackRequest + * + * + * Outputs: + * @param - rollbackError + * @param - rolledBack (no localRB->null, localRB F->false, localRB S->true) + * + */ +public class DoCreateServiceInstanceRollback extends AbstractServiceTaskProcessor{ + + String Prefix="DCRESIRB_" + + public void preProcessRequest(Execution execution) { + def isDebugEnabled = execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix",Prefix) + String msg = "" + utils.log("DEBUG"," ***** preProcessRequest *****", isDebugEnabled) + execution.setVariable("rollbackAAI",false) + execution.setVariable("rollbackSDNC",false) + + try { + def rollbackData = execution.getVariable("rollbackData") + utils.log("DEBUG", "RollbackData:" + rollbackData, isDebugEnabled) + + if (rollbackData != null) { + if (rollbackData.hasType("SERVICEINSTANCE")) { + + def serviceInstanceId = rollbackData.get("SERVICEINSTANCE", "serviceInstanceId") + execution.setVariable("serviceInstanceId", serviceInstanceId) + + def subscriptionServiceType = rollbackData.get("SERVICEINSTANCE", "subscriptionServiceType") + execution.setVariable("subscriptionServiceType", subscriptionServiceType) + + def globalSubscriberId = rollbackData.get("SERVICEINSTANCE", "globalSubscriberId") + execution.setVariable("globalSubscriberId", globalSubscriberId) + + def rollbackAAI = rollbackData.get("SERVICEINSTANCE", "rollbackAAI") + if ("true".equals(rollbackAAI)) + { + execution.setVariable("rollbackAAI",true) + } + + def rollbackSDNC = rollbackData.get("SERVICEINSTANCE", "rollbackSDNC") + if ("true".equals(rollbackSDNC)) + { + execution.setVariable("rollbackSDNC", true) + } + + if (execution.getVariable("rollbackAAI") != true && execution.getVariable("rollbackSDNC") != true) + { + execution.setVariable("skipRollback", true) + } + + def sdncRollbackRequest = rollbackData.get("SERVICEINSTANCE", "sdncRollbackRequest") + execution.setVariable("sdncRollbackRequest", sdncRollbackRequest) + } + else { + execution.setVariable("skipRollback", true) + } + } + else { + execution.setVariable("skipRollback", true) + } + if (execution.getVariable("disableRollback").equals("true" )) + { + execution.setVariable("skipRollback", true) + } + + } catch (BpmnError e) { + throw e; + } catch (Exception ex){ + msg = "Exception in Create ServiceInstance Rollback preProcessRequest " + ex.getMessage() + utils.log("DEBUG", msg, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + utils.log("DEBUG"," ***** Exit preProcessRequest *****", isDebugEnabled) + } + + public void validateSDNCResponse(Execution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + utils.log("DEBUG"," ***** validateSDNCResponse ***** ", isDebugEnabled) + String msg = "" + try { + WorkflowException workflowException = execution.getVariable("WorkflowException") + + boolean successIndicator = execution.getVariable("SDNCA_SuccessIndicator") + String response = execution.getVariable("sdncAdapterResponse") + + SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils(this) + sdncAdapterUtils.validateSDNCResponse(execution, response, workflowException, successIndicator) + + if(execution.getVariable(Prefix + 'sdncResponseSuccess') == true){ + utils.log("DEBUG", "SDNC Adapter for service-instance delete for rollback successful. response", isDebugEnabled) + }else{ + execution.setVariable("rolledBack", false) + execution.setVariable("rollbackError", "Error Response from SDNC Adapter for service-instance delete for rollback") + utils.log("DEBUG","Error Response from SDNC Adapter for service-instance delete for rollback", isDebugEnabled) + throw new BpmnError("MSOWorkflowException") + } + } catch (BpmnError e) { + throw e; + } catch (Exception ex){ + msg = "Exception in Create ServiceInstance Rollback validateSDNCResponse " + ex.getMessage() + utils.log("DEBUG", msg, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + utils.log("DEBUG"," ***** Exit validateSDNCResponse ***** ", isDebugEnabled) + } + + public void postProcessRequest(Execution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + utils.log("DEBUG"," ***** postProcessRequest ***** ", isDebugEnabled) + String msg = "" + try { + execution.setVariable("rollbackData", null) + String serviceInstanceId = execution.getVariable("serviceInstanceId") + boolean rollbackAAI = execution.getVariable("rollbackAAI") + boolean rollbackSDNC = execution.getVariable("rollbackSDNC") + if (rollbackAAI == true || rollbackSDNC == true) + { + execution.setVariable("rolledBack", true) + } + if (rollbackAAI == true) + { + boolean succInAAI = execution.getVariable("GENDS_SuccessIndicator") + if(succInAAI != true){ + execution.setVariable("rolledBack", false) //both sdnc and aai must be successful to declare rollback Succesful + execution.setVariable("rollbackError", "Error deleting service-instance in AAI for rollback") + utils.log("DEBUG","Error deleting service-instance in AAI for rollback", + serviceInstanceId, isDebugEnabled) + } + } + utils.log("DEBUG","*** Exit postProcessRequest ***", isDebugEnabled) + + } catch (BpmnError e) { + msg = "Exception in Create ServiceInstance Rollback postProcessRequest. " + ex.getMessage() + utils.log("DEBUG", msg, isDebugEnabled) + } catch (Exception ex) { + msg = "Exception in Create ServiceInstance Rollback postProcessRequest. " + ex.getMessage() + utils.log("DEBUG", msg, isDebugEnabled) + } + + } + + public void processRollbackException(Execution execution){ + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + utils.log("DEBUG"," ***** processRollbackException ***** ", isDebugEnabled) + try{ + utils.log("DEBUG", "Caught an Exception in DoCreateServiceInstanceRollback", isDebugEnabled) + execution.setVariable("rollbackData", null) + execution.setVariable("rollbackError", "Caught exception in ServiceInstance Create Rollback") + execution.setVariable("WorkflowException", null) + + }catch(BpmnError b){ + utils.log("DEBUG", "BPMN Error during processRollbackExceptions Method: ", isDebugEnabled) + }catch(Exception e){ + utils.log("DEBUG", "Caught Exception during processRollbackExceptions Method: " + e.getMessage(), isDebugEnabled) + } + + utils.log("DEBUG", " Exit processRollbackException", isDebugEnabled) + } + + public void processRollbackJavaException(Execution execution){ + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + utils.log("DEBUG"," ***** processRollbackJavaException ***** ", isDebugEnabled) + try{ + execution.setVariable("rollbackData", null) + execution.setVariable("rollbackError", "Caught Java exception in ServiceInstance Create Rollback") + utils.log("DEBUG", "Caught Exception in processRollbackJavaException", isDebugEnabled) + + }catch(Exception e){ + utils.log("DEBUG", "Caught Exception in processRollbackJavaException " + e.getMessage(), isDebugEnabled) + } + utils.log("DEBUG", "***** Exit processRollbackJavaException *****", isDebugEnabled) + } + +} diff --git a/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/DoCreateVfModule.groovy b/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/DoCreateVfModule.groovy index 739a9dd027..269cb808c4 100644 --- a/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/DoCreateVfModule.groovy +++ b/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/DoCreateVfModule.groovy @@ -17,12 +17,12 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - + package org.openecomp.mso.bpmn.infrastructure.scripts; - -import javax.xml.parsers.DocumentBuilder -import javax.xml.parsers.DocumentBuilderFactory - + +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.runtime.Execution @@ -37,21 +37,22 @@ import org.openecomp.mso.bpmn.core.json.JsonUtils import org.openecomp.mso.rest.APIResponse import org.openecomp.mso.rest.RESTClient import org.openecomp.mso.rest.RESTConfig -import org.springframework.web.util.UriUtils -import org.w3c.dom.Document -import org.w3c.dom.Element -import org.w3c.dom.NamedNodeMap -import org.w3c.dom.Node +import org.springframework.web.util.UriUtils +import org.w3c.dom.Document +import org.w3c.dom.Element +import org.w3c.dom.NamedNodeMap +import org.w3c.dom.Node import org.w3c.dom.NodeList -import org.xml.sax.InputSource - - +import org.xml.sax.InputSource + + public class DoCreateVfModule extends VfModuleBase { String Prefix="DCVFM_" ExceptionUtil exceptionUtil = new ExceptionUtil() JsonUtils jsonUtil = new JsonUtils() + SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils(this) /** * Validates the request message and sets up the workflow. @@ -65,36 +66,40 @@ public class DoCreateVfModule extends VfModuleBase { logDebug('Entered ' + method, isDebugLogEnabled) execution.setVariable('prefix', Prefix) - try{ + try{ def rollbackData = execution.getVariable("RollbackData") if (rollbackData == null) { rollbackData = new RollbackData() } - + execution.setVariable("DCVFM_vnfParamsExistFlag", false) execution.setVariable("DCVFM_oamManagementV4Address", "") execution.setVariable("DCVFM_oamManagementV6Address", "") - + String request = execution.getVariable("DoCreateVfModuleRequest") - + if (request == null || request.isEmpty()) { // Building Block-type request + + String vfModuleModelInfo = execution.getVariable("vfModuleModelInfo") - String cloudConfiguration = execution.getVariable("cloudConfiguration") - String vfModuleModelInfo = execution.getVariable("vfModuleModelInfo") + def serviceModelInfo = execution.getVariable("serviceModelInfo") + logDebug("serviceModelInfo: " + serviceModelInfo, isDebugLogEnabled) + def vnfModelInfo = execution.getVariable("vnfModelInfo") + //tenantId - def tenantId = jsonUtil.getJsonValue(cloudConfiguration, "cloudConfiguration.tenantId") + def tenantId = execution.getVariable("tenantId") execution.setVariable("DCVFM_tenantId", tenantId) rollbackData.put("VFMODULE", "tenantid", tenantId) //volumeGroupId - def volumeGroupId = execution.getVariable("volumeGroupId") + def volumeGroupId = execution.getVariable("volumeGroupId") execution.setVariable("DCVFM_volumeGroupId", volumeGroupId) //volumeGroupName - def volumeGroupName = execution.getVariable("volumeGroupName") + def volumeGroupName = execution.getVariable("volumeGroupName") execution.setVariable("DCVFM_volumeGroupName", volumeGroupName) //cloudSiteId - def cloudSiteId = jsonUtil.getJsonValue(cloudConfiguration, "cloudConfiguration.lcpCloudRegionId") + def cloudSiteId = execution.getVariable("lcpCloudRegionId") execution.setVariable("DCVFM_cloudSiteId", cloudSiteId) rollbackData.put("VFMODULE", "aiccloudregion", cloudSiteId) logDebug("cloudSiteId: " + cloudSiteId, isDebugLogEnabled) @@ -104,50 +109,50 @@ public class DoCreateVfModule extends VfModuleBase { rollbackData.put("VFMODULE", "vnftype", vnfType) logDebug("vnfType: " + vnfType, isDebugLogEnabled) //vnfName - def vnfName = execution.getVariable("vnfName") + def vnfName = execution.getVariable("vnfName") execution.setVariable("DCVFM_vnfName", vnfName) rollbackData.put("VFMODULE", "vnfname", vnfName) logDebug("vnfName: " + vnfName, isDebugLogEnabled) //vnfId - def vnfId = execution.getVariable("vnfId") + def vnfId = execution.getVariable("vnfId") execution.setVariable("DCVFM_vnfId", vnfId) rollbackData.put("VFMODULE", "vnfid", vnfId) logDebug("vnfId: " + vnfId, isDebugLogEnabled) //vfModuleName - def vfModuleName = execution.getVariable("vfModuleName") + def vfModuleName = execution.getVariable("vfModuleName") execution.setVariable("DCVFM_vfModuleName", vfModuleName) rollbackData.put("VFMODULE", "vfmodulename", vfModuleName) logDebug("vfModuleName: " + vfModuleName, isDebugLogEnabled) //vfModuleModelName - def vfModuleModelName = jsonUtil.getJsonValue(vfModuleModelInfo, "modelInfo.modelName") + def vfModuleModelName = jsonUtil.getJsonValue(vfModuleModelInfo, "modelName") execution.setVariable("DCVFM_vfModuleModelName", vfModuleModelName) rollbackData.put("VFMODULE", "vfmodulemodelname", vfModuleModelName) logDebug("vfModuleModelName: " + vfModuleModelName, isDebugLogEnabled) //modelCustomizationUuid - def modelCustomizationUuid = jsonUtil.getJsonValue(vfModuleModelInfo, "modelInfo.modelCustomizationId") + def modelCustomizationUuid = jsonUtil.getJsonValue(vfModuleModelInfo, "modelCustomizationUuid") execution.setVariable("DCVFM_modelCustomizationUuid", modelCustomizationUuid) rollbackData.put("VFMODULE", "modelcustomizationuuid", modelCustomizationUuid) logDebug("modelCustomizationUuid: " + modelCustomizationUuid, isDebugLogEnabled) //vfModuleId - def vfModuleId = execution.getVariable("vfModuleId") + def vfModuleId = execution.getVariable("vfModuleId") execution.setVariable("DCVFM_vfModuleId", vfModuleId) logDebug("vfModuleId: " + vfModuleId, isDebugLogEnabled) - def requestId = execution.getVariable("requestId") + def requestId = execution.getVariable("msoRequestId") execution.setVariable("DCVFM_requestId", requestId) logDebug("requestId: " + requestId, isDebugLogEnabled) // Set mso-request-id to request-id for VNF Adapter interface execution.setVariable("mso-request-id", requestId) //serviceId - def serviceId = execution.getVariable("serviceId") + def serviceId = execution.getVariable("serviceId") execution.setVariable("DCVFM_serviceId", serviceId) logDebug("serviceId: " + serviceId, isDebugLogEnabled) //serviceInstanceId - def serviceInstanceId = execution.getVariable("serviceInstanceId") + def serviceInstanceId = execution.getVariable("serviceInstanceId") execution.setVariable("DCVFM_serviceInstanceId", serviceInstanceId) rollbackData.put("VFMODULE", "serviceInstanceId", serviceInstanceId) logDebug("serviceInstanceId: " + serviceInstanceId, isDebugLogEnabled) //source - HARDCODED - def source = "VID" + def source = "VID" execution.setVariable("DCVFM_source", source) rollbackData.put("VFMODULE", "source", source) logDebug("source: " + source, isDebugLogEnabled) @@ -156,21 +161,27 @@ public class DoCreateVfModule extends VfModuleBase { def backoutOnFailure = true if (disableRollback != null && disableRollback.equals("true")) { backoutOnFailure = false - } + } execution.setVariable("DCVFM_backoutOnFailure", backoutOnFailure) logDebug("backoutOnFailure: " + backoutOnFailure, isDebugLogEnabled) //isBaseVfModule - def isBaseVfModule = execution.getVariable("isBaseVfModule") + def isBaseVfModule = execution.getVariable("isBaseVfModule") execution.setVariable("DCVFM_isBaseVfModule", isBaseVfModule) - logDebug("isBaseVfModule: " + isBaseVfModule, isDebugLogEnabled) + logDebug("isBaseVfModule: " + isBaseVfModule, isDebugLogEnabled) //asdcServiceModelVersion - def asdcServiceModelVersion = execution.getVariable("asdcServiceModelVersion") + def asdcServiceModelVersion = execution.getVariable("asdcServiceModelVersion") execution.setVariable("DCVFM_asdcServiceModelVersion", asdcServiceModelVersion) - logDebug("asdcServiceModelVersion: " + asdcServiceModelVersion, isDebugLogEnabled) + logDebug("asdcServiceModelVersion: " + asdcServiceModelVersion, isDebugLogEnabled) //personaModelId - execution.setVariable("DCVFM_personaModelId", jsonUtil.getJsonValue(vfModuleModelInfo, "modelInfo.modelInvariantId")) + execution.setVariable("DCVFM_personaModelId", jsonUtil.getJsonValue(vfModuleModelInfo, "modelInvariantId")) //personaModelVersion - execution.setVariable("DCVFM_personaModelVersion", jsonUtil.getJsonValue(vfModuleModelInfo, "modelInfo.modelVersion")) + execution.setVariable("DCVFM_personaModelVersion", jsonUtil.getJsonValue(vfModuleModelInfo, "modelVersion")) + //vfModuleLabel + def vfModuleLabel = execution.getVariable("vfModuleLabel") + if (vfModuleLabel != null) { + execution.setVariable("DCVFM_vfModuleLabel", vfModuleLabel) + logDebug("vfModuleLabel: " + vfModuleLabel, isDebugLogEnabled) + } //Get or Generate UUID String uuid = execution.getVariable("DCVFM_uuid") if(uuid == null){ @@ -185,14 +196,25 @@ public class DoCreateVfModule extends VfModuleBase { if (isVidRequest == null || isVidRequest.isEmpty()) { execution.setVariable("isVidRequest", "true") } - - String vnfParamsChildNodes = execution.getVariable("vfModuleInputParams") - + //globalSubscriberId + String globalSubscriberId = execution.getVariable("globalSubscriberId") + execution.setVariable("DCVFM_globalSubscriberId", globalSubscriberId) + logDebug("globalSubsrciberId: " + globalSubscriberId, isDebugLogEnabled) + Map vfModuleInputParams = execution.getVariable("vfModuleInputParams") + if (vfModuleInputParams != null) { + execution.setVariable("DCVFM_vnfParamsMap", vfModuleInputParams) + execution.setVariable("DCVFM_vnfParamsExistFlag", true) + } + //usePreload + def usePreload = execution.getVariable("usePreload") + execution.setVariable("DCVFM_usePreload", usePreload) + logDebug("usePreload: " + usePreload, isDebugLogEnabled) + } else { - // The info is inside the request + // The info is inside the request - DEAD CODE utils.logAudit("DoCreateVfModule request: " + request) - + //tenantId def tenantId = "" if (utils.nodeExists(request, "tenant-id")) { @@ -316,15 +338,15 @@ public class DoCreateVfModule extends VfModuleBase { } execution.setVariable("DCVFM_isBaseVfModule", isBaseVfModule) logDebug("isBaseVfModule: " + isBaseVfModule, isDebugLogEnabled) - + //asdcServiceModelVersion def asdcServiceModelVersion = "" if (utils.nodeExists(request, "asdc-service-model-version")) { asdcServiceModelVersion = utils.getNodeText(request, "asdc-service-model-version") } execution.setVariable("DCVFM_asdcServiceModelVersion", asdcServiceModelVersion) - logDebug("asdcServiceModelVersion: " + asdcServiceModelVersion, isDebugLogEnabled) - + logDebug("asdcServiceModelVersion: " + asdcServiceModelVersion, isDebugLogEnabled) + //personaModelId def personaModelId = "" if (utils.nodeExists(request, "persona-model-id")) { @@ -332,7 +354,7 @@ public class DoCreateVfModule extends VfModuleBase { } execution.setVariable("DCVFM_personaModelId", personaModelId) logDebug("personaModelId: " + personaModelId, isDebugLogEnabled) - + //personaModelVersion def personaModelVersion = "" if (utils.nodeExists(request, "persona-model-version")) { @@ -340,16 +362,16 @@ public class DoCreateVfModule extends VfModuleBase { } execution.setVariable("DCVFM_personaModelVersion", personaModelVersion) logDebug("personaModelVersion: " + personaModelVersion, isDebugLogEnabled) - + // Process the parameters - + String vnfParamsChildNodes = utils.getChildNodes(request, "vnf-params") if(vnfParamsChildNodes == null || vnfParamsChildNodes.length() < 1){ utils.log("DEBUG", "Request contains NO VNF Params", isDebugLogEnabled) }else{ utils.log("DEBUG", "Request does contain VNF Params", isDebugLogEnabled) execution.setVariable("DCVFM_vnfParamsExistFlag", true) - + InputSource xmlSource = new InputSource(new StringReader(request)); DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); docFactory.setNamespaceAware(true) @@ -358,7 +380,7 @@ public class DoCreateVfModule extends VfModuleBase { //Get params, build map Map paramsMap = new HashMap() NodeList paramsList = xml.getElementsByTagNameNS("*", "param") - + for (int z = 0; z < paramsList.getLength(); z++) { Node node = paramsList.item(z) String paramValue = node.getTextContent() @@ -369,7 +391,7 @@ public class DoCreateVfModule extends VfModuleBase { execution.setVariable("DCVFM_vnfParamsMap", paramsMap) } } - + //Get or Generate UUID String uuid = execution.getVariable("DCVFM_uuid") if(uuid == null){ @@ -378,6 +400,14 @@ public class DoCreateVfModule extends VfModuleBase { }else{ logDebug("Found messageId (UUID) is: " + uuid, isDebugLogEnabled) } + // Get sdncVersion, default to empty + String sdncVersion = execution.getVariable("sdncVersion") + if (sdncVersion == null) { + sdncVersion = "" + } + logDebug("sdncVersion: " + sdncVersion, isDebugLogEnabled) + execution.setVariable("DCVFM_sdncVersion", sdncVersion) + execution.setVariable("DCVFM_uuid", uuid) execution.setVariable("DCVFM_baseVfModuleId", "") execution.setVariable("DCVFM_baseVfModuleHeatStackId", "") @@ -386,6 +416,7 @@ public class DoCreateVfModule extends VfModuleBase { execution.setVariable("DCVFM_volumeGroupStackId", "") execution.setVariable("DCVFM_cloudRegionForVolume", "") execution.setVariable("DCVFM_contrailNetworkPolicyFqdnList", "") + execution.setVariable("DCVFM_vnfTypeToQuery", "generic-vnf") rollbackData.put("VFMODULE", "rollbackPrepareUpdateVfModule", "false") rollbackData.put("VFMODULE", "rollbackUpdateAAIVfModule", "false") rollbackData.put("VFMODULE", "rollbackVnfAdapterCreate", "false") @@ -394,7 +425,7 @@ public class DoCreateVfModule extends VfModuleBase { rollbackData.put("VFMODULE", "rollbackCreateAAIVfModule", "false") rollbackData.put("VFMODULE", "rollbackCreateNetworkPoliciesAAI", "false") rollbackData.put("VFMODULE", "rollbackUpdateVnfAAI", "false") - + String sdncCallbackUrl = (String) execution.getVariable('URN_mso_workflow_sdncadapter_callback') if (sdncCallbackUrl == null || sdncCallbackUrl.trim().isEmpty()) { def msg = 'Required variable \'URN_mso_workflow_sdncadapter_callback\' is missing' @@ -403,9 +434,9 @@ public class DoCreateVfModule extends VfModuleBase { } execution.setVariable("DCVFM_sdncCallbackUrl", sdncCallbackUrl) utils.logAudit("SDNC Callback URL: " + sdncCallbackUrl) - logDebug("SDNC Callback URL is: " + sdncCallbackUrl, isDebugLogEnabled) - - + logDebug("SDNC Callback URL is: " + sdncCallbackUrl, isDebugLogEnabled) + + execution.setVariable("RollbackData", rollbackData) }catch(BpmnError b){ throw b @@ -442,7 +473,7 @@ public class DoCreateVfModule extends VfModuleBase { logDebug('Entered ' + method, isDebugLogEnabled) try { - buildResponse(execution, "", 200) + sendWorkflowResponse(execution, 200, "") logDebug('Exited ' + method, isDebugLogEnabled) } catch (BpmnError e) { throw e; @@ -483,6 +514,9 @@ public class DoCreateVfModule extends VfModuleBase { String vfModuleId = utils.getNodeText1(createResponse, 'vf-module-id') execution.setVariable('DCVFM_vfModuleId', vfModuleId) logDebug("vfModuleId is: " + vfModuleId, isDebugLogEnabled) + String vfModuleIndex= utils.getNodeText1(createResponse, 'vf-module-index') + execution.setVariable('DCVFM_vfModuleIndex', vfModuleIndex) + logDebug("vfModuleIndex is: " + vfModuleIndex, isDebugLogEnabled) rollbackData.put("VFMODULE", "vnfid", vnfId) rollbackData.put("VFMODULE", "vfmoduleid", vfModuleId) rollbackData.put("VFMODULE", "rollbackCreateAAIVfModule", "true") @@ -621,30 +655,24 @@ public class DoCreateVfModule extends VfModuleBase { logDebug("======== COMPLETED preProcessSDNCAssignRequest ======== ", isDebugLogEnabled) } - public void preProcessSDNCGetRequest(Execution execution){ + public void preProcessSDNCGetRequest(Execution execution, String element){ def isDebugLogEnabled = execution.getVariable("isDebugLogEnabled") + String sdncVersion = execution.getVariable("DCVFM_sdncVersion") execution.setVariable("prefix", Prefix) utils.log("DEBUG", " ======== STARTED preProcessSDNCGetRequest Process ======== ", isDebugLogEnabled) try{ - String response = execution.getVariable("DCVFM_assignSDNCAdapterResponse") - utils.logAudit("DCVFM_assignSDNCAdapterResponse is: \n" + response) - - String data = utils.getNodeXml(response, "response-data") - data = data.replaceAll("<", "<") - data = data.replaceAll(">", ">") - String vnfId = utils.getNodeText1(data, "vnf-id") - def vfModuleId = execution.getVariable('DCVFM_vfModuleId') def serviceInstanceId = execution.getVariable('DCVFM_serviceInstanceId') - + String uuid = execution.getVariable('testReqId') // for junits if(uuid==null){ - uuid = execution.getVariable("mso-request-id") + "-" + System.currentTimeMillis() + uuid = execution.getVariable("mso-request-id") + "-" + System.currentTimeMillis() } - - String serviceOperation = "/VNF-API:vnfs/vnf-list/" + vfModuleId + def callbackUrl = execution.getVariable("DCVFM_sdncCallbackUrl") utils.logAudit("callbackUrl:" + callbackUrl) - + + def vfModuleId = execution.getVariable('DCVFM_vfModuleId') + def svcInstId = "" if (serviceInstanceId == null || serviceInstanceId.isEmpty()) { svcInstId = vfModuleId @@ -652,6 +680,35 @@ public class DoCreateVfModule extends VfModuleBase { else { svcInstId = serviceInstanceId } + // For VNF, serviceOperation (URI for topology GET) will be retrieved from "selflink" element + // in the response from GenericGetVnf + // For VF Module, in 1707 serviceOperation will be retrieved from "object-path" element + // in SDNC Assign Response + // For VF Module for older versions, serviceOperation is constructed using vfModuleId + + String serviceOperation = "" + if (element.equals("vnf")) { + def vnfQueryResponse = execution.getVariable("DCVFM_vnfQueryResponse") + serviceOperation = utils.getNodeText1(vnfQueryResponse, "selflink") + utils.log("DEBUG", "VNF - service operation: " + serviceOperation, isDebugLogEnabled) + } + else if (element.equals("vfmodule")) { + String response = execution.getVariable("DCVFM_assignSDNCAdapterResponse") + utils.logAudit("DCVFM_assignSDNCAdapterResponse is: \n" + response) + + if (!sdncVersion.equals("1707")) { + serviceOperation = "/VNF-API:vnfs/vnf-list/" + vfModuleId + utils.log("DEBUG", "VF Module with sdncVersion before 1707 - service operation: " + serviceOperation, isDebugLogEnabled) + } + else { + String data = utils.getNodeXml(response, "response-data") + data = data.replaceAll("<", "<") + data = data.replaceAll(">", ">") + utils.log("DEBUG", "responseData: " + data, isDebugLogEnabled) + serviceOperation = utils.getNodeText1(data, "object-path") + utils.log("DEBUG", "VF Module with sdncVersion of 1707 - service operation: " + serviceOperation, isDebugLogEnabled) + } + } //!!!! TEMPORARY WORKAROUND FOR SDNC REPLICATION ISSUE sleep(5000) @@ -710,6 +767,8 @@ public class DoCreateVfModule extends VfModuleBase { def vfModuleModelName = execution.getVariable("DCVFM_vfModuleModelName") //vfModuleId def vfModuleId = execution.getVariable("DCVFM_vfModuleId") + //vfModuleIndex + def vfModuleIndex = execution.getVariable("DCVFM_vfModuleIndex") //requestId def requestId = execution.getVariable("DCVFM_requestId") //serviceId @@ -744,34 +803,14 @@ public class DoCreateVfModule extends VfModuleBase { notificationUrl = utils.getQualifiedHostNameForCallback(notificationUrl) } - String vnfParams - if(execution.getVariable("DCVFM_vnfParamsExistFlag") == true){ - StringBuilder sbParams = new StringBuilder() - Map paramsMap = execution.getVariable("DCVFM_vnfParamsMap") - - for (Map.Entry entry : paramsMap.entrySet()) { - String paramsXml - String paramName = entry.getKey(); - String paramValue = entry.getValue() - paramsXml = - """ - ${paramName} - ${paramValue} - - """ - - vnfParams = sbParams.append(paramsXml) - } - }else{ - vnfParams = "" - } - + Map vnfParamsMap = execution.getVariable("DCVFM_vnfParamsMap") + //Get SDNC Response Data for VnfSubCreate Request String sdncGetResponse = execution.getVariable('DCVFM_getSDNCAdapterResponse') utils.logAudit("sdncGetResponse: " + sdncGetResponse) - String vfModuleParams = buildVfModuleParams(vnfParams, sdncGetResponse, vnfId, vnfName, - vfModuleId, vfModuleName) + String vfModuleParams = buildVfModuleParams(vnfParamsMap, sdncGetResponse, vnfId, vnfName, + vfModuleId, vfModuleName, vfModuleIndex) def svcInstId = "" if (serviceInstanceId == null || serviceInstanceId.isEmpty()) { @@ -781,7 +820,6 @@ public class DoCreateVfModule extends VfModuleBase { svcInstId = serviceInstanceId } - def createVnfARequest = """ ${cloudSiteId} @@ -864,13 +902,13 @@ public class DoCreateVfModule extends VfModuleBase { def requestId = execution.getVariable("mso-request-id") if (requestId == null) { - createWorkflowException(execution, 1002, processKey + " request has no mso-request-id") + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, processKey + " request has no mso-request-id") } def serviceInstanceId = execution.getVariable("mso-service-instance-id") if (serviceInstanceId == null) { - createWorkflowException(execution, 1002, processKey + " request message has no mso-service-instance-id") + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, processKey + " request message has no mso-service-instance-id") } utils.logContext(requestId, serviceInstanceId) @@ -947,6 +985,21 @@ public class DoCreateVfModule extends VfModuleBase { def vfModuleModelName = execution.getVariable("DCVFM_vfModuleModelName") def vnfId = execution.getVariable("DCVFM_vnfId") def cloudSiteId = execution.getVariable("DCVFM_cloudSiteId") + def sdncVersion = execution.getVariable("DCVFM_sdncVersion") + def serviceModelInfo = execution.getVariable("serviceModelInfo") + def vnfModelInfo = execution.getVariable("vnfModelInfo") + def vfModuleModelInfo = execution.getVariable("vfModuleModelInfo") + String serviceEcompModelInformation = sdncAdapterUtils.modelInfoToEcompModelInformation(serviceModelInfo) + String vnfEcompModelInformation = sdncAdapterUtils.modelInfoToEcompModelInformation(vnfModelInfo) + String vfModuleEcompModelInformation = sdncAdapterUtils.modelInfoToEcompModelInformation(vfModuleModelInfo) + def globalSubscriberId = execution.getVariable("DCVFM_globalSubscriberId") + boolean usePreload = execution.getVariable("DCVFM_usePreload") + String usePreloadToSDNC = usePreload ? "Y" : "N" + def modelCustomizationUuid = execution.getVariable("DCVFM_modelCustomizationUuid") + def modelCustomizationUuidString = "" + if (!usePreload) { + modelCustomizationUuidString = "" + modelCustomizationUuid + "" + } String sdncVNFParamsXml = "" @@ -955,11 +1008,15 @@ public class DoCreateVfModule extends VfModuleBase { }else{ sdncVNFParamsXml = "" } + + String sdncRequest = "" + + if (!sdncVersion.equals("1707")) { - String sdncRequest = - """ + sdncRequest = + """ ${requestId} ${svcInstId} @@ -989,10 +1046,114 @@ public class DoCreateVfModule extends VfModuleBase { ${vnfType} ${cloudSiteId} ${tenantId} + ${modelCustomizationUuidString} + ${usePreloadToSDNC} ${sdncVNFParamsXml} """ + + } + else { + + sdncRequest = + """ + + ${requestId} + ${svcInstId} + ${action} + vnf-topology-operation + ${callbackURL} + generic-resource + + + + ${requestId} + CreateVfModuleInstance + ${source} + + + + ${serviceId} + ${serviceId} + ${serviceEcompModelInformation} + ${svcInstId} + ${globalSubscriberId} + + + ${vfModuleModelName} + + + ${vnfId} + ${vnfType} + ${vnfEcompModelInformation} + + + ${vfModuleId} + ${vfModuleModelName} + ${vfModuleEcompModelInformation} + + + ${sdncVersion} + ${vfModuleName} + ${tenantId} + ${cloudSiteId} + ${sdncVNFParamsXml} + + + """ + + + /* + sdncRequest = + """ + + ${requestId} + ${svcInstId} + ${action} + vnf-topology-operation + ${callbackURL} + + + + ${requestId} + CreateVfModuleInstance + ${source} + + + + ${serviceId} + ${serviceId} + ${serviceEcompModelInformation} + ${svcInstId} + ${globalSubscriberId} + + + ${vnfId} + ${vnfType} + ${vnfEcompModelInformation} + + + ${vfModuleId} + ${vfModuleModelName} + ${vfModuleEcompModelInformation} + + + ${sdncVersion} + ${vfModuleName} + ${tenantId} + ${cloudSiteId} + ${sdncVNFParamsXml} + + + """ + */ + + } utils.logAudit("sdncRequest: " + sdncRequest) return sdncRequest @@ -1080,20 +1241,20 @@ public class DoCreateVfModule extends VfModuleBase { else if (key.endsWith("contrail_network_policy_fqdn")) { String contrailNetworkPolicyFqdn = element.getElementsByTagNameNS("*", "value").item(0).getTextContent() logDebug("Obtained contrailNetworkPolicyFqdn: " + contrailNetworkPolicyFqdn, isDebugLogEnabled) - contrailNetworkPolicyFqdnList.add(contrailNetworkPolicyFqdn) + contrailNetworkPolicyFqdnList.add(contrailNetworkPolicyFqdn) } else if (key.equals("oam_management_v4_address")) { String oamManagementV4Address = element.getElementsByTagNameNS("*", "value").item(0).getTextContent() logDebug("Obtained oamManagementV4Address: " + oamManagementV4Address, isDebugLogEnabled) - execution.setVariable("DCVFM_oamManagementV4Address", oamManagementV4Address) + execution.setVariable("DCVFM_oamManagementV4Address", oamManagementV4Address) } else if (key.equals("oam_management_v6_address")) { String oamManagementV6Address = element.getElementsByTagNameNS("*", "value").item(0).getTextContent() logDebug("Obtained oamManagementV6Address: " + oamManagementV6Address, isDebugLogEnabled) execution.setVariable("DCVFM_oamManagementV6Address", oamManagementV6Address) } - - } + + } } if (!contrailNetworkPolicyFqdnList.isEmpty()) { execution.setVariable("DCVFM_contrailNetworkPolicyFqdnList", contrailNetworkPolicyFqdnList) @@ -1435,7 +1596,7 @@ public class DoCreateVfModule extends VfModuleBase { logDebug("======== COMPLETED prepareCreateAAIVfModuleVolumeGroupRequest ======== ", isDebugLogEnabled) } - + public void createNetworkPoliciesInAAI(Execution execution) { def method = getClass().getSimpleName() + '.createNetworkPoliciesInAAI(' + 'execution=' + execution.getId() + @@ -1444,13 +1605,13 @@ public class DoCreateVfModule extends VfModuleBase { logDebug('Entered ' + method, isDebugLogEnabled) execution.setVariable("prefix", Prefix) logDebug(" ======== STARTED createNetworkPoliciesInAAI ======== ", isDebugLogEnabled) - + try { // get variables List fqdnList = execution.getVariable("DCVFM_contrailNetworkPolicyFqdnList") int fqdnCount = fqdnList.size() def rollbackData = execution.getVariable("RollbackData") - + execution.setVariable("DCVFM_networkPolicyFqdnCount", fqdnCount) logDebug("DCVFM_networkPolicyFqdnCount - " + fqdnCount, isDebugLogEnabled) @@ -1458,8 +1619,8 @@ public class DoCreateVfModule extends VfModuleBase { AaiUtil aaiUriUtil = new AaiUtil(this) String aai_uri = aaiUriUtil.getNetworkPolicyUri(execution) - if (fqdnCount > 0) { - + if (fqdnCount > 0) { + // AII loop call over contrail network policy fqdn list for (i in 0..fqdnCount-1) { @@ -1467,10 +1628,10 @@ public class DoCreateVfModule extends VfModuleBase { String fqdn = fqdnList[i] // Query AAI for this network policy FQDN - + String queryNetworkPolicyByFqdnAAIRequest = "${aai_endpoint}${aai_uri}?network-policy-fqdn=" + UriUtils.encode(fqdn, "UTF-8") utils.logAudit("AAI request endpoint: " + queryNetworkPolicyByFqdnAAIRequest) - + def aaiRequestId = UUID.randomUUID().toString() RESTConfig config = new RESTConfig(queryNetworkPolicyByFqdnAAIRequest); RESTClient client = new RESTClient(config).addHeader("X-TransactionId", aaiRequestId) @@ -1489,32 +1650,32 @@ public class DoCreateVfModule extends VfModuleBase { // This network policy FQDN already exists in AAI utils.logAudit(aaiResponseAsString) execution.setVariable("DCVFM_queryNetworkPolicyByFqdnAAIResponse", aaiResponseAsString) - logDebug(" QueryAAINetworkPolicyByFQDN Success REST Response, , NetworkPolicy #" + counting + " : " + "\n" + aaiResponseAsString, isDebugLogEnabled) + logDebug(" QueryAAINetworkPolicyByFQDN Success REST Response, , NetworkPolicy #" + counting + " : " + "\n" + aaiResponseAsString, isDebugLogEnabled) } else { if (returnCode == 404) { // This network policy FQDN is not in AAI yet. Add it now logDebug("The return code is: " + returnCode, isDebugLogEnabled) logDebug("This network policy FQDN is not in AAI yet: " + fqdn, isDebugLogEnabled) - utils.logAudit("Network policy FQDN is not in AAI yet") + utils.logAudit("Network policy FQDN is not in AAI yet") // Add the network policy with this FQDN to AAI def networkPolicyId = UUID.randomUUID().toString() - logDebug("Adding network-policy with network-policy-id " + networkPolicyId, isDebugLogEnabled) - + logDebug("Adding network-policy with network-policy-id " + networkPolicyId, isDebugLogEnabled) + String aaiNamespace = aaiUriUtil.getNamespaceFromUri(aai_uri) logDebug('AAI namespace is: ' + aaiNamespace, isDebugLogEnabled) String payload = """ ${networkPolicyId} ${fqdn} - ${execution.getVariable("DCVFM_heatStackId")} + ${execution.getVariable("DCVFM_heatStackId")} """ as String - + execution.setVariable("DCVFM_addNetworkPolicyAAIRequestBody", payload) - + String addNetworkPolicyAAIRequest = "${aai_endpoint}${aai_uri}/" + UriUtils.encode(networkPolicyId, "UTF-8") utils.logAudit("AAI request endpoint: " + addNetworkPolicyAAIRequest) logDebug("AAI request endpoint: " + addNetworkPolicyAAIRequest, isDebugLogEnabled) - + def aaiRequestIdPut = UUID.randomUUID().toString() RESTConfig configPut = new RESTConfig(addNetworkPolicyAAIRequest); RESTClient clientPut = new RESTClient(configPut).addHeader("X-TransactionId", aaiRequestIdPut) @@ -1527,8 +1688,8 @@ public class DoCreateVfModule extends VfModuleBase { int returnCodePut = responsePut.getStatusCode() execution.setVariable("DCVFM_aaiAddNetworkPolicyReturnCode", returnCodePut) logDebug(" ***** AAI add network policy Response Code, NetworkPolicy #" + counting + " : " + returnCodePut, isDebugLogEnabled) - - String aaiResponseAsStringPut = responsePut.getResponseBodyAsString() + + String aaiResponseAsStringPut = responsePut.getResponseBodyAsString() if (isOneOf(returnCodePut, 200, 201)) { logDebug("The return code from adding network policy is: " + returnCodePut, isDebugLogEnabled) // This network policy was created in AAI successfully @@ -1538,14 +1699,14 @@ public class DoCreateVfModule extends VfModuleBase { rollbackData.put("VFMODULE", "rollbackCreateNetworkPoliciesAAI", "true") rollbackData.put("VFMODULE", "contrailNetworkPolicyFqdn" + i, fqdn) execution.setVariable("RollbackData", rollbackData) - + } else { // aai all errors String putErrorMessage = "Unable to add network-policy to AAI createNetworkPoliciesInAAI - " + returnCodePut logDebug(putErrorMessage, isDebugLogEnabled) - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, putErrorMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, putErrorMessage) } - + } else { if (aaiResponseAsString.contains("RESTFault")) { WorkflowException exceptionObject = exceptionUtil.MapAAIExceptionToWorkflowException(aaiResponseAsString, execution) @@ -1564,7 +1725,7 @@ public class DoCreateVfModule extends VfModuleBase { } // end loop - + } else { logDebug("No contrail network policies to query/create", isDebugLogEnabled) @@ -1580,7 +1741,7 @@ public class DoCreateVfModule extends VfModuleBase { } } - + /** * Prepare a Request for invoking the UpdateAAIGenericVnf subflow. * @@ -1600,18 +1761,18 @@ public class DoCreateVfModule extends VfModuleBase { def oamManagementV6Address = execution.getVariable("DCVFM_oamManagementV6Address") def ipv4OamAddressElement = '' def managementV6AddressElement = '' - + if (oamManagementV4Address != null && !oamManagementV4Address.isEmpty()) { - ipv4OamAddressElement = '' + oamManagementV4Address + '' + ipv4OamAddressElement = '' + oamManagementV4Address + '' } - + if (oamManagementV6Address != null && !oamManagementV6Address.isEmpty()) { managementV6AddressElement = '' + oamManagementV6Address + '' } - + rollbackData.put("VFMODULE", "oamManagementV4Address", oamManagementV4Address) - - + + String updateAAIGenericVnfRequest = """ ${vnfId} @@ -1623,17 +1784,17 @@ public class DoCreateVfModule extends VfModuleBase { execution.setVariable('DCVM_updateAAIGenericVnfRequest', updateAAIGenericVnfRequest) utils.logAudit("updateAAIGenericVnfRequest : " + updateAAIGenericVnfRequest) logDebug('Request for UpdateAAIGenericVnf:\n' + updateAAIGenericVnfRequest, isDebugLogEnabled) - + logDebug('Exited ' + method, isDebugLogEnabled) } catch (BpmnError e) { throw e; } catch (Exception e) { logError('Caught exception in ' + method, e) - createWorkflowException(execution, 1002, 'Error in prepUpdateAAIGenericVnf(): ' + e.getMessage()) + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in prepUpdateAAIGenericVnf(): ' + e.getMessage()) } } - + /** * Post process a result from invoking the UpdateAAIGenericVnf subflow. * @@ -1648,31 +1809,33 @@ public class DoCreateVfModule extends VfModuleBase { try { def rollbackData = execution.getVariable("RollbackData") - + rollbackData.put("VFMODULE", "rollbackUpdateVnfAAI", "true") - + def vnfId = execution.getVariable('DCVFM_vnfId') def oamManagementV4Address = execution.getVariable("DCVFM_oamManagementV4Address") def oamManagementV6Address = execution.getVariable("DCVFM_oamManagementV6Address") def ipv4OamAddressElement = '' def managementV6AddressElement = '' - - if (oamManagementV4Address != null && !oamManagementV4Address.isEmpty()) { + + if (oamManagementV4Address != null && !oamManagementV4Address.isEmpty()) { rollbackData.put("VFMODULE", "oamManagementV4Address", oamManagementV4Address) } - + if (oamManagementV6Address != null && !oamManagementV6Address.isEmpty()) { - rollbackData.put("VFMODULE", "oamManagementV6Address", oamManagementV6Address) + rollbackData.put("VFMODULE", "oamManagementV6Address", oamManagementV6Address) } - - execution.setVariable("RollbackData", rollbackData) - + + execution.setVariable("RollbackData", rollbackData) + logDebug('Exited ' + method, isDebugLogEnabled) } catch (BpmnError e) { throw e; } catch (Exception e) { logError('Caught exception in ' + method, e) - createWorkflowException(execution, 1002, 'Error in postProcessUpdateAAIGenericVnf(): ' + e.getMessage()) + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in postProcessUpdateAAIGenericVnf(): ' + e.getMessage()) } } + + } diff --git a/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/DoCreateVfModuleRollback.groovy b/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/DoCreateVfModuleRollback.groovy index 391b76a21a..8ca749d1ec 100644 --- a/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/DoCreateVfModuleRollback.groovy +++ b/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/DoCreateVfModuleRollback.groovy @@ -1,38 +1,38 @@ -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - MSO - * ================================================================================ - * 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.openecomp.mso.bpmn.infrastructure.scripts +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.bpmn.infrastructure.scripts import org.camunda.bpm.engine.delegate.BpmnError import org.camunda.bpm.engine.runtime.Execution -import org.openecomp.mso.bpmn.common.scripts.AaiUtil -import org.openecomp.mso.bpmn.common.scripts.AbstractServiceTaskProcessor -import org.openecomp.mso.bpmn.common.scripts.ExceptionUtil -import org.openecomp.mso.bpmn.common.scripts.SDNCAdapterUtils -import org.openecomp.mso.bpmn.core.WorkflowException -import org.openecomp.mso.rest.APIResponse -import org.springframework.web.util.UriUtils +import org.openecomp.mso.bpmn.common.scripts.AaiUtil +import org.openecomp.mso.bpmn.common.scripts.AbstractServiceTaskProcessor +import org.openecomp.mso.bpmn.common.scripts.ExceptionUtil +import org.openecomp.mso.bpmn.common.scripts.SDNCAdapterUtils +import org.openecomp.mso.bpmn.core.WorkflowException +import org.openecomp.mso.rest.APIResponse +import org.springframework.web.util.UriUtils public class DoCreateVfModuleRollback extends AbstractServiceTaskProcessor{ - + def Prefix="DCVFMR_" ExceptionUtil exceptionUtil = new ExceptionUtil() @@ -72,7 +72,7 @@ public class DoCreateVfModuleRollback extends AbstractServiceTaskProcessor{ execution.setVariable("DCVFMR_cloudSiteId", cloudSiteId) String heatStackId = rollbackData.get("VFMODULE", "heatstackid") execution.setVariable("DCVFMR_heatStackId", heatStackId) - String requestId = rollbackData.get("VFMODULE", "msorequestid") + String requestId = rollbackData.get("VFMODULE", "msorequestid") execution.setVariable("DCVFMR_requestId", requestId) List createdNetworkPolicyFqdnList = [] int i = 0 @@ -84,15 +84,15 @@ public class DoCreateVfModuleRollback extends AbstractServiceTaskProcessor{ createdNetworkPolicyFqdnList.add(fqdn) logDebug("got fqdn # " + i + ": " + fqdn, isDebugEnabled) i = i + 1 - + } - + execution.setVariable("DCVFMR_createdNetworkPolicyFqdnList", createdNetworkPolicyFqdnList) String oamManagementV4Address = rollbackData.get("VFMODULE", "oamManagementV4Address") execution.setVariable("DCVFMR_oamManagementV4Address", oamManagementV4Address) String oamManagementV6Address = rollbackData.get("VFMODULE", "oamManagementV6Address") execution.setVariable("DCVFMR_oamManagementV6Address", oamManagementV6Address) - //String serviceInstanceId = rollbackData.get("VFMODULE", "msoserviceinstanceid") + //String serviceInstanceId = rollbackData.get("VFMODULE", "msoserviceinstanceid") //execution.setVariable("DCVFMR_serviceInstanceId", serviceInstanceId) execution.setVariable("DCVFMR_rollbackPrepareUpdateVfModule", rollbackData.get("VFMODULE", "rollbackPrepareUpdateVfModule")) execution.setVariable("DCVFMR_rollbackUpdateAAIVfModule", rollbackData.get("VFMODULE", "rollbackUpdateAAIVfModule")) @@ -105,10 +105,10 @@ public class DoCreateVfModuleRollback extends AbstractServiceTaskProcessor{ // formulate the request for PrepareUpdateAAIVfModule String request = """ - ${vnfId} - ${vfModuleId} - pending-delete - """ as String + ${vnfId} + ${vfModuleId} + pending-delete + """ as String utils.log("DEBUG", "PrepareUpdateAAIVfModuleRequest :" + request, isDebugEnabled) utils.logAudit("DoCreateVfModuleRollback PrepareUpdateAAIVfModule Request: " + request) execution.setVariable("PrepareUpdateAAIVfModuleRequest", request) @@ -119,7 +119,7 @@ public class DoCreateVfModuleRollback extends AbstractServiceTaskProcessor{ public void prepSDNCAdapterRequest(Execution execution) { def isDebugEnabled=execution.getVariable("isDebugLogEnabled") String srvInstId = execution.getVariable("DCVFMR_serviceInstanceId") - + def callbackUrl = execution.getVariable("URN_mso_workflow_sdncadapter_callback") String source = execution.getVariable("DCVFMR_source") @@ -133,12 +133,12 @@ public class DoCreateVfModuleRollback extends AbstractServiceTaskProcessor{ String vfModuleModelName = execution.getVariable("DCVFMR_vfModuleModelName") String cloudSiteId = execution.getVariable("DCVFMR_cloudSiteId") String requestId = execution.getVariable("DCVFMR_requestId") - + String serviceInstanceIdToSdnc = "" if (srvInstId != null && !srvInstId.isEmpty()) { serviceInstanceIdToSdnc = srvInstId } else { - serviceInstanceIdToSdnc = vfModuleId + serviceInstanceIdToSdnc = vfModuleId } def doSDNCActivateRollback = execution.getVariable("DCVFMR_rollbackSDNCRequestActivate") @@ -159,43 +159,43 @@ public class DoCreateVfModuleRollback extends AbstractServiceTaskProcessor{ return - String request = """ - - ${requestId} - ${vfModuleId} - ${action} - vnf-topology-operation - ${callbackUrl} - - - - ${requestId} - ${requestAction} - ${source} - - - - - - ${serviceId} - ${serviceId} - ${serviceInstanceIdToSdnc} - notsurewecare - - - ${vfModuleId} - ${vfModuleModelName} - ${vfModuleName} - ${vnfId} - ${vnfName} - ${vnfType} - ${cloudSiteId} - ${tenantId} - - - """ + String request = """ + + ${requestId} + ${vfModuleId} + ${action} + vnf-topology-operation + ${callbackUrl} + + + + ${requestId} + ${requestAction} + ${source} + + + + + + ${serviceId} + ${serviceId} + ${serviceInstanceIdToSdnc} + notsurewecare + + + ${vfModuleId} + ${vfModuleModelName} + ${vfModuleName} + ${vnfId} + ${vnfName} + ${vnfType} + ${cloudSiteId} + ${tenantId} + + + """ utils.log("DEBUG", "sdncAdapterWorkflowRequest: " + request, isDebugEnabled) utils.logAudit("DoCreateVfModuleRollback sdncAdapterWorkflow Request: " + request) @@ -214,7 +214,7 @@ public class DoCreateVfModuleRollback extends AbstractServiceTaskProcessor{ String vfModuleId = execution.getVariable("DCVFMR_vfModuleId") String vfModuleStackId = execution.getVariable("DCVFMR_heatStackId") String tenantId = execution.getVariable("DCVFMR_tenantId") - def messageId = execution.getVariable('mso-request-id') + '-' + + def messageId = execution.getVariable('mso-request-id') + '-' + System.currentTimeMillis() def notificationUrl = createCallbackURL(execution, "VNFAResponse", messageId) def useQualifiedHostName = execution.getVariable("URN_mso_use_qualified_host") @@ -223,21 +223,21 @@ public class DoCreateVfModuleRollback extends AbstractServiceTaskProcessor{ } String request = """ - - ${aicCloudRegion} - ${tenantId} - ${vnfId} - ${vfModuleId} - ${vfModuleStackId} - true - - ${origRequestId} - ${srvInstId} - - ${messageId} - ${notificationUrl} - - """ as String + + ${aicCloudRegion} + ${tenantId} + ${vnfId} + ${vfModuleId} + ${vfModuleStackId} + true + + ${origRequestId} + ${srvInstId} + + ${messageId} + ${notificationUrl} + + """ as String utils.log("DEBUG", "vnfAdapterRestV1Request: " + request, isDebugEnabled) utils.logAudit("PrepareUpdateAAIVfModule vnfAdapterRestV1 Request: " + request) @@ -252,11 +252,11 @@ public class DoCreateVfModuleRollback extends AbstractServiceTaskProcessor{ String vfModuleId = execution.getVariable("DCVFMR_vfModuleId") // formulate the request for UpdateAAIVfModule String request = """ - ${vnfId} - ${vfModuleId} - DELETE - deleted - """ as String + ${vnfId} + ${vfModuleId} + DELETE + deleted + """ as String utils.log("DEBUG", "UpdateAAIVfModuleRequest :" + request, isDebugEnabled) utils.logAudit("UpdateAAIVfModule Request: " + request) execution.setVariable("UpdateAAIVfModuleRequest", request) @@ -270,9 +270,9 @@ public class DoCreateVfModuleRollback extends AbstractServiceTaskProcessor{ String vfModuleId = execution.getVariable("DCVFMR_vfModuleId") // formulate the request for UpdateAAIVfModule String request = """ - ${vnfId} - ${vfModuleId} - """ as String + ${vnfId} + ${vfModuleId} + """ as String utils.log("DEBUG", "DeleteAAIVfModuleRequest :" + request, isDebugEnabled) utils.logAudit("DeleteAAIVfModule Request: " + request) execution.setVariable("DeleteAAIVfModuleRequest", request) @@ -305,7 +305,7 @@ public class DoCreateVfModuleRollback extends AbstractServiceTaskProcessor{ throw new BpmnError("MSOWorkflowException") } } - + public void deleteNetworkPoliciesFromAAI(Execution execution) { def method = getClass().getSimpleName() + '.deleteNetworkPoliciesFromAAI(' + 'execution=' + execution.getId() + @@ -314,7 +314,7 @@ public class DoCreateVfModuleRollback extends AbstractServiceTaskProcessor{ logDebug('Entered ' + method, isDebugLogEnabled) execution.setVariable("prefix", Prefix) logDebug(" ======== STARTED deleteNetworkPoliciesFromAAI ======== ", isDebugLogEnabled) - + try { // get variables List fqdnList = execution.getVariable(Prefix + "createdNetworkPolicyFqdnList") @@ -323,35 +323,35 @@ public class DoCreateVfModuleRollback extends AbstractServiceTaskProcessor{ return } int fqdnCount = fqdnList.size() - + execution.setVariable(Prefix + "networkPolicyFqdnCount", fqdnCount) logDebug("networkPolicyFqdnCount - " + fqdnCount, isDebugLogEnabled) - + String aai_endpoint = execution.getVariable("URN_aai_endpoint") AaiUtil aaiUriUtil = new AaiUtil(this) String aai_uri = aaiUriUtil.getNetworkPolicyUri(execution) - + if (fqdnCount > 0) { // AII loop call over contrail network policy fqdn list for (i in 0..fqdnCount-1) { - + int counting = i+1 String fqdn = fqdnList[i] - + // Query AAI for this network policy FQDN - + String queryNetworkPolicyByFqdnAAIRequest = "${aai_endpoint}${aai_uri}?network-policy-fqdn=" + UriUtils.encode(fqdn, "UTF-8") utils.logAudit("AAI request endpoint: " + queryNetworkPolicyByFqdnAAIRequest) logDebug("AAI request endpoint: " + queryNetworkPolicyByFqdnAAIRequest, isDebugLogEnabled) - + def aaiRequestId = UUID.randomUUID().toString() APIResponse response = aaiUriUtil.executeAAIGetCall(execution, queryNetworkPolicyByFqdnAAIRequest) int returnCode = response.getStatusCode() execution.setVariable(Prefix + "aaiQueryNetworkPolicyByFqdnReturnCode", returnCode) logDebug(" ***** AAI query network policy Response Code, NetworkPolicy #" + counting + " : " + returnCode, isDebugLogEnabled) - + String aaiResponseAsString = response.getResponseBodyAsString() - + if (isOneOf(returnCode, 200, 201)) { logDebug("The return code is: " + returnCode, isDebugLogEnabled) // This network policy FQDN exists in AAI - need to delete it now @@ -361,32 +361,32 @@ public class DoCreateVfModuleRollback extends AbstractServiceTaskProcessor{ // Retrieve the network policy id for this FQDN def networkPolicyId = utils.getNodeText1(aaiResponseAsString, "network-policy-id") logDebug("Deleting network-policy with network-policy-id " + networkPolicyId, isDebugLogEnabled) - + // Retrieve the resource version for this network policy def resourceVersion = utils.getNodeText1(aaiResponseAsString, "resource-version") logDebug("Deleting network-policy with resource-version " + resourceVersion, isDebugLogEnabled) - + String delNetworkPolicyAAIRequest = "${aai_endpoint}${aai_uri}/" + UriUtils.encode(networkPolicyId, "UTF-8") + "?resource-version=" + UriUtils.encode(resourceVersion, "UTF-8") - + utils.logAudit("AAI request endpoint: " + delNetworkPolicyAAIRequest) logDebug("AAI request endpoint: " + delNetworkPolicyAAIRequest, isDebugLogEnabled) - + def aaiRequestIdDel = UUID.randomUUID().toString() logDebug("invoking DELETE call to AAI", isDebugLogEnabled) utils.logAudit("Sending DELETE call to AAI with Endpoint /n" + delNetworkPolicyAAIRequest) - + APIResponse responseDel = aaiUriUtil.executeAAIDeleteCall(execution, delNetworkPolicyAAIRequest) - + int returnCodeDel = responseDel.getStatusCode() execution.setVariable(Prefix + "aaiDeleteNetworkPolicyReturnCode", returnCodeDel) logDebug(" ***** AAI delete network policy Response Code, NetworkPolicy #" + counting + " : " + returnCodeDel, isDebugLogEnabled) - + if (isOneOf(returnCodeDel, 200, 201, 204)) { logDebug("The return code from deleting network policy is: " + returnCodeDel, isDebugLogEnabled) // This network policy was deleted from AAI successfully logDebug(" DelAAINetworkPolicy Success REST Response, , NetworkPolicy #" + counting + " : ", isDebugLogEnabled) - + } else { // aai all errors String delErrorMessage = "Unable to delete network-policy to AAI deleteNetworkPoliciesFromAAI - " + returnCodeDel @@ -412,29 +412,29 @@ public class DoCreateVfModuleRollback extends AbstractServiceTaskProcessor{ } } - - - + + + } // end loop - - + + } else { logDebug("No contrail network policies to query/create", isDebugLogEnabled) - + } - + } catch (BpmnError e) { throw e; - + } catch (Exception ex) { String exceptionMessage = "Bpmn error encountered in DoCreateVfModuleRollback flow. deleteNetworkPoliciesFromAAI() - " + ex.getMessage() logDebug(exceptionMessage, isDebugLogEnabled) exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) } - + } - - + + /** * Prepare a Request for invoking the UpdateAAIGenericVnf subflow. * @@ -446,42 +446,42 @@ public class DoCreateVfModuleRollback extends AbstractServiceTaskProcessor{ ')' def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') logDebug('Entered ' + method, isDebugLogEnabled) - + try { def vnfId = execution.getVariable('DCVFMR_vnfId') def oamManagementV4Address = execution.getVariable(Prefix + 'oamManagementV4Address') def oamManagementV6Address = execution.getVariable(Prefix + 'oamManagementV6Address') def ipv4OamAddressElement = '' def managementV6AddressElement = '' - + if (oamManagementV4Address != null) { ipv4OamAddressElement = '' + 'DELETE' + '' } - + if (oamManagementV6Address != null) { managementV6AddressElement = '' + 'DELETE' + '' } - - + + String updateAAIGenericVnfRequest = """ - - ${vnfId} - ${ipv4OamAddressElement} - ${managementV6AddressElement} - - """ + + ${vnfId} + ${ipv4OamAddressElement} + ${managementV6AddressElement} + + """ updateAAIGenericVnfRequest = utils.formatXml(updateAAIGenericVnfRequest) execution.setVariable(Prefix + 'updateAAIGenericVnfRequest', updateAAIGenericVnfRequest) utils.logAudit("updateAAIGenericVnfRequest : " + updateAAIGenericVnfRequest) logDebug('Request for UpdateAAIGenericVnf:\n' + updateAAIGenericVnfRequest, isDebugLogEnabled) - - + + logDebug('Exited ' + method, isDebugLogEnabled) } catch (BpmnError e) { throw e; } catch (Exception e) { logError('Caught exception in ' + method, e) - createWorkflowException(execution, 1002, 'Error in preProcessUpdateAAIGenericVnf((): ' + e.getMessage()) + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in preProcessUpdateAAIGenericVnf((): ' + e.getMessage()) } } -} \ No newline at end of file +} diff --git a/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/DoCreateVnf.groovy b/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/DoCreateVnf.groovy index 23763c63b8..55d56a6194 100644 --- a/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/DoCreateVnf.groovy +++ b/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/DoCreateVnf.groovy @@ -16,12 +16,12 @@ * See the License for the specific language governing permissions and * limitations under the License. * ============LICENSE_END========================================================= - */ + */ package org.openecomp.mso.bpmn.infrastructure.scripts - + import static org.apache.commons.lang3.StringUtils.* - -import org.camunda.bpm.engine.delegate.BpmnError +import org.openecomp.mso.bpmn.core.RollbackData +import org.camunda.bpm.engine.delegate.BpmnError import org.camunda.bpm.engine.runtime.Execution import org.openecomp.mso.bpmn.common.scripts.AaiUtil import org.openecomp.mso.bpmn.common.scripts.AbstractServiceTaskProcessor @@ -30,385 +30,429 @@ import org.openecomp.mso.bpmn.common.scripts.SDNCAdapterUtils import org.openecomp.mso.bpmn.common.scripts.VidUtils import org.openecomp.mso.bpmn.core.WorkflowException import org.openecomp.mso.bpmn.core.json.JsonUtils - - -/** - * This class supports the DoCreateVnf building block subflow - * with the creation of a generic vnf for - * infrastructure. - * - */ -class DoCreateVnf extends AbstractServiceTaskProcessor { - - String Prefix="DoCVNF_" - ExceptionUtil exceptionUtil = new ExceptionUtil() - JsonUtils jsonUtil = new JsonUtils() - VidUtils vidUtils = new VidUtils(this) - - /** - * This method gets and validates the incoming - * request. - * - * @param - execution - * - */ - public void preProcessRequest(Execution execution) { - def isDebugEnabled = execution.getVariable("isDebugLogEnabled") - execution.setVariable("prefix",Prefix) - utils.log("DEBUG", " *** STARTED DoCreateVnf PreProcessRequest Process*** ", isDebugEnabled) - - // DISABLE SDNC INTERACTION FOR NOW - execution.setVariable("SDNCInteractionEnabled", false) - - - /*******************/ - try{ - // Get Variables - - String cloudConfiguration = execution.getVariable("cloudConfiguration") - String vnfModelInfo = execution.getVariable("vnfModelInfo") - - String requestId = execution.getVariable("requestId") - execution.setVariable("DoCVNF_requestId", requestId) + + +/** + * This class supports the DoCreateVnf building block subflow + * with the creation of a generic vnf for + * infrastructure. + * + */ +class DoCreateVnf extends AbstractServiceTaskProcessor { + + String Prefix="DoCVNF_" + ExceptionUtil exceptionUtil = new ExceptionUtil() + JsonUtils jsonUtil = new JsonUtils() + VidUtils vidUtils = new VidUtils(this) + SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils(this) + + /** + * This method gets and validates the incoming + * request. + * + * @param - execution + * + */ + public void preProcessRequest(Execution execution) { + def isDebugEnabled = execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix",Prefix) + utils.log("DEBUG", " *** STARTED DoCreateVnf PreProcessRequest Process*** ", isDebugEnabled) + + // DISABLE SDNC INTERACTION FOR NOW + execution.setVariable("SDNCInteractionEnabled", false) + + + /*******************/ + try{ + // Get Variables + + String cloudConfiguration = execution.getVariable("cloudConfiguration") + String vnfModelInfo = execution.getVariable("vnfModelInfo") + String serviceModelInfo = execution.getVariable("serviceModelInfo") + + String requestId = execution.getVariable("requestId") + execution.setVariable("DoCVNF_requestId", requestId) execution.setVariable("mso-request-id", requestId) - utils.log("DEBUG", "Incoming Request Id is: " + requestId, isDebugEnabled) - - String serviceInstanceId = execution.getVariable("serviceInstanceId") - execution.setVariable("DoCVNF_serviceInstanceId", serviceInstanceId) - utils.log("DEBUG", "Incoming Service Instance Id is: " + serviceInstanceId, isDebugEnabled) - - String vnfType = execution.getVariable("vnfType") - execution.setVariable("DoCVNF_vnfType", vnfType) - utils.log("DEBUG", "Incoming Vnf Type is: " + vnfType, isDebugEnabled) - - String vnfName = execution.getVariable("vnfName") - execution.setVariable("DoCVNF_vnfName", vnfName) - utils.log("DEBUG", "Incoming Vnf Name is: " + vnfName, isDebugEnabled) - - String serviceId = execution.getVariable("productFamilyId") - execution.setVariable("DoCVNF_serviceId", serviceId) - utils.log("DEBUG", "Incoming Service Id is: " + serviceId, isDebugEnabled) - - String source = "VID" - execution.setVariable("DoCVNF_source", source) - utils.log("DEBUG", "Incoming Source is: " + source, isDebugEnabled) - - String suppressRollback = execution.getVariable("disableRollback") - execution.setVariable("DoCVNF_suppressRollback", suppressRollback) - utils.log("DEBUG", "Incoming Suppress Rollback is: " + suppressRollback, isDebugEnabled) - - String modelInvariantId = jsonUtil.getJsonValue(vnfModelInfo, "modelInvariantId") - execution.setVariable("DoCVNF_modelInvariantId", modelInvariantId) - utils.log("DEBUG", "Incoming Invariant Id is: " + modelInvariantId, isDebugEnabled) - - String modelVersionId = jsonUtil.getJsonValue(vnfModelInfo, "modelVersionId") - if (modelVersionId == null) { - modelVersionId = "" - } - execution.setVariable("DoCVNF_modelVersionId", modelVersionId) - utils.log("DEBUG", "Incoming Version Id is: " + modelVersionId, isDebugEnabled) - - String modelVersion = jsonUtil.getJsonValue(vnfModelInfo, "modelVersion") - execution.setVariable("DoCVNF_modelVersion", modelVersion) - utils.log("DEBUG", "Incoming Model Version is: " + modelVersion, isDebugEnabled) - - String modelName = jsonUtil.getJsonValue(vnfModelInfo, "modelName") - execution.setVariable("DoCVNF_modelName", modelName) - utils.log("DEBUG", "Incoming Model Name is: " + modelName, isDebugEnabled) - - String modelCustomizationId = jsonUtil.getJsonValue(vnfModelInfo, "modelCustomizationId") - if (modelCustomizationId == null) { - modelCustomizationId = "" - } - execution.setVariable("DoCVNF_modelCustomizationId", modelCustomizationId) - utils.log("DEBUG", "Incoming Model Customization Id is: " + modelCustomizationId, isDebugEnabled) - - String cloudSiteId = jsonUtil.getJsonValue(cloudConfiguration, "lcpCloudRegionId") - execution.setVariable("DoCVNF_cloudSiteId", cloudSiteId) - utils.log("DEBUG", "Incoming Cloud Site Id is: " + cloudSiteId, isDebugEnabled) - - String tenantId = jsonUtil.getJsonValue(cloudConfiguration, "tenantId") - execution.setVariable("DoCVNF_tenantId", tenantId) - utils.log("DEBUG", "Incoming Tenant Id is: " + tenantId, isDebugEnabled) - - //For Completion Handler & Fallout Handler - String requestInfo = + utils.log("DEBUG", "Incoming Request Id is: " + requestId, isDebugEnabled) + + String serviceInstanceId = execution.getVariable("serviceInstanceId") + execution.setVariable("DoCVNF_serviceInstanceId", serviceInstanceId) + utils.log("DEBUG", "Incoming Service Instance Id is: " + serviceInstanceId, isDebugEnabled) + + String vnfType = execution.getVariable("vnfType") + execution.setVariable("DoCVNF_vnfType", vnfType) + utils.log("DEBUG", "Incoming Vnf Type is: " + vnfType, isDebugEnabled) + + String vnfName = execution.getVariable("vnfName") + execution.setVariable("DoCVNF_vnfName", vnfName) + utils.log("DEBUG", "Incoming Vnf Name is: " + vnfName, isDebugEnabled) + + String serviceId = execution.getVariable("productFamilyId") + execution.setVariable("DoCVNF_serviceId", serviceId) + utils.log("DEBUG", "Incoming Service Id is: " + serviceId, isDebugEnabled) + + String source = "VID" + execution.setVariable("DoCVNF_source", source) + utils.log("DEBUG", "Incoming Source is: " + source, isDebugEnabled) + + String suppressRollback = execution.getVariable("disableRollback") + execution.setVariable("DoCVNF_suppressRollback", suppressRollback) + utils.log("DEBUG", "Incoming Suppress Rollback is: " + suppressRollback, isDebugEnabled) + + String modelInvariantId = jsonUtil.getJsonValue(vnfModelInfo, "modelInvariantId") + execution.setVariable("DoCVNF_modelInvariantId", modelInvariantId) + utils.log("DEBUG", "Incoming Invariant Id is: " + modelInvariantId, isDebugEnabled) + + String modelVersionId = jsonUtil.getJsonValue(vnfModelInfo, "modelVersionId") + if (modelVersionId == null) { + modelVersionId = "" + } + execution.setVariable("DoCVNF_modelVersionId", modelVersionId) + utils.log("DEBUG", "Incoming Version Id is: " + modelVersionId, isDebugEnabled) + + String modelVersion = jsonUtil.getJsonValue(vnfModelInfo, "modelVersion") + execution.setVariable("DoCVNF_modelVersion", modelVersion) + utils.log("DEBUG", "Incoming Model Version is: " + modelVersion, isDebugEnabled) + + String modelName = jsonUtil.getJsonValue(vnfModelInfo, "modelName") + execution.setVariable("DoCVNF_modelName", modelName) + utils.log("DEBUG", "Incoming Model Name is: " + modelName, isDebugEnabled) + + String modelCustomizationId = jsonUtil.getJsonValue(vnfModelInfo, "modelCustomizationId") + if (modelCustomizationId == null) { + modelCustomizationId = "" + } + execution.setVariable("DoCVNF_modelCustomizationId", modelCustomizationId) + utils.log("DEBUG", "Incoming Model Customization Id is: " + modelCustomizationId, isDebugEnabled) + + String cloudSiteId = jsonUtil.getJsonValue(cloudConfiguration, "lcpCloudRegionId") + execution.setVariable("DoCVNF_cloudSiteId", cloudSiteId) + utils.log("DEBUG", "Incoming Cloud Site Id is: " + cloudSiteId, isDebugEnabled) + + String tenantId = jsonUtil.getJsonValue(cloudConfiguration, "tenantId") + execution.setVariable("DoCVNF_tenantId", tenantId) + utils.log("DEBUG", "Incoming Tenant Id is: " + tenantId, isDebugEnabled) + + String globalSubscriberId = execution.getVariable("globalSubscriberId") + if (globalSubscriberId == null) { + globalSubscriberId = "" + } + execution.setVariable("DoCVNF_globalSubscriberId", globalSubscriberId) + utils.log("DEBUG", "Incoming Global Subscriber Id is: " + globalSubscriberId, isDebugEnabled) + + String sdncVersion = execution.getVariable("sdncVersion") + if (sdncVersion == null) { + sdncVersion = "1702" + } + execution.setVariable("DoCVNF_sdncVersion", sdncVersion) + utils.log("DEBUG", "Incoming Sdnc Version is: " + sdncVersion, isDebugEnabled) + + //For Completion Handler & Fallout Handler + String requestInfo = """ - ${requestId} - CREATE - ${source} - """ - - execution.setVariable("DoCVNF_requestInfo", requestInfo) - //TODO: Orch Status - TBD, will come from SDN-C Response in 1702 - String orchStatus = "Created" - execution.setVariable("DoCVNF_orchStatus", orchStatus) - - //TODO: Equipment Role - Should come from SDN-C Response in 1702 - String equipmentRole = " " - execution.setVariable("DoCVNF_equipmentRole", equipmentRole) - String vnfId = execution.getVariable("testVnfId") // for junits - if(isBlank(vnfId)){ - vnfId = execution.getVariable("vnfId") - if (isBlank(vnfId)) { - vnfId = UUID.randomUUID().toString() - utils.log("DEBUG", "Generated Vnf Id is: " + vnfId, isDebugEnabled) - } - } - execution.setVariable("DoCVNF_vnfId", vnfId) - - // Setting for Sub Flow Calls - execution.setVariable("DoCVNF_type", "generic-vnf") - execution.setVariable("GENGS_type", "service-instance") - - String sdncCallbackUrl = (String) execution.getVariable('URN_mso_workflow_sdncadapter_callback') - if (sdncCallbackUrl == null || sdncCallbackUrl.trim().isEmpty()) { - def msg = 'Required variable \'URN_mso_workflow_sdncadapter_callback\' is missing' - logError(msg) - exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg) - } - execution.setVariable("DoCVNF_sdncCallbackUrl", sdncCallbackUrl) - utils.logAudit("SDNC Callback URL: " + sdncCallbackUrl) - logDebug("SDNC Callback URL is: " + sdncCallbackUrl, isDebugEnabled) - - }catch(BpmnError b){ - utils.log("DEBUG", "Rethrowing MSOWorkflowException", isDebugEnabled) - throw b - }catch(Exception e){ - utils.log("DEBUG", " Error Occured in DoCreateVnf PreProcessRequest method!" + e.getMessage(), isDebugEnabled) - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured in DoCreateVnf PreProcessRequest") - - } - utils.log("DEBUG", "*** COMPLETED DoCreateVnf PreProcessRequest Process ***", isDebugEnabled) - } - - - public void prepareCreateGenericVnf (Execution execution) { - def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - execution.setVariable("prefix",Prefix) - - utils.log("DEBUG", " *** STARTED DoCreateVnf PrepareCreateGenericVnf Process *** ", isDebugEnabled) - try { - //Get Vnf Info - String vnfId = execution.getVariable("DoCVNF_vnfId") - def vnfName = execution.getVariable("DoCVNF_vnfName") - def vnfType = execution.getVariable("DoCVNF_vnfType") - def serviceId = execution.getVariable("DoCVNF_serviceId") - def orchStatus = execution.getVariable("DoCVNF_orchStatus") - def modelInvariantId = execution.getVariable("DoCVNF_modelInvariantId") - def modelVersion = execution.getVariable("DoCVNF_modelVersion") - def modelCustomizationId = execution.getVariable("DoCVNF_modelCustomizationId") - // TODO: 1702 Variable - def equipmentRole = execution.getVariable("DoCVNF_equipmentRole") - - //Get Service Instance Info - def serviceInstanceId = execution.getVariable("DoCVNF_serviceInstanceId") - String siRelatedLink = execution.getVariable("GENGS_siResourceLink") - - int custStart = siRelatedLink.indexOf("customer/") - int custEnd = siRelatedLink.indexOf("/service-subscriptions") - String globalCustId = siRelatedLink.substring(custStart + 9, custEnd) - int serviceStart = siRelatedLink.indexOf("service-subscription/") - int serviceEnd = siRelatedLink.indexOf("/service-instances/") - String serviceType = siRelatedLink.substring(serviceStart + 21, serviceEnd) - - //Get Namespace - AaiUtil aaiUtil = new AaiUtil(this) - def aai_uri = aaiUtil.getNetworkGenericVnfUri(execution) - String namespace = aaiUtil.getNamespaceFromUri(aai_uri) - - String payload = - """ - ${vnfId} - ${vnfName} - ${serviceId} - ${vnfType} - ${orchStatus} - ${modelInvariantId} - ${modelVersion} - ${modelCustomizationId} - - - service-instance - ${siRelatedLink} - - customer.global-customer-id - ${globalCustId} - - - service-subscription.service-type - ${serviceType} - - - service-instance.service-instance-id - ${serviceInstanceId} - - - - """ - - execution.setVariable("DoCVNF_genericVnfPayload", payload) - - }catch(Exception ex) { - utils.log("DEBUG", "Error Occured in DoCreateVnf PrepareCreateGenericVnf Process " + ex.getMessage(), isDebugEnabled) - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured in DoCreateVnf PrepareCreateGenericVnf Process") - } - utils.log("DEBUG", "*** COMPLETED DoCreateVnf PrepareCreateGenericVnf Process ***", isDebugEnabled) - } - - public void preProcessSDNCAssignRequest(Execution execution){ - def isDebugLogEnabled = execution.getVariable("isDebugLogEnabled") - execution.setVariable("prefix", Prefix) - logDebug(" ======== STARTED preProcessSDNCAssignRequest ======== ", isDebugLogEnabled) - def vnfId = execution.getVariable("DoCVNF_vnfId") - def serviceInstanceId = execution.getVariable("DoCVNF_serviceInstanceId") - logDebug("NEW VNF ID: " + vnfId, isDebugLogEnabled) - utils.logAudit("NEW VNF ID: " + vnfId) - - try{ - //Build SDNC Request - - String assignSDNCRequest = buildSDNCRequest(execution, serviceInstanceId, "assign") - - assignSDNCRequest = utils.formatXml(assignSDNCRequest) - execution.setVariable("DoCVNF_assignSDNCRequest", assignSDNCRequest) - logDebug("Outgoing AssignSDNCRequest is: \n" + assignSDNCRequest, isDebugLogEnabled) - utils.logAudit("Outgoing AssignSDNCRequest is: \n" + assignSDNCRequest) - - }catch(Exception e){ - utils.log("ERROR", "Exception Occured Processing preProcessSDNCAssignRequest. Exception is:\n" + e, isDebugLogEnabled) - exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occurred during prepareProvision Method:\n" + e.getMessage()) - } - logDebug("======== COMPLETED preProcessSDNCAssignRequest ======== ", isDebugLogEnabled) - } - - public void preProcessSDNCActivateRequest(Execution execution) { - def method = getClass().getSimpleName() + '.preProcessSDNCActivateRequest(' + - 'execution=' + execution.getId() + - ')' - def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') - logDebug('Entered ' + method, isDebugLogEnabled) - execution.setVariable("prefix", Prefix) - logDebug(" ======== STARTED preProcessSDNCActivateRequest Process ======== ", isDebugLogEnabled) - try{ - String vnfId = execution.getVariable("DoCVNF_vnfId") - String serviceInstanceId = execution.getVariable("DoCVNF_serviceInstanceId") - - String activateSDNCRequest = buildSDNCRequest(execution, serviceInstanceId, "activate") - - execution.setVariable("DoCVNF_activateSDNCRequest", activateSDNCRequest) - logDebug("Outgoing CommitSDNCRequest is: \n" + activateSDNCRequest, isDebugLogEnabled) - utils.logAudit("Outgoing CommitSDNCRequest is: \n" + activateSDNCRequest) - - }catch(Exception e){ - log.debug("Exception Occured Processing preProcessSDNCActivateRequest. Exception is:\n" + e, isDebugLogEnabled) - exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occured during preProcessSDNCActivateRequest Method:\n" + e.getMessage()) - } - logDebug("======== COMPLETED preProcessSDNCActivateRequest Process ======== ", isDebugLogEnabled) - } - - public String buildSDNCRequest(Execution execution, String svcInstId, String action){ - - String uuid = execution.getVariable('testReqId') // for junits - if(uuid==null){ + ${requestId} + CREATE + ${source} + """ + + execution.setVariable("DoCVNF_requestInfo", requestInfo) + //TODO: Orch Status - TBD, will come from SDN-C Response in 1702 + String orchStatus = "Created" + execution.setVariable("DoCVNF_orchStatus", orchStatus) + + //TODO: Equipment Role - Should come from SDN-C Response in 1702 + String equipmentRole = " " + execution.setVariable("DoCVNF_equipmentRole", equipmentRole) + String vnfId = execution.getVariable("testVnfId") // for junits + if(isBlank(vnfId)){ + vnfId = execution.getVariable("vnfId") + if (isBlank(vnfId)) { + vnfId = UUID.randomUUID().toString() + utils.log("DEBUG", "Generated Vnf Id is: " + vnfId, isDebugEnabled) + } + } + execution.setVariable("DoCVNF_vnfId", vnfId) + + // Setting for Sub Flow Calls + execution.setVariable("DoCVNF_type", "generic-vnf") + execution.setVariable("GENGS_type", "service-instance") + + String sdncCallbackUrl = (String) execution.getVariable('URN_mso_workflow_sdncadapter_callback') + if (sdncCallbackUrl == null || sdncCallbackUrl.trim().isEmpty()) { + def msg = 'Required variable \'URN_mso_workflow_sdncadapter_callback\' is missing' + logError(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg) + } + execution.setVariable("DoCVNF_sdncCallbackUrl", sdncCallbackUrl) + utils.logAudit("SDNC Callback URL: " + sdncCallbackUrl) + logDebug("SDNC Callback URL is: " + sdncCallbackUrl, isDebugEnabled) + + def rollbackData = execution.getVariable("RollbackData") + if (rollbackData == null) { + rollbackData = new RollbackData() + } + + execution.setVariable("RollbackData", rollbackData) + + }catch(BpmnError b){ + utils.log("DEBUG", "Rethrowing MSOWorkflowException", isDebugEnabled) + throw b + }catch(Exception e){ + utils.log("DEBUG", " Error Occured in DoCreateVnf PreProcessRequest method!" + e.getMessage(), isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured in DoCreateVnf PreProcessRequest") + + } + utils.log("DEBUG", "*** COMPLETED DoCreateVnf PreProcessRequest Process ***", isDebugEnabled) + } + + + public void prepareCreateGenericVnf (Execution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix",Prefix) + + utils.log("DEBUG", " *** STARTED DoCreateVnf PrepareCreateGenericVnf Process *** ", isDebugEnabled) + try { + //Get Vnf Info + String vnfId = execution.getVariable("DoCVNF_vnfId") + def vnfName = execution.getVariable("DoCVNF_vnfName") + def vnfType = execution.getVariable("DoCVNF_vnfType") + def serviceId = execution.getVariable("DoCVNF_serviceId") + def orchStatus = execution.getVariable("DoCVNF_orchStatus") + def modelInvariantId = execution.getVariable("DoCVNF_modelInvariantId") + def modelVersion = execution.getVariable("DoCVNF_modelVersion") + def modelCustomizationId = execution.getVariable("DoCVNF_modelCustomizationId") + // TODO: 1702 Variable + def equipmentRole = execution.getVariable("DoCVNF_equipmentRole") + + //Get Service Instance Info + def serviceInstanceId = execution.getVariable("DoCVNF_serviceInstanceId") + String siRelatedLink = execution.getVariable("GENGS_siResourceLink") + + int custStart = siRelatedLink.indexOf("customer/") + int custEnd = siRelatedLink.indexOf("/service-subscriptions") + String globalCustId = siRelatedLink.substring(custStart + 9, custEnd) + int serviceStart = siRelatedLink.indexOf("service-subscription/") + int serviceEnd = siRelatedLink.indexOf("/service-instances/") + String serviceType = siRelatedLink.substring(serviceStart + 21, serviceEnd) + + //Get Namespace + AaiUtil aaiUtil = new AaiUtil(this) + def aai_uri = aaiUtil.getNetworkGenericVnfUri(execution) + String namespace = aaiUtil.getNamespaceFromUri(aai_uri) + + String payload = + """ + ${vnfId} + ${vnfName} + ${serviceId} + ${vnfType} + PREPROV + ${orchStatus} + ${modelInvariantId} + ${modelVersion} + ${modelCustomizationId} + + + service-instance + ${siRelatedLink} + + customer.global-customer-id + ${globalCustId} + + + service-subscription.service-type + ${serviceType} + + + service-instance.service-instance-id + ${serviceInstanceId} + + + + """ + + execution.setVariable("DoCVNF_genericVnfPayload", payload) + + }catch(Exception ex) { + utils.log("DEBUG", "Error Occured in DoCreateVnf PrepareCreateGenericVnf Process " + ex.getMessage(), isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured in DoCreateVnf PrepareCreateGenericVnf Process") + } + utils.log("DEBUG", "*** COMPLETED DoCreateVnf PrepareCreateGenericVnf Process ***", isDebugEnabled) + } + + public void postProcessCreateGenericVnf (Execution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix",Prefix) + + utils.log("DEBUG", " *** STARTED DoCreateVnf PostProcessCreateGenericVnf Process *** ", isDebugEnabled) + try { + //Get Vnf Info + String vnfId = execution.getVariable("DoCVNF_vnfId") + def rollbackData = execution.getVariable("RollbackData") + rollbackData.put("VNF", "vnfId", vnfId) + execution.setVariable("RollbackData", rollbackData) + }catch(Exception ex) { + utils.log("DEBUG", "Error Occured in DoCreateVnf PostProcessCreateGenericVnf Process " + ex.getMessage(), isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured in DoCreateVnf PostProcessCreateGenericVnf Process") + } + utils.log("DEBUG", "*** COMPLETED DoCreateVnf PostProcessCreateGenericVnf Process ***", isDebugEnabled) + } + + + public void preProcessSDNCAssignRequest(Execution execution){ + def isDebugLogEnabled = execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix", Prefix) + logDebug(" ======== STARTED preProcessSDNCAssignRequest ======== ", isDebugLogEnabled) + def vnfId = execution.getVariable("DoCVNF_vnfId") + def serviceInstanceId = execution.getVariable("DoCVNF_serviceInstanceId") + logDebug("NEW VNF ID: " + vnfId, isDebugLogEnabled) + utils.logAudit("NEW VNF ID: " + vnfId) + + try{ + //Build SDNC Request + + String assignSDNCRequest = buildSDNCRequest(execution, serviceInstanceId, "assign") + + assignSDNCRequest = utils.formatXml(assignSDNCRequest) + execution.setVariable("DoCVNF_assignSDNCRequest", assignSDNCRequest) + logDebug("Outgoing AssignSDNCRequest is: \n" + assignSDNCRequest, isDebugLogEnabled) + utils.logAudit("Outgoing AssignSDNCRequest is: \n" + assignSDNCRequest) + + }catch(Exception e){ + utils.log("ERROR", "Exception Occured Processing preProcessSDNCAssignRequest. Exception is:\n" + e, isDebugLogEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occurred during preProcessSDNCAssignRequest Method:\n" + e.getMessage()) + } + logDebug("======== COMPLETED preProcessSDNCAssignRequest ======== ", isDebugLogEnabled) + } + + public void preProcessSDNCActivateRequest(Execution execution) { + def method = getClass().getSimpleName() + '.preProcessSDNCActivateRequest(' + + 'execution=' + execution.getId() + + ')' + def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') + logDebug('Entered ' + method, isDebugLogEnabled) + execution.setVariable("prefix", Prefix) + logDebug(" ======== STARTED preProcessSDNCActivateRequest Process ======== ", isDebugLogEnabled) + try{ + String vnfId = execution.getVariable("DoCVNF_vnfId") + String serviceInstanceId = execution.getVariable("DoCVNF_serviceInstanceId") + + String activateSDNCRequest = buildSDNCRequest(execution, serviceInstanceId, "activate") + + execution.setVariable("DoCVNF_activateSDNCRequest", activateSDNCRequest) + logDebug("Outgoing CommitSDNCRequest is: \n" + activateSDNCRequest, isDebugLogEnabled) + utils.logAudit("Outgoing CommitSDNCRequest is: \n" + activateSDNCRequest) + + }catch(Exception e){ + log.debug("Exception Occured Processing preProcessSDNCActivateRequest. Exception is:\n" + e, isDebugLogEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occured during preProcessSDNCActivateRequest Method:\n" + e.getMessage()) + } + logDebug("======== COMPLETED preProcessSDNCActivateRequest Process ======== ", isDebugLogEnabled) + } + + public String buildSDNCRequest(Execution execution, String svcInstId, String action){ + + String uuid = execution.getVariable('testReqId') // for junits + if(uuid==null){ uuid = execution.getVariable("mso-request-id") + "-" + System.currentTimeMillis() - } - def callbackURL = execution.getVariable("DoCVNF_sdncCallbackUrl") - def requestId = execution.getVariable("DoCVNF_requestId") - def serviceId = execution.getVariable("DoCVNF_serviceId") - def vnfType = execution.getVariable("DoCVNF_vnfType") - def vnfName = execution.getVariable("DoCVNF_vnfName") - def tenantId = execution.getVariable("DoCVNF_tenantId") - def source = execution.getVariable("DoCVNF_source") - def vnfId = execution.getVariable("DoCVNF_vnfId") - def cloudSiteId = execution.getVariable("DoCVNF_cloudSiteId") - def modelInvariantId = execution.getVariable("DoCVNF_modelInvariantId") - def modelVersionId = execution.getVariable("DoCVNF_modelVersionId") - def modelVersion = execution.getVariable("DoCVNF_modelVersion") - def modelName = execution.getVariable("DoCVNF_modelName") - - String sdncVNFParamsXml = "" - - if(execution.getVariable("DoCVNF_vnfParamsExistFlag") == true){ - sdncVNFParamsXml = buildSDNCParamsXml(execution) - }else{ - sdncVNFParamsXml = "" - } - - String sdncRequest = + } + def callbackURL = execution.getVariable("DoCVNF_sdncCallbackUrl") + def requestId = execution.getVariable("DoCVNF_requestId") + def serviceId = execution.getVariable("DoCVNF_serviceId") + def vnfType = execution.getVariable("DoCVNF_vnfType") + def vnfName = execution.getVariable("DoCVNF_vnfName") + def tenantId = execution.getVariable("DoCVNF_tenantId") + def source = execution.getVariable("DoCVNF_source") + def vnfId = execution.getVariable("DoCVNF_vnfId") + def cloudSiteId = execution.getVariable("DoCVNF_cloudSiteId") + def modelCustomizationId = execution.getVariable("DoCVNF_modelCustomizationId") + def serviceModelInfo = execution.getVariable("serviceModelInfo") + def vnfModelInfo = execution.getVariable("vnfModelInfo") + String serviceEcompModelInformation = sdncAdapterUtils.modelInfoToEcompModelInformation(serviceModelInfo) + String vnfEcompModelInformation = sdncAdapterUtils.modelInfoToEcompModelInformation(vnfModelInfo) + def globalSubscriberId = execution.getVariable("DoCVNF_globalSubscriberId") + def sdncVersion = execution.getVariable("DoCVNF_sdncVersion") + + String sdncVNFParamsXml = "" + + if(execution.getVariable("DoCVNF_vnfParamsExistFlag") == true){ + sdncVNFParamsXml = buildSDNCParamsXml(execution) + }else{ + sdncVNFParamsXml = "" + } + + String sdncRequest = """ - - ${requestId} - ${svcInstId} - ${action} - vnf-topology-operation - ${callbackURL} - - - - ${requestId} - VNFActivateRequest - ${source} - - - - - - ${serviceId} - ${serviceId} - ${svcInstId} - notsurewecare - - - ${vnfId} - ${vnfType} - - ${modelInvariantId} - ${modelVersionId} - ${modelVersion} - ${modelName} - - - - ${vnfName} - ${cloudSiteId} - ${tenantId} - ${sdncVNFParamsXml} - - - """ - - utils.logAudit("sdncRequest: " + sdncRequest) - return sdncRequest - } - - public void validateSDNCResponse(Execution execution, String response, String method){ - def isDebugLogEnabled=execution.getVariable("isDebugLogEnabled") - execution.setVariable("prefix",Prefix) - logDebug(" *** STARTED ValidateSDNCResponse Process*** ", isDebugLogEnabled) - - WorkflowException workflowException = execution.getVariable("WorkflowException") - boolean successIndicator = execution.getVariable("SDNCA_SuccessIndicator") - - utils.logAudit("workflowException: " + workflowException) - - SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils(this) - sdncAdapterUtils.validateSDNCResponse(execution, response, workflowException, successIndicator) - - utils.logAudit("SDNCResponse: " + response) - - String sdncResponse = response - if(execution.getVariable(Prefix + 'sdncResponseSuccess') == true){ - logDebug("Received a Good Response from SDNC Adapter for " + method + " SDNC Call. Response is: \n" + sdncResponse, isDebugLogEnabled) - - }else{ - logDebug("Received a BAD Response from SDNC Adapter for " + method + " SDNC Call.", isDebugLogEnabled) - throw new BpmnError("MSOWorkflowException") - } - logDebug(" *** COMPLETED ValidateSDNCResponse Process*** ", isDebugLogEnabled) - } - - -} + + ${requestId} + ${svcInstId} + ${action} + vnf-topology-operation + ${callbackURL} + generic-resource + + + + ${requestId} + CreateVnfInstance + ${source} + + + + + + ${serviceId} + ${serviceId} + ${serviceEcompModelInformation} + ${svcInstId} + ${globalSubscriberId} + + + ${vnfId} + ${vnfType} + ${vnfEcompModelInformation} + + + ${sdncVersion} + + ${tenantId} + ${cloudSiteId} + ${sdncVNFParamsXml} + + + """ + + utils.logAudit("sdncRequest: " + sdncRequest) + return sdncRequest + } + + public void validateSDNCResponse(Execution execution, String response, String method){ + def isDebugLogEnabled=execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix",Prefix) + logDebug(" *** STARTED ValidateSDNCResponse Process*** ", isDebugLogEnabled) + + WorkflowException workflowException = execution.getVariable("WorkflowException") + boolean successIndicator = execution.getVariable("SDNCA_SuccessIndicator") + + utils.logAudit("workflowException: " + workflowException) + + SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils(this) + sdncAdapterUtils.validateSDNCResponse(execution, response, workflowException, successIndicator) + + utils.logAudit("SDNCResponse: " + response) + + String sdncResponse = response + if(execution.getVariable(Prefix + 'sdncResponseSuccess') == true){ + logDebug("Received a Good Response from SDNC Adapter for " + method + " SDNC Call. Response is: \n" + sdncResponse, isDebugLogEnabled) + + }else{ + logDebug("Received a BAD Response from SDNC Adapter for " + method + " SDNC Call.", isDebugLogEnabled) + throw new BpmnError("MSOWorkflowException") + } + logDebug(" *** COMPLETED ValidateSDNCResponse Process*** ", isDebugLogEnabled) + } + + +} diff --git a/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/DoCreateVnfAndModules.groovy b/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/DoCreateVnfAndModules.groovy index e1fca3ddc3..861da52397 100644 --- a/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/DoCreateVnfAndModules.groovy +++ b/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/DoCreateVnfAndModules.groovy @@ -1,241 +1,285 @@ -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - MSO - * ================================================================================ - * 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.openecomp.mso.bpmn.infrastructure.scripts - -import java.util.UUID; - -import org.json.JSONObject; -import org.json.JSONArray; - -import org.camunda.bpm.engine.delegate.BpmnError -import org.camunda.bpm.engine.runtime.Execution; - -import static org.apache.commons.lang3.StringUtils.*; - -import org.openecomp.mso.bpmn.core.json.JsonUtils -import org.openecomp.mso.bpmn.common.scripts.AbstractServiceTaskProcessor -import org.openecomp.mso.bpmn.common.scripts.CatalogDbUtils -import org.openecomp.mso.bpmn.common.scripts.ExceptionUtil -import org.openecomp.mso.bpmn.common.scripts.VidUtils -import org.openecomp.mso.bpmn.core.RollbackData -import org.openecomp.mso.bpmn.core.WorkflowException - - - -/** - * This class supports the macro VID Flow - * with the creation of a generic vnf and related VF modules. - */ -class DoCreateVnfAndModules extends AbstractServiceTaskProcessor { - - String Prefix="DCVAM_" - ExceptionUtil exceptionUtil = new ExceptionUtil() - JsonUtils jsonUtil = new JsonUtils() - VidUtils vidUtils = new VidUtils(this) - CatalogDbUtils cutils = new CatalogDbUtils() - - /** - * This method gets and validates the incoming - * request. - * - * @param - execution - */ - public void preProcessRequest(Execution execution) { - def isDebugEnabled = execution.getVariable("isDebugLogEnabled") - execution.setVariable("prefix",Prefix) - utils.log("DEBUG", " *** STARTED DoCreateVnfAndModules PreProcessRequest Process*** ", isDebugEnabled) - - try{ - // Get Variables - - - String cloudConfiguration = execution.getVariable("cloudConfiguration") - String vnfModelInfo = execution.getVariable("vnfModelInfo") - - String requestId = execution.getVariable("requestId") - execution.setVariable("mso-request-id", requestId) - 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 vnfType = execution.getVariable("vnfType") - utils.log("DEBUG", "Incoming Vnf Type is: " + vnfType, isDebugEnabled) - - String vnfName = execution.getVariable("vnfName") - execution.setVariable("CREVI_vnfName", vnfName) - utils.log("DEBUG", "Incoming Vnf Name is: " + vnfName, isDebugEnabled) - - String productFamilyId = execution.getVariable("productFamilyId") - utils.log("DEBUG", "Incoming Product Family Id is: " + productFamilyId, isDebugEnabled) - - String source = "VID" - execution.setVariable("source", source) - utils.log("DEBUG", "Incoming Source is: " + source, isDebugEnabled) - - String disableRollback = execution.getVariable("disableRollback") - utils.log("DEBUG", "Incoming Disable Rollback is: " + disableRollback, isDebugEnabled) - - String asdcServiceModelVersion = execution.getVariable("asdcServiceModelVersion") - utils.log("DEBUG", "Incoming asdcServiceModelVersion: " + asdcServiceModelVersion, isDebugEnabled) - - String vnfId = execution.getVariable("testVnfId") // for junits - if(isBlank(vnfId)){ - vnfId = execution.getVariable("vnfId") - if (isBlank(vnfId)) { - vnfId = UUID.randomUUID().toString() - utils.log("DEBUG", "Generated Vnf Id is: " + vnfId, isDebugEnabled) - } - } - execution.setVariable("vnfId", vnfId) - - }catch(BpmnError b){ - utils.log("DEBUG", "Rethrowing MSOWorkflowException", isDebugEnabled) - throw b - }catch(Exception e){ - utils.log("DEBUG", " Error Occured in DoCreateVnfAndModules PreProcessRequest method!" + e.getMessage(), isDebugEnabled) - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured in DoCreateVnf PreProcessRequest") - - } - utils.log("DEBUG", "*** COMPLETED DoCreateVnfAndModules PreProcessRequest Process ***", isDebugEnabled) - } - - - public void queryCatalogDB (Execution execution) { - def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - execution.setVariable("prefix",Prefix) - - utils.log("DEBUG", " *** STARTED DoCreateVnfAndModules QueryCatalogDB Process *** ", isDebugEnabled) - try { - //Get Vnf Info - String vnfModelInfo = execution.getVariable("vnfModelInfo") - String vnfModelCustomizationUuid = jsonUtil.getJsonValueForKey(vnfModelInfo, "modelCustomizationId") - utils.log("DEBUG", "querying Catalog DB by vnfModelCustomizationUuid: " + vnfModelCustomizationUuid) - String catalogDbEndpoint = execution.getVariable("URN_mso_catalog_db_endpoint") - - JSONArray vnfs = cutils.getAllVnfsByVnfModelCustomizationUuid(catalogDbEndpoint, - vnfModelCustomizationUuid) - utils.log("DEBUG", "obtained VNF list") - // Only one match here - JSONObject vnf = vnfs[0] - JSONArray vfModules = vnf.getJSONArray("vfModules") - JSONArray addOnModules = new JSONArray() - - // Set up base Vf Module info - for (int i = 0; i < vfModules.length(); i++) { - utils.log("DEBUG", "handling VF Module ") - JSONObject vfModule = vfModules[i] - String isBase = jsonUtil.getJsonValueForKey(vfModule, "isBase") - if (isBase.equals("true")) { - JSONObject baseVfModuleModelInfoObject = vfModule.getJSONObject("modelInfo") - String baseVfModuleModelInfo = baseVfModuleModelInfoObject.toString() - execution.setVariable("baseVfModuleModelInfo", baseVfModuleModelInfo) - String baseVfModuleLabel = jsonUtil.getJsonValueForKey(vfModule, "vfModuleLabel") - execution.setVariable("baseVfModuleLabel", baseVfModuleLabel) - String basePersonaModelId = jsonUtil.getJsonValueForKey(baseVfModuleModelInfoObject, "modelInvariantId") - execution.setVariable("basePersonaModelId", basePersonaModelId) - } - else { - addOnModules.add(vfModules[i]) - } - } - - execution.setVariable("addOnModules", addOnModules) - execution.setVariable("addOnModulesToDeploy", addOnModules.length()) - execution.setVariable("addOnModulesDeployed", 0) - - }catch(Exception ex) { - utils.log("DEBUG", "Error Occured in DoCreateVnfAndModules QueryCatalogDB Process " + ex.getMessage(), isDebugEnabled) - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured in DoCreateVnfAndModules QueryCatalogDB Process") - } - - // Generate vfModuleId for base VF Module - def baseVfModuleId = UUID.randomUUID().toString() - execution.setVariable("baseVfModuleId", baseVfModuleId) - utils.log("DEBUG", "*** COMPLETED CreateVnfInfra PrepareCreateGenericVnf Process ***", isDebugEnabled) - } - - public void preProcessAddOnModule(Execution execution){ - def isDebugLogEnabled = execution.getVariable("isDebugLogEnabled") - execution.setVariable("prefix", Prefix) - logDebug(" ======== STARTED preProcessAddOnModule ======== ", isDebugLogEnabled) - - try { - JSONArray addOnModules = (JSONArray) execution.getVariable("addOnModules") - int addOnIndex = (int) execution.getVariable("addOnModulesDeployed") - - JSONObject addOnModule = addOnModules[addOnIndex] - - def newVfModuleId = UUID.randomUUID().toString() - execution.setVariable("addOnVfModuleId", newVfModuleId) - - execution.setVariable("instancesOfThisModelDeployed", 0) - - JSONObject addOnVfModuleModelInfoObject = jsonUtil.getJsonValueForKey(addOnModule, "modelInfo") - String addOnVfModuleModelInfo = addOnVfModuleModelInfoObject.toString() - execution.setVariable("addOnVfModuleModelInfo", addOnVfModuleModelInfo) - String addOnVfModuleLabel = jsonUtil.getJsonValueForKey(addOnModule, "vfModuleLabel") - execution.setVariable("addOnVfModuleLabel", addOnVfModuleLabel) - String addOnPersonaModelId = jsonUtil.getJsonValueForKey(addOnVfModuleModelInfoObject, "modelInvariantId") - execution.setVariable("addOnPersonaModelId", addOnPersonaModelId) - String addOnInitialCount = jsonUtil.getJsonValueForKey(addOnModule, "initialCount") - execution.setVariable("initialCount", addOnInitialCount) - - - }catch(Exception e){ - utils.log("ERROR", "Exception Occured Processing preProcessAddOnModule. Exception is:\n" + e, isDebugLogEnabled) - exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occurred during preProcessAddOnModule Method:\n" + e.getMessage()) - } - logDebug("======== COMPLETED preProcessSDNCAssignRequest ======== ", isDebugLogEnabled) - } - - public void validateAddOnModule(Execution execution){ - def isDebugLogEnabled = execution.getVariable("isDebugLogEnabled") - execution.setVariable("prefix", Prefix) - logDebug(" ======== STARTED validateAddOnModule ======== ", isDebugLogEnabled) - - try { - int instancesOfThisModuleDeployed = execution.getVariable("instancesOfThisModuleDeployed") - execution.setVariable("instancesOfThisModuleDeployed", instancesOfThisModuleDeployed + 1) - }catch(Exception e){ - utils.log("ERROR", "Exception Occured Processing preProcessAddOnModule. Exception is:\n" + e, isDebugLogEnabled) - exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occurred during preProcessAddOnModule Method:\n" + e.getMessage()) - } - logDebug("======== COMPLETED preProcessSDNCAssignRequest ======== ", isDebugLogEnabled) - } - - public void finishProcessingInitialCountDeployment(Execution execution){ - def isDebugLogEnabled = execution.getVariable("isDebugLogEnabled") - execution.setVariable("prefix", Prefix) - logDebug(" ======== STARTED finishProcessingInitialCountDeployment ======== ", isDebugLogEnabled) - - try { - int addOnModulesDeployed = execution.getVariable("addOnModulesDeployed") - execution.setVariable("addOnModulesDeployed", addOnModulesDeployed + 1) - }catch(Exception e){ - utils.log("ERROR", "Exception Occured Processing preProcessAddOnModule. Exception is:\n" + e, isDebugLogEnabled) - exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occurred during preProcessAddOnModule Method:\n" + e.getMessage()) - } - logDebug("======== COMPLETED preProcessSDNCAssignRequest ======== ", isDebugLogEnabled) - } - - - -} +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.bpmn.infrastructure.scripts + +import java.util.UUID; + +import org.json.JSONObject; +import org.json.JSONArray; + +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.runtime.Execution; + +import static org.apache.commons.lang3.StringUtils.*; + +import org.openecomp.mso.bpmn.core.json.JsonUtils +import org.openecomp.mso.bpmn.common.scripts.AbstractServiceTaskProcessor +import org.openecomp.mso.bpmn.common.scripts.CatalogDbUtils +import org.openecomp.mso.bpmn.common.scripts.ExceptionUtil +import org.openecomp.mso.bpmn.common.scripts.VidUtils +import org.openecomp.mso.bpmn.core.RollbackData +import org.openecomp.mso.bpmn.core.WorkflowException + + + +/** +* This class supports the macro VID Flow +* with the creation of a generic vnf and related VF modules. +*/ +class DoCreateVnfAndModules extends AbstractServiceTaskProcessor { + + String Prefix="DCVAM_" + ExceptionUtil exceptionUtil = new ExceptionUtil() + JsonUtils jsonUtil = new JsonUtils() + VidUtils vidUtils = new VidUtils(this) + CatalogDbUtils cutils = new CatalogDbUtils() + + /** + * This method gets and validates the incoming + * request. + * + * @param - execution + */ + public void preProcessRequest(Execution execution) { + def isDebugEnabled = execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix",Prefix) + utils.log("DEBUG", " *** STARTED DoCreateVnfAndModules PreProcessRequest Process*** ", isDebugEnabled) + + try{ + // Get Variables + + + String cloudConfiguration = execution.getVariable("cloudConfiguration") + String vnfModelInfo = execution.getVariable("vnfModelInfo") + + String requestId = execution.getVariable("requestId") + execution.setVariable("mso-request-id", requestId) + 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 vnfType = execution.getVariable("vnfType") + utils.log("DEBUG", "Incoming Vnf Type is: " + vnfType, isDebugEnabled) + + String vnfName = execution.getVariable("vnfName") + execution.setVariable("CREVI_vnfName", vnfName) + utils.log("DEBUG", "Incoming Vnf Name is: " + vnfName, isDebugEnabled) + + String productFamilyId = execution.getVariable("productFamilyId") + utils.log("DEBUG", "Incoming Product Family Id is: " + productFamilyId, isDebugEnabled) + + String source = "VID" + execution.setVariable("source", source) + utils.log("DEBUG", "Incoming Source is: " + source, isDebugEnabled) + + String disableRollback = execution.getVariable("disableRollback") + utils.log("DEBUG", "Incoming Disable Rollback is: " + disableRollback, isDebugEnabled) + + String asdcServiceModelVersion = execution.getVariable("asdcServiceModelVersion") + utils.log("DEBUG", "Incoming asdcServiceModelVersion: " + asdcServiceModelVersion, isDebugEnabled) + + String vnfId = execution.getVariable("testVnfId") // for junits + if(isBlank(vnfId)){ + vnfId = execution.getVariable("vnfId") + if (isBlank(vnfId)) { + vnfId = UUID.randomUUID().toString() + utils.log("DEBUG", "Generated Vnf Id is: " + vnfId, isDebugEnabled) + } + } + execution.setVariable("vnfId", vnfId) + + def rollbackData = execution.getVariable("RollbackData") + if (rollbackData == null) { + rollbackData = new RollbackData() + } + + execution.setVariable("numOfCreatedAddOnModules", 0) + + rollbackData.put("VNFANDMODULES", "numOfCreatedAddOnModules", 0) + execution.setVariable("RollbackData", rollbackData) + + }catch(BpmnError b){ + utils.log("DEBUG", "Rethrowing MSOWorkflowException", isDebugEnabled) + throw b + }catch(Exception e){ + utils.log("DEBUG", " Error Occured in DoCreateVnfAndModules PreProcessRequest method!" + e.getMessage(), isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured in DoCreateVnf PreProcessRequest") + + } + utils.log("DEBUG", "*** COMPLETED DoCreateVnfAndModules PreProcessRequest Process ***", isDebugEnabled) + } + + + public void queryCatalogDB (Execution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix",Prefix) + + utils.log("DEBUG", " *** STARTED DoCreateVnfAndModules QueryCatalogDB Process *** ", isDebugEnabled) + try { + //Get Vnf Info + String vnfModelInfo = execution.getVariable("vnfModelInfo") + String vnfModelCustomizationUuid = jsonUtil.getJsonValueForKey(vnfModelInfo, "modelCustomizationId") + utils.log("DEBUG", "querying Catalog DB by vnfModelCustomizationUuid: " + vnfModelCustomizationUuid) + String catalogDbEndpoint = execution.getVariable("URN_mso_catalog_db_endpoint") + + JSONArray vnfs = cutils.getAllVnfsByVnfModelCustomizationUuid(catalogDbEndpoint, + vnfModelCustomizationUuid) + utils.log("DEBUG", "obtained VNF list") + // Only one match here + JSONObject vnf = vnfs[0] + JSONArray vfModules = vnf.getJSONArray("vfModules") + JSONArray addOnModules = new JSONArray() + + // Set up base Vf Module info + for (int i = 0; i < vfModules.length(); i++) { + utils.log("DEBUG", "handling VF Module ") + JSONObject vfModule = vfModules[i] + String isBase = jsonUtil.getJsonValueForKey(vfModule, "isBase") + if (isBase.equals("true")) { + JSONObject baseVfModuleModelInfoObject = vfModule.getJSONObject("modelInfo") + String baseVfModuleModelInfo = baseVfModuleModelInfoObject.toString() + execution.setVariable("baseVfModuleModelInfo", baseVfModuleModelInfo) + String baseVfModuleLabel = jsonUtil.getJsonValueForKey(vfModule, "vfModuleLabel") + execution.setVariable("baseVfModuleLabel", baseVfModuleLabel) + String basePersonaModelId = jsonUtil.getJsonValueForKey(baseVfModuleModelInfoObject, "modelInvariantId") + execution.setVariable("basePersonaModelId", basePersonaModelId) + } + else { + addOnModules.add(vfModules[i]) + } + } + + execution.setVariable("addOnModules", addOnModules) + execution.setVariable("addOnModulesToDeploy", addOnModules.length()) + execution.setVariable("addOnModulesDeployed", 0) + + }catch(Exception ex) { + utils.log("DEBUG", "Error Occured in DoCreateVnfAndModules QueryCatalogDB Process " + ex.getMessage(), isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured in DoCreateVnfAndModules QueryCatalogDB Process") + } + + // Generate vfModuleId for base VF Module + def baseVfModuleId = UUID.randomUUID().toString() + execution.setVariable("baseVfModuleId", baseVfModuleId) + utils.log("DEBUG", "*** COMPLETED CreateVnfInfra PrepareCreateGenericVnf Process ***", isDebugEnabled) + } + + public void preProcessAddOnModule(Execution execution){ + def isDebugLogEnabled = execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix", Prefix) + logDebug(" ======== STARTED preProcessAddOnModule ======== ", isDebugLogEnabled) + + try { + JSONArray addOnModules = (JSONArray) execution.getVariable("addOnModules") + int addOnIndex = (int) execution.getVariable("addOnModulesDeployed") + + JSONObject addOnModule = addOnModules[addOnIndex] + + def newVfModuleId = UUID.randomUUID().toString() + execution.setVariable("addOnVfModuleId", newVfModuleId) + + execution.setVariable("instancesOfThisModelDeployed", 0) + + JSONObject addOnVfModuleModelInfoObject = jsonUtil.getJsonValueForKey(addOnModule, "modelInfo") + String addOnVfModuleModelInfo = addOnVfModuleModelInfoObject.toString() + execution.setVariable("addOnVfModuleModelInfo", addOnVfModuleModelInfo) + String addOnVfModuleLabel = jsonUtil.getJsonValueForKey(addOnModule, "vfModuleLabel") + execution.setVariable("addOnVfModuleLabel", addOnVfModuleLabel) + String addOnPersonaModelId = jsonUtil.getJsonValueForKey(addOnVfModuleModelInfoObject, "modelInvariantId") + execution.setVariable("addOnPersonaModelId", addOnPersonaModelId) + String addOnInitialCount = jsonUtil.getJsonValueForKey(addOnModule, "initialCount") + execution.setVariable("initialCount", addOnInitialCount) + + + }catch(Exception e){ + utils.log("ERROR", "Exception Occured Processing preProcessAddOnModule. Exception is:\n" + e, isDebugLogEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occurred during preProcessAddOnModule Method:\n" + e.getMessage()) + } + logDebug("======== COMPLETED preProcessSDNCAssignRequest ======== ", isDebugLogEnabled) + } + + public void validateBaseModule(Execution execution){ + def isDebugLogEnabled = execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix", Prefix) + logDebug(" ======== STARTED validateBaseModule ======== ", isDebugLogEnabled) + + try { + def baseRollbackData = execution.getVariable("DCVAM_baseRollbackData") + def rollbackData = execution.getVariable("RollbackData") + + def baseModuleMap = baseRollbackData.get("VFMODULE") + baseModuleMap.each{ k, v -> rollbackData.put("VFMODULE_BASE", "${k}","${v}") } + execution.setVariable("RollbackData", rollbackData) + + }catch(Exception e){ + utils.log("ERROR", "Exception Occured Processing validateBaseModule. Exception is:\n" + e, isDebugLogEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occurred during validateBaseModule Method:\n" + e.getMessage()) + } + logDebug("======== COMPLETED validateBaseModule ======== ", isDebugLogEnabled) + } + + public void validateAddOnModule(Execution execution){ + def isDebugLogEnabled = execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix", Prefix) + logDebug(" ======== STARTED validateAddOnModule ======== ", isDebugLogEnabled) + + try { + int instancesOfThisModuleDeployed = execution.getVariable("instancesOfThisModuleDeployed") + int numOfCreatedAddOnModules = execution.getVariable("numOfCreatedAddOnModules") + def addOnRollbackData = execution.getVariable("DCVAM_addOnRollbackData") + def rollbackData = execution.getVariable("RollbackData") + + def addOnModuleMap = addOnRollbackData.get("VFMODULE") + numOfCreatedAddOnModules = numOfCreatedAddOnModules + 1 + addOnModuleMap.each{ k, v -> rollbackData.put("VFMODULE_ADDON_" + numOfCreatedAddOnModules, "${k}","${v}") } + + execution.setVariable("DCVAM_addOnRollbackData", null) + + execution.setVariable("instancesOfThisModuleDeployed", instancesOfThisModuleDeployed + 1) + + execution.setVariable("numOfCreatedAddOnModules", numOfCreatedAddOnModules) + rollbackData.put("VNFANDMODULES", "numOfCreatedAddOnModules", numOfCreatedAddOnModules) + execution.setVariable("RollbackData", rollbackData) + }catch(Exception e){ + utils.log("ERROR", "Exception Occured Processing preProcessAddOnModule. Exception is:\n" + e, isDebugLogEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occurred during preProcessAddOnModule Method:\n" + e.getMessage()) + } + logDebug("======== COMPLETED preProcessSDNCAssignRequest ======== ", isDebugLogEnabled) + } + + public void finishProcessingInitialCountDeployment(Execution execution){ + def isDebugLogEnabled = execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix", Prefix) + logDebug(" ======== STARTED finishProcessingInitialCountDeployment ======== ", isDebugLogEnabled) + + try { + int addOnModulesDeployed = execution.getVariable("addOnModulesDeployed") + execution.setVariable("addOnModulesDeployed", addOnModulesDeployed + 1) + }catch(Exception e){ + utils.log("ERROR", "Exception Occured Processing preProcessAddOnModule. Exception is:\n" + e, isDebugLogEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occurred during preProcessAddOnModule Method:\n" + e.getMessage()) + } + logDebug("======== COMPLETED preProcessSDNCAssignRequest ======== ", isDebugLogEnabled) + } + + + +} diff --git a/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/DoCreateVnfAndModulesRollback.groovy b/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/DoCreateVnfAndModulesRollback.groovy new file mode 100644 index 0000000000..7b9bed3f7a --- /dev/null +++ b/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/DoCreateVnfAndModulesRollback.groovy @@ -0,0 +1,153 @@ +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.bpmn.infrastructure.scripts + +import java.util.UUID; + +import org.json.JSONObject; +import org.json.JSONArray; + +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.runtime.Execution; + +import static org.apache.commons.lang3.StringUtils.*; + +import org.openecomp.mso.bpmn.core.json.JsonUtils +import org.openecomp.mso.bpmn.common.scripts.AbstractServiceTaskProcessor +import org.openecomp.mso.bpmn.common.scripts.CatalogDbUtils +import org.openecomp.mso.bpmn.common.scripts.ExceptionUtil +import org.openecomp.mso.bpmn.common.scripts.VidUtils +import org.openecomp.mso.bpmn.core.RollbackData +import org.openecomp.mso.bpmn.core.WorkflowException + +/** + * This class supports the macro VID Flow + * with the rollback of a creation of a generic vnf and related VF modules. + */ +class DoCreateVnfAndModulesRollback extends AbstractServiceTaskProcessor { + + String Prefix="DCVAMR_" + ExceptionUtil exceptionUtil = new ExceptionUtil() + JsonUtils jsonUtil = new JsonUtils() + + + /** + * This method gets and validates the incoming + * request. + * + * @param - execution + * + */ + public void preProcessRequest(Execution execution) { + def isDebugEnabled = execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix",Prefix) + utils.log("DEBUG", " *** STARTED DoCreateVnfAndModulesRollback PreProcessRequest Process*** ", isDebugEnabled) + + try{ + // Get Rollback Variables + + def rollbackData = execution.getVariable("RollbackData") + utils.log("DEBUG", "Incoming RollbackData is: " + rollbackData.toString(), isDebugEnabled) + String vnfId = rollbackData.get("VNF", "vnfId") + utils.log("DEBUG", "Rollback vnfId is: " + vnfId, isDebugEnabled) + execution.setVariable("DCVAMR_vnfId", vnfId) + + def numOfAddOnModulesString = rollbackData.get("VNFANDMODULES", "numOfCreatedAddOnModules") + int numOfAddOnModules = 0 + if (numOfAddOnModulesString != null) { + numOfAddOnModules = Integer.parseInt(numOfAddOnModulesString) + } + execution.setVariable("DCVAMR_numOfAddOnModules", numOfAddOnModules) + + def baseVfModuleRollbackMap = rollbackData.get("VFMODULE_BASE") + if (baseVfModuleRollbackMap == null) { + // there are no VF Modules to delete + execution.setVariable("DCVAMR_numOfModulesToDelete", 0) + } + else { + execution.setVariable("DCVAMR_numOfModulesToDelete", numOfAddOnModules + 1) + } + + }catch(BpmnError b){ + utils.log("DEBUG", "Rethrowing MSOWorkflowException", isDebugEnabled) + throw b + }catch(Exception e){ + utils.log("DEBUG", " Error Occured in DoCreateVnfAndModulesRollback PreProcessRequest method!" + e.getMessage(), isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured in DoCreateVnfAndModulesRollback PreProcessRequest") + + } + utils.log("DEBUG", "*** COMPLETED DoCreateVnfAndModulesRollback PreProcessRequest Process ***", isDebugEnabled) + } + + + + public void preProcessCreateVfModuleRollback(Execution execution){ + def isDebugLogEnabled = execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix", Prefix) + logDebug(" ======== STARTED preProcessCreateVfModuleRollback ======== ", isDebugLogEnabled) + + try { + + def rollbackData = execution.getVariable("RollbackData") + + def vfModuleRollbackData = new RollbackData() + + def numOfModulesToDelete = execution.getVariable("DCVAMR_numOfModulesToDelete") + logDebug("numOfModulesToDelete: " + numOfModulesToDelete, isDebugLogEnabled) + def moduleMap = null + + if (numOfModulesToDelete > 1) { + int addOnModuleIndex = numOfModulesToDelete - 1 + moduleMap = rollbackData.get("VFMODULE_ADDON_" + addOnModuleIndex) + logDebug("Removing ADDON VF module # " + addOnModuleIndex, isDebugLogEnabled) + } + else { + moduleMap = rollbackData.get("VFMODULE_BASE") + logDebug("Removing BASE VF module", isDebugLogEnabled) + } + moduleMap.each{ k, v -> vfModuleRollbackData.put("VFMODULE", "${k}","${v}") } + execution.setVariable("DCVAMR_RollbackData", vfModuleRollbackData) + + }catch(Exception e){ + utils.log("ERROR", "Exception Occured Processing preProcessCreateVfModuleRollback. Exception is:\n" + e, isDebugLogEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occurred during preProcessCreateVfModuleRollback Method:\n" + e.getMessage()) + } + logDebug("======== COMPLETED preProcessCreateVfModuleRollback ======== ", isDebugLogEnabled) + } + + + public void postProcessCreateVfModuleRollback(Execution execution){ + def isDebugLogEnabled = execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix", Prefix) + logDebug(" ======== STARTED postProcessCreateVfModuleRollback ======== ", isDebugLogEnabled) + + try { + def numOfModulesToDelete = execution.getVariable("DCVAMR_numOfModulesToDelete") + execution.setVariable("DCVAMR_numOfModulesToDelete", numOfModulesToDelete - 1) + }catch(Exception e){ + utils.log("ERROR", "Exception Occured Processing postProcessCreateVfModuleRollback. Exception is:\n" + e, isDebugLogEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occurred during postProcessCreateVfModuleRollback Method:\n" + e.getMessage()) + } + logDebug("======== COMPLETED postProcessCreateVfModuleRollback ======== ", isDebugLogEnabled) + } + + + +} diff --git a/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/DoDeleteNetworkInstance.groovy b/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/DoDeleteNetworkInstance.groovy index dbe31528cf..76a86ff516 100644 --- a/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/DoDeleteNetworkInstance.groovy +++ b/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/DoDeleteNetworkInstance.groovy @@ -1,35 +1,35 @@ -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - MSO - * ================================================================================ - * 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.openecomp.mso.bpmn.infrastructure.scripts; - -import org.openecomp.mso.bpmn.core.json.JsonUtils -import org.openecomp.mso.bpmn.common.scripts.AaiUtil -import org.openecomp.mso.bpmn.common.scripts.AbstractServiceTaskProcessor -import org.openecomp.mso.bpmn.common.scripts.ExceptionUtil -import org.openecomp.mso.bpmn.common.scripts.NetworkUtils -import org.openecomp.mso.bpmn.common.scripts.SDNCAdapterUtils -import org.openecomp.mso.bpmn.common.scripts.VidUtils -import org.openecomp.mso.bpmn.core.WorkflowException -import org.openecomp.mso.rest.APIResponse; -import org.openecomp.mso.rest.RESTClient -import org.openecomp.mso.rest.RESTConfig +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.bpmn.infrastructure.scripts; + +import org.openecomp.mso.bpmn.core.json.JsonUtils +import org.openecomp.mso.bpmn.common.scripts.AaiUtil +import org.openecomp.mso.bpmn.common.scripts.AbstractServiceTaskProcessor +import org.openecomp.mso.bpmn.common.scripts.ExceptionUtil +import org.openecomp.mso.bpmn.common.scripts.NetworkUtils +import org.openecomp.mso.bpmn.common.scripts.SDNCAdapterUtils +import org.openecomp.mso.bpmn.common.scripts.VidUtils +import org.openecomp.mso.bpmn.core.WorkflowException +import org.openecomp.mso.rest.APIResponse; +import org.openecomp.mso.rest.RESTClient +import org.openecomp.mso.rest.RESTConfig import java.util.UUID; @@ -179,7 +179,7 @@ public class DoDeleteNetworkInstance extends AbstractServiceTaskProcessor { // lcpCloudRegion or tenantId not sent, will be extracted from query AA&I def lcpCloudRegion = null if (utils.nodeExists(networkInputs, "aic-cloud-region")) { - lcpCloudRegion = utils.getNodeText(networkInputs, "aic-cloud-region") + lcpCloudRegion = utils.getNodeText1(networkInputs, "aic-cloud-region") if (lcpCloudRegion == 'null') { lcpCloudRegion = null } @@ -245,7 +245,7 @@ public class DoDeleteNetworkInstance extends AbstractServiceTaskProcessor { String aai_endpoint = execution.getVariable("URN_aai_endpoint") AaiUtil aaiUriUtil = new AaiUtil(this) String aai_uri = aaiUriUtil.getNetworkL3NetworkUri(execution) - String queryAAIRequest = "${aai_endpoint}${aai_uri}/" + networkId + String queryAAIRequest = "${aai_endpoint}${aai_uri}/" + networkId + "?depth=1" utils.logAudit(queryAAIRequest) execution.setVariable(Prefix + "queryAAIRequest", queryAAIRequest) utils.log("DEBUG", Prefix + "AAIRequest - " + "\n" + queryAAIRequest, isDebugEnabled) @@ -388,7 +388,7 @@ public class DoDeleteNetworkInstance extends AbstractServiceTaskProcessor { ExceptionUtil exceptionUtil = new ExceptionUtil() try { // get variables - String networkInputs = execution.getVariable(Prefix + "networkInputs") + String networkRequest = execution.getVariable(Prefix + "networkRequest") String cloudSiteId = execution.getVariable(Prefix + "cloudRegionPo") String tenantId = execution.getVariable(Prefix + "tenantId") @@ -399,11 +399,16 @@ public class DoDeleteNetworkInstance extends AbstractServiceTaskProcessor { String networkStackId = "" networkStackId = utils.getNodeText1(queryAAIResponse, "heat-stack-id") - if (networkStackId == 'null' || networkStackId == "") { + if (networkStackId == 'null' || networkStackId == "" || networkStackId == null) { networkStackId = "force_delete" } - String requestId = execution.getVariable(Prefix + "requestId") + String requestId = execution.getVariable("msoRequestId") + if (requestId != null) { + execution.setVariable("mso-request-id", requestId) + } else { + requestId = execution.getVariable("mso-request-id") + } String serviceInstanceId = execution.getVariable("serviceInstanceId") // Added new Elements @@ -411,6 +416,12 @@ public class DoDeleteNetworkInstance extends AbstractServiceTaskProcessor { 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? + String modelCustomizationUuid = "" + if (utils.nodeExists(networkRequest, "networkModelInfo")) { + String networkModelInfo = utils.getNodeXml(networkRequest, "networkModelInfo", false).replace("tag0:","").replace(":tag0","") + modelCustomizationUuid = utils.getNodeText1(networkModelInfo, "modelCustomizationUuid") + } + String deleteNetworkRequest = """ ${cloudSiteId} @@ -418,6 +429,7 @@ public class DoDeleteNetworkInstance extends AbstractServiceTaskProcessor { ${networkId} ${networkStackId} ${networkType} + ${modelCustomizationUuid} true ${requestId} @@ -508,15 +520,16 @@ public class DoDeleteNetworkInstance extends AbstractServiceTaskProcessor { String serviceInstanceId = utils.getNodeText1(deleteNetworkInput, "service-instance-id") - // get/set 'msoRequestId' and 'mso-request-id' + // get/set 'msoRequestId' and 'mso-request-id' String requestId = execution.getVariable("msoRequestId") if (requestId != null) { - execution.setVariable("mso-request-id", requestId) + execution.setVariable("mso-request-id", requestId) } else { - requestId = execution.getVariable("mso-request-id") + requestId = execution.getVariable("mso-request-id") } execution.setVariable(Prefix + "requestId", requestId) - + + utils.log("DEBUG", Prefix + "requestId " + requestId, isDebugEnabled) String queryAAIResponse = execution.getVariable(Prefix + "queryAAIResponse") SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils() @@ -642,7 +655,7 @@ public class DoDeleteNetworkInstance extends AbstractServiceTaskProcessor { execution.setVariable(Prefix + "rollbackNetworkRequest", "") } else { String rollbackNetwork = - """ + """ ${rollbackData} """ String rollbackNetworkXml = utils.formatXml(rollbackNetwork) @@ -847,8 +860,14 @@ public class DoDeleteNetworkInstance extends AbstractServiceTaskProcessor { if (execution.getVariable(Prefix + "WorkflowException") != null) { WorkflowException pwfex = execution.getVariable(Prefix + "WorkflowException") exceptionMessage = pwfex.getErrorMessage() - } + } else { + if (execution.getVariable("WorkflowException") != null) { + WorkflowException pwfex = execution.getVariable("WorkflowException") + exceptionMessage = pwfex.getErrorMessage() + } + } } + // going to the Main flow: a-la-carte or macro utils.log("DEBUG", " ***** postProcessResponse(), BAD !!!", isDebugEnabled) exceptionUtil.buildWorkflowException(execution, 7000, exceptionMessage) @@ -977,12 +996,12 @@ public class DoDeleteNetworkInstance extends AbstractServiceTaskProcessor { String serviceInstanceId = utils.getNodeText1(deleteNetworkInput, "service-instance-id") - // get/set 'msoRequestId' and 'mso-request-id' + // get/set 'msoRequestId' and 'mso-request-id' String requestId = execution.getVariable("msoRequestId") if (requestId != null) { - execution.setVariable("mso-request-id", requestId) + execution.setVariable("mso-request-id", requestId) } else { - requestId = execution.getVariable("mso-request-id") + requestId = execution.getVariable("mso-request-id") } execution.setVariable(Prefix + "requestId", requestId) diff --git a/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/DoDeleteNetworkInstanceRollback.groovy b/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/DoDeleteNetworkInstanceRollback.groovy index 5863fdcb65..58c6f68bb3 100644 --- a/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/DoDeleteNetworkInstanceRollback.groovy +++ b/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/DoDeleteNetworkInstanceRollback.groovy @@ -1,335 +1,335 @@ -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - MSO - * ================================================================================ - * 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.openecomp.mso.bpmn.infrastructure.scripts; - -import groovy.xml.XmlUtil -import groovy.json.* - -import org.openecomp.mso.bpmn.core.json.JsonUtils -import org.openecomp.mso.bpmn.common.scripts.AbstractServiceTaskProcessor -import org.openecomp.mso.bpmn.common.scripts.ExceptionUtil -import org.openecomp.mso.bpmn.common.scripts.NetworkUtils -import org.openecomp.mso.bpmn.common.scripts.SDNCAdapterUtils -import org.openecomp.mso.bpmn.common.scripts.VidUtils -import org.openecomp.mso.bpmn.core.WorkflowException -import org.openecomp.mso.rest.APIResponse; -import org.openecomp.mso.rest.RESTClient -import org.openecomp.mso.rest.RESTConfig - -import java.util.UUID; - -import org.camunda.bpm.engine.delegate.BpmnError -import org.camunda.bpm.engine.runtime.Execution -import org.apache.commons.lang3.* -import org.apache.commons.codec.binary.Base64; -import org.springframework.web.util.UriUtils - -/** - * This groovy class supports the DoCreateNetworkInstanceRollback.bpmn process. - * - */ -public class DoDeleteNetworkInstanceRollback extends AbstractServiceTaskProcessor { - String Prefix="DELNWKIR_" - ExceptionUtil exceptionUtil = new ExceptionUtil() - JsonUtils jsonUtil = new JsonUtils() - VidUtils vidUtils = new VidUtils(this) - NetworkUtils networkUtils = new NetworkUtils() - SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils() - - def className = getClass().getSimpleName() - - /** - * This method is executed during the preProcessRequest task of the DoDeleteNetworkInstanceRollback.bpmn process. - * @param execution - */ - public InitializeProcessVariables(Execution execution){ - /* Initialize all the process variables in this block */ - - execution.setVariable(Prefix + "WorkflowException", null) - - execution.setVariable(Prefix + "rollbackDeactivateSDNCRequest", null) - execution.setVariable(Prefix + "rollbackDeactivateSDNCResponse", "") - execution.setVariable(Prefix + "rollbackDeactivateSDNCReturnCode", "") - - execution.setVariable(Prefix + "rollbackSDNCRequest", "") - execution.setVariable(Prefix + "rollbackSDNCResponse", "") - execution.setVariable(Prefix + "rollbackSDNCReturnCode", "") - - execution.setVariable(Prefix + "rollbackNetworkRequest", null) - execution.setVariable(Prefix + "rollbackNetworkResponse", "") - execution.setVariable(Prefix + "rollbackNetworkReturnCode", "") - - execution.setVariable(Prefix + "Success", false) - execution.setVariable(Prefix + "fullRollback", false) - - } - - // ************************************************** - // Pre or Prepare Request Section - // ************************************************** - /** - * This method is executed during the preProcessRequest task of the DoDeleteNetworkInstanceRollback.bpmn process. - * @param execution - */ - public void preProcessRequest (Execution execution) { - def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - execution.setVariable("prefix",Prefix) - - utils.log("DEBUG", " ***** Inside preProcessRequest() of " + className + ".groovy ***** ", isDebugEnabled) - - try { - // initialize flow variables - InitializeProcessVariables(execution) - - // GET Incoming request/variables - String rollbackDeactivateSDNCRequest = null - String rollbackSDNCRequest = null - String rollbackNetworkRequest = null - - Map rollbackData = execution.getVariable("rollbackData") - if (rollbackData != null && rollbackData instanceof Map) { - - if(rollbackData.containsKey("rollbackDeactivateSDNCRequest")) { - rollbackDeactivateSDNCRequest = rollbackData["rollbackDeactivateSDNCRequest"] - } - - if(rollbackData.containsKey("rollbackSDNCRequest")) { - rollbackSDNCRequest = rollbackData["rollbackSDNCRequest"] - } - - if(rollbackData.containsKey("rollbackNetworkRequest")) { - rollbackNetworkRequest = rollbackData["rollbackNetworkRequest"] - } - } - - execution.setVariable(Prefix + "rollbackNetworkRequest", rollbackNetworkRequest) - execution.setVariable(Prefix + "rollbackSDNCRequest", rollbackSDNCRequest) - execution.setVariable(Prefix + "rollbackDeactivateSDNCRequest", rollbackDeactivateSDNCRequest) - utils.log("DEBUG", "'rollbackData': " + '\n' + execution.getVariable("rollbackData"), isDebugEnabled) - - String sdncVersion = execution.getVariable("sdncVersion") - utils.log("DEBUG", "sdncVersion? : " + sdncVersion, isDebugEnabled) - - // PO Authorization Info / headers Authorization= - String basicAuthValuePO = execution.getVariable("URN_mso_adapters_po_auth") - utils.log("DEBUG", " Obtained BasicAuth userid password for PO/SDNC adapter: " + basicAuthValuePO, isDebugEnabled) - try { - def encodedString = utils.getBasicAuth(basicAuthValuePO, execution.getVariable("URN_mso_msoKey")) - execution.setVariable("BasicAuthHeaderValuePO",encodedString) - execution.setVariable("BasicAuthHeaderValueSDNC", encodedString) - - } catch (IOException ex) { - String exceptionMessage = "Exception Encountered in DoCreateNetworkInstance, PreProcessRequest() - " - String dataErrorMessage = exceptionMessage + " Unable to encode PO/SDNC user/password string - " + ex.getMessage() - utils.log("DEBUG", dataErrorMessage , isDebugEnabled) - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) - } - - if (execution.getVariable("SavedWorkflowException1") != null) { - execution.setVariable(Prefix + "WorkflowException", execution.getVariable("SavedWorkflowException1")) - } else { - execution.setVariable(Prefix + "WorkflowException", execution.getVariable("WorkflowException")) - } - utils.log("DEBUG", "*** WorkflowException : " + execution.getVariable(Prefix + "WorkflowException"), isDebugEnabled) - if(execution.getVariable(Prefix + "WorkflowException") != null) { - // called by: DoCreateNetworkInstance, partial rollback - execution.setVariable(Prefix + "fullRollback", false) - - } else { - // called by: Macro - Full Rollback, WorkflowException = null - execution.setVariable(Prefix + "fullRollback", true) - - } - - utils.log("DEBUG", "*** fullRollback? : " + execution.getVariable(Prefix + "fullRollback"), isDebugEnabled) - - } catch (BpmnError e) { - throw e; - - } catch (Exception ex) { - sendSyncError(execution) - // caught exception - String exceptionMessage = "Exception Encountered in PreProcessRequest() of " + className + ".groovy ***** : " + ex.getMessage() - utils.log("DEBUG", exceptionMessage, isDebugEnabled) - exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) - - } - - } - - public void validateRollbackResponses (Execution execution) { - def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - execution.setVariable("prefix",Prefix) - - utils.log("DEBUG", " ***** Inside validateRollbackResponses() of DoDeleteNetworkInstanceRollback ***** ", isDebugEnabled) - - try { - - // validate SDNC activate response - String rollbackDeactivateSDNCMessages = "" - String rollbackDeactivateSDNCReturnCode = "200" - if (execution.getVariable(Prefix + "rollbackDeactivateSDNCRequest") != null) { - rollbackDeactivateSDNCReturnCode = execution.getVariable(Prefix + "rollbackDeactivateSDNCReturnCode") - String rollbackDeactivateSDNCResponse = execution.getVariable(Prefix + "rollbackDeactivateSDNCResponse") - String rollbackDeactivateSDNCReturnInnerCode = "" - rollbackDeactivateSDNCResponse = sdncAdapterUtils.decodeXML(rollbackDeactivateSDNCResponse) - rollbackDeactivateSDNCResponse = rollbackDeactivateSDNCResponse.replace("&", "&").replace('$', '').replace('', "") - if (rollbackDeactivateSDNCReturnCode == "200") { - if (utils.nodeExists(rollbackDeactivateSDNCResponse, "response-code")) { - rollbackDeactivateSDNCReturnInnerCode = utils.getNodeText1(rollbackDeactivateSDNCResponse, "response-code") - if (rollbackDeactivateSDNCReturnInnerCode == "200" || rollbackDeactivateSDNCReturnInnerCode == "" || rollbackDeactivateSDNCReturnInnerCode == "0") { - rollbackDeactivateSDNCMessages = " + SNDC deactivate rollback completed." - } else { - rollbackDeactivateSDNCMessages = " + SDNC deactivate rollback failed. " - } - } else { - rollbackDeactivateSDNCMessages = " + SNDC deactivate rollback completed." - } - } else { - rollbackDeactivateSDNCMessages = " + SDNC deactivate rollback failed. " - } - utils.log("DEBUG", " SDNC deactivate rollback Code - " + rollbackDeactivateSDNCReturnCode, isDebugEnabled) - utils.log("DEBUG", " SDNC deactivate rollback Response - " + rollbackDeactivateSDNCResponse, isDebugEnabled) - } - - // validate SDNC rollback response - String rollbackSdncErrorMessages = "" - String rollbackSDNCReturnCode = "200" - if (execution.getVariable(Prefix + "rollbackSDNCRequest") != null) { - rollbackSDNCReturnCode = execution.getVariable(Prefix + "rollbackSDNCReturnCode") - String rollbackSDNCResponse = execution.getVariable(Prefix + "rollbackSDNCResponse") - String rollbackSDNCReturnInnerCode = "" - SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils(this) - rollbackSDNCResponse = sdncAdapterUtils.decodeXML(rollbackSDNCResponse) - rollbackSDNCResponse = rollbackSDNCResponse.replace("&", "&").replace('$', '').replace('', "") - if (rollbackSDNCReturnCode == "200") { - if (utils.nodeExists(rollbackSDNCResponse, "response-code")) { - rollbackSDNCReturnInnerCode = utils.getNodeText1(rollbackSDNCResponse, "response-code") - if (rollbackSDNCReturnInnerCode == "200" || rollbackSDNCReturnInnerCode == "" || rollbackSDNCReturnInnerCode == "0") { - rollbackSdncErrorMessages = " + SNDC unassign rollback completed." - } else { - rollbackSdncErrorMessages = " + SDNC unassign rollback failed. " - } - } else { - rollbackSdncErrorMessages = " + SNDC unassign rollback completed." - } - } else { - rollbackSdncErrorMessages = " + SDNC unassign rollback failed. " - } - utils.log("DEBUG", " SDNC assign rollback Code - " + rollbackSDNCReturnCode, isDebugEnabled) - utils.log("DEBUG", " SDNC assign rollback Response - " + rollbackSDNCResponse, isDebugEnabled) - } - - // validate PO network rollback response - String rollbackNetworkErrorMessages = "" - String rollbackNetworkReturnCode = "200" - if (execution.getVariable(Prefix + "rollbackNetworkRequest") != null) { - rollbackNetworkReturnCode = execution.getVariable(Prefix + "rollbackNetworkReturnCode") - String rollbackNetworkResponse = execution.getVariable(Prefix + "rollbackNetworkResponse") - if (rollbackNetworkReturnCode != "200") { - rollbackNetworkErrorMessages = " + PO Network rollback failed. " - } else { - rollbackNetworkErrorMessages = " + PO Network rollback completed." - } - - utils.log("DEBUG", " NetworkRollback Code - " + rollbackNetworkReturnCode, isDebugEnabled) - utils.log("DEBUG", " NetworkRollback Response - " + rollbackNetworkResponse, isDebugEnabled) - } - - String statusMessage = "" - int errorCode = 7000 - utils.log("DEBUG", "*** fullRollback? : " + execution.getVariable(Prefix + "fullRollback"), isDebugEnabled) - if (execution.getVariable(Prefix + "fullRollback") == false) { - WorkflowException wfe = execution.getVariable(Prefix + "WorkflowException") // original WorkflowException - if (wfe != null) { - statusMessage = wfe.getErrorMessage() - errorCode = wfe.getErrorCode() - } else { - statusMessage = "See Previous Camunda flows for cause of Error: Undetermined Exception." - errorCode = '7000' - } - - // set if all rolledbacks are successful - if (rollbackDeactivateSDNCReturnCode == "200" && rollbackNetworkReturnCode == "200" && rollbackSDNCReturnCode == "200") { - execution.setVariable("rolledBack", true) - execution.setVariable("wasDeleted", true) - - } else { - execution.setVariable("rolledBack", false) - execution.setVariable("wasDeleted", true) - } - - statusMessage = statusMessage + rollbackDeactivateSDNCMessages + rollbackNetworkErrorMessages + rollbackSdncErrorMessages - utils.log("DEBUG", "Final DoDeleteNetworkInstanceRollback status message: " + statusMessage, isDebugEnabled) - String processKey = getProcessKey(execution); - WorkflowException exception = new WorkflowException(processKey, errorCode, statusMessage); - execution.setVariable("workflowException", exception); - - } else { - // rollback due to failures in Main flow (Macro or a-ala-carte) - Full rollback - if (rollbackDeactivateSDNCReturnCode == "200" && rollbackNetworkReturnCode == "200" && rollbackSDNCReturnCode == "200") { - execution.setVariable("rollbackSuccessful", true) - execution.setVariable("rollbackError", false) - } else { - String exceptionMessage = "Network Delete Rollback was not Successful. " - utils.log("DEBUG", exceptionMessage, isDebugEnabled) - execution.setVariable("rollbackSuccessful", false) - execution.setVariable("rollbackError", true) - exceptionUtil.buildWorkflowException(execution, 7000, exceptionMessage) - throw new BpmnError("MSOWorkflowException") - } - } - - } catch (Exception ex) { - String errorMessage = "See Previous Camunda flows for cause of Error: Undetermined Exception." - String exceptionMessage = " Bpmn error encountered in DoDeleteNetworkInstanceRollback flow. validateRollbackResponses() - " + errorMessage + ": " + ex.getMessage() - utils.log("DEBUG", exceptionMessage, isDebugEnabled) - exceptionUtil.buildWorkflowException(execution, 7000, exceptionMessage) - - } - - } - - // ******************************* - // Build Error Section - // ******************************* - - - - public void processJavaException(Execution execution){ - def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - execution.setVariable("prefix",Prefix) - - try{ - utils.log("DEBUG", "Caught a Java Exception in " + Prefix, isDebugEnabled) - utils.log("DEBUG", "Started processJavaException Method", isDebugEnabled) - utils.log("DEBUG", "Variables List: " + execution.getVariables(), isDebugEnabled) - execution.setVariable("UnexpectedError", "Caught a Java Lang Exception - " + Prefix) // Adding this line temporarily until this flows error handling gets updated - exceptionUtil.buildWorkflowException(execution, 500, "Caught a Java Lang Exception") - - }catch(Exception e){ - utils.log("DEBUG", "Caught Exception during processJavaException Method: " + e, isDebugEnabled) - execution.setVariable("UnexpectedError", "Exception in processJavaException method - " + Prefix) // Adding this line temporarily until this flows error handling gets updated - exceptionUtil.buildWorkflowException(execution, 500, "Exception in processJavaException method" + Prefix) - } - utils.log("DEBUG", "Completed processJavaException Method in " + Prefix, isDebugEnabled) - } - -} +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.bpmn.infrastructure.scripts; + +import groovy.xml.XmlUtil +import groovy.json.* + +import org.openecomp.mso.bpmn.core.json.JsonUtils +import org.openecomp.mso.bpmn.common.scripts.AbstractServiceTaskProcessor +import org.openecomp.mso.bpmn.common.scripts.ExceptionUtil +import org.openecomp.mso.bpmn.common.scripts.NetworkUtils +import org.openecomp.mso.bpmn.common.scripts.SDNCAdapterUtils +import org.openecomp.mso.bpmn.common.scripts.VidUtils +import org.openecomp.mso.bpmn.core.WorkflowException +import org.openecomp.mso.rest.APIResponse; +import org.openecomp.mso.rest.RESTClient +import org.openecomp.mso.rest.RESTConfig + +import java.util.UUID; + +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.runtime.Execution +import org.apache.commons.lang3.* +import org.apache.commons.codec.binary.Base64; +import org.springframework.web.util.UriUtils + +/** + * This groovy class supports the DoCreateNetworkInstanceRollback.bpmn process. + * + */ +public class DoDeleteNetworkInstanceRollback extends AbstractServiceTaskProcessor { + String Prefix="DELNWKIR_" + ExceptionUtil exceptionUtil = new ExceptionUtil() + JsonUtils jsonUtil = new JsonUtils() + VidUtils vidUtils = new VidUtils(this) + NetworkUtils networkUtils = new NetworkUtils() + SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils() + + def className = getClass().getSimpleName() + + /** + * This method is executed during the preProcessRequest task of the DoDeleteNetworkInstanceRollback.bpmn process. + * @param execution + */ + public InitializeProcessVariables(Execution execution){ + /* Initialize all the process variables in this block */ + + execution.setVariable(Prefix + "WorkflowException", null) + + execution.setVariable(Prefix + "rollbackDeactivateSDNCRequest", null) + execution.setVariable(Prefix + "rollbackDeactivateSDNCResponse", "") + execution.setVariable(Prefix + "rollbackDeactivateSDNCReturnCode", "") + + execution.setVariable(Prefix + "rollbackSDNCRequest", "") + execution.setVariable(Prefix + "rollbackSDNCResponse", "") + execution.setVariable(Prefix + "rollbackSDNCReturnCode", "") + + execution.setVariable(Prefix + "rollbackNetworkRequest", null) + execution.setVariable(Prefix + "rollbackNetworkResponse", "") + execution.setVariable(Prefix + "rollbackNetworkReturnCode", "") + + execution.setVariable(Prefix + "Success", false) + execution.setVariable(Prefix + "fullRollback", false) + + } + + // ************************************************** + // Pre or Prepare Request Section + // ************************************************** + /** + * This method is executed during the preProcessRequest task of the DoDeleteNetworkInstanceRollback.bpmn process. + * @param execution + */ + public void preProcessRequest (Execution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix",Prefix) + + utils.log("DEBUG", " ***** Inside preProcessRequest() of " + className + ".groovy ***** ", isDebugEnabled) + + try { + // initialize flow variables + InitializeProcessVariables(execution) + + // GET Incoming request/variables + String rollbackDeactivateSDNCRequest = null + String rollbackSDNCRequest = null + String rollbackNetworkRequest = null + + Map rollbackData = execution.getVariable("rollbackData") + if (rollbackData != null && rollbackData instanceof Map) { + + if(rollbackData.containsKey("rollbackDeactivateSDNCRequest")) { + rollbackDeactivateSDNCRequest = rollbackData["rollbackDeactivateSDNCRequest"] + } + + if(rollbackData.containsKey("rollbackSDNCRequest")) { + rollbackSDNCRequest = rollbackData["rollbackSDNCRequest"] + } + + if(rollbackData.containsKey("rollbackNetworkRequest")) { + rollbackNetworkRequest = rollbackData["rollbackNetworkRequest"] + } + } + + execution.setVariable(Prefix + "rollbackNetworkRequest", rollbackNetworkRequest) + execution.setVariable(Prefix + "rollbackSDNCRequest", rollbackSDNCRequest) + execution.setVariable(Prefix + "rollbackDeactivateSDNCRequest", rollbackDeactivateSDNCRequest) + utils.log("DEBUG", "'rollbackData': " + '\n' + execution.getVariable("rollbackData"), isDebugEnabled) + + String sdncVersion = execution.getVariable("sdncVersion") + utils.log("DEBUG", "sdncVersion? : " + sdncVersion, isDebugEnabled) + + // PO Authorization Info / headers Authorization= + String basicAuthValuePO = execution.getVariable("URN_mso_adapters_po_auth") + utils.log("DEBUG", " Obtained BasicAuth userid password for PO/SDNC adapter: " + basicAuthValuePO, isDebugEnabled) + try { + def encodedString = utils.getBasicAuth(basicAuthValuePO, execution.getVariable("URN_mso_msoKey")) + execution.setVariable("BasicAuthHeaderValuePO",encodedString) + execution.setVariable("BasicAuthHeaderValueSDNC", encodedString) + + } catch (IOException ex) { + String exceptionMessage = "Exception Encountered in DoCreateNetworkInstance, PreProcessRequest() - " + String dataErrorMessage = exceptionMessage + " Unable to encode PO/SDNC user/password string - " + ex.getMessage() + utils.log("DEBUG", dataErrorMessage , isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) + } + + if (execution.getVariable("SavedWorkflowException1") != null) { + execution.setVariable(Prefix + "WorkflowException", execution.getVariable("SavedWorkflowException1")) + } else { + execution.setVariable(Prefix + "WorkflowException", execution.getVariable("WorkflowException")) + } + utils.log("DEBUG", "*** WorkflowException : " + execution.getVariable(Prefix + "WorkflowException"), isDebugEnabled) + if(execution.getVariable(Prefix + "WorkflowException") != null) { + // called by: DoCreateNetworkInstance, partial rollback + execution.setVariable(Prefix + "fullRollback", false) + + } else { + // called by: Macro - Full Rollback, WorkflowException = null + execution.setVariable(Prefix + "fullRollback", true) + + } + + utils.log("DEBUG", "*** fullRollback? : " + execution.getVariable(Prefix + "fullRollback"), isDebugEnabled) + + } catch (BpmnError e) { + throw e; + + } catch (Exception ex) { + sendSyncError(execution) + // caught exception + String exceptionMessage = "Exception Encountered in PreProcessRequest() of " + className + ".groovy ***** : " + ex.getMessage() + utils.log("DEBUG", exceptionMessage, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + + } + + } + + public void validateRollbackResponses (Execution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix",Prefix) + + utils.log("DEBUG", " ***** Inside validateRollbackResponses() of DoDeleteNetworkInstanceRollback ***** ", isDebugEnabled) + + try { + + // validate SDNC activate response + String rollbackDeactivateSDNCMessages = "" + String rollbackDeactivateSDNCReturnCode = "200" + if (execution.getVariable(Prefix + "rollbackDeactivateSDNCRequest") != null) { + rollbackDeactivateSDNCReturnCode = execution.getVariable(Prefix + "rollbackDeactivateSDNCReturnCode") + String rollbackDeactivateSDNCResponse = execution.getVariable(Prefix + "rollbackDeactivateSDNCResponse") + String rollbackDeactivateSDNCReturnInnerCode = "" + rollbackDeactivateSDNCResponse = sdncAdapterUtils.decodeXML(rollbackDeactivateSDNCResponse) + rollbackDeactivateSDNCResponse = rollbackDeactivateSDNCResponse.replace("&", "&").replace('$', '').replace('', "") + if (rollbackDeactivateSDNCReturnCode == "200") { + if (utils.nodeExists(rollbackDeactivateSDNCResponse, "response-code")) { + rollbackDeactivateSDNCReturnInnerCode = utils.getNodeText1(rollbackDeactivateSDNCResponse, "response-code") + if (rollbackDeactivateSDNCReturnInnerCode == "200" || rollbackDeactivateSDNCReturnInnerCode == "" || rollbackDeactivateSDNCReturnInnerCode == "0") { + rollbackDeactivateSDNCMessages = " + SNDC deactivate rollback completed." + } else { + rollbackDeactivateSDNCMessages = " + SDNC deactivate rollback failed. " + } + } else { + rollbackDeactivateSDNCMessages = " + SNDC deactivate rollback completed." + } + } else { + rollbackDeactivateSDNCMessages = " + SDNC deactivate rollback failed. " + } + utils.log("DEBUG", " SDNC deactivate rollback Code - " + rollbackDeactivateSDNCReturnCode, isDebugEnabled) + utils.log("DEBUG", " SDNC deactivate rollback Response - " + rollbackDeactivateSDNCResponse, isDebugEnabled) + } + + // validate SDNC rollback response + String rollbackSdncErrorMessages = "" + String rollbackSDNCReturnCode = "200" + if (execution.getVariable(Prefix + "rollbackSDNCRequest") != null) { + rollbackSDNCReturnCode = execution.getVariable(Prefix + "rollbackSDNCReturnCode") + String rollbackSDNCResponse = execution.getVariable(Prefix + "rollbackSDNCResponse") + String rollbackSDNCReturnInnerCode = "" + SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils(this) + rollbackSDNCResponse = sdncAdapterUtils.decodeXML(rollbackSDNCResponse) + rollbackSDNCResponse = rollbackSDNCResponse.replace("&", "&").replace('$', '').replace('', "") + if (rollbackSDNCReturnCode == "200") { + if (utils.nodeExists(rollbackSDNCResponse, "response-code")) { + rollbackSDNCReturnInnerCode = utils.getNodeText1(rollbackSDNCResponse, "response-code") + if (rollbackSDNCReturnInnerCode == "200" || rollbackSDNCReturnInnerCode == "" || rollbackSDNCReturnInnerCode == "0") { + rollbackSdncErrorMessages = " + SNDC unassign rollback completed." + } else { + rollbackSdncErrorMessages = " + SDNC unassign rollback failed. " + } + } else { + rollbackSdncErrorMessages = " + SNDC unassign rollback completed." + } + } else { + rollbackSdncErrorMessages = " + SDNC unassign rollback failed. " + } + utils.log("DEBUG", " SDNC assign rollback Code - " + rollbackSDNCReturnCode, isDebugEnabled) + utils.log("DEBUG", " SDNC assign rollback Response - " + rollbackSDNCResponse, isDebugEnabled) + } + + // validate PO network rollback response + String rollbackNetworkErrorMessages = "" + String rollbackNetworkReturnCode = "200" + if (execution.getVariable(Prefix + "rollbackNetworkRequest") != null) { + rollbackNetworkReturnCode = execution.getVariable(Prefix + "rollbackNetworkReturnCode") + String rollbackNetworkResponse = execution.getVariable(Prefix + "rollbackNetworkResponse") + if (rollbackNetworkReturnCode != "200") { + rollbackNetworkErrorMessages = " + PO Network rollback failed. " + } else { + rollbackNetworkErrorMessages = " + PO Network rollback completed." + } + + utils.log("DEBUG", " NetworkRollback Code - " + rollbackNetworkReturnCode, isDebugEnabled) + utils.log("DEBUG", " NetworkRollback Response - " + rollbackNetworkResponse, isDebugEnabled) + } + + String statusMessage = "" + int errorCode = 7000 + utils.log("DEBUG", "*** fullRollback? : " + execution.getVariable(Prefix + "fullRollback"), isDebugEnabled) + if (execution.getVariable(Prefix + "fullRollback") == false) { + WorkflowException wfe = execution.getVariable(Prefix + "WorkflowException") // original WorkflowException + if (wfe != null) { + statusMessage = wfe.getErrorMessage() + errorCode = wfe.getErrorCode() + } else { + statusMessage = "See Previous Camunda flows for cause of Error: Undetermined Exception." + errorCode = '7000' + } + + // set if all rolledbacks are successful + if (rollbackDeactivateSDNCReturnCode == "200" && rollbackNetworkReturnCode == "200" && rollbackSDNCReturnCode == "200") { + execution.setVariable("rolledBack", true) + execution.setVariable("wasDeleted", true) + + } else { + execution.setVariable("rolledBack", false) + execution.setVariable("wasDeleted", true) + } + + statusMessage = statusMessage + rollbackDeactivateSDNCMessages + rollbackNetworkErrorMessages + rollbackSdncErrorMessages + utils.log("DEBUG", "Final DoDeleteNetworkInstanceRollback status message: " + statusMessage, isDebugEnabled) + String processKey = getProcessKey(execution); + WorkflowException exception = new WorkflowException(processKey, errorCode, statusMessage); + execution.setVariable("workflowException", exception); + + } else { + // rollback due to failures in Main flow (Macro or a-ala-carte) - Full rollback + if (rollbackDeactivateSDNCReturnCode == "200" && rollbackNetworkReturnCode == "200" && rollbackSDNCReturnCode == "200") { + execution.setVariable("rollbackSuccessful", true) + execution.setVariable("rollbackError", false) + } else { + String exceptionMessage = "Network Delete Rollback was not Successful. " + utils.log("DEBUG", exceptionMessage, isDebugEnabled) + execution.setVariable("rollbackSuccessful", false) + execution.setVariable("rollbackError", true) + exceptionUtil.buildWorkflowException(execution, 7000, exceptionMessage) + throw new BpmnError("MSOWorkflowException") + } + } + + } catch (Exception ex) { + String errorMessage = "See Previous Camunda flows for cause of Error: Undetermined Exception." + String exceptionMessage = " Bpmn error encountered in DoDeleteNetworkInstanceRollback flow. validateRollbackResponses() - " + errorMessage + ": " + ex.getMessage() + utils.log("DEBUG", exceptionMessage, isDebugEnabled) + exceptionUtil.buildWorkflowException(execution, 7000, exceptionMessage) + + } + + } + + // ******************************* + // Build Error Section + // ******************************* + + + + public void processJavaException(Execution execution){ + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix",Prefix) + + try{ + utils.log("DEBUG", "Caught a Java Exception in " + Prefix, isDebugEnabled) + utils.log("DEBUG", "Started processJavaException Method", isDebugEnabled) + utils.log("DEBUG", "Variables List: " + execution.getVariables(), isDebugEnabled) + execution.setVariable("UnexpectedError", "Caught a Java Lang Exception - " + Prefix) // Adding this line temporarily until this flows error handling gets updated + exceptionUtil.buildWorkflowException(execution, 500, "Caught a Java Lang Exception") + + }catch(Exception e){ + utils.log("DEBUG", "Caught Exception during processJavaException Method: " + e, isDebugEnabled) + execution.setVariable("UnexpectedError", "Exception in processJavaException method - " + Prefix) // Adding this line temporarily until this flows error handling gets updated + exceptionUtil.buildWorkflowException(execution, 500, "Exception in processJavaException method" + Prefix) + } + utils.log("DEBUG", "Completed processJavaException Method in " + Prefix, isDebugEnabled) + } + +} diff --git a/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/DoDeleteServiceInstance.groovy b/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/DoDeleteServiceInstance.groovy index 83fcd33443..6daec69b9d 100644 --- a/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/DoDeleteServiceInstance.groovy +++ b/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/DoDeleteServiceInstance.groovy @@ -1,420 +1,420 @@ -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - MSO - * ================================================================================ - * 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.openecomp.mso.bpmn.infrastructure.scripts; - -import static org.apache.commons.lang3.StringUtils.*; -import groovy.xml.XmlUtil -import groovy.json.* - -import org.openecomp.mso.bpmn.core.json.JsonUtils -import org.openecomp.mso.bpmn.common.scripts.AbstractServiceTaskProcessor -import org.openecomp.mso.bpmn.common.scripts.ExceptionUtil -import org.openecomp.mso.bpmn.common.scripts.SDNCAdapterUtils -import org.openecomp.mso.bpmn.common.scripts.VidUtils -import org.openecomp.mso.bpmn.core.WorkflowException -import org.openecomp.mso.rest.APIResponse; -import org.openecomp.mso.rest.RESTClient -import org.openecomp.mso.rest.RESTConfig - -import java.util.UUID; -import javax.xml.parsers.DocumentBuilder -import javax.xml.parsers.DocumentBuilderFactory - -import org.camunda.bpm.engine.delegate.BpmnError -import org.camunda.bpm.engine.runtime.Execution -import org.json.JSONObject; -import org.apache.commons.lang3.* -import org.apache.commons.codec.binary.Base64; -import org.springframework.web.util.UriUtils; -import org.w3c.dom.Document -import org.w3c.dom.Element -import org.w3c.dom.Node -import org.w3c.dom.NodeList -import org.xml.sax.InputSource - -/** - * This groovy class supports the DoDeleteServiceInstance.bpmn process. - * - * Inputs: - * @param - msoRequestId - * @param - globalSubscriberId - O - * @param - subscriptionServiceType - O - * @param - serviceInstanceId - * @param - serviceInstanceName - O - * @param - serviceModelInfo - O - * @param - productFamilyId - * @param - sdncVersion - * @param - failNotFound - TODO - * @param - serviceInputParams - TODO - * - * Outputs: - * @param - WorkflowException - * - * Rollback - Deferred - */ -public class DoDeleteServiceInstance extends AbstractServiceTaskProcessor { - - String Prefix="DDELSI_" - ExceptionUtil exceptionUtil = new ExceptionUtil() - JsonUtils jsonUtil = new JsonUtils() - VidUtils vidUtils = new VidUtils() - - public void preProcessRequest (Execution execution) { - def isDebugEnabled = execution.getVariable("isDebugLogEnabled") - utils.log("DEBUG"," ***** preProcessRequest *****", isDebugEnabled) - String msg = "" - - try { - String requestId = execution.getVariable("msoRequestId") - execution.setVariable("prefix",Prefix) - - //Inputs - //requestDetails.subscriberInfo. for AAI GET & PUT & SDNC assignToplology - String globalSubscriberId = execution.getVariable("globalSubscriberId") //globalCustomerId - if (globalSubscriberId == null) - { - execution.setVariable("globalSubscriberId", "") - } - - //requestDetails.requestParameters. for AAI PUT & SDNC assignTopology - String subscriptionServiceType = execution.getVariable("subscriptionServiceType") - if (subscriptionServiceType == null) - { - execution.setVariable("subscriptionServiceType", "") - } - - //Generated in parent for AAI PUT - String serviceInstanceId = execution.getVariable("serviceInstanceId") - if (isBlank(serviceInstanceId)){ - msg = "Input serviceInstanceId is null" - utils.log("DEBUG", msg, isDebugEnabled) - exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) - } - - String sdncCallbackUrl = execution.getVariable('URN_mso_workflow_sdncadapter_callback') - if (isBlank(sdncCallbackUrl)) { - msg = "URN_mso_workflow_sdncadapter_callback is null" - utils.log("DEBUG", msg, isDebugEnabled) - exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) - } - execution.setVariable("sdncCallbackUrl", sdncCallbackUrl) - utils.log("DEBUG","SDNC Callback URL: " + sdncCallbackUrl, isDebugEnabled) - - } catch (BpmnError e) { - throw e; - } catch (Exception ex){ - msg = "Exception in preProcessRequest " + ex.getMessage() - utils.log("DEBUG", msg, isDebugEnabled) - exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) - } - utils.log("DEBUG"," ***** Exit preProcessRequest *****", isDebugEnabled) - } - - public void preProcessSDNCDelete (Execution execution) { - def isDebugEnabled = execution.getVariable("isDebugLogEnabled") - utils.log("DEBUG"," ***** preProcessSDNCDelete *****", isDebugEnabled) - String msg = "" - - try { - /* - String uuid = execution.getVariable('testReqId') // for junits - if(uuid==null){ - uuid = execution.getVariable("msoRequestId") + "-" + System.currentTimeMillis() - } - */ - def serviceInstanceId = execution.getVariable("serviceInstanceId") - def serviceInstanceName = execution.getVariable("serviceInstanceName") - def callbackURL = execution.getVariable("sdncCallbackUrl") - def requestId = execution.getVariable("msoRequestId") - def serviceId = execution.getVariable("productFamilyId") - def subscriptionServiceType = execution.getVariable("subscriptionServiceType") - def globalSubscriberId = execution.getVariable("globalSubscriberId") //globalCustomerId - - String serviceModelInfo = execution.getVariable("serviceModelInfo") - def modelInvariantId = "" - def modelVersion = "" - def modelUUId = "" - def modelName = "" - if (!isBlank(serviceModelInfo)) - { - modelInvariantId = jsonUtil.getJsonValue(serviceModelInfo, "modelInvariantId") - modelVersion = jsonUtil.getJsonValue(serviceModelInfo, "modelVersion") - modelUUId = jsonUtil.getJsonValue(serviceModelInfo, "modelVersionId") - modelName = jsonUtil.getJsonValue(serviceModelInfo, "modelName") - - if (modelInvariantId == null) { - modelInvariantId = "" - } - if (modelVersion == null) { - modelVersion = "" - } - if (modelUUId == null) { - modelUUId = "" - } - if (modelName == null) { - modelName = "" - } - } - if (serviceInstanceName == null) { - serviceInstanceName = "" - } - if (serviceId == null) { - serviceId = "" - } - - def sdncRequestId = UUID.randomUUID().toString() - - String sdncDelete = - """ - - ${sdncRequestId} - ${serviceInstanceId} - delete - service-topology-operation - ${callbackURL} - - - - ${requestId} - MSO - - - - DeleteServiceInstance - - - ${serviceId} - ${subscriptionServiceType} - - ${modelInvariantId} - ${modelUUId} - ${modelVersion} - ${modelName} - - ${serviceInstanceId} - - ${globalSubscriberId} - - - ${serviceInstanceName} - - - """ - - utils.log("DEBUG","sdncDelete:\n" + sdncDelete, isDebugEnabled) - sdncDelete = utils.formatXml(sdncDelete) - execution.setVariable("sdncDelete", sdncDelete) - utils.logAudit("sdncDelete: " + sdncDelete) - - - } catch (BpmnError e) { - throw e; - } catch(Exception ex) { - msg = "Exception in preProcessSDNCDelete. " + ex.getMessage() - utils.log("DEBUG", msg, isDebugEnabled) - exceptionUtil.buildAndThrowWorkflowException(execution, 7000, "Exception Occured in preProcessSDNCDelete.\n" + ex.getMessage()) - } - utils.log("DEBUG"," *****Exit preProcessSDNCDelete *****", isDebugEnabled) - } - - public void postProcessSDNCDelete(Execution execution) { - - def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - utils.log("DEBUG"," ***** postProcessSDNCDelete ***** ", isDebugEnabled) - String msg = "" - - try { - WorkflowException workflowException = execution.getVariable("WorkflowException") - utils.logAudit("workflowException: " + workflowException) - - boolean successIndicator = execution.getVariable("SDNCA_SuccessIndicator") - String response = execution.getVariable("sdncAdapterResponse") - utils.logAudit("SDNCResponse: " + response) - - SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils(this) - sdncAdapterUtils.validateSDNCResponse(execution, response, workflowException, successIndicator) - - if(execution.getVariable(Prefix + 'sdncResponseSuccess') == true){ - utils.log("DEBUG","Good response from SDNC Adapter for service-instance topology assign: \n" + response, isDebugEnabled) - - }else{ - msg = "Bad Response from SDNC Adapter for service-instance delete" - utils.log("DEBUG", msg, isDebugEnabled) - exceptionUtil.buildAndThrowWorkflowException(execution, 3500, msg) - } - } catch (BpmnError e) { - throw e; - } catch(Exception ex) { - msg = "Exception in postProcessSDNCDelete. " + ex.getMessage() - utils.log("DEBUG", msg, isDebugEnabled) - exceptionUtil.buildAndThrowWorkflowException(execution, 7000, "Exception Occured in preProcessSDNCDelete.\n" + ex.getMessage()) - } - utils.log("DEBUG"," *** Exit postProcessSDNCDelete *** ", isDebugEnabled) - } - - public void postProcessAAIGET(Execution execution) { - def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - utils.log("DEBUG"," ***** postProcessAAIGET ***** ", isDebugEnabled) - String msg = "" - - try { - - String serviceInstanceId = execution.getVariable("serviceInstanceId") - boolean foundInAAI = execution.getVariable("GENGS_FoundIndicator") - - if(foundInAAI == true){ - utils.log("DEBUG","Found Service-instance in AAI", isDebugEnabled) - - //Extract GlobalSubscriberId - String siRelatedLink = execution.getVariable("GENGS_siResourceLink") - if (isBlank(siRelatedLink)) - { - msg = "Could not retrive ServiceInstance data from AAI to delete id:" + serviceInstanceId - utils.log("DEBUG", msg, isDebugEnabled) - exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) - } - else - { - utils.log("DEBUG","Found Service-instance in AAI. link: " + siRelatedLink, isDebugEnabled) - String globalSubscriberId = execution.getVariable("globalSubscriberId") - if(isBlank(globalSubscriberId)){ - int custStart = siRelatedLink.indexOf("customer/") - int custEnd = siRelatedLink.indexOf("/service-subscriptions") - globalSubscriberId = siRelatedLink.substring(custStart + 9, custEnd) - execution.setVariable("globalSubscriberId", globalSubscriberId) - } - - //Extract Service Type if not provided on request - String serviceType = execution.getVariable("subscriptionServiceType") - if(isBlank(serviceType)){ - int serviceStart = siRelatedLink.indexOf("service-subscription/") - int serviceEnd = siRelatedLink.indexOf("/service-instances/") - String serviceTypeEncoded = siRelatedLink.substring(serviceStart + 21, serviceEnd) - serviceType = UriUtils.decode(serviceTypeEncoded, "UTF-8") - execution.setVariable("subscriptionServiceType", serviceType) - } - - if (isBlank(globalSubscriberId) || isBlank(serviceType)) - { - msg = "Could not retrive global-customer-id & service-type from AAI to delete id:" + serviceInstanceId - utils.log("DEBUG", msg, isDebugEnabled) - exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) - } - } - - String siData = execution.getVariable("GENGS_service") - utils.log("DEBUG", "SI Data", isDebugEnabled) - if (isBlank(siData)) - { - msg = "Could not retrive ServiceInstance data from AAI to delete id:" + serviceInstanceId - utils.log("DEBUG", msg, isDebugEnabled) - exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) - } - else - { - utils.log("DEBUG", "SI Data" + siData, isDebugEnabled) - //Confirm there are no related service instances (vnf/network or volume) - if (utils.nodeExists(siData, "relationship-list")) { - utils.log("DEBUG", "SI Data relationship-list exists:", isDebugEnabled) - InputSource source = new InputSource(new StringReader(siData)); - DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); - DocumentBuilder docBuilder = docFactory.newDocumentBuilder() - Document serviceXml = docBuilder.parse(source) - - NodeList nodeList = serviceXml.getElementsByTagName("relationship") - for (int x = 0; x < nodeList.getLength(); x++) { - Node node = nodeList.item(x) - if (node.getNodeType() == Node.ELEMENT_NODE) { - Element eElement = (Element) node - def e = eElement.getElementsByTagName("related-to").item(0).getTextContent() - if(e.equals("generic-vnf") || e.equals("l3-network")){ - utils.log("DEBUG", "ServiceInstance still has relationship(s) to generic-vnfs or l3-networks", isDebugEnabled) - execution.setVariable("siInUse", true) - //there are relationship dependencies to this Service Instance - msg = " Stopped deleting Service Instance, it has dependencies. Service instance id: " + serviceInstanceId - utils.log("DEBUG", msg, isDebugEnabled) - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg) - }else{ - utils.log("DEBUG", "Relationship NOT related to OpenStack", isDebugEnabled) - } - } - } - } - } - }else{ - boolean succInAAI = execution.getVariable("GENGS_SuccessIndicator") - if(succInAAI != true){ - utils.log("DEBUG","Error getting Service-instance from AAI", + serviceInstanceId, isDebugEnabled) - WorkflowException workflowException = execution.getVariable("WorkflowException") - utils.logAudit("workflowException: " + workflowException) - if(workflowException != null){ - exceptionUtil.buildAndThrowWorkflowException(execution, workflowException.getErrorCode(), workflowException.getErrorMessage()) - } - else - { - msg = "Failure in postProcessAAIGET GENGS_SuccessIndicator:" + succInAAI - utils.log("DEBUG", msg, isDebugEnabled) - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg) - } - } - utils.log("DEBUG","Service-instance NOT found in AAI. Silent Success", isDebugEnabled) - } - } catch (BpmnError e) { - throw e; - } catch (Exception ex) { - msg = "Exception in DoDeleteServiceInstance.postProcessAAIGET. " + ex.getMessage() - utils.log("DEBUG", msg, isDebugEnabled) - exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) - } - utils.log("DEBUG"," *** Exit postProcessAAIGET *** ", isDebugEnabled) - } - - public void postProcessAAIDEL(Execution execution) { - def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - utils.log("DEBUG"," ***** postProcessAAIDEL ***** ", isDebugEnabled) - String msg = "" - try { - String serviceInstanceId = execution.getVariable("serviceInstanceId") - boolean succInAAI = execution.getVariable("GENDS_SuccessIndicator") - if(succInAAI != true){ - msg = "Error deleting Service-instance in AAI" + serviceInstanceId - utils.log("DEBUG", msg, isDebugEnabled) - WorkflowException workflowException = execution.getVariable("WorkflowException") - utils.logAudit("workflowException: " + workflowException) - if(workflowException != null){ - exceptionUtil.buildAndThrowWorkflowException(execution, workflowException.getErrorCode(), workflowException.getErrorMessage()) - } - else - { - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg) - } - } - } catch (BpmnError e) { - throw e; - } catch (Exception ex) { - msg = "Exception in DoDeleteServiceInstance.postProcessAAIDEL. " + ex.getMessage() - utils.log("DEBUG", msg, isDebugEnabled) - exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) - } - utils.log("DEBUG"," *** Exit postProcessAAIDEL *** ", isDebugEnabled) - } -} +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.bpmn.infrastructure.scripts; + +import static org.apache.commons.lang3.StringUtils.*; +import groovy.xml.XmlUtil +import groovy.json.* + +import org.openecomp.mso.bpmn.core.json.JsonUtils +import org.openecomp.mso.bpmn.common.scripts.AbstractServiceTaskProcessor +import org.openecomp.mso.bpmn.common.scripts.ExceptionUtil +import org.openecomp.mso.bpmn.common.scripts.SDNCAdapterUtils +import org.openecomp.mso.bpmn.common.scripts.VidUtils +import org.openecomp.mso.bpmn.core.WorkflowException +import org.openecomp.mso.rest.APIResponse; +import org.openecomp.mso.rest.RESTClient +import org.openecomp.mso.rest.RESTConfig + +import java.util.UUID; +import javax.xml.parsers.DocumentBuilder +import javax.xml.parsers.DocumentBuilderFactory + +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.runtime.Execution +import org.json.JSONObject; +import org.apache.commons.lang3.* +import org.apache.commons.codec.binary.Base64; +import org.springframework.web.util.UriUtils; +import org.w3c.dom.Document +import org.w3c.dom.Element +import org.w3c.dom.Node +import org.w3c.dom.NodeList +import org.xml.sax.InputSource + +/** + * This groovy class supports the DoDeleteServiceInstance.bpmn process. + * + * Inputs: + * @param - msoRequestId + * @param - globalSubscriberId - O + * @param - subscriptionServiceType - O + * @param - serviceInstanceId + * @param - serviceInstanceName - O + * @param - serviceModelInfo - O + * @param - productFamilyId + * @param - sdncVersion + * @param - failNotFound - TODO + * @param - serviceInputParams - TODO + * + * Outputs: + * @param - WorkflowException + * + * Rollback - Deferred + */ +public class DoDeleteServiceInstance extends AbstractServiceTaskProcessor { + + String Prefix="DDELSI_" + ExceptionUtil exceptionUtil = new ExceptionUtil() + JsonUtils jsonUtil = new JsonUtils() + VidUtils vidUtils = new VidUtils() + + public void preProcessRequest (Execution execution) { + def isDebugEnabled = execution.getVariable("isDebugLogEnabled") + utils.log("DEBUG"," ***** preProcessRequest *****", isDebugEnabled) + String msg = "" + + try { + String requestId = execution.getVariable("msoRequestId") + execution.setVariable("prefix",Prefix) + + //Inputs + //requestDetails.subscriberInfo. for AAI GET & PUT & SDNC assignToplology + String globalSubscriberId = execution.getVariable("globalSubscriberId") //globalCustomerId + if (globalSubscriberId == null) + { + execution.setVariable("globalSubscriberId", "") + } + + //requestDetails.requestParameters. for AAI PUT & SDNC assignTopology + String subscriptionServiceType = execution.getVariable("subscriptionServiceType") + if (subscriptionServiceType == null) + { + execution.setVariable("subscriptionServiceType", "") + } + + //Generated in parent for AAI PUT + String serviceInstanceId = execution.getVariable("serviceInstanceId") + if (isBlank(serviceInstanceId)){ + msg = "Input serviceInstanceId is null" + utils.log("DEBUG", msg, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } + + String sdncCallbackUrl = execution.getVariable('URN_mso_workflow_sdncadapter_callback') + if (isBlank(sdncCallbackUrl)) { + msg = "URN_mso_workflow_sdncadapter_callback is null" + utils.log("DEBUG", msg, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } + execution.setVariable("sdncCallbackUrl", sdncCallbackUrl) + utils.log("DEBUG","SDNC Callback URL: " + sdncCallbackUrl, isDebugEnabled) + + } catch (BpmnError e) { + throw e; + } catch (Exception ex){ + msg = "Exception in preProcessRequest " + ex.getMessage() + utils.log("DEBUG", msg, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + utils.log("DEBUG"," ***** Exit preProcessRequest *****", isDebugEnabled) + } + + public void preProcessSDNCDelete (Execution execution) { + def isDebugEnabled = execution.getVariable("isDebugLogEnabled") + utils.log("DEBUG"," ***** preProcessSDNCDelete *****", isDebugEnabled) + String msg = "" + + try { + /* + String uuid = execution.getVariable('testReqId') // for junits + if(uuid==null){ + uuid = execution.getVariable("msoRequestId") + "-" + System.currentTimeMillis() + } + */ + def serviceInstanceId = execution.getVariable("serviceInstanceId") + def serviceInstanceName = execution.getVariable("serviceInstanceName") + def callbackURL = execution.getVariable("sdncCallbackUrl") + def requestId = execution.getVariable("msoRequestId") + def serviceId = execution.getVariable("productFamilyId") + def subscriptionServiceType = execution.getVariable("subscriptionServiceType") + def globalSubscriberId = execution.getVariable("globalSubscriberId") //globalCustomerId + + String serviceModelInfo = execution.getVariable("serviceModelInfo") + def modelInvariantId = "" + def modelVersion = "" + def modelUUId = "" + def modelName = "" + if (!isBlank(serviceModelInfo)) + { + modelInvariantId = jsonUtil.getJsonValue(serviceModelInfo, "modelInvariantId") + modelVersion = jsonUtil.getJsonValue(serviceModelInfo, "modelVersion") + modelUUId = jsonUtil.getJsonValue(serviceModelInfo, "modelVersionId") + modelName = jsonUtil.getJsonValue(serviceModelInfo, "modelName") + + if (modelInvariantId == null) { + modelInvariantId = "" + } + if (modelVersion == null) { + modelVersion = "" + } + if (modelUUId == null) { + modelUUId = "" + } + if (modelName == null) { + modelName = "" + } + } + if (serviceInstanceName == null) { + serviceInstanceName = "" + } + if (serviceId == null) { + serviceId = "" + } + + def sdncRequestId = UUID.randomUUID().toString() + + String sdncDelete = + """ + + ${sdncRequestId} + ${serviceInstanceId} + delete + service-topology-operation + ${callbackURL} + + + + ${requestId} + MSO + + + + DeleteServiceInstance + + + ${serviceId} + ${subscriptionServiceType} + + ${modelInvariantId} + ${modelUUId} + ${modelVersion} + ${modelName} + + ${serviceInstanceId} + + ${globalSubscriberId} + + + ${serviceInstanceName} + + + """ + + utils.log("DEBUG","sdncDelete:\n" + sdncDelete, isDebugEnabled) + sdncDelete = utils.formatXml(sdncDelete) + execution.setVariable("sdncDelete", sdncDelete) + utils.logAudit("sdncDelete: " + sdncDelete) + + + } catch (BpmnError e) { + throw e; + } catch(Exception ex) { + msg = "Exception in preProcessSDNCDelete. " + ex.getMessage() + utils.log("DEBUG", msg, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, "Exception Occured in preProcessSDNCDelete.\n" + ex.getMessage()) + } + utils.log("DEBUG"," *****Exit preProcessSDNCDelete *****", isDebugEnabled) + } + + public void postProcessSDNCDelete(Execution execution) { + + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + utils.log("DEBUG"," ***** postProcessSDNCDelete ***** ", isDebugEnabled) + String msg = "" + + try { + WorkflowException workflowException = execution.getVariable("WorkflowException") + utils.logAudit("workflowException: " + workflowException) + + boolean successIndicator = execution.getVariable("SDNCA_SuccessIndicator") + String response = execution.getVariable("sdncAdapterResponse") + utils.logAudit("SDNCResponse: " + response) + + SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils(this) + sdncAdapterUtils.validateSDNCResponse(execution, response, workflowException, successIndicator) + + if(execution.getVariable(Prefix + 'sdncResponseSuccess') == true){ + utils.log("DEBUG","Good response from SDNC Adapter for service-instance topology assign: \n" + response, isDebugEnabled) + + }else{ + msg = "Bad Response from SDNC Adapter for service-instance delete" + utils.log("DEBUG", msg, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 3500, msg) + } + } catch (BpmnError e) { + throw e; + } catch(Exception ex) { + msg = "Exception in postProcessSDNCDelete. " + ex.getMessage() + utils.log("DEBUG", msg, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, "Exception Occured in preProcessSDNCDelete.\n" + ex.getMessage()) + } + utils.log("DEBUG"," *** Exit postProcessSDNCDelete *** ", isDebugEnabled) + } + + public void postProcessAAIGET(Execution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + utils.log("DEBUG"," ***** postProcessAAIGET ***** ", isDebugEnabled) + String msg = "" + + try { + + String serviceInstanceId = execution.getVariable("serviceInstanceId") + boolean foundInAAI = execution.getVariable("GENGS_FoundIndicator") + + if(foundInAAI == true){ + utils.log("DEBUG","Found Service-instance in AAI", isDebugEnabled) + + //Extract GlobalSubscriberId + String siRelatedLink = execution.getVariable("GENGS_siResourceLink") + if (isBlank(siRelatedLink)) + { + msg = "Could not retrive ServiceInstance data from AAI to delete id:" + serviceInstanceId + utils.log("DEBUG", msg, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } + else + { + utils.log("DEBUG","Found Service-instance in AAI. link: " + siRelatedLink, isDebugEnabled) + String globalSubscriberId = execution.getVariable("globalSubscriberId") + if(isBlank(globalSubscriberId)){ + int custStart = siRelatedLink.indexOf("customer/") + int custEnd = siRelatedLink.indexOf("/service-subscriptions") + globalSubscriberId = siRelatedLink.substring(custStart + 9, custEnd) + execution.setVariable("globalSubscriberId", globalSubscriberId) + } + + //Extract Service Type if not provided on request + String serviceType = execution.getVariable("subscriptionServiceType") + if(isBlank(serviceType)){ + int serviceStart = siRelatedLink.indexOf("service-subscription/") + int serviceEnd = siRelatedLink.indexOf("/service-instances/") + String serviceTypeEncoded = siRelatedLink.substring(serviceStart + 21, serviceEnd) + serviceType = UriUtils.decode(serviceTypeEncoded, "UTF-8") + execution.setVariable("subscriptionServiceType", serviceType) + } + + if (isBlank(globalSubscriberId) || isBlank(serviceType)) + { + msg = "Could not retrive global-customer-id & service-type from AAI to delete id:" + serviceInstanceId + utils.log("DEBUG", msg, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } + } + + String siData = execution.getVariable("GENGS_service") + utils.log("DEBUG", "SI Data", isDebugEnabled) + if (isBlank(siData)) + { + msg = "Could not retrive ServiceInstance data from AAI to delete id:" + serviceInstanceId + utils.log("DEBUG", msg, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } + else + { + utils.log("DEBUG", "SI Data" + siData, isDebugEnabled) + //Confirm there are no related service instances (vnf/network or volume) + if (utils.nodeExists(siData, "relationship-list")) { + utils.log("DEBUG", "SI Data relationship-list exists:", isDebugEnabled) + InputSource source = new InputSource(new StringReader(siData)); + DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder docBuilder = docFactory.newDocumentBuilder() + Document serviceXml = docBuilder.parse(source) + + NodeList nodeList = serviceXml.getElementsByTagName("relationship") + for (int x = 0; x < nodeList.getLength(); x++) { + Node node = nodeList.item(x) + if (node.getNodeType() == Node.ELEMENT_NODE) { + Element eElement = (Element) node + def e = eElement.getElementsByTagName("related-to").item(0).getTextContent() + if(e.equals("generic-vnf") || e.equals("l3-network")){ + utils.log("DEBUG", "ServiceInstance still has relationship(s) to generic-vnfs or l3-networks", isDebugEnabled) + execution.setVariable("siInUse", true) + //there are relationship dependencies to this Service Instance + msg = " Stopped deleting Service Instance, it has dependencies. Service instance id: " + serviceInstanceId + utils.log("DEBUG", msg, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg) + }else{ + utils.log("DEBUG", "Relationship NOT related to OpenStack", isDebugEnabled) + } + } + } + } + } + }else{ + boolean succInAAI = execution.getVariable("GENGS_SuccessIndicator") + if(succInAAI != true){ + utils.log("DEBUG","Error getting Service-instance from AAI", + serviceInstanceId, isDebugEnabled) + WorkflowException workflowException = execution.getVariable("WorkflowException") + utils.logAudit("workflowException: " + workflowException) + if(workflowException != null){ + exceptionUtil.buildAndThrowWorkflowException(execution, workflowException.getErrorCode(), workflowException.getErrorMessage()) + } + else + { + msg = "Failure in postProcessAAIGET GENGS_SuccessIndicator:" + succInAAI + utils.log("DEBUG", msg, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg) + } + } + utils.log("DEBUG","Service-instance NOT found in AAI. Silent Success", isDebugEnabled) + } + } catch (BpmnError e) { + throw e; + } catch (Exception ex) { + msg = "Exception in DoDeleteServiceInstance.postProcessAAIGET. " + ex.getMessage() + utils.log("DEBUG", msg, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + utils.log("DEBUG"," *** Exit postProcessAAIGET *** ", isDebugEnabled) + } + + public void postProcessAAIDEL(Execution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + utils.log("DEBUG"," ***** postProcessAAIDEL ***** ", isDebugEnabled) + String msg = "" + try { + String serviceInstanceId = execution.getVariable("serviceInstanceId") + boolean succInAAI = execution.getVariable("GENDS_SuccessIndicator") + if(succInAAI != true){ + msg = "Error deleting Service-instance in AAI" + serviceInstanceId + utils.log("DEBUG", msg, isDebugEnabled) + WorkflowException workflowException = execution.getVariable("WorkflowException") + utils.logAudit("workflowException: " + workflowException) + if(workflowException != null){ + exceptionUtil.buildAndThrowWorkflowException(execution, workflowException.getErrorCode(), workflowException.getErrorMessage()) + } + else + { + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg) + } + } + } catch (BpmnError e) { + throw e; + } catch (Exception ex) { + msg = "Exception in DoDeleteServiceInstance.postProcessAAIDEL. " + ex.getMessage() + utils.log("DEBUG", msg, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + utils.log("DEBUG"," *** Exit postProcessAAIDEL *** ", isDebugEnabled) + } +} diff --git a/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/DoDeleteVfModule.groovy b/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/DoDeleteVfModule.groovy index dcb70ff712..cd9c798c09 100644 --- a/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/DoDeleteVfModule.groovy +++ b/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/DoDeleteVfModule.groovy @@ -40,7 +40,7 @@ import org.xml.sax.InputSource /* Subflow for Delete VF Module. When no DoDeleteVfModuleRequest is specified on input, * functions as a building block subflow - + * Inputs for building block interface: * @param - requestId * @param - isDebugLogEnabled @@ -68,7 +68,7 @@ public class DoDeleteVfModule extends AbstractServiceTaskProcessor{ execution.setVariable("DoDVfMod_contrailNetworkPolicyFqdnList", null) execution.setVariable("DoDVfMod_oamManagementV4Address", null) execution.setVariable("DoDVfMod_oamManagementV6Address", null) - + } // parse the incoming DELETE_VF_MODULE request for the Generic Vnf and Vf Module Ids @@ -76,19 +76,19 @@ public class DoDeleteVfModule extends AbstractServiceTaskProcessor{ public void preProcessRequest(Execution execution) { def isDebugEnabled=execution.getVariable("isDebugLogEnabled") initProcessVariables(execution) - + try { def xml = execution.getVariable("DoDeleteVfModuleRequest") String vnfId = "" String vfModuleId = "" - + if (xml == null || xml.isEmpty()) { // Building Block-type request - + // Set mso-request-id to request-id for VNF Adapter interface String requestId = execution.getVariable("requestId") execution.setVariable("mso-request-id", requestId) - + String cloudConfiguration = execution.getVariable("cloudConfiguration") String vfModuleModelInfo = execution.getVariable("vfModuleModelInfo") String tenantId = jsonUtil.getJsonValue(cloudConfiguration, "tenantId") @@ -114,14 +114,14 @@ public class DoDeleteVfModule extends AbstractServiceTaskProcessor{ //vfModuleModelName def vfModuleModelName = jsonUtil.getJsonValue(vfModuleModelInfo, "modelName") execution.setVariable("vfModuleModelName", vfModuleModelName) - + } else { - + utils.logAudit("DoDeleteVfModule Request: " + xml) - + utils.log("DEBUG", "input request xml: " + xml, isDebugEnabled) - + vnfId = utils.getNodeText1(xml,"vnf-id") execution.setVariable("vnfId", vnfId) vfModuleId = utils.getNodeText1(xml,"vf-module-id") @@ -141,7 +141,7 @@ public class DoDeleteVfModule extends AbstractServiceTaskProcessor{ execution.setVariable("serviceId", serviceId) String tenantId = utils.getNodeText1(xml, "tenant-id") execution.setVariable("tenantId", tenantId) - + String serviceInstanceIdToSdnc = "" if (xml.contains("service-instance-id")) { serviceInstanceIdToSdnc = utils.getNodeText1(xml, "service-instance-id") @@ -156,7 +156,7 @@ public class DoDeleteVfModule extends AbstractServiceTaskProcessor{ String cloudSiteId = utils.getNodeText1(xml, "aic-cloud-region") execution.setVariable("cloudSiteId", cloudSiteId) } - + // formulate the request for PrepareUpdateAAIVfModule String request = """ ${vnfId} @@ -178,7 +178,7 @@ public class DoDeleteVfModule extends AbstractServiceTaskProcessor{ // (note: the action passed is expected to be 'changedelete' or 'delete') public void prepSDNCAdapterRequest(Execution execution, String action) { def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - + def srvInstId = execution.getVariable("srvInstId") def callbackUrl = execution.getVariable("URN_mso_workflow_sdncadapter_callback") String requestId = execution.getVariable("requestId") @@ -305,7 +305,7 @@ public class DoDeleteVfModule extends AbstractServiceTaskProcessor{ // and formulate the outgoing DeleteAAIVfModuleRequest request public void prepDeleteAAIVfModule(Execution execution) { def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - + def vnfId = execution.getVariable("vnfId") def vfModuleId = execution.getVariable("vfModuleId") // formulate the request for UpdateAAIVfModule @@ -346,7 +346,7 @@ public class DoDeleteVfModule extends AbstractServiceTaskProcessor{ throw new BpmnError("MSOWorkflowException") } } - + public void postProcessVNFAdapterRequest(Execution execution) { def method = getClass().getSimpleName() + '.postProcessVNFAdapterRequest(' + 'execution=' + execution.getId() + @@ -366,15 +366,15 @@ public class DoDeleteVfModule extends AbstractServiceTaskProcessor{ if(vnfResponse.contains("deleteVfModuleResponse")){ logDebug("Received a Good Response from VNF Adapter for DELETE_VF_MODULE Call.", isDebugLogEnabled) execution.setVariable("DoDVfMod_vnfVfModuleDeleteCompleted", true) - + // Parse vnfOutputs for contrail network polcy FQDNs if (vnfResponse.contains("vfModuleOutputs")) { def vfModuleOutputsXml = utils.getNodeXml(vnfResponse, "vfModuleOutputs") InputSource source = new InputSource(new StringReader(vfModuleOutputsXml)); - DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); - docFactory.setNamespaceAware(true) - DocumentBuilder docBuilder = docFactory.newDocumentBuilder() - Document outputsXml = docBuilder.parse(source) + DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); + docFactory.setNamespaceAware(true) + DocumentBuilder docBuilder = docFactory.newDocumentBuilder() + Document outputsXml = docBuilder.parse(source) NodeList entries = outputsXml.getElementsByTagNameNS("*", "entry") List contrailNetworkPolicyFqdnList = [] @@ -398,7 +398,7 @@ public class DoDeleteVfModule extends AbstractServiceTaskProcessor{ logDebug("Obtained oamManagementV6Address: " + oamManagementV6Address, isDebugLogEnabled) execution.setVariable(Prefix + "oamManagementV6Address", oamManagementV6Address) } - + } } if (!contrailNetworkPolicyFqdnList.isEmpty()) { @@ -423,7 +423,7 @@ public class DoDeleteVfModule extends AbstractServiceTaskProcessor{ } logDebug(" *** COMPLETED postProcessVnfAdapterResponse Process*** ", isDebugLogEnabled) } - + public void deleteNetworkPoliciesFromAAI(Execution execution) { def method = getClass().getSimpleName() + '.deleteNetworkPoliciesFromAAI(' + 'execution=' + execution.getId() + @@ -432,7 +432,7 @@ public class DoDeleteVfModule extends AbstractServiceTaskProcessor{ logDebug('Entered ' + method, isDebugLogEnabled) execution.setVariable("prefix", Prefix) logDebug(" ======== STARTED deleteNetworkPoliciesFromAAI ======== ", isDebugLogEnabled) - + try { // get variables List fqdnList = execution.getVariable("DoDVfMod_contrailNetworkPolicyFqdnList") @@ -441,34 +441,34 @@ public class DoDeleteVfModule extends AbstractServiceTaskProcessor{ return } int fqdnCount = fqdnList.size() - + execution.setVariable("DoDVfMod_networkPolicyFqdnCount", fqdnCount) logDebug("DoDVfMod_networkPolicyFqdnCount - " + fqdnCount, isDebugLogEnabled) - + String aai_endpoint = execution.getVariable("URN_aai_endpoint") AaiUtil aaiUriUtil = new AaiUtil(this) String aai_uri = aaiUriUtil.getNetworkPolicyUri(execution) - + if (fqdnCount > 0) { // AII loop call over contrail network policy fqdn list for (i in 0..fqdnCount-1) { - + int counting = i+1 String fqdn = fqdnList[i] - + // Query AAI for this network policy FQDN - + String queryNetworkPolicyByFqdnAAIRequest = "${aai_endpoint}${aai_uri}?network-policy-fqdn=" + UriUtils.encode(fqdn, "UTF-8") utils.logAudit("AAI request endpoint: " + queryNetworkPolicyByFqdnAAIRequest) logDebug("AAI request endpoint: " + queryNetworkPolicyByFqdnAAIRequest, isDebugLogEnabled) - + APIResponse response = aaiUriUtil.executeAAIGetCall(execution, queryNetworkPolicyByFqdnAAIRequest) int returnCode = response.getStatusCode() execution.setVariable("DCVFM_aaiQueryNetworkPolicyByFqdnReturnCode", returnCode) logDebug(" ***** AAI query network policy Response Code, NetworkPolicy #" + counting + " : " + returnCode, isDebugLogEnabled) - + String aaiResponseAsString = response.getResponseBodyAsString() - + if (isOneOf(returnCode, 200, 201)) { logDebug("The return code is: " + returnCode, isDebugLogEnabled) // This network policy FQDN exists in AAI - need to delete it now @@ -478,28 +478,28 @@ public class DoDeleteVfModule extends AbstractServiceTaskProcessor{ // Retrieve the network policy id for this FQDN def networkPolicyId = utils.getNodeText1(aaiResponseAsString, "network-policy-id") logDebug("Deleting network-policy with network-policy-id " + networkPolicyId, isDebugLogEnabled) - + // Retrieve the resource version for this network policy def resourceVersion = utils.getNodeText1(aaiResponseAsString, "resource-version") logDebug("Deleting network-policy with resource-version " + resourceVersion, isDebugLogEnabled) - - String delNetworkPolicyAAIRequest = "${aai_endpoint}${aai_uri}/" + UriUtils.encode(networkPolicyId, "UTF-8") + + + String delNetworkPolicyAAIRequest = "${aai_endpoint}${aai_uri}/" + UriUtils.encode(networkPolicyId, "UTF-8") + "?resource-version=" + UriUtils.encode(resourceVersion, "UTF-8") utils.logAudit("AAI request endpoint: " + delNetworkPolicyAAIRequest) logDebug("AAI request endpoint: " + delNetworkPolicyAAIRequest, isDebugLogEnabled) - + logDebug("invoking DELETE call to AAI", isDebugLogEnabled) utils.logAudit("Sending DELETE call to AAI with Endpoint /n" + delNetworkPolicyAAIRequest) APIResponse responseDel = aaiUriUtil.executeAAIDeleteCall(execution, delNetworkPolicyAAIRequest) int returnCodeDel = responseDel.getStatusCode() execution.setVariable("DoDVfMod_aaiDeleteNetworkPolicyReturnCode", returnCodeDel) logDebug(" ***** AAI delete network policy Response Code, NetworkPolicy #" + counting + " : " + returnCodeDel, isDebugLogEnabled) - + if (isOneOf(returnCodeDel, 200, 201, 204)) { logDebug("The return code from deleting network policy is: " + returnCodeDel, isDebugLogEnabled) // This network policy was deleted from AAI successfully logDebug(" DelAAINetworkPolicy Success REST Response, , NetworkPolicy #" + counting + " : ", isDebugLogEnabled) - + } else { // aai all errors String delErrorMessage = "Unable to delete network-policy to AAI deleteNetworkPoliciesFromAAI - " + returnCodeDel @@ -525,28 +525,28 @@ public class DoDeleteVfModule extends AbstractServiceTaskProcessor{ } } - - - + + + } // end loop - - + + } else { logDebug("No contrail network policies to query/create", isDebugLogEnabled) - + } - + } catch (BpmnError e) { throw e; - + } catch (Exception ex) { String exceptionMessage = "Bpmn error encountered in DoDeletVfModule flow. deleteNetworkPoliciesFromAAI() - " + ex.getMessage() logDebug(exceptionMessage, isDebugLogEnabled) exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) } - + } - + /** * Prepare a Request for invoking the UpdateAAIGenericVnf subflow. * @@ -558,23 +558,23 @@ public class DoDeleteVfModule extends AbstractServiceTaskProcessor{ ')' def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') logDebug('Entered ' + method, isDebugLogEnabled) - + try { def vnfId = execution.getVariable('vnfId') def oamManagementV4Address = execution.getVariable(Prefix + 'oamManagementV4Address') def oamManagementV6Address = execution.getVariable(Prefix + 'oamManagementV6Address') def ipv4OamAddressElement = '' def managementV6AddressElement = '' - + if (oamManagementV4Address != null) { ipv4OamAddressElement = '' + 'DELETE' + '' } - + if (oamManagementV6Address != null) { managementV6AddressElement = '' + 'DELETE' + '' } - - + + String updateAAIGenericVnfRequest = """ ${vnfId} @@ -586,14 +586,18 @@ public class DoDeleteVfModule extends AbstractServiceTaskProcessor{ execution.setVariable(Prefix + 'updateAAIGenericVnfRequest', updateAAIGenericVnfRequest) utils.logAudit("updateAAIGenericVnfRequest : " + updateAAIGenericVnfRequest) logDebug('Request for UpdateAAIGenericVnf:\n' + updateAAIGenericVnfRequest, isDebugLogEnabled) - - + + logDebug('Exited ' + method, isDebugLogEnabled) } catch (BpmnError e) { throw e; } catch (Exception e) { logError('Caught exception in ' + method, e) - createWorkflowException(execution, 1002, 'Error in prepUpdateAAIGenericVnf(): ' + e.getMessage()) + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in prepUpdateAAIGenericVnf(): ' + e.getMessage()) } } -} + + + + +} \ No newline at end of file diff --git a/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/DoDeleteVnf.groovy b/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/DoDeleteVnf.groovy index fe98b709a5..66a3fed6a5 100644 --- a/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/DoDeleteVnf.groovy +++ b/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/DoDeleteVnf.groovy @@ -1,136 +1,136 @@ -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - MSO - * ================================================================================ - * 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.openecomp.mso.bpmn.infrastructure.scripts - - -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.runtime.Execution -import org.openecomp.mso.bpmn.common.scripts.AbstractServiceTaskProcessor -import org.openecomp.mso.bpmn.common.scripts.ExceptionUtil -import org.openecomp.mso.bpmn.common.scripts.VidUtils -import org.openecomp.mso.bpmn.core.json.JsonUtils -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 - - -/** - * This class supports the DoDeleteVnf subFlow - * with the Deletion of a generic vnf for - * infrastructure. - * - */ -class DoDeleteVnf extends AbstractServiceTaskProcessor { - - String Prefix="DoDVNF_" - ExceptionUtil exceptionUtil = new ExceptionUtil() - JsonUtils jsonUtil = new JsonUtils() - VidUtils vidUtils = new VidUtils(this) - - /** - * This method gets and validates the incoming - * request. - * - * @param - execution - * - */ - public void preProcessRequest(Execution execution) { - def isDebugEnabled = execution.getVariable("isDebugLogEnabled") - execution.setVariable("prefix",Prefix) - utils.log("DEBUG", " *** STARTED DoDeleteVnf PreProcessRequest Process*** ", isDebugEnabled) - - execution.setVariable("DoDVNF_SuccessIndicator", false) - execution.setVariable("DoDVNF_vnfInUse", false) - - try{ - // Get Variables - - String vnfId = execution.getVariable("vnfId") - execution.setVariable("DoDVNF_vnfId", vnfId) - utils.log("DEBUG", "Incoming Vnf(Instance) Id is: " + vnfId, isDebugEnabled) - - // Setting for sub flow calls - execution.setVariable("DoDVNF_type", "generic-vnf") - }catch(BpmnError b){ - utils.log("DEBUG", "Rethrowing MSOWorkflowException", isDebugEnabled) - throw b - }catch(Exception e){ - utils.log("DEBUG", " Error Occured in DoDeleteVnf PreProcessRequest method!" + e, isDebugEnabled) - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured in DoDeleteVnf PreProcessRequest") - - } - utils.log("DEBUG", "*** COMPLETED DoDeleteVnf PreProcessRequest Process ***", isDebugEnabled) - } - - - public void processGetVnfResponse(Execution execution){ - def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - execution.setVariable("prefix",Prefix) - utils.log("DEBUG", " *** STARTED DoDeleteVnf processGetVnfResponse Process *** ", isDebugEnabled) - try { - String vnf = execution.getVariable("DoDVNF_genericVnf") - String resourceVersion = utils.getNodeText1(vnf, "resource-version") - execution.setVariable("DoDVNF_resourceVersion", resourceVersion) - - if(utils.nodeExists(vnf, "relationship")){ - InputSource source = new InputSource(new StringReader(vnf)); - DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); - DocumentBuilder docBuilder = docFactory.newDocumentBuilder() - Document vnfXml = docBuilder.parse(source) - - NodeList nodeList = vnfXml.getElementsByTagName("relationship") - for (int x = 0; x < nodeList.getLength(); x++) { - Node node = nodeList.item(x) - if (node.getNodeType() == Node.ELEMENT_NODE) { - Element eElement = (Element) node - def e = eElement.getElementsByTagName("related-to").item(0).getTextContent() - if(e.equals("volume-group") || e.equals("l3-network")){ - utils.log("DEBUG", "Generic Vnf still has relationship to OpenStack.", isDebugEnabled) - execution.setVariable("DoDVNF_vnfInUse", true) - }else{ - utils.log("DEBUG", "Relationship NOT related to OpenStack", isDebugEnabled) - } - } - } - } - - if(utils.nodeExists(vnf, "vf-module")){ - execution.setVariable("DoDVNF_vnfInUse", true) - utils.log("DEBUG", "Generic Vnf still has vf-modules.", isDebugEnabled) - } - - - } catch (Exception ex) { - utils.log("DEBUG", "Error Occured in DoDeleteVnf processGetVnfResponse Process " + ex.getMessage(), isDebugEnabled) - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured in DoDeleteVnf processGetVnfResponse Process") - - } - utils.log("DEBUG", "*** COMPLETED DoDeleteVnf processGetVnfResponse Process ***", isDebugEnabled) - } - - - -} +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.bpmn.infrastructure.scripts + + +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.runtime.Execution +import org.openecomp.mso.bpmn.common.scripts.AbstractServiceTaskProcessor +import org.openecomp.mso.bpmn.common.scripts.ExceptionUtil +import org.openecomp.mso.bpmn.common.scripts.VidUtils +import org.openecomp.mso.bpmn.core.json.JsonUtils +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 + + +/** + * This class supports the DoDeleteVnf subFlow + * with the Deletion of a generic vnf for + * infrastructure. + * + */ +class DoDeleteVnf extends AbstractServiceTaskProcessor { + + String Prefix="DoDVNF_" + ExceptionUtil exceptionUtil = new ExceptionUtil() + JsonUtils jsonUtil = new JsonUtils() + VidUtils vidUtils = new VidUtils(this) + + /** + * This method gets and validates the incoming + * request. + * + * @param - execution + * + */ + public void preProcessRequest(Execution execution) { + def isDebugEnabled = execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix",Prefix) + utils.log("DEBUG", " *** STARTED DoDeleteVnf PreProcessRequest Process*** ", isDebugEnabled) + + execution.setVariable("DoDVNF_SuccessIndicator", false) + execution.setVariable("DoDVNF_vnfInUse", false) + + try{ + // Get Variables + + String vnfId = execution.getVariable("vnfId") + execution.setVariable("DoDVNF_vnfId", vnfId) + utils.log("DEBUG", "Incoming Vnf(Instance) Id is: " + vnfId, isDebugEnabled) + + // Setting for sub flow calls + execution.setVariable("DoDVNF_type", "generic-vnf") + }catch(BpmnError b){ + utils.log("DEBUG", "Rethrowing MSOWorkflowException", isDebugEnabled) + throw b + }catch(Exception e){ + utils.log("DEBUG", " Error Occured in DoDeleteVnf PreProcessRequest method!" + e, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured in DoDeleteVnf PreProcessRequest") + + } + utils.log("DEBUG", "*** COMPLETED DoDeleteVnf PreProcessRequest Process ***", isDebugEnabled) + } + + + public void processGetVnfResponse(Execution execution){ + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix",Prefix) + utils.log("DEBUG", " *** STARTED DoDeleteVnf processGetVnfResponse Process *** ", isDebugEnabled) + try { + String vnf = execution.getVariable("DoDVNF_genericVnf") + String resourceVersion = utils.getNodeText1(vnf, "resource-version") + execution.setVariable("DoDVNF_resourceVersion", resourceVersion) + + if(utils.nodeExists(vnf, "relationship")){ + InputSource source = new InputSource(new StringReader(vnf)); + DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder docBuilder = docFactory.newDocumentBuilder() + Document vnfXml = docBuilder.parse(source) + + NodeList nodeList = vnfXml.getElementsByTagName("relationship") + for (int x = 0; x < nodeList.getLength(); x++) { + Node node = nodeList.item(x) + if (node.getNodeType() == Node.ELEMENT_NODE) { + Element eElement = (Element) node + def e = eElement.getElementsByTagName("related-to").item(0).getTextContent() + if(e.equals("volume-group") || e.equals("l3-network")){ + utils.log("DEBUG", "Generic Vnf still has relationship to OpenStack.", isDebugEnabled) + execution.setVariable("DoDVNF_vnfInUse", true) + }else{ + utils.log("DEBUG", "Relationship NOT related to OpenStack", isDebugEnabled) + } + } + } + } + + if(utils.nodeExists(vnf, "vf-module")){ + execution.setVariable("DoDVNF_vnfInUse", true) + utils.log("DEBUG", "Generic Vnf still has vf-modules.", isDebugEnabled) + } + + + } catch (Exception ex) { + utils.log("DEBUG", "Error Occured in DoDeleteVnf processGetVnfResponse Process " + ex.getMessage(), isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured in DoDeleteVnf processGetVnfResponse Process") + + } + utils.log("DEBUG", "*** COMPLETED DoDeleteVnf processGetVnfResponse Process ***", isDebugEnabled) + } + + + +} diff --git a/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/DoDeleteVnfAndModules.groovy b/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/DoDeleteVnfAndModules.groovy new file mode 100644 index 0000000000..92456b0216 --- /dev/null +++ b/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/DoDeleteVnfAndModules.groovy @@ -0,0 +1,256 @@ +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.bpmn.infrastructure.scripts + +import java.util.UUID; + +import org.json.JSONObject; +import org.json.JSONArray; + +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.runtime.Execution; + +import static org.apache.commons.lang3.StringUtils.*; + +import org.openecomp.mso.bpmn.core.json.JsonUtils +import org.openecomp.mso.rest.APIResponse +import org.openecomp.mso.rest.RESTClient +import org.openecomp.mso.rest.RESTConfig +import org.openecomp.mso.bpmn.common.scripts.AaiUtil +import org.openecomp.mso.bpmn.common.scripts.AbstractServiceTaskProcessor +import org.openecomp.mso.bpmn.common.scripts.CatalogDbUtils +import org.openecomp.mso.bpmn.common.scripts.ExceptionUtil +import org.openecomp.mso.bpmn.common.scripts.VidUtils +import org.openecomp.mso.bpmn.core.RollbackData +import org.openecomp.mso.bpmn.core.WorkflowException + +/** + * This class supports the macro VID Flow + * with the deletion of a generic vnf and related VF modules. + */ +class DoDeleteVnfAndModules extends AbstractServiceTaskProcessor { + + String Prefix="DDVAM_" + ExceptionUtil exceptionUtil = new ExceptionUtil() + JsonUtils jsonUtil = new JsonUtils() + VidUtils vidUtils = new VidUtils(this) + + /** + * This method gets and validates the incoming + * request. + * + * @param - execution + * + */ + public void preProcessRequest(Execution execution) { + def isDebugEnabled = execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix",Prefix) + utils.log("DEBUG", " *** STARTED DoDeleteVnfAndModules PreProcessRequest Process*** ", isDebugEnabled) + + try{ + // Get Variables + + String cloudConfiguration = execution.getVariable("cloudConfiguration") + + String requestId = execution.getVariable("requestId") + execution.setVariable("mso-request-id", requestId) + 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 vnfId = execution.getVariable("vnfId") + utils.log("DEBUG", "Incoming Vnf Id is: " + vnfId, isDebugEnabled) + + String source = "VID" + execution.setVariable("source", source) + utils.log("DEBUG", "Incoming Source is: " + source, isDebugEnabled) + + execution.setVariable("DDVAM_moduleCount", 0) + execution.setVariable("DDVAM_nextModule", 0) + + + }catch(BpmnError b){ + utils.log("DEBUG", "Rethrowing MSOWorkflowException", isDebugEnabled) + throw b + }catch(Exception e){ + utils.log("DEBUG", " Error Occured in DoCreateVnfAndModules PreProcessRequest method!" + e.getMessage(), isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured in DoCreateVnf PreProcessRequest") + + } + utils.log("DEBUG", "*** COMPLETED DoCreateVnfAndModules PreProcessRequest Process ***", isDebugEnabled) + } + + + + public void preProcessAddOnModule(Execution execution){ + def isDebugLogEnabled = execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix", Prefix) + logDebug(" ======== STARTED preProcessAddOnModule ======== ", isDebugLogEnabled) + + try { + JSONArray addOnModules = (JSONArray) execution.getVariable("addOnModules") + int addOnIndex = (int) execution.getVariable("addOnModulesDeployed") + + JSONObject addOnModule = addOnModules[addOnIndex] + + def newVfModuleId = UUID.randomUUID().toString() + execution.setVariable("addOnVfModuleId", newVfModuleId) + + execution.setVariable("instancesOfThisModelDeployed", 0) + + JSONObject addOnVfModuleModelInfoObject = jsonUtil.getJsonValueForKey(addOnModule, "modelInfo") + String addOnVfModuleModelInfo = addOnVfModuleModelInfoObject.toString() + execution.setVariable("addOnVfModuleModelInfo", addOnVfModuleModelInfo) + String addOnVfModuleLabel = jsonUtil.getJsonValueForKey(addOnModule, "vfModuleLabel") + execution.setVariable("addOnVfModuleLabel", addOnVfModuleLabel) + String addOnPersonaModelId = jsonUtil.getJsonValueForKey(addOnVfModuleModelInfoObject, "modelInvariantId") + execution.setVariable("addOnPersonaModelId", addOnPersonaModelId) + String addOnInitialCount = jsonUtil.getJsonValueForKey(addOnModule, "initialCount") + execution.setVariable("initialCount", addOnInitialCount) + + + }catch(Exception e){ + utils.log("ERROR", "Exception Occured Processing preProcessAddOnModule. Exception is:\n" + e, isDebugLogEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occurred during preProcessAddOnModule Method:\n" + e.getMessage()) + } + logDebug("======== COMPLETED preProcessSDNCAssignRequest ======== ", isDebugLogEnabled) + } + + /** + * Using the received vnfId and vfModuleId, query AAI to get the corresponding VNF info. + * A 200 response is expected with the VNF info in the response body. Will find out the base module info. + * + * @param execution The flow's execution instance. + */ + public void queryAAIVfModule(Execution execution) { + def isDebugLogEnabled=execution.getVariable("isDebugLogEnabled") + def method = getClass().getSimpleName() + '.queryAAIVfModule(' + + 'execution=' + execution.getId() + + ')' + logDebug('Entered ' + method, isDebugLogEnabled) + + try { + def vnfId = execution.getVariable('DvnfId') + + AaiUtil aaiUriUtil = new AaiUtil(this) + String aai_uri = aaiUriUtil.getNetworkGenericVnfUri(execution) + logDebug('AAI URI is: ' + aai_uri, isDebugLogEnabled) + + String endPoint = execution.getVariable("URN_aai_endpoint") + "${aai_uri}/" + UriUtils.encode(vnfId, "UTF-8") + "?depth=1" + utils.logAudit("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'); + logDebug('sending GET to AAI endpoint \'' + endPoint + '\'', isDebugLogEnabled) + APIResponse response = client.httpGet() + utils.logAudit("createVfModule - invoking httpGet() to AAI") + + responseData = response.getResponseBodyAsString() + if (responseData != null) { + logDebug("Received generic VNF data: " + responseData, isDebugLogEnabled) + + } + + utils.logAudit("createVfModule - queryAAIVfModule Response: " + responseData) + utils.logAudit("createVfModule - queryAAIVfModule ResponseCode: " + response.getStatusCode()) + + execution.setVariable('DCVFM_queryAAIVfModuleResponseCode', response.getStatusCode()) + execution.setVariable('DCVFM_queryAAIVfModuleResponse', responseData) + logDebug('Response code:' + response.getStatusCode(), isDebugLogEnabled) + logDebug('Response:' + System.lineSeparator() + responseData, isDebugLogEnabled) + //Map[] vfModules = new HashMap[] + List> vfModulesList = new ArrayList>(); + if (response.getStatusCode() == 200) { + // Parse the VNF record from A&AI to find base module info + logDebug('Parsing the VNF data to find base module info', isDebugLogEnabled) + if (responseData != null) { + def vfModulesText = utils.getNodeXml(responseData, "vf-modules") + def xmlVfModules= new XmlSlurper().parseText(vfModulesText) + def vfModules = xmlVfModules.'**'.findAll {it.name() == "vf-module"} + execution.setVariable("DDVAM_moduleCount", vfModules.size()) + int vfModulesSize = 0 + for (i in 0..vfModules.size()-1) { + def vfModuleXml = groovy.xml.XmlUtil.serialize(vfModules[i]) + + Map vfModuleEntry = new HashMap() + def vfModuleId = utils.getNodeText1(vfModuleXml, "vf-module-id") + vfModuleEntry.put("vfModuleId", vfModuleName) + def vfModuleName = utils.getNodeText1(vfModuleXml, "vf-module-name") + vfModuleEntry.put("vfModuleName", vfModuleName) + vfModulesList.add(vfModuleEntry) + } + + } + } + execution.setVariable("DDVAM_vfModules", vfModules) + } catch (Exception ex) { + ex.printStackTrace() + logDebug('Exception occurred while executing AAI GET:' + ex.getMessage(),isDebugLogEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'AAI GET Failed:' + ex.getMessage()) + } + logDebug('Exited ' + method, isDebugLogEnabled) + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + logError('Caught exception in ' + method, e) + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in queryAAIVfModule(): ' + e.getMessage()) + } + } + + public void prepareNextModuleToDelete(Execution execution){ + def isDebugLogEnabled = execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix", Prefix) + logDebug(" ======== STARTED prepareNextModuleToDelete ======== ", isDebugLogEnabled) + + try { + int i = execution.getVariable("DDVAM_nextModule") + def vfModules = execution.getVariable("DDVAM_vfModules") + def vfModule = vfModules[i] + + def vfModuleId = vfModule.get("vfModuleId") + execution.setVariable("DDVAM_vfModuleId", vfModuleId) + + def vfModuleName = vfModule.get("vfModuleName") + execution.setVariable("DDVAM_vfModuleName", vfModuleName) + + + // HARDCODED FOR NOW + def vfModuleModelInfo = "" + execution.setVariable("DDVAM_vfModuleModelInfo", vfModuleModelInfo) + + }catch(Exception e){ + utils.log("ERROR", "Exception Occured Processing preProcessAddOnModule. Exception is:\n" + e, isDebugLogEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occurred during preProcessAddOnModule Method:\n" + e.getMessage()) + } + logDebug("======== COMPLETED preProcessSDNCAssignRequest ======== ", isDebugLogEnabled) + } + + + + +} diff --git a/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/DoUpdateNetworkInstance.groovy b/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/DoUpdateNetworkInstance.groovy new file mode 100644 index 0000000000..dd35334ddf --- /dev/null +++ b/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/DoUpdateNetworkInstance.groovy @@ -0,0 +1,1399 @@ +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.bpmn.infrastructure.scripts; + +import groovy.xml.XmlUtil +import groovy.json.* +import org.openecomp.mso.bpmn.common.scripts.AaiUtil +import org.openecomp.mso.bpmn.common.scripts.AbstractServiceTaskProcessor +import org.openecomp.mso.bpmn.common.scripts.ExceptionUtil +import org.openecomp.mso.bpmn.common.scripts.NetworkUtils +import org.openecomp.mso.bpmn.common.scripts.SDNCAdapterUtils +import org.openecomp.mso.bpmn.common.scripts.VidUtils +import org.openecomp.mso.bpmn.core.WorkflowException +import org.openecomp.mso.bpmn.core.json.JsonUtils +import org.openecomp.mso.rest.APIResponse + +import java.util.UUID; + +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.runtime.Execution +import org.apache.commons.lang3.* +import org.apache.commons.codec.binary.Base64; +import org.springframework.web.util.UriUtils + +/** + * This groovy class supports the DoUpdateNetworkInstance.bpmn process. + * + */ +public class DoUpdateNetworkInstance extends AbstractServiceTaskProcessor { + String Prefix="UPDNETI_" + ExceptionUtil exceptionUtil = new ExceptionUtil() + JsonUtils jsonUtil = new JsonUtils() + VidUtils vidUtils = new VidUtils(this) + NetworkUtils networkUtils = new NetworkUtils() + SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils() + + /** + * This method is executed during the preProcessRequest task of the DoUpdateNetworkInstance.bpmn process. + * @param execution + */ + public InitializeProcessVariables(Execution execution){ + /* Initialize all the process variables in this block */ + + execution.setVariable(Prefix + "messageId", "") + execution.setVariable("BasicAuthHeaderValuePO", "") + execution.setVariable("BasicAuthHeaderValueSDNC", "") + execution.setVariable(Prefix + "networkRequest", "") + execution.setVariable(Prefix + "networkInputs", "") + execution.setVariable(Prefix + "networkOutputs", "") + execution.setVariable(Prefix + "requestId", "") + execution.setVariable(Prefix + "source", "") + execution.setVariable(Prefix + "networkId", "") + + execution.setVariable(Prefix + "isPONR", false) // Point-of-no-return, means, rollback is not needed + + // AAI query Cloud Region + execution.setVariable(Prefix + "queryCloudRegionRequest","") + execution.setVariable(Prefix + "queryCloudRegionReturnCode","") + execution.setVariable(Prefix + "queryCloudRegionResponse","") + execution.setVariable(Prefix + "cloudRegionPo","") + execution.setVariable(Prefix + "cloudRegionSdnc","") + execution.setVariable(Prefix + "isCloudRegionGood", false) + + // AAI query Id + execution.setVariable(Prefix + "queryIdAAIRequest","") + execution.setVariable(Prefix + "queryIdAAIResponse", "") + execution.setVariable(Prefix + "aaiIdReturnCode", "") + + // AAI query vpn binding + execution.setVariable(Prefix + "queryVpnBindingAAIRequest","") + execution.setVariable(Prefix + "queryVpnBindingAAIResponse", "") + execution.setVariable(Prefix + "aaiQqueryVpnBindingReturnCode", "") + execution.setVariable(Prefix + "vpnBindings", null) + execution.setVariable(Prefix + "vpnCount", 0) + execution.setVariable(Prefix + "routeCollection", "") + + // AAI query network policy + execution.setVariable(Prefix + "queryNetworkPolicyAAIRequest","") + execution.setVariable(Prefix + "queryNetworkPolicyAAIResponse", "") + execution.setVariable(Prefix + "aaiQqueryNetworkPolicyReturnCode", "") + execution.setVariable(Prefix + "networkPolicyUriList", null) + execution.setVariable(Prefix + "networkPolicyCount", 0) + execution.setVariable(Prefix + "networkCollection", "") + + // AAI query route table reference + execution.setVariable(Prefix + "queryNetworkTableRefAAIRequest","") + execution.setVariable(Prefix + "queryNetworkTableRefAAIResponse", "") + execution.setVariable(Prefix + "aaiQqueryNetworkTableRefReturnCode", "") + execution.setVariable(Prefix + "networkTableRefUriList", null) + execution.setVariable(Prefix + "networkTableRefCount", 0) + execution.setVariable(Prefix + "tableRefCollection", "") + + // AAI requery Id + execution.setVariable(Prefix + "requeryIdAAIRequest","") + execution.setVariable(Prefix + "requeryIdAAIResponse", "") + execution.setVariable(Prefix + "aaiRequeryIdReturnCode", "") + + // AAI update contrail + execution.setVariable(Prefix + "updateContrailAAIUrlRequest","") + execution.setVariable(Prefix + "updateContrailAAIPayloadRequest","") + execution.setVariable(Prefix + "updateContrailAAIResponse", "") + execution.setVariable(Prefix + "aaiUpdateContrailReturnCode", "") + + execution.setVariable(Prefix + "updateNetworkRequest", "") + execution.setVariable(Prefix + "updateNetworkResponse", "") + execution.setVariable(Prefix + "rollbackNetworkRequest", "") + execution.setVariable(Prefix + "networkReturnCode", "") + execution.setVariable(Prefix + "isNetworkRollbackNeeded", false) + + execution.setVariable(Prefix + "changeAssignSDNCRequest", "") + execution.setVariable(Prefix + "changeAssignSDNCResponse", "") + execution.setVariable(Prefix + "rollbackSDNCRequest", "") + execution.setVariable(Prefix + "sdncReturnCode", "") + execution.setVariable(Prefix + "isSdncRollbackNeeded", false) + execution.setVariable(Prefix + "sdncResponseSuccess", false) + + execution.setVariable(Prefix + "isVnfBindingPresent", false) + execution.setVariable(Prefix + "Success", false) + execution.setVariable(Prefix + "serviceInstanceId", "") + + execution.setVariable(Prefix + "isException", false) + + } + + // ************************************************** + // Pre or Prepare Request Section + // ************************************************** + /** + * This method is executed during the preProcessRequest task of the DoUpdateNetworkInstance.bpmn process. + * @param execution + */ + public void preProcessRequest (Execution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix",Prefix) + + utils.log("DEBUG", " ***** Inside preProcessRequest DoUpdateNetworkInstance Request ***** ", isDebugEnabled) + + try { + // initialize flow variables + InitializeProcessVariables(execution) + + // GET Incoming request & validate 3 kinds of format. + execution.setVariable("action", "UPDATE") + String networkRequest = execution.getVariable("bpmnRequest") + if (networkRequest != null) { + if (networkRequest.contains("requestDetails")) { + // JSON format request is sent, create xml + try { + def prettyJson = JsonOutput.prettyPrint(networkRequest.toString()) + utils.log("DEBUG", " Incoming message formatted . . . : " + '\n' + prettyJson, isDebugEnabled) + networkRequest = vidUtils.createXmlNetworkRequestInfra(execution, networkRequest) + + } catch (Exception ex) { + String dataErrorMessage = " Invalid json format Request - " + ex.getMessage() + utils.log("DEBUG", dataErrorMessage, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) + } + } else { + // XML format request is sent + + } + } else { + // vIPR format request is sent, create xml from individual variables + networkRequest = vidUtils.createXmlNetworkRequestInstance(execution) + } + + networkRequest = utils.formatXml(networkRequest) + utils.logAudit(networkRequest) + execution.setVariable(Prefix + "networkRequest", networkRequest) + utils.log("DEBUG", " network-request - " + '\n' + networkRequest, isDebugEnabled) + + // validate 'disableRollback' (aka, 'suppressRollback') + boolean rollbackEnabled = networkUtils.isRollbackEnabled(execution, networkRequest) + execution.setVariable(Prefix + "rollbackEnabled", rollbackEnabled) + utils.log("DEBUG", Prefix + "rollbackEnabled - " + rollbackEnabled, isDebugEnabled) + + String networkInputs = utils.getNodeXml(networkRequest, "network-inputs", false).replace("tag0:","").replace(":tag0","") + execution.setVariable(Prefix + "networkInputs", networkInputs) + utils.log("DEBUG", Prefix + "networkInputs - " + '\n' + networkInputs, isDebugEnabled) + + // prepare messageId + String messageId = execution.getVariable(Prefix + "messageId") // for testing + if (messageId == null || messageId == "") { + messageId = UUID.randomUUID() + utils.log("DEBUG", " UPDNETI_messageId, random generated: " + messageId, isDebugEnabled) + } else { + utils.log("DEBUG", " UPDNETI_messageId, pre-assigned: " + messageId, isDebugEnabled) + } + execution.setVariable(Prefix + "messageId", messageId) + + String source = utils.getNodeText1(networkRequest, "source") + execution.setVariable(Prefix + "source", source) + utils.log("DEBUG", Prefix + "source - " + source, isDebugEnabled) + + String networkId = "" + if (utils.nodeExists(networkRequest, "network-id")) { + networkId = utils.getNodeText1(networkRequest, "network-id") + if (networkId == 'null' || networkId == "") { + sendSyncError(execution) + // missing value of networkId + String dataErrorMessage = "Variable 'network-id' value/element is missing." + utils.log("DEBUG", " Invalid Request - " + dataErrorMessage, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) + + } + } + + String lcpCloudRegion = "" + if (utils.nodeExists(networkRequest, "aic-cloud-region")) { + lcpCloudRegion = utils.getNodeText1(networkRequest, "aic-cloud-region") + if ((lcpCloudRegion == 'null') || (lcpCloudRegion == "")) { + sendSyncError(execution) + String dataErrorMessage = "requestDetails has missing 'aic-cloud-region' value/element." + utils.log("DEBUG", " Invalid Request - " + dataErrorMessage, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) + } + } + + String serviceInstanceId = "" + if (utils.nodeExists(networkRequest, "service-instance-id")) { + serviceInstanceId = utils.getNodeText1(networkRequest, "service-instance-id") + if ((serviceInstanceId == 'null') || (lcpCloudRegion == "")) { + sendSyncError(execution) + String dataErrorMessage = "Variable 'serviceInstanceId' value/element is missing." + utils.log("DEBUG", " Invalid Request - " + dataErrorMessage, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) + } + } + + // PO Authorization Info / headers Authorization= + String basicAuthValuePO = execution.getVariable("URN_mso_adapters_po_auth") + utils.log("DEBUG", " Obtained BasicAuth userid password for PO/SDNC adapter: " + basicAuthValuePO, isDebugEnabled) + try { + def encodedString = utils.getBasicAuth(basicAuthValuePO, execution.getVariable("URN_mso_msoKey")) + execution.setVariable("BasicAuthHeaderValuePO",encodedString) + execution.setVariable("BasicAuthHeaderValueSDNC", encodedString) + + } catch (IOException ex) { + String exceptionMessage = "Exception Encountered in DoUpdateNetworkInstance, PreProcessRequest() - " + String dataErrorMessage = exceptionMessage + " Unable to encode PO/SDNC user/password string - " + ex.getMessage() + utils.log("DEBUG", dataErrorMessage, , isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) + } + + // Set variables for Generic Get Sub Flow use + execution.setVariable(Prefix + "serviceInstanceId", serviceInstanceId) + utils.log("DEBUG", Prefix + "serviceInstanceId - " + serviceInstanceId, isDebugEnabled) + + execution.setVariable("GENGS_type", "service-instance") + utils.log("DEBUG", "GENGS_type - " + "service-instance", isDebugEnabled) + utils.log("DEBUG", " Url for SDNC adapter: " + execution.getVariable("URN_mso_adapters_sdnc_endpoint"), isDebugEnabled) + + String sdncVersion = execution.getVariable("sdncVersion") + utils.log("DEBUG", "sdncVersion? : " + sdncVersion, isDebugEnabled) + + // build 'networkOutputs' + networkId = utils.getNodeText1(networkRequest, "network-id") + if ((networkId == null) || (networkId == "null")) { + networkId = "" + } + String networkName = utils.getNodeText1(networkRequest, "network-name") + if ((networkName == null) || (networkName == "null")) { + networkName = "" + } + String networkOutputs = + """ + ${networkId} + ${networkName} + """ + execution.setVariable(Prefix + "networkOutputs", networkOutputs) + utils.log("DEBUG", Prefix + "networkOutputs - " + '\n' + networkOutputs, isDebugEnabled) + execution.setVariable(Prefix + "networkId", networkId) + execution.setVariable(Prefix + "networkName", networkName) + + + } catch (BpmnError e) { + throw e; + + } catch (Exception ex){ + sendSyncError(execution) + // caught exception + String exceptionMessage = "Exception Encountered in DoUpdateNetworkInstance, PreProcessRequest() - " + ex.getMessage() + utils.log("DEBUG", exceptionMessage, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + + } + } + + public void callRESTQueryAAICloudRegion (Execution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix", Prefix) + + utils.log("DEBUG", " ***** Inside callRESTQueryAAICloudRegion of DoUpdateNetworkInstance ***** " , isDebugEnabled) + + try { + String networkInputs = execution.getVariable(Prefix + "networkInputs") + String cloudRegion = utils.getNodeText1(networkInputs, "aic-cloud-region") + cloudRegion = UriUtils.encode(cloudRegion,"UTF-8") + + // Prepare AA&I url + String aai_endpoint = execution.getVariable("URN_aai_endpoint") + AaiUtil aaiUtil = new AaiUtil(this) + String aai_uri = aaiUtil.getCloudInfrastructureCloudRegionUri(execution) + String queryCloudRegionRequest = "${aai_endpoint}${aai_uri}/" + cloudRegion + utils.logAudit(queryCloudRegionRequest) + execution.setVariable(Prefix + "queryCloudRegionRequest", queryCloudRegionRequest) + utils.log("DEBUG", " UPDNETI_queryCloudRegionRequest - " + "\n" + queryCloudRegionRequest, isDebugEnabled) + + String cloudRegionPo = aaiUtil.getAAICloudReqion(execution, queryCloudRegionRequest, "PO", cloudRegion) + String cloudRegionSdnc = aaiUtil.getAAICloudReqion(execution, queryCloudRegionRequest, "SDNC", cloudRegion) + + if ((cloudRegionPo != "ERROR") && (cloudRegionSdnc != "ERROR")) { + execution.setVariable(Prefix + "cloudRegionPo", cloudRegionPo) + execution.setVariable(Prefix + "cloudRegionSdnc", cloudRegionSdnc) + execution.setVariable(Prefix + "isCloudRegionGood", true) + + } else { + String dataErrorMessage = "QueryAAICloudRegion Unsuccessful. Return Code: " + execution.getVariable(Prefix + "queryCloudRegionReturnCode") + utils.log("DEBUG", dataErrorMessage, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) + + } + + utils.log("DEBUG", " is Cloud Region Good: " + execution.getVariable(Prefix + "isCloudRegionGood"), isDebugEnabled) + + } catch (BpmnError e) { + throw e; + + } catch (Exception ex) { + // try error + String exceptionMessage = "Bpmn error encountered in DoUpdateNetworkInstance flow - callRESTQueryAAICloudRegion() - " + ex.getMessage() + utils.log("DEBUG", exceptionMessage, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + + } + + } + + public void callRESTQueryAAINetworkId(Execution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix", Prefix) + + utils.log("DEBUG", " ***** Inside callRESTQueryAAINetworkId of DoUpdateNetworkInstance ***** " , isDebugEnabled) + + try { + // get variables + String networkRequest = execution.getVariable(Prefix + "networkRequest") + String networkId = utils.getNodeText1(networkRequest, "network-id") + networkId = UriUtils.encode(networkId,"UTF-8") + execution.setVariable(Prefix + "networkId", networkId) + String messageId = execution.getVariable(Prefix + "messageId") + + // Prepare AA&I url + String aai_endpoint = execution.getVariable("URN_aai_endpoint") + AaiUtil aaiUriUtil = new AaiUtil(this) + String aai_uri = aaiUriUtil.getNetworkL3NetworkUri(execution) + String queryIdAAIRequest = "${aai_endpoint}${aai_uri}/" + networkId + "?depth=1" + utils.logAudit(queryIdAAIRequest) + execution.setVariable(Prefix + "queryIdAAIRequest", queryIdAAIRequest) + utils.log("DEBUG", Prefix + "queryIdAAIRequest - " + "\n" + queryIdAAIRequest, isDebugEnabled) + + APIResponse response = aaiUriUtil.executeAAIGetCall(execution, queryIdAAIRequest) + String returnCode = response.getStatusCode() + execution.setVariable(Prefix + "aaiIdReturnCode", returnCode) + utils.log("DEBUG", " ***** AAI Response Code : " + returnCode, isDebugEnabled) + + String aaiResponseAsString = response.getResponseBodyAsString() + + if (returnCode=='200') { + utils.logAudit(aaiResponseAsString) + execution.setVariable(Prefix + "queryIdAAIResponse", aaiResponseAsString) + utils.log("DEBUG", " QueryAAINetworkId Success REST Response - " + "\n" + aaiResponseAsString, isDebugEnabled) + + } else { + if (returnCode=='404') { + String dataErrorMessage = "Response Error from QueryAAINetworkId is 404 (Not Found)." + utils.log("DEBUG", " AAI Query Failed. " + dataErrorMessage, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) + + } else { + if (aaiResponseAsString.contains("RESTFault")) { + WorkflowException exceptionObject = exceptionUtil.MapAAIExceptionToWorkflowException(aaiResponseAsString, execution) + execution.setVariable("WorkflowException", exceptionObject) + throw new BpmnError("MSOWorkflowException") + + } else { + // aai all errors + String dataErrorMessage = "Unexpected Response from QueryAAINetworkId - " + returnCode + utils.log("DEBUG", "Unexpected Response from QueryAAINetworkId - " + dataErrorMessage, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) + + } + } + } + + } catch (BpmnError e) { + throw e; + + } catch (Exception ex) { + String exceptionMessage = "Bpmn error encountered in DoUpdateNetworkInstance flow. callRESTQueryAAINetworkId() - " + ex.getMessage() + utils.log("DEBUG", exceptionMessage, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + + } + + } + + public void callRESTReQueryAAINetworkId(Execution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix", Prefix) + + utils.log("DEBUG", " ***** Inside callRESTReQueryAAINetworkId of DoUpdateNetworkInstance ***** " , isDebugEnabled) + + try { + // get variables + String networkRequest = execution.getVariable(Prefix + "networkRequest") + String networkId = utils.getNodeText1(networkRequest, "network-id") + networkId = UriUtils.encode(networkId,"UTF-8") + String messageId = execution.getVariable(Prefix + "messageId") + + // Prepare AA&I url + String aai_endpoint = execution.getVariable("URN_aai_endpoint") + AaiUtil aaiUriUtil = new AaiUtil(this) + String aai_uri = aaiUriUtil.getNetworkL3NetworkUri(execution) + String requeryIdAAIRequest = "${aai_endpoint}${aai_uri}/" + networkId + "?depth=1" + utils.logAudit(requeryIdAAIRequest) + execution.setVariable(Prefix + "requeryIdAAIRequest", requeryIdAAIRequest) + utils.log("DEBUG", " UPDNETI_requeryIdAAIRequest - " + "\n" + requeryIdAAIRequest, isDebugEnabled) + + APIResponse response = aaiUriUtil.executeAAIGetCall(execution, requeryIdAAIRequest) + String returnCode = response.getStatusCode() + execution.setVariable(Prefix + "aaiRequeryIdReturnCode", returnCode) + utils.log("DEBUG", " ***** AAI ReQuery Response Code : " + returnCode, isDebugEnabled) + + String aaiResponseAsString = response.getResponseBodyAsString() + + if (returnCode=='200') { + utils.logAudit(aaiResponseAsString) + execution.setVariable(Prefix + "requeryIdAAIResponse", aaiResponseAsString) + utils.log("DEBUG", " ReQueryAAINetworkId Success REST Response - " + "\n" + aaiResponseAsString, isDebugEnabled) + + String netId = utils.getNodeText1(aaiResponseAsString, "network-id") + String netName = utils.getNodeText1(aaiResponseAsString, "network-name") + String networkOutputs = + """ + ${netId} + ${netName} + """ + execution.setVariable(Prefix + "networkOutputs", networkOutputs) + utils.log("DEBUG", " networkOutputs - " + '\n' + networkOutputs, isDebugEnabled) + + } else { + if (returnCode=='404') { + String dataErrorMessage = "Response Error from ReQueryAAINetworkId is 404 (Not Found)." + utils.log("DEBUG", " AAI ReQuery Failed. - " + dataErrorMessage, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) + + } else { + if (aaiResponseAsString.contains("RESTFault")) { + WorkflowException exceptionObject = exceptionUtil.MapAAIExceptionToWorkflowException(aaiResponseAsString, execution) + execution.setVariable("WorkflowException", exceptionObject) + throw new BpmnError("MSOWorkflowException") + + } else { + // aai all errors + String dataErrorMessage = "Unexpected Response from ReQueryAAINetworkId - " + returnCode + utils.log("DEBUG", dataErrorMessage, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) + + } + } + } + + } catch (BpmnError e) { + throw e; + + } catch (Exception ex) { + String exceptionMessage = "Bpmn error encountered in DoUpdateNetworkInstance flow. callRESTReQueryAAINetworkId() - " + ex.getMessage() + utils.log("DEBUG", exceptionMessage, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + + } + + } + + public void callRESTQueryAAINetworkVpnBinding(Execution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix", Prefix) + + utils.log("DEBUG", " ***** Inside callRESTQueryAAINetworkVpnBinding of DoUpdateNetworkInstance ***** " , isDebugEnabled) + + try { + + // get variables + String messageId = execution.getVariable(Prefix + "messageId") + String queryIdAAIResponse = execution.getVariable(Prefix + "requeryIdAAIResponse").replace('', "") + String relationship = networkUtils.getFirstNodeXml(queryIdAAIResponse, "relationship-list").trim().replace("tag0:","").replace(":tag0","") + utils.log("DEBUG", " relationship - " + relationship, isDebugEnabled) + + // Check if Vnf Binding is present, then build a List of vnfBinding + List vpnBindingUri = networkUtils.getVnfBindingObject(relationship) + int vpnCount = vpnBindingUri.size() + execution.setVariable(Prefix + "vpnCount", vpnCount) + utils.log("DEBUG", " UPDNETI_vpnCount - " + vpnCount, isDebugEnabled) + + String aai_endpoint = execution.getVariable("URN_aai_endpoint") + AaiUtil aaiUriUtil = new AaiUtil(this) + + if (vpnCount > 0) { + execution.setVariable(Prefix + "vpnBindings", vpnBindingUri) + utils.log("DEBUG", " vpnBindingUri List - " + vpnBindingUri, isDebugEnabled) + + String routeTargets = "" + // AII loop call using list vpnBindings + for (i in 0..vpnBindingUri.size()-1) { + + int counting = i+1 + + // prepare url using vpnBinding + String queryVpnBindingAAIRequest = "" + String aai_uri = aaiUriUtil.getNetworkVpnBindingUri(execution) + + // Note: By default, the vpnBinding url is found in 'related-link' of the response, + // so, the default in URN mappings for this is set to "" (ie, space), unless forced to use the URN mapping. + if (aai_uri == null || aai_uri == "") { + // using value of 'related-link' from response + if (vpnBindingUri[i].charAt(vpnBindingUri[i].length()-1) == '/') { + queryVpnBindingAAIRequest = "${aai_endpoint}" + vpnBindingUri[i].substring(0, vpnBindingUri[i].length()-1) + } else { + queryVpnBindingAAIRequest = "${aai_endpoint}" + vpnBindingUri[i] + } + + } else { + // using uri value in URN mapping + String vpnBindingId = vpnBindingUri[i].substring(vpnBindingUri[i].indexOf("/vpn-binding/")+13, vpnBindingUri[i].length()) + if (vpnBindingId.charAt(vpnBindingId.length()-1) == '/') { + vpnBindingId = vpnBindingId.substring(0, vpnBindingId.length()-1) + } + queryVpnBindingAAIRequest = "${aai_endpoint}${aai_uri}/" + vpnBindingId + } + + utils.logAudit(queryVpnBindingAAIRequest) + execution.setVariable(Prefix + "queryVpnBindingAAIRequest", queryVpnBindingAAIRequest) + utils.log("DEBUG", " UPDNETI_queryVpnBindingAAIRequest, , vpnBinding #" + counting + " : " + "\n" + queryVpnBindingAAIRequest, isDebugEnabled) + + APIResponse response = aaiUriUtil.executeAAIGetCall(execution, queryVpnBindingAAIRequest) + String returnCode = response.getStatusCode() + execution.setVariable(Prefix + "aaiQqueryVpnBindingReturnCode", returnCode) + utils.log("DEBUG", " ***** AAI query vpn binding Response Code, vpnBinding #" + counting + " : " + returnCode, isDebugEnabled) + + String aaiResponseAsString = response.getResponseBodyAsString() + + if (returnCode=='200') { + utils.logAudit(aaiResponseAsString) + execution.setVariable(Prefix + "queryVpnBindingAAIResponse", aaiResponseAsString) + utils.log("DEBUG", " AAI Query Vpn Binding Success REST Response, , vpnBinding #" + counting + " : " + "\n" + aaiResponseAsString, isDebugEnabled) + + String routeTarget = "" + if (utils.nodeExists(aaiResponseAsString, "global-route-target")) { + routeTarget = utils.getNodeText1(aaiResponseAsString, "global-route-target") + routeTargets += "" + routeTarget + "" + '\n' + } + + } else { + if (returnCode=='404') { + String dataErrorMessage = "Response Error from AAINetworkVpnBinding is 404 (Not Found)." + utils.log("DEBUG", dataErrorMessage, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) + + } else { + if (aaiResponseAsString.contains("RESTFault")) { + WorkflowException exceptionObject = exceptionUtil.MapAAIExceptionToWorkflowException(aaiResponseAsString, execution) + execution.setVariable("WorkflowException", exceptionObject) + throw new BpmnError("MSOWorkflowException") + + } else { + // aai all errors + String dataErrorMessage = " Unexpected Response from AAINetworkVpnBinding - " + returnCode + utils.log("DEBUG", dataErrorMessage, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) + + } + } + } + + } // end loop + + execution.setVariable(Prefix + "routeCollection", routeTargets) + utils.log("DEBUG", " UPDNETI_routeCollection - " + '\n' + routeTargets, isDebugEnabled) + + } else { + // reset return code to success + execution.setVariable(Prefix + "aaiQqueryVpnBindingReturnCode", "200") + String aai_uri = aaiUriUtil.getNetworkL3NetworkUri(execution) + String schemaVersion = aaiUriUtil.getNamespaceFromUri(aai_uri) + String aaiStubResponse = + """ + + + + """ + String aaiStubResponseAsXml = utils.formatXml(aaiStubResponse) + execution.setVariable(Prefix + "queryVpnBindingAAIResponse", aaiStubResponseAsXml) + execution.setVariable(Prefix + "routeCollection", "") + utils.log("DEBUG", " No vpnBinding, using this stub as response - " + '\n' + aaiStubResponseAsXml, isDebugEnabled) + + } + + } catch (BpmnError e) { + throw e; + + } catch (Exception ex) { + String exceptionMessage = "Bpmn error encountered in DoUpdateNetworkInstance flow. callRESTQueryAAINetworkVpnBinding() - " + ex.getMessage() + utils.log("DEBUG", exceptionMessage, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + + } + + } + + public void callRESTQueryAAINetworkPolicy(Execution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix", Prefix) + + utils.log("DEBUG", " ***** Inside callRESTQueryAAINetworkPolicy of DoUpdateNetworkInstance ***** " , isDebugEnabled) + + try { + // get variables + String messageId = execution.getVariable(Prefix + "messageId") + String queryIdAAIResponse = execution.getVariable(Prefix + "requeryIdAAIResponse").replace('', "") + String relationship = networkUtils.getFirstNodeXml(queryIdAAIResponse, "relationship-list").trim().replace("tag0:","").replace(":tag0","") + utils.log("DEBUG", " relationship - " + relationship, isDebugEnabled) + + // Check if Network Policy is present, then build a List of network policy + List networkPolicyUriList = networkUtils.getNetworkPolicyObject(relationship) + int networkPolicyCount = networkPolicyUriList.size() + execution.setVariable(Prefix + "networkPolicyCount", networkPolicyCount) + utils.log("DEBUG", " UPDNETI_networkPolicyCount - " + networkPolicyCount, isDebugEnabled) + + String aai_endpoint = execution.getVariable("URN_aai_endpoint") + AaiUtil aaiUriUtil = new AaiUtil(this) + + if (networkPolicyCount > 0) { + execution.setVariable(Prefix + "networkPolicyUriList", networkPolicyUriList) + utils.log("DEBUG", " networkPolicyUri List - " + networkPolicyUriList, isDebugEnabled) + + String networkPolicies = "" + // AII loop call using list vpnBindings + for (i in 0..networkPolicyUriList.size()-1) { + + int counting = i+1 + + // prepare url using vpnBinding + String queryNetworkPolicyAAIRequest = "" + + String aai_uri = aaiUriUtil.getNetworkPolicyUri(execution) + + // Note: By default, the network policy url is found in 'related-link' of the response, + // so, the default in URN mappings for this is set to "" (ie, space), unless forced to use the URN mapping. + if (aai_uri == null || aai_uri == "") { + // using value of 'related-link' from response + if (networkPolicyUriList[i].charAt(networkPolicyUriList[i].length()-1) == '/') { + queryNetworkPolicyAAIRequest = "${aai_endpoint}" + networkPolicyUriList[i].substring(0, networkPolicyUriList[i].length()-1) + } else { + queryNetworkPolicyAAIRequest = "${aai_endpoint}" + networkPolicyUriList[i] + } + } else { + // using uri value in URN mapping + String networkPolicyId = networkPolicyUriList[i].substring(networkPolicyUriList[i].indexOf("/network-policy/")+16, networkPolicyUriList[i].length()) + println " networkPolicyId - " + networkPolicyId + if (networkPolicyId.charAt(networkPolicyId.length()-1) == '/') { + networkPolicyId = networkPolicyId.substring(0, networkPolicyId.length()-1) + } + queryNetworkPolicyAAIRequest = "${aai_endpoint}${aai_uri}/" + networkPolicyId + + } + + + utils.logAudit(queryNetworkPolicyAAIRequest) + execution.setVariable(Prefix + "queryNetworkPolicyAAIRequest", queryNetworkPolicyAAIRequest) + utils.log("DEBUG", " UPDNETI_queryNetworkPolicyAAIRequest, , NetworkPolicy #" + counting + " : " + "\n" + queryNetworkPolicyAAIRequest, isDebugEnabled) + + APIResponse response = aaiUriUtil.executeAAIGetCall(execution, queryNetworkPolicyAAIRequest) + String returnCode = response.getStatusCode() + execution.setVariable(Prefix + "aaiQqueryNetworkPolicyReturnCode", returnCode) + utils.log("DEBUG", " ***** AAI query network policy Response Code, NetworkPolicy #" + counting + " : " + returnCode, isDebugEnabled) + + String aaiResponseAsString = response.getResponseBodyAsString() + + if (returnCode=='200') { + utils.logAudit(aaiResponseAsString) + execution.setVariable(Prefix + "queryNetworkPolicyAAIResponse", aaiResponseAsString) + utils.log("DEBUG", " QueryAAINetworkPolicy Success REST Response, , NetworkPolicy #" + counting + " : " + "\n" + aaiResponseAsString, isDebugEnabled) + + String networkPolicy = "" + if (utils.nodeExists(aaiResponseAsString, "network-policy-fqdn")) { + networkPolicy = utils.getNodeText1(aaiResponseAsString, "network-policy-fqdn") + networkPolicies += "" + networkPolicy + "" + '\n' + } + + } else { + if (returnCode=='404') { + String dataErrorMessage = "Response Error from QueryAAINetworkPolicy is 404 (Not Found)." + utils.log("DEBUG", dataErrorMessage, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) + + } else { + if (aaiResponseAsString.contains("RESTFault")) { + WorkflowException exceptionObject = exceptionUtil.MapAAIExceptionToWorkflowException(aaiResponseAsString, execution) + execution.setVariable("WorkflowException", exceptionObject) + throw new BpmnError("MSOWorkflowException") + + } else { + // aai all errors + String dataErrorMessage = "Unexpected Response from QueryAAINetworkPolicy - " + returnCode + utils.log("DEBUG", dataErrorMessage, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) + + } + } + } + + } // end loop + + execution.setVariable(Prefix + "networkCollection", networkPolicies) + utils.log("DEBUG", " UPDNETI_networkCollection - " + '\n' + networkPolicies, isDebugEnabled) + + } else { + // reset return code to success + execution.setVariable(Prefix + "aaiQqueryNetworkPolicyReturnCode", "200") + String aai_uri = aaiUriUtil.getNetworkL3NetworkUri(execution) + String schemaVersion = aaiUriUtil.getNamespaceFromUri(aai_uri) + String aaiStubResponse = + """ + + + + """ + String aaiStubResponseAsXml = utils.formatXml(aaiStubResponse) + execution.setVariable(Prefix + "queryNetworkPolicyAAIResponse", aaiStubResponseAsXml) + execution.setVariable(Prefix + "networkCollection", "") + utils.log("DEBUG", " No net policies, using this stub as response - " + '\n' + aaiStubResponseAsXml, isDebugEnabled) + + } + + } catch (BpmnError e) { + throw e; + + } catch (Exception ex) { + String exceptionMessage = "Bpmn error encountered in DoUpdateNetworkInstance flow. callRESTQueryAAINetworkPolicy() - " + ex.getMessage() + utils.log("DEBUG", exceptionMessage, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + + } + + } + + public void callRESTQueryAAINetworkTableRef(Execution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix", Prefix) + + utils.log("DEBUG", " ***** Inside callRESTQueryAAINetworkTableRef of DoUpdateNetworkInstance ***** " , isDebugEnabled) + + try { + // get variables + String messageId = execution.getVariable(Prefix + "messageId") + String queryIdAAIResponse = execution.getVariable(Prefix + "requeryIdAAIResponse").replace('', "") + String relationship = networkUtils.getFirstNodeXml(queryIdAAIResponse, "relationship-list").trim().replace("tag0:","").replace(":tag0","") + utils.log("DEBUG", " relationship - " + relationship, isDebugEnabled) + + // Check if Network TableREf is present, then build a List of network policy + List networkTableRefUriList = networkUtils.getNetworkTableRefObject(relationship) + int networkTableRefCount = networkTableRefUriList.size() + execution.setVariable(Prefix + "networkTableRefCount", networkTableRefCount) + utils.log("DEBUG", " UPDNETI_networkTableRefCount - " + networkTableRefCount, isDebugEnabled) + + String aai_endpoint = execution.getVariable("URN_aai_endpoint") + AaiUtil aaiUriUtil = new AaiUtil(this) + + if (networkTableRefCount > 0) { + execution.setVariable(Prefix + "networkTableRefUriList", networkTableRefUriList) + utils.log("DEBUG", " networkTableRefUri List - " + networkTableRefUriList, isDebugEnabled) + + // AII loop call using list vpnBindings + String networkTableRefs = "" + for (i in 0..networkTableRefUriList.size()-1) { + + int counting = i+1 + + // prepare url using tableRef + String queryNetworkTableRefAAIRequest = "" + + String aai_uri = aaiUriUtil.getNetworkTableReferencesUri(execution) + + // Note: By default, the network policy url is found in 'related-link' of the response, + // so, the default in URN mappings for this is set to "" (ie, space), unless forced to use the URN mapping. + if (aai_uri == null || aai_uri == "") { + // using value of 'related-link' from response + if (networkTableRefUriList[i].charAt(networkTableRefUriList[i].length()-1) == '/') { + queryNetworkTableRefAAIRequest = "${aai_endpoint}" + networkTableRefUriList[i].substring(0, networkTableRefUriList[i].length()-1) + } else { + queryNetworkTableRefAAIRequest = "${aai_endpoint}" + networkTableRefUriList[i] + } + } else { + // using uri value in URN mapping + String networkTableRefId = networkTableRefUriList[i].substring(networkTableRefUriList[i].indexOf("/route-table-reference/")+23, networkTableRefUriList[i].length()) + + if (networkTableRefId.charAt(networkTableRefId.length()-1) == '/') { + networkTableRefId = networkTableRefId.substring(0, networkTableRefId.length()-1) + } + queryNetworkTableRefAAIRequest = "${aai_endpoint}${aai_uri}/" + networkTableRefId + + } + + + utils.logAudit(queryNetworkTableRefAAIRequest) + execution.setVariable(Prefix + "queryNetworkTableRefAAIRequest", queryNetworkTableRefAAIRequest) + utils.log("DEBUG", " UPDNETI_queryNetworkTableRefAAIRequest, , NetworkTableRef #" + counting + " : " + "\n" + queryNetworkTableRefAAIRequest, isDebugEnabled) + + APIResponse response = aaiUriUtil.executeAAIGetCall(execution, queryNetworkTableRefAAIRequest) + String returnCode = response.getStatusCode() + execution.setVariable(Prefix + "aaiQqueryNetworkTableRefReturnCode", returnCode) + utils.log("DEBUG", " ***** AAI query network Table Reference Response Code, NetworkTableRef #" + counting + " : " + returnCode, isDebugEnabled) + + String aaiResponseAsString = response.getResponseBodyAsString() + + if (returnCode=='200') { + utils.logAudit(aaiResponseAsString) + execution.setVariable(Prefix + "queryNetworkTableRefAAIResponse", aaiResponseAsString) + utils.log("DEBUG", " QueryAAINetworkTableRef Success REST Response, , NetworkTableRef #" + counting + " : " + "\n" + aaiResponseAsString, isDebugEnabled) + + String networkTableRef = "" + if (utils.nodeExists(aaiResponseAsString, "route-table-reference-fqdn")) { + networkTableRef = utils.getNodeText1(aaiResponseAsString, "route-table-reference-fqdn") + networkTableRefs += "" + networkTableRef + "" + '\n' + } + + } else { + if (returnCode=='404') { + String dataErrorMessage = "Response Error from QueryAAINetworkTableRef is 404 (Not Found)." + utils.log("DEBUG", dataErrorMessage, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) + + } else { + if (aaiResponseAsString.contains("RESTFault")) { + WorkflowException exceptionObject = exceptionUtil.MapAAIExceptionToWorkflowException(aaiResponseAsString, execution) + execution.setVariable("WorkflowException", exceptionObject) + throw new BpmnError("MSOWorkflowException") + + } else { + // aai all errors + String dataErrorMessage = "Unexpected Response from QueryAAINetworkTableRef - " + returnCode + utils.log("DEBUG", dataErrorMessage, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) + + } + } + } + + } // end loop + + execution.setVariable(Prefix + "tableRefCollection", networkTableRefs) + utils.log("DEBUG", " UPDNETI_tableRefCollection - " + '\n' + networkTableRefs, isDebugEnabled) + + } else { + // reset return code to success + execution.setVariable(Prefix + "aaiQqueryNetworkTableRefReturnCode", "200") + String aai_uri = aaiUriUtil.getNetworkL3NetworkUri(execution) + String schemaVersion = aaiUriUtil.getNamespaceFromUri(aai_uri) + String aaiStubResponse = + """ + + + + """ + String aaiStubResponseAsXml = utils.formatXml(aaiStubResponse) + execution.setVariable(Prefix + "queryNetworkTableRefAAIResponse", aaiStubResponseAsXml) + execution.setVariable(Prefix + "tableRefCollection", "") + utils.log("DEBUG", " No net table references, using this stub as response - " + '\n' + aaiStubResponseAsXml, isDebugEnabled) + + } + + } catch (BpmnError e) { + throw e; + + } catch (Exception ex) { + String exceptionMessage = "Bpmn error encountered in DoUpdateNetworkInstance flow. callRESTQueryAAINetworkTableRef() - " + ex.getMessage() + utils.log("DEBUG", exceptionMessage, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + + } + + } + + public void callRESTUpdateContrailAAINetwork(Execution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix", Prefix) + + utils.log("DEBUG", " ***** Inside callRESTUpdateContrailAAINetwork of DoUpdateNetworkInstance ***** " , isDebugEnabled) + + try { + // get variables + String networkRequest = execution.getVariable(Prefix + "networkRequest") + String networkId = utils.getNodeText1(networkRequest, "network-id") + networkId = UriUtils.encode(networkId,"UTF-8") + String requeryIdAAIResponse = execution.getVariable(Prefix + "requeryIdAAIResponse") + String updateNetworkResponse = execution.getVariable(Prefix + "updateNetworkResponse") + String messageId = execution.getVariable(Prefix + "messageId") + + // Prepare url + String aai_endpoint = execution.getVariable("URN_aai_endpoint") + AaiUtil aaiUriUtil = new AaiUtil(this) + String aai_uri = aaiUriUtil.getNetworkL3NetworkUri(execution) + String updateContrailAAIUrlRequest = "${aai_endpoint}${aai_uri}/" + networkId + "?depth=1" + + utils.logAudit(updateContrailAAIUrlRequest) + execution.setVariable(Prefix + "updateContrailAAIUrlRequest", updateContrailAAIUrlRequest) + utils.log("DEBUG", " UPDNETI_updateContrailAAIUrlRequest - " + "\n" + updateContrailAAIUrlRequest, isDebugEnabled) + + //Prepare payload (PUT) + String schemaVersion = aaiUriUtil.getNamespaceFromUri(aai_uri) + String payload = networkUtils.ContrailNetworkCreatedUpdate(requeryIdAAIResponse, updateNetworkResponse, schemaVersion) + String payloadXml = utils.formatXml(payload) + utils.logAudit(payloadXml) + execution.setVariable(Prefix + "updateContrailAAIPayloadRequest", payloadXml) + utils.log("DEBUG", " 'payload' to Update Contrail - " + "\n" + payloadXml, isDebugEnabled) + + APIResponse response = aaiUriUtil.executeAAIPutCall(execution, updateContrailAAIUrlRequest, payload) + String returnCode = response.getStatusCode() + String aaiUpdateContrailResponseAsString = response.getResponseBodyAsString() + + execution.setVariable(Prefix + "aaiUpdateContrailReturnCode", returnCode) + utils.log("DEBUG", " ***** AAI Update Contrail Response Code : " + returnCode, isDebugEnabled) + + + if (returnCode=='200') { + utils.logAudit(aaiUpdateContrailResponseAsString) + execution.setVariable(Prefix + "updateContrailAAIResponse", aaiUpdateContrailResponseAsString) + utils.log("DEBUG", " AAI Update Contrail Success REST Response - " + "\n" + aaiUpdateContrailResponseAsString, isDebugEnabled) + // Point-of-no-return is set to false, rollback not needed. + execution.setVariable(Prefix + "isPONR", true) + + } else { + if (returnCode=='404') { + String dataErrorMessage = " Response Error from UpdateContrailAAINetwork is 404 (Not Found)." + utils.log("DEBUG", dataErrorMessage, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) + + } else { + if (aaiUpdateContrailResponseAsString.contains("RESTFault")) { + WorkflowException exceptionObject = exceptionUtil.MapAAIExceptionToWorkflowException(aaiUpdateContrailResponseAsString, execution) + execution.setVariable("WorkflowException", exceptionObject) + throw new BpmnError("MSOWorkflowException") + + } else { + // aai all errors + String errorMessage = "Unexpected Response from UpdateContrailAAINetwork - " + returnCode + utils.log("DEBUG", errorMessage, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, "2500", errorMessage) + } + } + } + + } catch (BpmnError e) { + throw e; + + } catch (Exception ex) { + String exceptionMessage = "Bpmn error encountered in DoUpdateNetworkInstance flow. callRESTUpdateContrailAAINetwork() - " + ex.getMessage() + utils.log("DEBUG", exceptionMessage, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + + } + + } + + public void prepareUpdateNetworkRequest (Execution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix", Prefix) + + utils.log("DEBUG", " ***** Inside prepareUpdateNetworkRequest of DoUpdateNetworkInstance ***** ", isDebugEnabled) + + try { + + // get variables + String requestId = execution.getVariable(Prefix + "requestId") + String messageId = execution.getVariable(Prefix + "messageId") + String source = execution.getVariable(Prefix + "source") + + String requestInput = execution.getVariable(Prefix + "networkRequest") + String queryIdResponse = execution.getVariable(Prefix + "requeryIdAAIResponse") + String cloudRegionId = execution.getVariable(Prefix + "cloudRegionPo") + String backoutOnFailure = execution.getVariable(Prefix + "rollbackEnabled") + + // Prepare Network request + String routeCollection = execution.getVariable(Prefix + "routeCollection") + String policyCollection = execution.getVariable(Prefix + "networkCollection") + String tableCollection = execution.getVariable(Prefix + "tableRefCollection") + String updateNetworkRequest = networkUtils.UpdateNetworkRequestV2(execution, requestId, messageId, requestInput, queryIdResponse, routeCollection, policyCollection, tableCollection, cloudRegionId, backoutOnFailure, source ) + // Format Response + String buildUpdateNetworkRequestAsString = utils.formatXml(updateNetworkRequest) + buildUpdateNetworkRequestAsString = buildUpdateNetworkRequestAsString.replace(":w1aac13n0", "").replace("w1aac13n0:", "") + utils.logAudit(buildUpdateNetworkRequestAsString) + + execution.setVariable(Prefix + "updateNetworkRequest", buildUpdateNetworkRequestAsString) + utils.log("DEBUG", " UPDNETI_updateNetworkRequest - " + "\n" + buildUpdateNetworkRequestAsString, isDebugEnabled) + + } catch (Exception ex) { + String exceptionMessage = " Bpmn error encountered in DoUpdateNetworkInstance flow. prepareUpdateNetworkRequest() - " + ex.getMessage() + utils.log("DEBUG", exceptionMessage, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + + } + + } + + public void prepareSDNCRequest (Execution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix", Prefix) + + utils.log("DEBUG", " ***** Inside prepareSDNCRequest of DoUpdateNetworkInstance ***** ", isDebugEnabled) + + try { + // get variables + String sdncCallback = execution.getVariable("URN_mso_workflow_sdncadapter_callback") + String updateNetworkInput = execution.getVariable(Prefix + "networkRequest") + String cloudRegionId = execution.getVariable(Prefix + "cloudRegionSdnc") + + String networkId = "" + if (utils.nodeExists(updateNetworkInput, "network-id")) { + networkId = utils.getNodeText1(updateNetworkInput, "network-id") + } + if (networkId == null) {networkId = ""} + + String serviceInstanceId = utils.getNodeText1(updateNetworkInput, "service-instance-id") + + // 1. prepare assign topology via SDNC Adapter SUBFLOW call + String sndcTopologyCreateRequest = sdncAdapterUtils.sdncTopologyRequestV2(execution, updateNetworkInput, serviceInstanceId, sdncCallback, "changeassign", "NetworkActivateRequest", cloudRegionId, networkId, null, null) + + String sndcTopologyUpdateRequesAsString = utils.formatXml(sndcTopologyCreateRequest) + utils.logAudit(sndcTopologyUpdateRequesAsString) + execution.setVariable(Prefix + "changeAssignSDNCRequest", sndcTopologyUpdateRequesAsString) + utils.log("DEBUG", " UPDNETI_changeAssignSDNCRequest - " + "\n" + sndcTopologyUpdateRequesAsString, isDebugEnabled) + + + } catch (Exception ex) { + String exceptionMessage = " Bpmn error encountered in DoUpdateNetworkInstance flow. prepareSDNCRequest() - " + ex.getMessage() + utils.log("DEBUG", exceptionMessage, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + + } + + } + + + + + // ************************************************** + // Post or Validate Response Section + // ************************************************** + + public void validateUpdateNetworkResponse (Execution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix", Prefix) + + utils.log("DEBUG", " ***** Inside validateUpdateNetworkResponse of DoUpdateNetworkInstance *****", isDebugEnabled) + + try { + String returnCode = execution.getVariable(Prefix + "networkReturnCode") + String networkResponse = execution.getVariable(Prefix + "updateNetworkResponse") + if (networkResponse==null) { + networkResponse="" // reset + } + + utils.log("DEBUG", " Network Adapter update responseCode: " + returnCode, isDebugEnabled) + + String errorMessage = "" + if (returnCode == "200") { + execution.setVariable(Prefix + "isNetworkRollbackNeeded", true) + utils.logAudit(networkResponse) + execution.setVariable(Prefix + "updateNetworkResponse", networkResponse) + utils.log("DEBUG", " Network Adapter update Success Response - " + "\n" + networkResponse, isDebugEnabled) + + // prepare rollback data + String rollbackData = utils.getNodeXml(networkResponse, "rollback", false).replace("tag0:","").replace(":tag0","") + rollbackData = rollbackData.replace("rollback>", "networkRollback>") + String rollbackNetwork = + """ + ${rollbackData} + """ + String rollbackNetworkXml = utils.formatXml(rollbackNetwork) + execution.setVariable(Prefix + "rollbackNetworkRequest", rollbackNetworkXml) + utils.log("DEBUG", " Network Adapter rollback data - " + "\n" + rollbackNetworkXml, isDebugEnabled) + + } else { // network error + if (returnCode.toInteger() > 399 && returnCode.toInteger() < 600) { //4xx, 5xx + if (networkResponse.contains("updateNetworkError")) { + networkResponse = networkResponse.replace('', '') + errorMessage = utils.getNodeText1(networkResponse, "message") + errorMessage = "Received error from Network Adapter: " + errorMessage + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, errorMessage) + + } else { // CatchAll exception + if (returnCode == "500") { + errorMessage = "JBWEB000065: HTTP Status 500." + } else { + errorMessage = "Return code is " + returnCode + } + errorMessage = "Received error from Network Adapter: " + errorMessage + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, errorMessage) + + } + + } else { // CatchAll exception + String dataErrorMessage = "Received error from Network Adapter. Return code is: " + returnCode + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) + + } + + } + + } catch (BpmnError e) { + throw e; + + } catch (Exception ex) { + String exceptionMessage = " Bpmn error encountered in DoUpdateNetworkInstance flow. validateUpdateNetworkResponse() - " + ex.getMessage() + utils.log("DEBUG", exceptionMessage, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + + } + + + } + + public void validateSDNCResponse (Execution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix", Prefix) + + utils.log("DEBUG", " ***** Inside validateSDNCResponse of DoUpdateNetworkInstance ***** ", isDebugEnabled) + + String response = execution.getVariable(Prefix + "changeAssignSDNCResponse") + WorkflowException workflowException = null + try { + workflowException = execution.getVariable(Prefix + "WorkflowException") + //execution.setVariable("WorkflowException", workflowException) + } catch (Exception ex) { + utils.log("DEBUG", " Sdnc 'WorkflowException' object is empty or null. ", isDebugEnabled) + } + + boolean successIndicator = execution.getVariable("SDNCA_SuccessIndicator") + + SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils(this) + sdncAdapterUtils.validateSDNCResponse(execution, response, workflowException, successIndicator) + // reset variable + String changeAssignSDNCResponseDecodeXml = sdncAdapterUtils.decodeXML(execution.getVariable(Prefix + "changeAssignSDNCResponse")) + changeAssignSDNCResponseDecodeXml = changeAssignSDNCResponseDecodeXml.replace("&", "&").replace('', "") + execution.setVariable(Prefix + "changeAssignSDNCResponse", changeAssignSDNCResponseDecodeXml) + + if (execution.getVariable(Prefix + "sdncResponseSuccess") == true) { // from sdnc util, prefix+'sdncResponseSuccess' + execution.setVariable(Prefix + "isSdncRollbackNeeded", true) + utils.log("DEBUG", "Successfully Validated SDNC Response", isDebugEnabled) + + } else { + utils.log("DEBUG", "Did NOT Successfully Validated SDNC Response", isDebugEnabled) + throw new BpmnError("MSOWorkflowException") + } + + } + + + public void postProcessResponse (Execution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix", Prefix) + + utils.log("DEBUG", " ***** Inside postProcessResponse of DoUpdateNetworkInstance ***** ", isDebugEnabled) + + try { + utils.log("DEBUG", " ***** Is Exception Encountered (isException)? : " + execution.getVariable(Prefix + "isException"), isDebugEnabled) + if (execution.getVariable(Prefix + "isException") == false) { + // set rollback data + execution.setVariable("orchestrationStatus", "") + execution.setVariable("networkId", execution.getVariable(Prefix + "networkId")) + execution.setVariable("networkName", execution.getVariable(Prefix + "networkName")) + prepareSuccessRollbackData(execution) // populate rollbackData + execution.setVariable("WorkflowException", null) + execution.setVariable(Prefix + "Success", true) + utils.log("DEBUG", " ***** postProcessResponse(), GOOD !!!", isDebugEnabled) + } else { + execution.setVariable(Prefix + "Success", false) + execution.setVariable("rollbackData", null) + String exceptionMessage = " Exception encountered in MSO Bpmn. " + if (execution.getVariable("workflowException") != null) { // Output of Rollback flow. + utils.log("DEBUG", " ***** workflowException: " + execution.getVariable("workflowException"), isDebugEnabled) + WorkflowException wfex = execution.getVariable("workflowException") + exceptionMessage = wfex.getErrorMessage() + } else { + if (execution.getVariable(Prefix + "WorkflowException") != null) { + WorkflowException pwfex = execution.getVariable(Prefix + "WorkflowException") + exceptionMessage = pwfex.getErrorMessage() + } + } + // going to the Main flow: a-la-carte or macro + utils.log("DEBUG", " ***** postProcessResponse(), BAD !!!", isDebugEnabled) + exceptionUtil.buildWorkflowException(execution, 7000, exceptionMessage) + throw new BpmnError("MSOWorkflowException") + } + + } catch(BpmnError b){ + utils.log("DEBUG", "Rethrowing MSOWorkflowException", isDebugEnabled) + throw b + + + } catch (Exception ex) { + String exceptionMessage = " Bpmn error encountered in DoUpdateNetworkInstance flow. postProcessResponse() - " + ex.getMessage() + utils.log("DEBUG", exceptionMessage, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + + } + + + } + + public void prepareSDNCRollbackRequest (Execution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix", Prefix) + + utils.log("DEBUG", " ***** Inside prepareSDNCRollbackRequest of DoUpdateNetworkInstance ***** ", isDebugEnabled) + + try { + // for some reason the WorkflowException object is null after the sdnc rollback call task, need to save WorkflowException. + execution.setVariable(Prefix + "WorkflowException", execution.getVariable("WorkflowException")) + // get variables + String sdncCallback = execution.getVariable("URN_mso_workflow_sdncadapter_callback") + String updateNetworkInput = execution.getVariable(Prefix + "networkRequest") + String cloudRegionId = execution.getVariable(Prefix + "cloudRegionSdnc") + String changeAssignSDNCResponse = execution.getVariable(Prefix + "changeAssignSDNCResponse") + String networkId = utils.getNodeText1(changeAssignSDNCResponse, "network-id") + + String serviceInstanceId = utils.getNodeText1(updateNetworkInput, "service-instance-id") + + // 2. prepare rollback topology via SDNC Adapter SUBFLOW call + String sndcTopologyRollbackRequest = sdncAdapterUtils.sdncTopologyRequestV2(execution, updateNetworkInput, serviceInstanceId, sdncCallback, "rollback", "NetworkActivateRequest", cloudRegionId, networkId, null, null) + String sndcTopologyRollbackRequestAsString = utils.formatXml(sndcTopologyRollbackRequest) + execution.setVariable(Prefix + "rollbackSDNCRequest", sndcTopologyRollbackRequestAsString) + utils.log("DEBUG", " Preparing request for SDNC Topology assign's rollback/compensation . . . - " + "\n" + sndcTopologyRollbackRequestAsString, isDebugEnabled) + + + } catch (Exception ex) { + String exceptionMessage = " Bpmn error encountered in DoUpdateNetworkInstance flow. prepareSDNCRollbackRequest() - " + ex.getMessage() + utils.log("DEBUG", exceptionMessage, isDebugEnabled) + exceptionUtil.buildWorkflowException(execution, 7000, exceptionMessage) + + } + + } + + public void prepareRollbackData(Execution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix",Prefix) + + utils.log("DEBUG", " ***** Inside prepareRollbackData() of DoUpdateNetworkInstance ***** ", isDebugEnabled) + + try { + + Map rollbackData = new HashMap(); + String rollbackSDNCRequest = execution.getVariable(Prefix + "rollbackSDNCRequest") + if (rollbackSDNCRequest != null) { + if (rollbackSDNCRequest != "") { + rollbackData.put("rollbackSDNCRequest", execution.getVariable(Prefix + "rollbackSDNCRequest")) + } + } + String rollbackNetworkRequest = execution.getVariable(Prefix + "rollbackNetworkRequest") + if (rollbackNetworkRequest != null) { + if (rollbackNetworkRequest != "") { + rollbackData.put("rollbackNetworkRequest", execution.getVariable(Prefix + "rollbackNetworkRequest")) + } + } + execution.setVariable("rollbackData", rollbackData) + utils.log("DEBUG", "** rollbackData : " + rollbackData, isDebugEnabled) + + execution.setVariable("WorkflowException", execution.getVariable(Prefix + "WorkflowException")) + utils.log("DEBUG", "** WorkflowException : " + execution.getVariable("WorkflowException"), isDebugEnabled) + + } catch (Exception ex) { + String exceptionMessage = " Bpmn error encountered in DoUpdateNetworkInstance flow. prepareRollbackData() - " + ex.getMessage() + utils.log("DEBUG", exceptionMessage, isDebugEnabled) + exceptionUtil.buildWorkflowException(execution, 7000, exceptionMessage) + + } + + } + + public void prepareSuccessRollbackData(Execution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix",Prefix) + + utils.log("DEBUG", " ***** Inside prepareSuccessRollbackData() of DoUpdateNetworkInstance ***** ", isDebugEnabled) + + try { + + if (execution.getVariable("sdncVersion") == '1702') { + // skip: 1702 for 'changeassign' or equivalent not yet defined in SNDC, so no rollback. + } else { + prepareSDNCRollbackRequest(execution) + } + + Map rollbackData = new HashMap(); + String rollbackSDNCRequest = execution.getVariable(Prefix + "rollbackSDNCRequest") + if (rollbackSDNCRequest != null) { + if (rollbackSDNCRequest != "") { + rollbackData.put("rollbackSDNCRequest", rollbackSDNCRequest) + } + } + String rollbackNetworkRequest = execution.getVariable(Prefix + "rollbackNetworkRequest") + if (rollbackNetworkRequest != null) { + if (rollbackNetworkRequest != "") { + rollbackData.put("rollbackNetworkRequest", rollbackNetworkRequest) + } + } + execution.setVariable("rollbackData", rollbackData) + + utils.log("DEBUG", "** 'rollbackData' for Full Rollback : " + rollbackData, isDebugEnabled) + execution.setVariable("WorkflowException", null) + + + } catch (Exception ex) { + String exceptionMessage = " Bpmn error encountered in DoUpdateNetworkInstance flow. prepareSuccessRollbackData() - " + ex.getMessage() + utils.log("DEBUG", exceptionMessage, isDebugEnabled) + exceptionUtil.buildWorkflowException(execution, 7000, exceptionMessage) + + } + + } + + public void setExceptionFlag(Execution execution){ + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix",Prefix) + + utils.log("DEBUG", " ***** Inside setExceptionFlag() of DoUpdateNetworkInstance ***** ", isDebugEnabled) + + try { + + execution.setVariable(Prefix + "isException", true) + + if (execution.getVariable("SavedWorkflowException1") != null) { + execution.setVariable(Prefix + "WorkflowException", execution.getVariable("SavedWorkflowException1")) + } else { + execution.setVariable(Prefix + "WorkflowException", execution.getVariable("WorkflowException")) + } + utils.log("DEBUG", Prefix + "WorkflowException - " +execution.getVariable(Prefix + "WorkflowException"), isDebugEnabled) + + } catch(Exception ex){ + String exceptionMessage = "Bpmn error encountered in DoUpdateNetworkInstance flow. setExceptionFlag(): " + ex.getMessage() + utils.log("DEBUG", exceptionMessage, isDebugEnabled) + exceptionUtil.buildWorkflowException(execution, 7000, exceptionMessage) + } + + } + + + // ******************************* + // Build Error Section + // ******************************* + + public void processJavaException(Execution execution){ + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix",Prefix) + try{ + utils.log("DEBUG", "Caught a Java Exception", isDebugEnabled) + utils.log("DEBUG", "Started processJavaException Method", isDebugEnabled) + utils.log("DEBUG", "Variables List: " + execution.getVariables(), isDebugEnabled) + execution.setVariable("UnexpectedError", "Caught a Java Lang Exception - " + Prefix) // Adding this line temporarily until this flows error handling gets updated + exceptionUtil.buildWorkflowException(execution, 500, "Caught a Java Lang Exception") + + }catch(Exception e){ + utils.log("DEBUG", "Caught Exception during processJavaException Method: " + e, isDebugEnabled) + execution.setVariable("UnexpectedError", "Exception in processJavaException method") // Adding this line temporarily until this flows error handling gets updated + exceptionUtil.buildWorkflowException(execution, 500, "Exception in processJavaException method") + } + utils.log("DEBUG", "Completed processJavaException Method", isDebugEnabled) + } + +} diff --git a/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/DoUpdateNetworkInstanceRollback.groovy b/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/DoUpdateNetworkInstanceRollback.groovy new file mode 100644 index 0000000000..c91771116f --- /dev/null +++ b/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/DoUpdateNetworkInstanceRollback.groovy @@ -0,0 +1,304 @@ +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.bpmn.infrastructure.scripts; + +import groovy.xml.XmlUtil +import groovy.json.* + +import org.openecomp.mso.bpmn.common.scripts.AaiUtil +import org.openecomp.mso.bpmn.common.scripts.AbstractServiceTaskProcessor +import org.openecomp.mso.bpmn.common.scripts.ExceptionUtil +import org.openecomp.mso.bpmn.common.scripts.NetworkUtils +import org.openecomp.mso.bpmn.common.scripts.SDNCAdapterUtils +import org.openecomp.mso.bpmn.common.scripts.VidUtils +import org.openecomp.mso.bpmn.core.WorkflowException +import org.openecomp.mso.bpmn.core.json.JsonUtils +import org.openecomp.mso.rest.APIResponse + +import java.util.UUID; + +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.runtime.Execution +import org.apache.commons.lang3.* +import org.apache.commons.codec.binary.Base64; +import org.springframework.web.util.UriUtils + +/** + * This groovy class supports the DoCreateNetworkInstance.bpmn process. + * + */ +public class DoUpdateNetworkInstanceRollback extends AbstractServiceTaskProcessor { + String Prefix="UPDNETIR_" + ExceptionUtil exceptionUtil = new ExceptionUtil() + JsonUtils jsonUtil = new JsonUtils() + VidUtils vidUtils = new VidUtils(this) + NetworkUtils networkUtils = new NetworkUtils() + SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils() + + def className = getClass().getSimpleName() + + /** + * This method is executed during the preProcessRequest task of the DoUpdateNetworkInstanceRollback.bpmn process. + * @param execution + */ + public InitializeProcessVariables(Execution execution){ + /* Initialize all the process variables in this block */ + + execution.setVariable(Prefix + "rollbackNetworkRequest", null) + execution.setVariable(Prefix + "rollbackSDNCRequest", null) + execution.setVariable(Prefix + "WorkflowException", null) + + execution.setVariable(Prefix + "rollbackNetworkRequest", "") + execution.setVariable(Prefix + "rollbackNetworkResponse", "") + execution.setVariable(Prefix + "rollbackNetworkReturnCode", "") + + execution.setVariable(Prefix + "rollbackSDNCRequest", "") + execution.setVariable(Prefix + "rollbackSDNCResponse", "") + execution.setVariable(Prefix + "rollbackSDNCReturnCode", "") + + execution.setVariable(Prefix + "Success", false) + execution.setVariable(Prefix + "fullRollback", false) + + } + + // ************************************************** + // Pre or Prepare Request Section + // ************************************************** + /** + * This method is executed during the preProcessRequest task of the DoUpdateNetworkInstanceRollback.bpmn process. + * @param execution + */ + public void preProcessRequest (Execution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix",Prefix) + + utils.log("DEBUG", " ***** Inside preProcessRequest() of " + className + ".groovy ***** ", isDebugEnabled) + + try { + // initialize flow variables + InitializeProcessVariables(execution) + + // GET Incoming request/variables + String rollbackNetworkRequest = null + String rollbackSDNCRequest = null + + // Partial Rollback + Map rollbackData = execution.getVariable("rollbackData") + if (rollbackData != null && rollbackData instanceof Map) { + + if(rollbackData.containsKey("rollbackNetworkRequest")) { + rollbackNetworkRequest = rollbackData["rollbackNetworkRequest"] + } + + if(rollbackData.containsKey("rollbackSDNCRequest")) { + rollbackSDNCRequest = rollbackData["rollbackSDNCRequest"] + } + } + + execution.setVariable(Prefix + "rollbackNetworkRequest", rollbackNetworkRequest) + execution.setVariable(Prefix + "rollbackSDNCRequest", rollbackSDNCRequest) + utils.log("DEBUG", "'rollbackData': " + '\n' + execution.getVariable("rollbackData"), isDebugEnabled) + + String sdncVersion = execution.getVariable("sdncVersion") + utils.log("DEBUG", "sdncVersion? : " + sdncVersion, isDebugEnabled) + + // PO Authorization Info / headers Authorization= + String basicAuthValuePO = execution.getVariable("URN_mso_adapters_po_auth") + utils.log("DEBUG", " Obtained BasicAuth userid password for PO/SDNC adapter: " + basicAuthValuePO, isDebugEnabled) + try { + def encodedString = utils.getBasicAuth(basicAuthValuePO, execution.getVariable("URN_mso_msoKey")) + execution.setVariable("BasicAuthHeaderValuePO",encodedString) + execution.setVariable("BasicAuthHeaderValueSDNC", encodedString) + + } catch (IOException ex) { + String exceptionMessage = "Exception Encountered in DoCreateNetworkInstance, PreProcessRequest() - " + String dataErrorMessage = exceptionMessage + " Unable to encode PO/SDNC user/password string - " + ex.getMessage() + utils.log("DEBUG", dataErrorMessage , isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) + } + + if (execution.getVariable("SavedWorkflowException1") != null) { + execution.setVariable(Prefix + "WorkflowException", execution.getVariable("SavedWorkflowException1")) + } else { + execution.setVariable(Prefix + "WorkflowException", execution.getVariable("WorkflowException")) + } + utils.log("DEBUG", "*** WorkflowException : " + execution.getVariable(Prefix + "WorkflowException"), isDebugEnabled) + if(execution.getVariable(Prefix + "WorkflowException") != null) { + // called by: DoCreateNetworkInstance, partial rollback + execution.setVariable(Prefix + "fullRollback", false) + + } else { + // called by: Macro - Full Rollback, WorkflowException = null + execution.setVariable(Prefix + "fullRollback", true) + + } + utils.log("DEBUG", "*** fullRollback? : " + execution.getVariable(Prefix + "fullRollback"), isDebugEnabled) + + + } catch (BpmnError e) { + throw e; + + } catch (Exception ex) { + sendSyncError(execution) + // caught exception + String exceptionMessage = "Exception Encountered in PreProcessRequest() of " + className + ".groovy ***** : " + ex.getMessage() + utils.log("DEBUG", exceptionMessage, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + + } + + } + + public void validateRollbackResponses (Execution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix",Prefix) + + utils.log("DEBUG", " ***** Inside validateRollbackResponses() of DoUpdateNetworkInstanceRollback ***** ", isDebugEnabled) + + try { + // validate PO network rollback response + String rollbackNetworkErrorMessages = "" + String rollbackNetworkReturnCode = "200" + if (execution.getVariable(Prefix + "rollbackNetworkRequest") != null) { + rollbackNetworkReturnCode = execution.getVariable(Prefix + "rollbackNetworkReturnCode") + String rollbackNetworkResponse = execution.getVariable(Prefix + "rollbackNetworkResponse") + utils.log("DEBUG", " NetworkRollback Code - " + rollbackNetworkReturnCode, isDebugEnabled) + utils.log("DEBUG", " NetworkRollback Response - " + rollbackNetworkResponse, isDebugEnabled) + if (rollbackNetworkReturnCode != "200") { + rollbackNetworkErrorMessages = " + PO Network rollback failed. " + } else { + rollbackNetworkErrorMessages = " + PO Network rollback completed." + } + } + + // validate SDNC rollback response + String rollbackSdncErrorMessages = "" + String rollbackSDNCReturnCode = "200" + if (execution.getVariable(Prefix + "rollbackSDNCRequest") != null) { + rollbackSDNCReturnCode = execution.getVariable(Prefix + "rollbackSDNCReturnCode") + String rollbackSDNCResponse = execution.getVariable(Prefix + "rollbackSDNCResponse") + String rollbackSDNCReturnInnerCode = "" + SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils(this) + rollbackSDNCResponse = sdncAdapterUtils.decodeXML(rollbackSDNCResponse) + rollbackSDNCResponse = rollbackSDNCResponse.replace("&", "&").replace('$', '').replace('', "") + if (rollbackSDNCReturnCode == "200") { + if (utils.nodeExists(rollbackSDNCResponse, "response-code")) { + rollbackSDNCReturnInnerCode = utils.getNodeText1(rollbackSDNCResponse, "response-code") + if (rollbackSDNCReturnInnerCode == "200" || rollbackSDNCReturnInnerCode == "" || rollbackSDNCReturnInnerCode == "0") { + rollbackSdncErrorMessages = " + SNDC changeassign rollback completed." + } else { + rollbackSdncErrorMessages = " + SDNC changeassign rollback failed. " + } + } else { + rollbackSdncErrorMessages = " + SNDC changeassign rollback completed." + } + } else { + rollbackSdncErrorMessages = " + SDNC changeassign rollback failed. " + } + utils.log("DEBUG", " SDNC changeassign rollback Code - " + rollbackSDNCReturnCode, isDebugEnabled) + utils.log("DEBUG", " SDNC changeassign rollback Response - " + rollbackSDNCResponse, isDebugEnabled) + } + + String statusMessage = "" + int errorCode = 7000 + utils.log("DEBUG", "*** fullRollback? : " + execution.getVariable(Prefix + "fullRollback"), isDebugEnabled) + if (execution.getVariable(Prefix + "fullRollback") == false) { + // original WorkflowException, + WorkflowException wfe = execution.getVariable(Prefix + "WorkflowException") + if (wfe != null) { + // rollback due to failure in DoCreate - Partial rollback + statusMessage = wfe.getErrorMessage() + errorCode = wfe.getErrorCode() + } else { + statusMessage = "See Previous Camunda flows for cause of Error: Undetermined Exception." + errorCode = '7000' + } + + // set if all rolledbacks are successful + if (rollbackNetworkReturnCode == "200" && rollbackSDNCReturnCode == "200") { + execution.setVariable("rolledBack", true) + + } else { + execution.setVariable("rolledBack", false) + + } + + statusMessage = statusMessage + rollbackNetworkErrorMessages + rollbackSdncErrorMessages + utils.log("DEBUG", "Final DoUpdateNetworkInstanceRollback status message: " + statusMessage, isDebugEnabled) + String processKey = getProcessKey(execution); + WorkflowException exception = new WorkflowException(processKey, errorCode, statusMessage); + execution.setVariable("workflowException", exception); + + } else { + // rollback due to failures in Main flow (Macro) - Full rollback + // WorkflowException = null + if (rollbackNetworkReturnCode == "200" && rollbackSDNCReturnCode == "200") { + execution.setVariable("rollbackSuccessful", true) + execution.setVariable("rollbackError", false) + } else { + String exceptionMessage = "Network Update Rollback was not Successful. " + utils.log("DEBUG", exceptionMessage, isDebugEnabled) + execution.setVariable("rollbackSuccessful", false) + execution.setVariable("rollbackError", true) + exceptionUtil.buildWorkflowException(execution, 7000, exceptionMessage) + throw new BpmnError("MSOWorkflowException") + } + + } + + + } catch (Exception ex) { + execution.setVariable("WorkflowException", null) + String errorMessage = "See Previous Camunda flows for cause of Error: Undetermined Exception." + String exceptionMessage = " Bpmn error encountered in DoUpdateNetworkInstanceRollback flow. validateRollbackResponses() - " + errorMessage + ": " + ex.getMessage() + utils.log("DEBUG", exceptionMessage, isDebugEnabled) + exceptionUtil.buildWorkflowException(execution, 7000, exceptionMessage) + execution.setVariable("WorkflowException", execution.getVariable("WorkflowException")) + + } + + } + + // ******************************* + // Build Error Section + // ******************************* + + + + public void processJavaException(Execution execution){ + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix",Prefix) + + try{ + utils.log("DEBUG", "Caught a Java Exception in " + Prefix, isDebugEnabled) + utils.log("DEBUG", "Started processJavaException Method", isDebugEnabled) + utils.log("DEBUG", "Variables List: " + execution.getVariables(), isDebugEnabled) + execution.setVariable("UnexpectedError", "Caught a Java Lang Exception - " + Prefix) // Adding this line temporarily until this flows error handling gets updated + exceptionUtil.buildWorkflowException(execution, 500, "Caught a Java Lang Exception") + + }catch(Exception e){ + utils.log("DEBUG", "Caught Exception during processJavaException Method: " + e, isDebugEnabled) + execution.setVariable("UnexpectedError", "Exception in processJavaException method - " + Prefix) // Adding this line temporarily until this flows error handling gets updated + exceptionUtil.buildWorkflowException(execution, 500, "Exception in processJavaException method" + Prefix) + } + utils.log("DEBUG", "Completed processJavaException Method in " + Prefix, isDebugEnabled) + } + +} diff --git a/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/DoUpdateVfModule.groovy b/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/DoUpdateVfModule.groovy index 7d6a21dc98..5999857608 100644 --- a/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/DoUpdateVfModule.groovy +++ b/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/DoUpdateVfModule.groovy @@ -1,789 +1,919 @@ -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - MSO - * ================================================================================ - * 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.openecomp.mso.bpmn.infrastructure.scripts - -import org.camunda.bpm.engine.delegate.BpmnError -import org.camunda.bpm.engine.runtime.Execution -import org.openecomp.mso.bpmn.common.scripts.AaiUtil -import org.openecomp.mso.bpmn.common.scripts.ExceptionUtil -import org.openecomp.mso.bpmn.common.scripts.NetworkUtils -import org.openecomp.mso.bpmn.common.scripts.SDNCAdapterUtils -import org.openecomp.mso.bpmn.common.scripts.VfModule -import org.openecomp.mso.bpmn.common.scripts.VfModuleBase -import org.openecomp.mso.bpmn.core.WorkflowException -import org.openecomp.mso.rest.APIResponse -import org.springframework.web.util.UriUtils - -public class DoUpdateVfModule extends VfModuleBase { - - ExceptionUtil exceptionUtil = new ExceptionUtil() - - /** - * Initialize the flow's variables. - * - * @param execution The flow's execution instance. - */ - public void initProcessVariables(Execution execution) { - execution.setVariable('prefix', 'DOUPVfMod_') - execution.setVariable('DOUPVfMod_requestInfo', null) - execution.setVariable('DOUPVfMod_serviceInstanceId', null) - execution.setVariable('DOUPVfMod_requestId', null) - execution.setVariable('DOUPVfMod_vnfInputs', null) - execution.setVariable('DOUPVfMod_vnfId', null) - execution.setVariable('DOUPVfMod_vnfName', null) - execution.setVariable('DOUPVfMod_vnfNameFromAAI', null) - execution.setVariable('DOUPVfMod_vfModuleName', null) - execution.setVariable('DOUPVfMod_vfModuleId', null) - execution.setVariable('DOUPVfMod_vnfType', null) - execution.setVariable('DOUPVfMod_asdcServiceModelVersion', null) - execution.setVariable('DOUPVfMod_vfModuleModelName', null) - execution.setVariable('DOUPVfMod_modelCustomizationUuid', null) - execution.setVariable("DOUPVfMod_isBaseVfModule", "false") - execution.setVariable('DOUPVfMod_serviceId', null) - execution.setVariable('DOUPVfMod_aicCloudRegion', null) - execution.setVariable('DOUPVfMod_tenantId', null) - execution.setVariable('DOUPVfMod_volumeGroupId', null) - execution.setVariable('DOUPVfMod_vfModule', null) - execution.setVariable('DOUPVfMod_vnfParams', null) - execution.setVariable("DOUPVfMod_baseVfModuleId", "") - execution.setVariable("DOUPVfMod_baseVfModuleHeatStackId", "") - execution.setVariable('DOUPVfMod_prepareUpdateAAIVfModuleRequest', null) - execution.setVariable('DOUPVfMod_sdncChangeAssignRequest', null) - execution.setVariable('DOUPVfMod_sdncChangeAssignResponse', null) - execution.setVariable('DOUPVfMod_sdncActivateRequest', null) - execution.setVariable('DOUPVfMod_sdncActivateResponse', null) - execution.setVariable('DOUPVfMod_sdncTopologyRequest', null) - execution.setVariable('DOUPVfMod_sdncTopologyResponse', null) - execution.setVariable('DOUPVfMod_vnfAdapterRestRequest', null) - execution.setVariable('DOUPVfMod_updateAAIGenericVnfRequest', null) - execution.setVariable('DOUPVfMod_updateAAIVfModuleRequest', null) - execution.setVariable('DOUPVfMod_skipUpdateGenericVnf', false) - execution.setVariable('DoUpdateVfModuleSuccessIndicator', false) - } - - /** - * Check for missing elements in the received request. - * - * @param execution The flow's execution instance. - */ - public void preProcessRequest(Execution execution) { - def method = getClass().getSimpleName() + '.preProcessRequest(' + - 'execution=' + execution.getId() + - ')' - def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') - logDebug('Entered ' + method, isDebugLogEnabled) - - try { - initProcessVariables(execution) - def xml = getVariable(execution, 'DoUpdateVfModuleRequest') - utils.logAudit("DoUpdateVfModule request: " + xml) - logDebug('Received request xml:\n' + xml, isDebugLogEnabled) - - def requestInfo = getRequiredNodeXml(execution, xml, 'request-info') - execution.setVariable('DOUPVfMod_requestInfo', requestInfo) - execution.setVariable('DOUPVfMod_requestId', getRequiredNodeText(execution, requestInfo, 'request-id')) - def serviceInstanceId = execution.getVariable('mso-service-instance-id') - if (serviceInstanceId == null) { - serviceInstanceId = '' - } - execution.setVariable('DOUPVfMod_serviceInstanceId', serviceInstanceId) - - def vnfInputs = getRequiredNodeXml(execution, xml, 'vnf-inputs') - execution.setVariable('DOUPVfMod_vnfInputs', vnfInputs) - execution.setVariable('DOUPVfMod_vnfId', getRequiredNodeText(execution, vnfInputs, 'vnf-id')) - execution.setVariable('DOUPVfMod_vfModuleId', getRequiredNodeText(execution, vnfInputs, 'vf-module-id')) - execution.setVariable('DOUPVfMod_vfModuleName', getNodeTextForce(vnfInputs, 'vf-module-name')) - execution.setVariable('DOUPVfMod_vnfType', getNodeTextForce(vnfInputs, 'vnf-type')) - execution.setVariable('DOUPVfMod_vnfName', getNodeTextForce(vnfInputs, 'vnf-name')) - execution.setVariable('DOUPVfMod_asdcServiceModelVersion', getNodeTextForce(vnfInputs, 'asdc-service-model-version')) - execution.setVariable('DOUPVfMod_vfModuleModelName', getRequiredNodeText(execution, vnfInputs, 'vf-module-model-name')) - execution.setVariable('DOUPVfMod_modelCustomizationUuid', getNodeTextForce(vnfInputs, 'model-customization-id')) - execution.setVariable('DOUPVfMod_serviceId', getRequiredNodeText(execution, vnfInputs, 'service-id')) - execution.setVariable('DOUPVfMod_aicCloudRegion', getRequiredNodeText(execution, vnfInputs, 'aic-cloud-region')) - execution.setVariable('DOUPVfMod_tenantId', getRequiredNodeText(execution, vnfInputs, 'tenant-id')) - //isBaseVfModule - def isBaseVfModule = "false" - if (utils.nodeExists(xml, "is-base-vf-module")) { - isBaseVfModule = utils.getNodeText(xml, "is-base-vf-module") - execution.setVariable("DOUPVfMod_isBaseVfModule", isBaseVfModule) - } - logDebug("isBaseVfModule: " + isBaseVfModule, isDebugLogEnabled) - - NetworkUtils networkUtils = new NetworkUtils() - def backoutOnFailure = networkUtils.isRollbackEnabled(execution, xml) - execution.setVariable("DOUPVfMod_backoutOnFailure", backoutOnFailure) - - def String vgi = getNodeTextForce(vnfInputs, 'volume-group-id') - execution.setVariable('DOUPVfMod_volumeGroupId', vgi) - - execution.setVariable('DOUPVfMod_vnfParams', utils.getNodeXml(xml, 'vnf-params', false)) - - def sdncCallbackUrl = (String) execution.getVariable('URN_mso_workflow_sdncadapter_callback') - if (sdncCallbackUrl == null || sdncCallbackUrl.trim().isEmpty()) { - def msg = 'Required variable \'URN_mso_workflow_sdncadapter_callback\' is missing' - logError(msg) - createWorkflowException(execution, 2000, msg) - } - - logDebug('Exited ' + method, isDebugLogEnabled) - } catch (BpmnError e) { - throw e; - } catch (Exception e) { - logError('Caught exception in ' + method, e) - createWorkflowException(execution, 1002, 'Error in preProcessRequest(): ' + e.getMessage()) - } - } - - /** - * Prepare a Request for invoking the PrepareUpdateAAIVfModule subflow. This will - * set the orchestration-status to 'pending-update'. - * - * @param execution The flow's execution instance. - */ - public void prepPrepareUpdateAAIVfModule(Execution execution) { - def method = getClass().getSimpleName() + '.preparePrepareUpdateAAIVfModule(' + - 'execution=' + execution.getId() + - ')' - def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') - logDebug('Entered ' + method, isDebugLogEnabled) - - try { - def vnfId = execution.getVariable('DOUPVfMod_vnfId') - def vfModuleId = execution.getVariable('DOUPVfMod_vfModuleId') - def orchestrationStatus = 'pending-update' - - String prepareUpdateAAIVfModuleRequest = """ - - ${vnfId} - ${vfModuleId} - ${orchestrationStatus} - - """ - prepareUpdateAAIVfModuleRequest = utils.formatXml(prepareUpdateAAIVfModuleRequest) - execution.setVariable('DOUPVfMod_prepareUpdateAAIVfModuleRequest', prepareUpdateAAIVfModuleRequest) - utils.logAudit("DoUpdateAAIVfModule request: " + prepareUpdateAAIVfModuleRequest) - logDebug('Request for PrepareUpdateAAIVfModule:\n' + prepareUpdateAAIVfModuleRequest, isDebugLogEnabled) - - logDebug('Exited ' + method, isDebugLogEnabled) - } catch (BpmnError e) { - throw e; - } catch (Exception e) { - logError('Caught exception in ' + method, e) - createWorkflowException(execution, 1002, 'Error in preparePrepareUpdateAAIVfModule(): ' + e.getMessage()) - } - } - - /** - * Prepare a Request for invoking the ConfirmVolumeGroupTenant subflow. Currently, - * there is really nothing to do, so we just log that we're passing through. - * - * @param execution The flow's execution instance. - */ - public void prepConfirmVolumeGroupTenant(Execution execution) { - def method = getClass().getSimpleName() + '.prepConfirmVolumeGroupTenant(' + - 'execution=' + execution.getId() + - ')' - def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') - logDebug('Entered ' + method, isDebugLogEnabled) - - try { - // Nothing to do - just log that we're passing through here - - logDebug('Exited ' + method, isDebugLogEnabled) - } catch (BpmnError e) { - throw e; - } catch (Exception e) { - logError('Caught exception in ' + method, e) - createWorkflowException(execution, 1002, 'Error in prepConfirmVolumeGroupTenant(): ' + e.getMessage()) - } - } - - /** - * Prepare a Request for invoking the SDNC Adapter subflow to perform - * a VNF topology 'changeassign' operation. - * - * @param execution The flow's execution instance. - */ - public void prepSDNCTopologyChg(Execution execution) { - def method = getClass().getSimpleName() + '.prepSDNCTopologyChg(' + - 'execution=' + execution.getId() + - ')' - def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') - logDebug('Entered ' + method, isDebugLogEnabled) - - try { - def requestId = execution.getVariable('DOUPVfMod_requestId') - def serviceInstanceId = execution.getVariable('DOUPVfMod_serviceInstanceId') - def callbackUrl = (String) execution.getVariable('URN_mso_workflow_sdncadapter_callback') - def serviceId = execution.getVariable('DOUPVfMod_serviceId') - def vnfId = execution.getVariable('DOUPVfMod_vnfId') - def vnfType = execution.getVariable('DOUPVfMod_vnfType') - def vfModuleId = execution.getVariable('DOUPVfMod_vfModuleId') - def vfModuleModelName = execution.getVariable('DOUPVfMod_vfModuleModelName') - def VfModule vfModule = (VfModule) execution.getVariable('DOUPVfMod_vfModule') - def vfModuleName = vfModule.getElementText('vf-module-name') - def tenantId = execution.getVariable('DOUPVfMod_tenantId') - def aicCloudRegion = execution.getVariable('DOUPVfMod_aicCloudRegion') - - // Retrieve vnf name from AAI response - def vnfName = execution.getVariable('DOUPVfMod_vnfNameFromAAI') - execution.setVariable('DOUPVfMod_vnfName', vnfName) - - def vnfParamsXml = execution.getVariable('DOUPVfMod_vnfParams') - def vnfNetworks = transformNetworkParamsToVnfNetworks(vnfParamsXml) - - String sdncTopologyRequest = """ - - - ${requestId} - ${serviceInstanceId} - changeassign - vnf-topology-operation - ${callbackUrl} - - - - ${requestId} - ChangeVNFActivateRequest - PORTAL - - - - - - ${serviceId} - ${vnfId} - dontcare - - - ${vfModuleId} - ${vfModuleModelName} - ${vfModuleName} - ${vnfId} - ${vnfName} - ${vnfType} - ${tenantId} - ${aicCloudRegion} - ${vnfNetworks} - - - - """ - sdncTopologyRequest = utils.formatXml(sdncTopologyRequest) - execution.setVariable('DOUPVfMod_sdncChangeAssignRequest', sdncTopologyRequest) - utils.logAudit("sdncChangeAssignRequest : " + sdncTopologyRequest) - logDebug('Request for SDNCAdapter topology/changeassign:\n' + sdncTopologyRequest, isDebugLogEnabled) - - logDebug('Exited ' + method, isDebugLogEnabled) - } catch (BpmnError e) { - throw e; - } catch (Exception e) { - logError('Caught exception in ' + method, e) - createWorkflowException(execution, 1002, 'Error in prepSDNCTopologyChg(): ' + e.getMessage()) - } - } - - /** - * Prepare a Request for invoking the SDNC Adapter subflow to perform - * a VNF topology 'query' operation. - * - * @param execution The flow's execution instance. - */ - public void prepSDNCTopologyQuery(Execution execution) { - def method = getClass().getSimpleName() + '.prepSDNCTopologyQuery(' + - 'execution=' + execution.getId() + - ')' - def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') - logDebug('Entered ' + method, isDebugLogEnabled) - - try { - def requestId = execution.getVariable('DOUPVfMod_requestId') - def serviceInstanceId = execution.getVariable('DOUPVfMod_serviceInstanceId') - def callbackUrl = (String) execution.getVariable('URN_mso_workflow_sdncadapter_callback') - def vfModuleId = execution.getVariable('DOUPVfMod_vfModuleId') - - def svcInstId = "" - if (serviceInstanceId == null || serviceInstanceId.isEmpty()) { - svcInstId = vfModuleId - } - else { - svcInstId = serviceInstanceId - } - - //!!!! TEMPORARY WORKAROUND FOR SDNC REPLICATION ISSUE - sleep(5000) - - String sdncTopologyRequest = """ - - - ${requestId} - ${svcInstId} - query - /VNF-API:vnfs/vnf-list/${vfModuleId} - ${callbackUrl} - mobility - - - """ - sdncTopologyRequest = utils.formatXml(sdncTopologyRequest) - execution.setVariable('DOUPVfMod_sdncTopologyRequest', sdncTopologyRequest) - utils.logAudit("sdncTopologyRequest : " + sdncTopologyRequest) - logDebug('Request for SDNCAdapter query:\n' + sdncTopologyRequest, isDebugLogEnabled) - - logDebug('Exited ' + method, isDebugLogEnabled) - } catch (BpmnError e) { - throw e; - } catch (Exception e) { - logError('Caught exception in ' + method, e) - createWorkflowException(execution, 1002, 'Error in prepSDNCTopologyQuery(): ' + e.getMessage()) - } - } - - /** - * Prepare a Request for invoking the VnfAdapterRest subflow. - * - * @param execution The flow's execution instance. - */ - public void prepVnfAdapterRest(Execution execution) { - def method = getClass().getSimpleName() + '.prepVnfAdapterRest(' + - 'execution=' + execution.getId() + - ')' - def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') - logDebug('Entered ' + method, isDebugLogEnabled) - - try { - def requestId = execution.getVariable('DOUPVfMod_requestId') - def serviceInstanceId = execution.getVariable('DOUPVfMod_serviceInstanceId') - def vnfId = execution.getVariable('DOUPVfMod_vnfId') - def vfModuleId = execution.getVariable('DOUPVfMod_vfModuleId') - def vfModuleName = execution.getVariable('DOUPVfMod_vfModuleName') - def vnfInputs = execution.getVariable('DOUPVfMod_vnfInputs') - def tenantId = execution.getVariable('DOUPVfMod_tenantId') - def volumeGroupId = execution.getVariable('DOUPVfMod_volumeGroupId') - def VfModule vfModule = (VfModule) execution.getVariable('DOUPVfMod_vfModule') - def heatStackId = vfModule.getElementText('heat-stack-id') - def cloudId = execution.getVariable('DOUPVfMod_aicCloudRegion') - def vnfType = execution.getVariable('DOUPVfMod_vnfType') - def vnfName = execution.getVariable('DOUPVfMod_vnfName') - def vfModuleModelName = execution.getVariable('DOUPVfMod_vfModuleModelName') - def baseVfModuleId = execution.getVariable("DOUPVfMod_baseVfModuleId") - def baseVfModuleStackId = execution.getVariable("DOUPVfMod_baseVfModuleHeatStackId") - def asdcServiceModelVersion = execution.getVariable('DOUPVfMod_asdcServiceModelVersion') - def modelCustomizationUuid = execution.getVariable('DOUPVfMod_modelCustomizationUuid') - def backoutOnFailure = execution.getVariable("DOUPVfMod_backoutOnFailure") - - def vnfParamsXml = execution.getVariable('DOUPVfMod_vnfParams') - def vfModuleParamsEntries = transformParamsToEntries(vnfParamsXml) - - def messageId = execution.getVariable('mso-request-id') + '-' + System.currentTimeMillis() - def notificationUrl = createCallbackURL(execution, "VNFAResponse", messageId) - def useQualifiedHostName = execution.getVariable("URN_mso_use_qualified_host") - if ('true'.equals(useQualifiedHostName)) { - notificationUrl = utils.getQualifiedHostNameForCallback(notificationUrl) - } - - String sdncGetResponse = execution.getVariable('DOUPVfMod_sdncTopologyResponse') - - String vfModuleParams = buildVfModuleParams(vfModuleParamsEntries, sdncGetResponse, vnfId, vnfName, - vfModuleId, vfModuleName) - - - String vnfAdapterRestRequest = """ - - ${cloudId} - ${tenantId} - ${vnfId} - ${vfModuleId} - ${heatStackId} - ${vnfType} - ${asdcServiceModelVersion} - ${modelCustomizationUuid} - ${vfModuleModelName} - ${volumeGroupId} - ${baseVfModuleId} - ${baseVfModuleStackId} - true - ${backoutOnFailure} - false - - ${vfModuleParams} - - - ${requestId} - ${serviceInstanceId} - - ${messageId} - ${notificationUrl} - - """ - vnfAdapterRestRequest = utils.formatXml(vnfAdapterRestRequest) - execution.setVariable('DOUPVfMod_vnfAdapterRestRequest', vnfAdapterRestRequest) - utils.logAudit("vnfAdapterRestRequest : " + vnfAdapterRestRequest) - logDebug('Request for VNFAdapter Rest:\n' + vnfAdapterRestRequest, isDebugLogEnabled) - - logDebug('Exited ' + method, isDebugLogEnabled) - } catch (BpmnError e) { - throw e; - } catch (Exception e) { - logError('Caught exception in ' + method, e) - createWorkflowException(execution, 1002, 'Error in prepVnfAdapterRest(): ' + e.getMessage()) - } - } - - /** - * Prepare a Request for invoking the UpdateAAIGenericVnf subflow. - * - * @param execution The flow's execution instance. - */ - public void prepUpdateAAIGenericVnf(Execution execution) { - def method = getClass().getSimpleName() + '.prepUpdateAAIGenericVnf(' + - 'execution=' + execution.getId() + - ')' - def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') - logDebug('Entered ' + method, isDebugLogEnabled) - - try { - def vnfId = execution.getVariable('DOUPVfMod_vnfId') - def vnfInputs = execution.getVariable('DOUPVfMod_vnfInputs') - - def personaModelId = utils.getNodeText1(vnfInputs, 'vnf-persona-model-id') - def personaModelVersion = utils.getNodeText1(vnfInputs, 'vnf-persona-model-version') - if ((personaModelId == null) || (personaModelVersion == null)) { - logDebug('Skipping update for Generic VNF ' + vnfId + - ' because either \'vnf-persona-model-id\' or \'vnf-persona-model-version\' is absent', isDebugLogEnabled) - execution.setVariable('DOUPVfMod_skipUpdateGenericVnf', true) - } else { - def personaModelIdElement = '' + personaModelId + '' - def personaModelVersionElement = '' + personaModelVersion + '' - - String updateAAIGenericVnfRequest = """ - - ${vnfId} - ${personaModelIdElement} - ${personaModelVersionElement} - - """ - updateAAIGenericVnfRequest = utils.formatXml(updateAAIGenericVnfRequest) - execution.setVariable('DOUPVfMod_updateAAIGenericVnfRequest', updateAAIGenericVnfRequest) - utils.logAudit("updateAAIGenericVnfRequest : " + updateAAIGenericVnfRequest) - logDebug('Request for UpdateAAIGenericVnf:\n' + updateAAIGenericVnfRequest, isDebugLogEnabled) - } - - logDebug('Exited ' + method, isDebugLogEnabled) - } catch (BpmnError e) { - throw e; - } catch (Exception e) { - logError('Caught exception in ' + method, e) - createWorkflowException(execution, 1002, 'Error in prepUpdateAAIGenericVnf(): ' + e.getMessage()) - } - } - - /** - * Prepare a Request for invoking the UpdateAAIVfModule subflow. - * - * @param execution The flow's execution instance. - */ - public void prepUpdateAAIVfModule(Execution execution) { - def method = getClass().getSimpleName() + '.prepUpdateAAIVfModule(' + - 'execution=' + execution.getId() + - ')' - def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') - logDebug('Entered ' + method, isDebugLogEnabled) - - try { - def vnfId = execution.getVariable('DOUPVfMod_vnfId') - def vfModuleId = execution.getVariable('DOUPVfMod_vfModuleId') - def orchestrationStatus = 'updated' - def vnfInputs = execution.getVariable('DOUPVfMod_vnfInputs') - - def volumeGroupIdElement = '' - def volumeGroupId = execution.getVariable('DOUPVfMod_volumeGroupId') - if (volumeGroupId != null) { - volumeGroupIdElement = '' + volumeGroupId + '' - } - def personaModelIdElement = '' - def personaModelId = utils.getNodeText1(vnfInputs, 'persona-model-id') - if (personaModelId != null) { - personaModelIdElement = '' + personaModelId + '' - } - def personaModelVersionElement = '' - def personaModelVersion = utils.getNodeText1(vnfInputs, 'persona-model-version') - if (personaModelVersion != null) { - personaModelVersionElement = '' + personaModelVersion + '' - } - def contrailServiceInstanceFqdnElement = '' - def contrailServiceInstanceFqdn = utils.getNodeText1(vnfInputs, 'contrail-service-instance-fqdn') - if (contrailServiceInstanceFqdn != null) { - contrailServiceInstanceFqdnElement = '' + contrailServiceInstanceFqdn + '' - } - def personaModelCustomizationIdElement = '' - def modelCustomizationId = execution.getVariable('DOUPVfMod_modelCustomizationUuid') - if (modelCustomizationId != null) { - personaModelCustomizationIdElement = '' + modelCustomizationId + '' - } - - String updateAAIVfModuleRequest = """ - - ${vnfId} - ${vfModuleId} - ${orchestrationStatus} - ${volumeGroupIdElement} - ${personaModelIdElement} - ${personaModelVersionElement} - ${contrailServiceInstanceFqdnElement} - ${personaModelCustomizationIdElement} - - """ - updateAAIVfModuleRequest = utils.formatXml(updateAAIVfModuleRequest) - execution.setVariable('DOUPVfMod_updateAAIVfModuleRequest', updateAAIVfModuleRequest) - utils.logAudit("updateAAIVfModuleRequest : " + updateAAIVfModuleRequest) - logDebug('Request for UpdateAAIVfModule:\n' + updateAAIVfModuleRequest, isDebugLogEnabled) - - logDebug('Exited ' + method, isDebugLogEnabled) - } catch (BpmnError e) { - throw e; - } catch (Exception e) { - logError('Caught exception in ' + method, e) - createWorkflowException(execution, 1002, 'Error in prepUpdateAAIVfModule(): ' + e.getMessage()) - } - } - - /** - * Prepare a Request for invoking the SDNC Adapter subflow to perform - * a VNF topology 'activate' operation. - * - * @param execution The flow's execution instance. - */ - public void prepSDNCTopologyAct(Execution execution) { - def method = getClass().getSimpleName() + '.prepSDNCTopologyAct(' + - 'execution=' + execution.getId() + - ')' - def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') - logDebug('Entered ' + method, isDebugLogEnabled) - - try { - def requestId = execution.getVariable('DOUPVfMod_requestId') - def serviceInstanceId = execution.getVariable('DOUPVfMod_serviceInstanceId') - def callbackUrl = (String) execution.getVariable('URN_mso_workflow_sdncadapter_callback') - def serviceId = execution.getVariable('DOUPVfMod_serviceId') - def vnfId = execution.getVariable('DOUPVfMod_vnfId') - def vnfName = execution.getVariable('DOUPVfMod_vnfName') - def vnfType = execution.getVariable('DOUPVfMod_vnfType') - def vfModuleId = execution.getVariable('DOUPVfMod_vfModuleId') - def vfModuleModelName = execution.getVariable('DOUPVfMod_vfModuleModelName') - def VfModule vfModule = (VfModule) execution.getVariable('DOUPVfMod_vfModule') - def vfModuleName = vfModule.getElementText('vf-module-name') - def tenantId = execution.getVariable('DOUPVfMod_tenantId') - def aicCloudRegion = execution.getVariable('DOUPVfMod_aicCloudRegion') - - def vnfParamsXml = execution.getVariable('DOUPVfMod_vnfParams') - def vnfNetworks = transformNetworkParamsToVnfNetworks(vnfParamsXml) - - String sdncTopologyRequest = """ - - - ${requestId} - ${serviceInstanceId} - activate - vnf-topology-operation - ${callbackUrl} - - - - ${requestId} - ChangeVNFActivateRequest - PORTAL - - - - - - ${serviceId} - ${vnfId} - dontcare - - - ${vfModuleId} - ${vfModuleModelName} - ${vfModuleName} - ${vnfId} - ${vnfName} - ${vnfType} - ${tenantId} - ${aicCloudRegion} - - - - """ - sdncTopologyRequest = utils.formatXml(sdncTopologyRequest) - execution.setVariable('DOUPVfMod_sdncActivateRequest', sdncTopologyRequest) - utils.logAudit("sdncActivateRequest : " + sdncTopologyRequest) - logDebug('Request for SDNCAdapter topology/activate:\n' + sdncTopologyRequest, isDebugLogEnabled) - - - logDebug('Exited ' + method, isDebugLogEnabled) - } catch (BpmnError e) { - throw e; - } catch (Exception e) { - logError('Caught exception in ' + method, e) - createWorkflowException(execution, 1002, 'Error in prepSDNCTopologyAct(): ' + e.getMessage()) - } - } - - /** - * Log a WorkflowException that has been created. - * - * @param execution The flow's execution instance. - */ - public void handleWorkflowException(Execution execution) { - def method = getClass().getSimpleName() + '.handleWorkflowException(' + - 'execution=' + execution.getId() + - ')' - def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') - logDebug('Entered ' + method, isDebugLogEnabled) - - try { - def WorkflowException workflowException = (WorkflowException) execution.getVariable('WorkflowException') - logError(method + ' caught WorkflowException: ' + workflowException.getErrorMessage()) - - logDebug('Exited ' + method, isDebugLogEnabled) - } catch (BpmnError e) { - throw e; - } catch (Exception e) { - logError('Caught exception in ' + method, e) - createWorkflowException(execution, 1002, 'Error in handleWorkflowException(): ' + e.getMessage()) - } - } - - public void validateSDNCResponse(Execution execution, String response, String method){ - def isDebugLogEnabled=execution.getVariable("isDebugLogEnabled") - def prefix = execution.getVariable("prefix") - - logDebug(" *** STARTED ValidateSDNCResponse Process*** ", isDebugLogEnabled) - - WorkflowException workflowException = execution.getVariable("WorkflowException") - boolean successIndicator = execution.getVariable("SDNCA_SuccessIndicator") - - utils.logAudit("workflowException: " + workflowException) - - SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils(this) - sdncAdapterUtils.validateSDNCResponse(execution, response, workflowException, successIndicator) - - utils.logAudit("SDNCResponse: " + response) - - String sdncResponse = response - if(execution.getVariable(prefix + 'sdncResponseSuccess') == true){ - logDebug("Received a Good Response from SDNC Adapter for " + method + " SDNC Call. Response is: \n" + sdncResponse, isDebugLogEnabled) - }else{ - logDebug("Received a BAD Response from SDNC Adapter for " + method + " SDNC Call.", isDebugLogEnabled) - throw new BpmnError("MSOWorkflowException") - } - logDebug(" *** COMPLETED ValidateSDNCResponse Process*** ", isDebugLogEnabled) - } - - /** - * Using the received vnfId and vfModuleId, query AAI to get the corresponding VNF info. - * A 200 response is expected with the VNF info in the response body. Will find out the base module info. - * - * @param execution The flow's execution instance. - */ - public void queryAAIVfModule(Execution execution) { - def isDebugLogEnabled=execution.getVariable("isDebugLogEnabled") - def method = getClass().getSimpleName() + '.getVfModule(' + - 'execution=' + execution.getId() + - ')' - logDebug('Entered ' + method, isDebugLogEnabled) - - try { - def vnfId = execution.getVariable('DOUPVfMod_vnfId') - def vfModuleId = execution.getVariable('DOUPVfMod_vfModuleId') - - AaiUtil aaiUriUtil = new AaiUtil(this) - String aai_uri = aaiUriUtil.getNetworkGenericVnfUri(execution) - logDebug('AAI URI is: ' + aai_uri, isDebugLogEnabled) - - String endPoint = execution.getVariable("URN_aai_endpoint") + "${aai_uri}/" + UriUtils.encode(vnfId, "UTF-8") + "?depth=1" - utils.logAudit("AAI endPoint: " + endPoint) - - try { - def aaiRequestId = UUID.randomUUID().toString() - logDebug('sending GET to AAI endpoint \'' + endPoint + '\'', isDebugLogEnabled) - APIResponse response = aaiUriUtil.executeAAIGetCall(execution, endPoint) - utils.logAudit("createVfModule - invoking httpGet() to AAI") - - def responseData = response.getResponseBodyAsString() - if (responseData != null) { - logDebug("Received generic VNF data: " + responseData, isDebugLogEnabled) - - } - - utils.logAudit("createVfModule - queryAAIVfModule Response: " + responseData) - utils.logAudit("createVfModule - queryAAIVfModule ResponseCode: " + response.getStatusCode()) - - execution.setVariable('DOUPVfMod_queryAAIVfModuleResponseCode', response.getStatusCode()) - execution.setVariable('DOUPVfMod_queryAAIVfModuleResponse', responseData) - logDebug('Response code:' + response.getStatusCode(), isDebugLogEnabled) - logDebug('Response:' + System.lineSeparator() + responseData, isDebugLogEnabled) - if (response.getStatusCode() == 200) { - // Parse the VNF record from A&AI to find base module info - logDebug('Parsing the VNF data to find base module info', isDebugLogEnabled) - if (responseData != null) { - def vfModulesText = utils.getNodeXml(responseData, "vf-modules") - def xmlVfModules= new XmlSlurper().parseText(vfModulesText) - def vfModules = xmlVfModules.'**'.findAll {it.name() == "vf-module"} - int vfModulesSize = 0 - for (i in 0..vfModules.size()-1) { - def vfModuleXml = groovy.xml.XmlUtil.serialize(vfModules[i]) - def isBaseVfModule = utils.getNodeText(vfModuleXml, "is-base-vf-module") - - if (isBaseVfModule == "true") { - String baseModuleId = utils.getNodeText1(vfModuleXml, "vf-module-id") - execution.setVariable("DOUPVfMod_baseVfModuleId", baseModuleId) - logDebug('Received baseVfModuleId: ' + baseModuleId, isDebugLogEnabled) - String baseModuleHeatStackId = utils.getNodeText1(vfModuleXml, "heat-stack-id") - execution.setVariable("DOUPVfMod_baseVfModuleHeatStackId", baseModuleHeatStackId) - logDebug('Received baseVfModuleHeatStackId: ' + baseModuleHeatStackId, isDebugLogEnabled) - } - } - } - } - } catch (Exception ex) { - ex.printStackTrace() - logDebug('Exception occurred while executing AAI GET:' + ex.getMessage(),isDebugLogEnabled) - exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'AAI GET Failed:' + ex.getMessage()) - } - logDebug('Exited ' + method, isDebugLogEnabled) - } catch (BpmnError e) { - throw e; - } catch (Exception e) { - logError('Caught exception in ' + method, e) - exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in queryAAIVfModule(): ' + e.getMessage()) - } - } - - -} +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.bpmn.infrastructure.scripts + +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.runtime.Execution +import org.openecomp.mso.bpmn.common.scripts.AaiUtil +import org.openecomp.mso.bpmn.common.scripts.ExceptionUtil +import org.openecomp.mso.bpmn.common.scripts.NetworkUtils +import org.openecomp.mso.bpmn.common.scripts.SDNCAdapterUtils +import org.openecomp.mso.bpmn.common.scripts.VfModule +import org.openecomp.mso.bpmn.common.scripts.VfModuleBase +import org.openecomp.mso.bpmn.core.WorkflowException +import org.openecomp.mso.bpmn.core.json.JsonUtils; +import org.openecomp.mso.rest.APIResponse +import org.springframework.web.util.UriUtils + +public class DoUpdateVfModule extends VfModuleBase { + + ExceptionUtil exceptionUtil = new ExceptionUtil() + JsonUtils jsonUtil = new JsonUtils() + + /** + * Initialize the flow's variables. + * + * @param execution The flow's execution instance. + */ + public void initProcessVariables(Execution execution) { + execution.setVariable('prefix', 'DOUPVfMod_') + execution.setVariable('DOUPVfMod_requestInfo', null) + execution.setVariable('DOUPVfMod_serviceInstanceId', null) + execution.setVariable('DOUPVfMod_requestId', null) + execution.setVariable('DOUPVfMod_vnfInputs', null) + execution.setVariable('DOUPVfMod_vnfId', null) + execution.setVariable('DOUPVfMod_vnfName', null) + execution.setVariable('DOUPVfMod_vnfNameFromAAI', null) + execution.setVariable('DOUPVfMod_vfModuleName', null) + execution.setVariable('DOUPVfMod_vfModuleId', null) + execution.setVariable('DOUPVfMod_vnfType', null) + execution.setVariable('DOUPVfMod_asdcServiceModelVersion', null) + execution.setVariable('DOUPVfMod_vfModuleModelName', null) + execution.setVariable('DOUPVfMod_modelCustomizationUuid', null) + execution.setVariable("DOUPVfMod_isBaseVfModule", "false") + execution.setVariable('DOUPVfMod_serviceId', null) + execution.setVariable('DOUPVfMod_aicCloudRegion', null) + execution.setVariable('DOUPVfMod_tenantId', null) + execution.setVariable('DOUPVfMod_volumeGroupId', null) + execution.setVariable('DOUPVfMod_vfModule', null) + execution.setVariable('DOUPVfMod_vnfParams', null) + execution.setVariable("DOUPVfMod_baseVfModuleId", "") + execution.setVariable("DOUPVfMod_baseVfModuleHeatStackId", "") + execution.setVariable('DOUPVfMod_prepareUpdateAAIVfModuleRequest', null) + execution.setVariable('DOUPVfMod_sdncChangeAssignRequest', null) + execution.setVariable('DOUPVfMod_sdncChangeAssignResponse', null) + execution.setVariable('DOUPVfMod_sdncActivateRequest', null) + execution.setVariable('DOUPVfMod_sdncActivateResponse', null) + execution.setVariable('DOUPVfMod_sdncTopologyRequest', null) + execution.setVariable('DOUPVfMod_sdncTopologyResponse', null) + execution.setVariable('DOUPVfMod_vnfAdapterRestRequest', null) + execution.setVariable('DOUPVfMod_updateAAIGenericVnfRequest', null) + execution.setVariable('DOUPVfMod_updateAAIVfModuleRequest', null) + execution.setVariable('DOUPVfMod_skipUpdateGenericVnf', false) + execution.setVariable('DoUpdateVfModuleSuccessIndicator', false) + } + + /** + * Check for missing elements in the received request. + * + * @param execution The flow's execution instance. + */ + public void preProcessRequest(Execution execution) { + def method = getClass().getSimpleName() + '.preProcessRequest(' + + 'execution=' + execution.getId() + + ')' + def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') + logDebug('Entered ' + method, isDebugLogEnabled) + + try { + initProcessVariables(execution) + def xml = getVariable(execution, 'DoUpdateVfModuleRequest') + utils.logAudit("DoUpdateVfModule request: " + xml) + logDebug('Received request xml:\n' + xml, isDebugLogEnabled) + + if (xml == null || xml.isEmpty()) { + // Building Block-type request + + String cloudConfiguration = execution.getVariable("cloudConfiguration") + String vfModuleModelInfo = execution.getVariable("vfModuleModelInfo") + + def serviceModelInfo = execution.getVariable("serviceModelInfo") + logDebug("serviceModelInfo: " + serviceModelInfo, isDebugLogEnabled) + def vnfModelInfo = execution.getVariable("vnfModelInfo") + + + //tenantId + def tenantId = jsonUtil.getJsonValue(cloudConfiguration, "cloudConfiguration.tenantId") + execution.setVariable("DOUPVfMod_tenantId", tenantId) + + //volumeGroupId + def volumeGroupId = execution.getVariable("volumeGroupId") + execution.setVariable("DOUPVfMod_volumeGroupId", volumeGroupId) + //volumeGroupName + def volumeGroupName = execution.getVariable("volumeGroupName") + execution.setVariable("DOUPVfMod_volumeGroupName", volumeGroupName) + //cloudSiteId + def cloudSiteId = jsonUtil.getJsonValue(cloudConfiguration, "cloudConfiguration.lcpCloudRegionId") + execution.setVariable("DOUPVfMod_cloudSiteId", cloudSiteId) + + logDebug("cloudSiteId: " + cloudSiteId, isDebugLogEnabled) + //vnfType + def vnfType = execution.getVariable("vnfType") + execution.setVariable("DOUPVfMod_vnfType", vnfType) + + logDebug("vnfType: " + vnfType, isDebugLogEnabled) + //vnfName + def vnfName = execution.getVariable("vnfName") + execution.setVariable("DOUPVfMod_vnfName", vnfName) + + logDebug("vnfName: " + vnfName, isDebugLogEnabled) + //vnfId + def vnfId = execution.getVariable("vnfId") + execution.setVariable("DOUPVfMod_vnfId", vnfId) + + logDebug("vnfId: " + vnfId, isDebugLogEnabled) + //vfModuleName + def vfModuleName = execution.getVariable("vfModuleName") + execution.setVariable("DOUPVfMod_vfModuleName", vfModuleName) + + logDebug("vfModuleName: " + vfModuleName, isDebugLogEnabled) + //vfModuleModelName + def vfModuleModelName = jsonUtil.getJsonValue(vfModuleModelInfo, "modelName") + execution.setVariable("DOUPVfMod_vfModuleModelName", vfModuleModelName) + + logDebug("vfModuleModelName: " + vfModuleModelName, isDebugLogEnabled) + //modelCustomizationUuid + def modelCustomizationUuid = jsonUtil.getJsonValue(vfModuleModelInfo, "modelCustomizationId") + execution.setVariable("DOUPVfMod_modelCustomizationUuid", modelCustomizationUuid) + + logDebug("modelCustomizationUuid: " + modelCustomizationUuid, isDebugLogEnabled) + //vfModuleId + def vfModuleId = execution.getVariable("vfModuleId") + execution.setVariable("DOUPVfMod_vfModuleId", vfModuleId) + logDebug("vfModuleId: " + vfModuleId, isDebugLogEnabled) + def requestId = execution.getVariable("requestId") + execution.setVariable("DOUPVfMod_requestId", requestId) + logDebug("requestId: " + requestId, isDebugLogEnabled) + // Set mso-request-id to request-id for VNF Adapter interface + execution.setVariable("mso-request-id", requestId) + //serviceId + def serviceId = execution.getVariable("serviceId") + execution.setVariable("DOUPVfMod_serviceId", serviceId) + logDebug("serviceId: " + serviceId, isDebugLogEnabled) + //serviceInstanceId + def serviceInstanceId = execution.getVariable("serviceInstanceId") + execution.setVariable("DOUPVfMod_serviceInstanceId", serviceInstanceId) + + logDebug("serviceInstanceId: " + serviceInstanceId, isDebugLogEnabled) + //source - HARDCODED + def source = "VID" + execution.setVariable("DOUPVfMod_source", source) + + logDebug("source: " + source, isDebugLogEnabled) + //backoutOnFailure + def disableRollback = execution.getVariable("disableRollback") + def backoutOnFailure = true + if (disableRollback != null && disableRollback.equals("true")) { + backoutOnFailure = false + } + execution.setVariable("DOUPVfMod_backoutOnFailure", backoutOnFailure) + logDebug("backoutOnFailure: " + backoutOnFailure, isDebugLogEnabled) + //isBaseVfModule + def isBaseVfModule = execution.getVariable("isBaseVfModule") + execution.setVariable("DOUPVfMod_isBaseVfModule", isBaseVfModule) + logDebug("isBaseVfModule: " + isBaseVfModule, isDebugLogEnabled) + //asdcServiceModelVersion + def asdcServiceModelVersion = execution.getVariable("asdcServiceModelVersion") + execution.setVariable("DOUPVfMod_asdcServiceModelVersion", asdcServiceModelVersion) + logDebug("asdcServiceModelVersion: " + asdcServiceModelVersion, isDebugLogEnabled) + //personaModelId + execution.setVariable("DOUPVfMod_personaModelId", jsonUtil.getJsonValue(vfModuleModelInfo, "modelInvariantId")) + //personaModelVersion + execution.setVariable("DOUPVfMod_personaModelVersion", jsonUtil.getJsonValue(vfModuleModelInfo, "modelVersion")) + //Get or Generate UUID + String uuid = execution.getVariable("DOUPVfMod_uuid") + if(uuid == null){ + uuid = UUID.randomUUID() + logDebug("Generated messageId (UUID) is: " + uuid, isDebugLogEnabled) + }else{ + logDebug("Found messageId (UUID) is: " + uuid, isDebugLogEnabled) + } + //isVidRequest + String isVidRequest = execution.getVariable("isVidRequest") + // default to true + if (isVidRequest == null || isVidRequest.isEmpty()) { + execution.setVariable("isVidRequest", "true") + } + //globalSubscriberId + String globalSubscriberId = execution.getVariable("globalSubscriberId") + execution.setVariable("DOUPVfMod_globalSubscriberId", globalSubscriberId) + logDebug("globalSubsrciberId: " + globalSubscriberId, isDebugLogEnabled) + //vnfQueryPath + String vnfQueryPath = execution.getVariable("vnfQueryPath") + execution.setVariable("DOUPVfMod_vnfQueryPath", vnfQueryPath) + logDebug("vnfQueryPath: " + vnfQueryPath, isDebugLogEnabled) + + String vnfParamsChildNodes = execution.getVariable("vfModuleInputParams") + execution.setVariable('DOUPVfMod_vnfParams', vnfParamsChildNodes) + } + else { + + def requestInfo = getRequiredNodeXml(execution, xml, 'request-info') + execution.setVariable('DOUPVfMod_requestInfo', requestInfo) + execution.setVariable('DOUPVfMod_requestId', getRequiredNodeText(execution, requestInfo, 'request-id')) + def serviceInstanceId = execution.getVariable('mso-service-instance-id') + if (serviceInstanceId == null) { + serviceInstanceId = '' + } + execution.setVariable('DOUPVfMod_serviceInstanceId', serviceInstanceId) + + def vnfInputs = getRequiredNodeXml(execution, xml, 'vnf-inputs') + execution.setVariable('DOUPVfMod_vnfInputs', vnfInputs) + execution.setVariable('DOUPVfMod_vnfId', getRequiredNodeText(execution, vnfInputs, 'vnf-id')) + execution.setVariable('DOUPVfMod_vfModuleId', getRequiredNodeText(execution, vnfInputs, 'vf-module-id')) + execution.setVariable('DOUPVfMod_vfModuleName', getNodeTextForce(vnfInputs, 'vf-module-name')) + execution.setVariable('DOUPVfMod_vnfType', getNodeTextForce(vnfInputs, 'vnf-type')) + execution.setVariable('DOUPVfMod_vnfName', getNodeTextForce(vnfInputs, 'vnf-name')) + execution.setVariable('DOUPVfMod_asdcServiceModelVersion', getNodeTextForce(vnfInputs, 'asdc-service-model-version')) + execution.setVariable('DOUPVfMod_vfModuleModelName', getRequiredNodeText(execution, vnfInputs, 'vf-module-model-name')) + execution.setVariable('DOUPVfMod_modelCustomizationUuid', getNodeTextForce(vnfInputs, 'model-customization-id')) + execution.setVariable('DOUPVfMod_serviceId', getRequiredNodeText(execution, vnfInputs, 'service-id')) + execution.setVariable('DOUPVfMod_aicCloudRegion', getRequiredNodeText(execution, vnfInputs, 'aic-cloud-region')) + execution.setVariable('DOUPVfMod_tenantId', getRequiredNodeText(execution, vnfInputs, 'tenant-id')) + //isBaseVfModule + def isBaseVfModule = "false" + if (utils.nodeExists(xml, "is-base-vf-module")) { + isBaseVfModule = utils.getNodeText(xml, "is-base-vf-module") + execution.setVariable("DOUPVfMod_isBaseVfModule", isBaseVfModule) + } + logDebug("isBaseVfModule: " + isBaseVfModule, isDebugLogEnabled) + + NetworkUtils networkUtils = new NetworkUtils() + def backoutOnFailure = networkUtils.isRollbackEnabled(execution, xml) + execution.setVariable("DOUPVfMod_backoutOnFailure", backoutOnFailure) + + def String vgi = getNodeTextForce(vnfInputs, 'volume-group-id') + execution.setVariable('DOUPVfMod_volumeGroupId', vgi) + + execution.setVariable('DOUPVfMod_vnfParams', utils.getNodeXml(xml, 'vnf-params', false)) + } + + def sdncCallbackUrl = (String) execution.getVariable('URN_mso_workflow_sdncadapter_callback') + if (sdncCallbackUrl == null || sdncCallbackUrl.trim().isEmpty()) { + def msg = 'Required variable \'URN_mso_workflow_sdncadapter_callback\' is missing' + logError(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg) + } + + logDebug('Exited ' + method, isDebugLogEnabled) + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + logError('Caught exception in ' + method, e) + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in preProcessRequest(): ' + e.getMessage()) + } + } + + /** + * Prepare a Request for invoking the PrepareUpdateAAIVfModule subflow. This will + * set the orchestration-status to 'pending-update'. + * + * @param execution The flow's execution instance. + */ + public void prepPrepareUpdateAAIVfModule(Execution execution) { + def method = getClass().getSimpleName() + '.preparePrepareUpdateAAIVfModule(' + + 'execution=' + execution.getId() + + ')' + def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') + logDebug('Entered ' + method, isDebugLogEnabled) + + try { + def vnfId = execution.getVariable('DOUPVfMod_vnfId') + def vfModuleId = execution.getVariable('DOUPVfMod_vfModuleId') + def orchestrationStatus = 'pending-update' + + String prepareUpdateAAIVfModuleRequest = """ + + ${vnfId} + ${vfModuleId} + ${orchestrationStatus} + + """ + prepareUpdateAAIVfModuleRequest = utils.formatXml(prepareUpdateAAIVfModuleRequest) + execution.setVariable('DOUPVfMod_prepareUpdateAAIVfModuleRequest', prepareUpdateAAIVfModuleRequest) + utils.logAudit("DoUpdateAAIVfModule request: " + prepareUpdateAAIVfModuleRequest) + logDebug('Request for PrepareUpdateAAIVfModule:\n' + prepareUpdateAAIVfModuleRequest, isDebugLogEnabled) + + logDebug('Exited ' + method, isDebugLogEnabled) + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + logError('Caught exception in ' + method, e) + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in preparePrepareUpdateAAIVfModule(): ' + e.getMessage()) + } + } + + /** + * Prepare a Request for invoking the ConfirmVolumeGroupTenant subflow. Currently, + * there is really nothing to do, so we just log that we're passing through. + * + * @param execution The flow's execution instance. + */ + public void prepConfirmVolumeGroupTenant(Execution execution) { + def method = getClass().getSimpleName() + '.prepConfirmVolumeGroupTenant(' + + 'execution=' + execution.getId() + + ')' + def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') + logDebug('Entered ' + method, isDebugLogEnabled) + + try { + // Nothing to do - just log that we're passing through here + + logDebug('Exited ' + method, isDebugLogEnabled) + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + logError('Caught exception in ' + method, e) + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in prepConfirmVolumeGroupTenant(): ' + e.getMessage()) + } + } + + /** + * Prepare a Request for invoking the SDNC Adapter subflow to perform + * a VNF topology 'changeassign' operation. + * + * @param execution The flow's execution instance. + */ + public void prepSDNCTopologyChg(Execution execution) { + def method = getClass().getSimpleName() + '.prepSDNCTopologyChg(' + + 'execution=' + execution.getId() + + ')' + def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') + logDebug('Entered ' + method, isDebugLogEnabled) + + try { + def requestId = execution.getVariable('DOUPVfMod_requestId') + def serviceInstanceId = execution.getVariable('DOUPVfMod_serviceInstanceId') + def callbackUrl = (String) execution.getVariable('URN_mso_workflow_sdncadapter_callback') + def serviceId = execution.getVariable('DOUPVfMod_serviceId') + def vnfId = execution.getVariable('DOUPVfMod_vnfId') + def vnfType = execution.getVariable('DOUPVfMod_vnfType') + def vfModuleId = execution.getVariable('DOUPVfMod_vfModuleId') + def vfModuleModelName = execution.getVariable('DOUPVfMod_vfModuleModelName') + def VfModule vfModule = (VfModule) execution.getVariable('DOUPVfMod_vfModule') + def vfModuleName = vfModule.getElementText('vf-module-name') + def tenantId = execution.getVariable('DOUPVfMod_tenantId') + def aicCloudRegion = execution.getVariable('DOUPVfMod_aicCloudRegion') + + // Retrieve vnf name from AAI response + def vnfName = execution.getVariable('DOUPVfMod_vnfNameFromAAI') + execution.setVariable('DOUPVfMod_vnfName', vnfName) + + def vnfParamsXml = execution.getVariable('DOUPVfMod_vnfParams') + def vnfNetworks = transformNetworkParamsToVnfNetworks(vnfParamsXml) + + String sdncTopologyRequest = """ + + + ${requestId} + ${serviceInstanceId} + changeassign + vnf-topology-operation + ${callbackUrl} + + + + ${requestId} + ChangeVNFActivateRequest + PORTAL + + + + + + ${serviceId} + ${vnfId} + dontcare + + + ${vfModuleId} + ${vfModuleModelName} + ${vfModuleName} + ${vnfId} + ${vnfName} + ${vnfType} + ${tenantId} + ${aicCloudRegion} + ${vnfNetworks} + + + + """ + sdncTopologyRequest = utils.formatXml(sdncTopologyRequest) + execution.setVariable('DOUPVfMod_sdncChangeAssignRequest', sdncTopologyRequest) + utils.logAudit("sdncChangeAssignRequest : " + sdncTopologyRequest) + logDebug('Request for SDNCAdapter topology/changeassign:\n' + sdncTopologyRequest, isDebugLogEnabled) + + logDebug('Exited ' + method, isDebugLogEnabled) + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + logError('Caught exception in ' + method, e) + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in prepSDNCTopologyChg(): ' + e.getMessage()) + } + } + + /** + * Prepare a Request for invoking the SDNC Adapter subflow to perform + * a VNF topology 'query' operation. + * + * @param execution The flow's execution instance. + */ + public void prepSDNCTopologyQuery(Execution execution) { + def method = getClass().getSimpleName() + '.prepSDNCTopologyQuery(' + + 'execution=' + execution.getId() + + ')' + def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') + logDebug('Entered ' + method, isDebugLogEnabled) + + try { + def requestId = execution.getVariable('DOUPVfMod_requestId') + def serviceInstanceId = execution.getVariable('DOUPVfMod_serviceInstanceId') + def callbackUrl = (String) execution.getVariable('URN_mso_workflow_sdncadapter_callback') + def vfModuleId = execution.getVariable('DOUPVfMod_vfModuleId') + + def svcInstId = "" + if (serviceInstanceId == null || serviceInstanceId.isEmpty()) { + svcInstId = vfModuleId + } + else { + svcInstId = serviceInstanceId + } + + //!!!! TEMPORARY WORKAROUND FOR SDNC REPLICATION ISSUE + sleep(5000) + + String sdncTopologyRequest = """ + + + ${requestId} + ${svcInstId} + query + /VNF-API:vnfs/vnf-list/${vfModuleId} + ${callbackUrl} + mobility + + + """ + sdncTopologyRequest = utils.formatXml(sdncTopologyRequest) + execution.setVariable('DOUPVfMod_sdncTopologyRequest', sdncTopologyRequest) + utils.logAudit("sdncTopologyRequest : " + sdncTopologyRequest) + logDebug('Request for SDNCAdapter query:\n' + sdncTopologyRequest, isDebugLogEnabled) + + logDebug('Exited ' + method, isDebugLogEnabled) + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + logError('Caught exception in ' + method, e) + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in prepSDNCTopologyQuery(): ' + e.getMessage()) + } + } + + /** + * Prepare a Request for invoking the VnfAdapterRest subflow. + * + * @param execution The flow's execution instance. + */ + public void prepVnfAdapterRest(Execution execution) { + def method = getClass().getSimpleName() + '.prepVnfAdapterRest(' + + 'execution=' + execution.getId() + + ')' + def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') + logDebug('Entered ' + method, isDebugLogEnabled) + + try { + def requestId = execution.getVariable('DOUPVfMod_requestId') + def serviceInstanceId = execution.getVariable('DOUPVfMod_serviceInstanceId') + def vnfId = execution.getVariable('DOUPVfMod_vnfId') + def vfModuleId = execution.getVariable('DOUPVfMod_vfModuleId') + def vfModuleName = execution.getVariable('DOUPVfMod_vfModuleName') + def vnfInputs = execution.getVariable('DOUPVfMod_vnfInputs') + def tenantId = execution.getVariable('DOUPVfMod_tenantId') + def volumeGroupId = execution.getVariable('DOUPVfMod_volumeGroupId') + def VfModule vfModule = (VfModule) execution.getVariable('DOUPVfMod_vfModule') + def heatStackId = vfModule.getElementText('heat-stack-id') + def cloudId = execution.getVariable('DOUPVfMod_aicCloudRegion') + def vnfType = execution.getVariable('DOUPVfMod_vnfType') + def vnfName = execution.getVariable('DOUPVfMod_vnfName') + def vfModuleModelName = execution.getVariable('DOUPVfMod_vfModuleModelName') + def baseVfModuleId = execution.getVariable("DOUPVfMod_baseVfModuleId") + def baseVfModuleStackId = execution.getVariable("DOUPVfMod_baseVfModuleHeatStackId") + def asdcServiceModelVersion = execution.getVariable('DOUPVfMod_asdcServiceModelVersion') + def modelCustomizationUuid = execution.getVariable('DOUPVfMod_modelCustomizationUuid') + def backoutOnFailure = execution.getVariable("DOUPVfMod_backoutOnFailure") + + def vnfParamsXml = execution.getVariable('DOUPVfMod_vnfParams') + def vfModuleParamsEntries = transformParamsToEntries(vnfParamsXml) + + def messageId = execution.getVariable('mso-request-id') + '-' + System.currentTimeMillis() + def notificationUrl = createCallbackURL(execution, "VNFAResponse", messageId) + def useQualifiedHostName = execution.getVariable("URN_mso_use_qualified_host") + if ('true'.equals(useQualifiedHostName)) { + notificationUrl = utils.getQualifiedHostNameForCallback(notificationUrl) + } + + String sdncGetResponse = execution.getVariable('DOUPVfMod_sdncTopologyResponse') + + String vfModuleParams = buildVfModuleParams(vfModuleParamsEntries, sdncGetResponse, vnfId, vnfName, + vfModuleId, vfModuleName, null) + + + String vnfAdapterRestRequest = """ + + ${cloudId} + ${tenantId} + ${vnfId} + ${vfModuleId} + ${heatStackId} + ${vnfType} + ${asdcServiceModelVersion} + ${modelCustomizationUuid} + ${vfModuleModelName} + ${volumeGroupId} + ${baseVfModuleId} + ${baseVfModuleStackId} + true + ${backoutOnFailure} + false + + ${vfModuleParams} + + + ${requestId} + ${serviceInstanceId} + + ${messageId} + ${notificationUrl} + + """ + vnfAdapterRestRequest = utils.formatXml(vnfAdapterRestRequest) + execution.setVariable('DOUPVfMod_vnfAdapterRestRequest', vnfAdapterRestRequest) + utils.logAudit("vnfAdapterRestRequest : " + vnfAdapterRestRequest) + logDebug('Request for VNFAdapter Rest:\n' + vnfAdapterRestRequest, isDebugLogEnabled) + + logDebug('Exited ' + method, isDebugLogEnabled) + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + logError('Caught exception in ' + method, e) + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in prepVnfAdapterRest(): ' + e.getMessage()) + } + } + + /** + * Prepare a Request for invoking the UpdateAAIGenericVnf subflow. + * + * @param execution The flow's execution instance. + */ + public void prepUpdateAAIGenericVnf(Execution execution) { + def method = getClass().getSimpleName() + '.prepUpdateAAIGenericVnf(' + + 'execution=' + execution.getId() + + ')' + def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') + logDebug('Entered ' + method, isDebugLogEnabled) + + try { + def vnfId = execution.getVariable('DOUPVfMod_vnfId') + def vnfInputs = execution.getVariable('DOUPVfMod_vnfInputs') + + def personaModelId = utils.getNodeText1(vnfInputs, 'vnf-persona-model-id') + def personaModelVersion = utils.getNodeText1(vnfInputs, 'vnf-persona-model-version') + if ((personaModelId == null) || (personaModelVersion == null)) { + logDebug('Skipping update for Generic VNF ' + vnfId + + ' because either \'vnf-persona-model-id\' or \'vnf-persona-model-version\' is absent', isDebugLogEnabled) + execution.setVariable('DOUPVfMod_skipUpdateGenericVnf', true) + } else { + def personaModelIdElement = '' + personaModelId + '' + def personaModelVersionElement = '' + personaModelVersion + '' + + String updateAAIGenericVnfRequest = """ + + ${vnfId} + ${personaModelIdElement} + ${personaModelVersionElement} + + """ + updateAAIGenericVnfRequest = utils.formatXml(updateAAIGenericVnfRequest) + execution.setVariable('DOUPVfMod_updateAAIGenericVnfRequest', updateAAIGenericVnfRequest) + utils.logAudit("updateAAIGenericVnfRequest : " + updateAAIGenericVnfRequest) + logDebug('Request for UpdateAAIGenericVnf:\n' + updateAAIGenericVnfRequest, isDebugLogEnabled) + } + + logDebug('Exited ' + method, isDebugLogEnabled) + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + logError('Caught exception in ' + method, e) + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in prepUpdateAAIGenericVnf(): ' + e.getMessage()) + } + } + + /** + * Prepare a Request for invoking the UpdateAAIVfModule subflow. + * + * @param execution The flow's execution instance. + */ + public void prepUpdateAAIVfModule(Execution execution) { + def method = getClass().getSimpleName() + '.prepUpdateAAIVfModule(' + + 'execution=' + execution.getId() + + ')' + def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') + logDebug('Entered ' + method, isDebugLogEnabled) + + try { + def vnfId = execution.getVariable('DOUPVfMod_vnfId') + def vfModuleId = execution.getVariable('DOUPVfMod_vfModuleId') + def orchestrationStatus = 'updated' + def vnfInputs = execution.getVariable('DOUPVfMod_vnfInputs') + + def volumeGroupIdElement = '' + def volumeGroupId = execution.getVariable('DOUPVfMod_volumeGroupId') + if (volumeGroupId != null) { + volumeGroupIdElement = '' + volumeGroupId + '' + } + def personaModelIdElement = '' + def personaModelId = utils.getNodeText1(vnfInputs, 'persona-model-id') + if (personaModelId != null) { + personaModelIdElement = '' + personaModelId + '' + } + def personaModelVersionElement = '' + def personaModelVersion = utils.getNodeText1(vnfInputs, 'persona-model-version') + if (personaModelVersion != null) { + personaModelVersionElement = '' + personaModelVersion + '' + } + def contrailServiceInstanceFqdnElement = '' + def contrailServiceInstanceFqdn = utils.getNodeText1(vnfInputs, 'contrail-service-instance-fqdn') + if (contrailServiceInstanceFqdn != null) { + contrailServiceInstanceFqdnElement = '' + contrailServiceInstanceFqdn + '' + } + def personaModelCustomizationIdElement = '' + def modelCustomizationId = execution.getVariable('DOUPVfMod_modelCustomizationUuid') + if (modelCustomizationId != null) { + personaModelCustomizationIdElement = '' + modelCustomizationId + '' + } + + String updateAAIVfModuleRequest = """ + + ${vnfId} + ${vfModuleId} + ${orchestrationStatus} + ${volumeGroupIdElement} + ${personaModelIdElement} + ${personaModelVersionElement} + ${contrailServiceInstanceFqdnElement} + ${personaModelCustomizationIdElement} + + """ + updateAAIVfModuleRequest = utils.formatXml(updateAAIVfModuleRequest) + execution.setVariable('DOUPVfMod_updateAAIVfModuleRequest', updateAAIVfModuleRequest) + utils.logAudit("updateAAIVfModuleRequest : " + updateAAIVfModuleRequest) + logDebug('Request for UpdateAAIVfModule:\n' + updateAAIVfModuleRequest, isDebugLogEnabled) + + logDebug('Exited ' + method, isDebugLogEnabled) + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + logError('Caught exception in ' + method, e) + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in prepUpdateAAIVfModule(): ' + e.getMessage()) + } + } + + /** + * Prepare a Request for invoking the SDNC Adapter subflow to perform + * a VNF topology 'activate' operation. + * + * @param execution The flow's execution instance. + */ + public void prepSDNCTopologyAct(Execution execution) { + def method = getClass().getSimpleName() + '.prepSDNCTopologyAct(' + + 'execution=' + execution.getId() + + ')' + def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') + logDebug('Entered ' + method, isDebugLogEnabled) + + try { + def requestId = execution.getVariable('DOUPVfMod_requestId') + def serviceInstanceId = execution.getVariable('DOUPVfMod_serviceInstanceId') + def callbackUrl = (String) execution.getVariable('URN_mso_workflow_sdncadapter_callback') + def serviceId = execution.getVariable('DOUPVfMod_serviceId') + def vnfId = execution.getVariable('DOUPVfMod_vnfId') + def vnfName = execution.getVariable('DOUPVfMod_vnfName') + def vnfType = execution.getVariable('DOUPVfMod_vnfType') + def vfModuleId = execution.getVariable('DOUPVfMod_vfModuleId') + def vfModuleModelName = execution.getVariable('DOUPVfMod_vfModuleModelName') + def VfModule vfModule = (VfModule) execution.getVariable('DOUPVfMod_vfModule') + def vfModuleName = vfModule.getElementText('vf-module-name') + def tenantId = execution.getVariable('DOUPVfMod_tenantId') + def aicCloudRegion = execution.getVariable('DOUPVfMod_aicCloudRegion') + + def vnfParamsXml = execution.getVariable('DOUPVfMod_vnfParams') + def vnfNetworks = transformNetworkParamsToVnfNetworks(vnfParamsXml) + + String sdncTopologyRequest = """ + + + ${requestId} + ${serviceInstanceId} + activate + vnf-topology-operation + ${callbackUrl} + + + + ${requestId} + ChangeVNFActivateRequest + PORTAL + + + + + + ${serviceId} + ${vnfId} + dontcare + + + ${vfModuleId} + ${vfModuleModelName} + ${vfModuleName} + ${vnfId} + ${vnfName} + ${vnfType} + ${tenantId} + ${aicCloudRegion} + + + + """ + sdncTopologyRequest = utils.formatXml(sdncTopologyRequest) + execution.setVariable('DOUPVfMod_sdncActivateRequest', sdncTopologyRequest) + utils.logAudit("sdncActivateRequest : " + sdncTopologyRequest) + logDebug('Request for SDNCAdapter topology/activate:\n' + sdncTopologyRequest, isDebugLogEnabled) + + + logDebug('Exited ' + method, isDebugLogEnabled) + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + logError('Caught exception in ' + method, e) + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in prepSDNCTopologyAct(): ' + e.getMessage()) + } + } + + /** + * Log a WorkflowException that has been created. + * + * @param execution The flow's execution instance. + */ + public void handleWorkflowException(Execution execution) { + def method = getClass().getSimpleName() + '.handleWorkflowException(' + + 'execution=' + execution.getId() + + ')' + def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') + logDebug('Entered ' + method, isDebugLogEnabled) + + try { + def WorkflowException workflowException = (WorkflowException) execution.getVariable('WorkflowException') + logError(method + ' caught WorkflowException: ' + workflowException.getErrorMessage()) + + logDebug('Exited ' + method, isDebugLogEnabled) + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + logError('Caught exception in ' + method, e) + exceptionUtil.buildWorkflowException(execution, 1002, 'Error in handleWorkflowException(): ' + e.getMessage()) + } + } + + public void validateSDNCResponse(Execution execution, String response, String method){ + def isDebugLogEnabled=execution.getVariable("isDebugLogEnabled") + def prefix = execution.getVariable("prefix") + + logDebug(" *** STARTED ValidateSDNCResponse Process*** ", isDebugLogEnabled) + + WorkflowException workflowException = execution.getVariable("WorkflowException") + boolean successIndicator = execution.getVariable("SDNCA_SuccessIndicator") + + utils.logAudit("workflowException: " + workflowException) + + SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils(this) + sdncAdapterUtils.validateSDNCResponse(execution, response, workflowException, successIndicator) + + utils.logAudit("SDNCResponse: " + response) + + String sdncResponse = response + if(execution.getVariable(prefix + 'sdncResponseSuccess') == true){ + logDebug("Received a Good Response from SDNC Adapter for " + method + " SDNC Call. Response is: \n" + sdncResponse, isDebugLogEnabled) + }else{ + logDebug("Received a BAD Response from SDNC Adapter for " + method + " SDNC Call.", isDebugLogEnabled) + throw new BpmnError("MSOWorkflowException") + } + logDebug(" *** COMPLETED ValidateSDNCResponse Process*** ", isDebugLogEnabled) + } + + /** + * Using the received vnfId and vfModuleId, query AAI to get the corresponding VNF info. + * A 200 response is expected with the VNF info in the response body. Will find out the base module info. + * + * @param execution The flow's execution instance. + */ + public void queryAAIVfModule(Execution execution) { + def isDebugLogEnabled=execution.getVariable("isDebugLogEnabled") + def method = getClass().getSimpleName() + '.getVfModule(' + + 'execution=' + execution.getId() + + ')' + logDebug('Entered ' + method, isDebugLogEnabled) + + try { + def vnfId = execution.getVariable('DOUPVfMod_vnfId') + def vfModuleId = execution.getVariable('DOUPVfMod_vfModuleId') + + AaiUtil aaiUriUtil = new AaiUtil(this) + String aai_uri = aaiUriUtil.getNetworkGenericVnfUri(execution) + logDebug('AAI URI is: ' + aai_uri, isDebugLogEnabled) + + String endPoint = execution.getVariable("URN_aai_endpoint") + "${aai_uri}/" + UriUtils.encode(vnfId, "UTF-8") + "?depth=1" + utils.logAudit("AAI endPoint: " + endPoint) + + try { + def aaiRequestId = UUID.randomUUID().toString() + logDebug('sending GET to AAI endpoint \'' + endPoint + '\'', isDebugLogEnabled) + APIResponse response = aaiUriUtil.executeAAIGetCall(execution, endPoint) + utils.logAudit("createVfModule - invoking httpGet() to AAI") + + def responseData = response.getResponseBodyAsString() + if (responseData != null) { + logDebug("Received generic VNF data: " + responseData, isDebugLogEnabled) + + } + + utils.logAudit("createVfModule - queryAAIVfModule Response: " + responseData) + utils.logAudit("createVfModule - queryAAIVfModule ResponseCode: " + response.getStatusCode()) + + execution.setVariable('DOUPVfMod_queryAAIVfModuleResponseCode', response.getStatusCode()) + execution.setVariable('DOUPVfMod_queryAAIVfModuleResponse', responseData) + logDebug('Response code:' + response.getStatusCode(), isDebugLogEnabled) + logDebug('Response:' + System.lineSeparator() + responseData, isDebugLogEnabled) + if (response.getStatusCode() == 200) { + // Parse the VNF record from A&AI to find base module info + logDebug('Parsing the VNF data to find base module info', isDebugLogEnabled) + if (responseData != null) { + def vfModulesText = utils.getNodeXml(responseData, "vf-modules") + def xmlVfModules= new XmlSlurper().parseText(vfModulesText) + def vfModules = xmlVfModules.'**'.findAll {it.name() == "vf-module"} + int vfModulesSize = 0 + for (i in 0..vfModules.size()-1) { + def vfModuleXml = groovy.xml.XmlUtil.serialize(vfModules[i]) + def isBaseVfModule = utils.getNodeText(vfModuleXml, "is-base-vf-module") + + if (isBaseVfModule == "true") { + String baseModuleId = utils.getNodeText1(vfModuleXml, "vf-module-id") + execution.setVariable("DOUPVfMod_baseVfModuleId", baseModuleId) + logDebug('Received baseVfModuleId: ' + baseModuleId, isDebugLogEnabled) + String baseModuleHeatStackId = utils.getNodeText1(vfModuleXml, "heat-stack-id") + execution.setVariable("DOUPVfMod_baseVfModuleHeatStackId", baseModuleHeatStackId) + logDebug('Received baseVfModuleHeatStackId: ' + baseModuleHeatStackId, isDebugLogEnabled) + } + } + } + } + } catch (Exception ex) { + ex.printStackTrace() + logDebug('Exception occurred while executing AAI GET:' + ex.getMessage(),isDebugLogEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'AAI GET Failed:' + ex.getMessage()) + } + logDebug('Exited ' + method, isDebugLogEnabled) + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + logError('Caught exception in ' + method, e) + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in queryAAIVfModule(): ' + e.getMessage()) + } + } + + +} diff --git a/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/HealchCheckActivate.groovy b/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/HealchCheckActivate.groovy index dd9f94d2f2..c2d394f02e 100644 --- a/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/HealchCheckActivate.groovy +++ b/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/HealchCheckActivate.groovy @@ -1,54 +1,54 @@ -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - MSO - * ================================================================================ - * 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.openecomp.mso.bpmn.infrastructure.scripts; - -import org.camunda.bpm.engine.delegate.BpmnError -import org.camunda.bpm.engine.runtime.Execution -import org.openecomp.mso.bpmn.common.scripts.AbstractServiceTaskProcessor; -import org.apache.commons.lang3.* - -public class HealthCheckActivate extends AbstractServiceTaskProcessor { - - - /** - * Validates the request message and sets up the workflow. - * @param execution the execution - */ - public void preProcessRequest(Execution execution) { - - } - - - /** - * Sends the synchronous response back to the API Handler. - * @param execution the execution - */ - public void sendResponse(Execution execution) { - def status = execution.getVariable("healthyStatus") - def healthcheckmessage = execution.getVariable("healthcheckmessage") - if (status == "true") { - sendWorkflowResponse(execution, 200, healthcheckmessage) - }else{ - sendWorkflowResponse(execution, 503, healthcheckmessage) - } - } - -} +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.bpmn.infrastructure.scripts; + +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.runtime.Execution +import org.openecomp.mso.bpmn.common.scripts.AbstractServiceTaskProcessor; +import org.apache.commons.lang3.* + +public class HealthCheckActivate extends AbstractServiceTaskProcessor { + + + /** + * Validates the request message and sets up the workflow. + * @param execution the execution + */ + public void preProcessRequest(Execution execution) { + + } + + + /** + * Sends the synchronous response back to the API Handler. + * @param execution the execution + */ + public void sendResponse(Execution execution) { + def status = execution.getVariable("healthyStatus") + def healthcheckmessage = execution.getVariable("healthcheckmessage") + if (status == "true") { + sendWorkflowResponse(execution, 200, healthcheckmessage) + }else{ + sendWorkflowResponse(execution, 503, healthcheckmessage) + } + } + +} diff --git a/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/UpdateNetworkInstance.groovy b/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/UpdateNetworkInstance.groovy new file mode 100644 index 0000000000..68b0e58b57 --- /dev/null +++ b/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/UpdateNetworkInstance.groovy @@ -0,0 +1,452 @@ +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.bpmn.infrastructure.scripts; + +import groovy.xml.XmlUtil +import groovy.json.* +import org.openecomp.mso.bpmn.common.scripts.AbstractServiceTaskProcessor +import org.openecomp.mso.bpmn.common.scripts.ExceptionUtil +import org.openecomp.mso.bpmn.core.WorkflowException +import org.openecomp.mso.bpmn.core.json.JsonUtils +import org.openecomp.mso.rest.APIResponse + +import java.util.UUID; + +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.runtime.Execution +import org.apache.commons.lang3.* +import org.apache.commons.codec.binary.Base64; +import org.springframework.web.util.UriUtils + +/** + * This groovy class supports the UpdateNetworkInstance.bpmn process. + * + */ +public class UpdateNetworkInstance extends AbstractServiceTaskProcessor { + String Prefix="UPDNI_" + ExceptionUtil exceptionUtil = new ExceptionUtil() + JsonUtils jsonUtil = new JsonUtils() + + public InitializeProcessVariables(Execution execution){ + + execution.setVariable(Prefix + "source", "") + execution.setVariable(Prefix + "Success", false) + + execution.setVariable(Prefix + "CompleteMsoProcessRequest", "") + execution.setVariable(Prefix + "FalloutHandlerRequest", "") + + } + + + /** + * This method is executed during the preProcessRequest task of the UpdateNetworkInstance.bpmn process. + * @param execution + */ + + // ************************************************** + // Pre or Prepare Request Section + // ************************************************** + /** + * This method is executed during the preProcessRequest task of the UpdateNetworkInstance.bpmn process. + * @param execution + */ + public void preProcessRequest (Execution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix",Prefix) + + utils.log("DEBUG", " ***** Inside preProcessRequest() of UpdateNetworkInstance Request ***** ", isDebugEnabled) + + try { + // initialize flow variables + InitializeProcessVariables(execution) + + String sdncVersion = execution.getVariable("sdncVersion") + if (sdncVersion == null || sdncVersion == "1610") { + // 'a-la-cart' default, sdncVersion = '1610' + execution.setVariable("sdncVersion", "1610") + String bpmnRequest = execution.getVariable("bpmnRequest") + if (bpmnRequest != null) { + String disableRollback = jsonUtil.getJsonValue(bpmnRequest, "requestDetails.requestInfo.suppressRollback") + if (disableRollback != null) { + execution.setVariable("disableRollback", disableRollback) + utils.log("DEBUG", "Received 'suppressRollback': " + disableRollback , isDebugEnabled) + } else { + execution.setVariable("disableRollback", false) + } + utils.log("DEBUG", " Set 'disableRollback' : " + execution.getVariable("disableRollback") , isDebugEnabled) + } else { + String dataErrorMessage = " Invalid 'bpmnRequest' request." + utils.log("DEBUG", dataErrorMessage, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) + } + + } else { + // 'macro' TEST ONLY, sdncVersion = '1702' + utils.log("DEBUG", " 'disableRollback' : " + execution.getVariable("disableRollback") , isDebugEnabled) + } + + // get/set 'msoRequestId' and 'mso-request-id' + String requestId = execution.getVariable("msoRequestId") + if (requestId != null) { + execution.setVariable("mso-request-id", requestId) + } else { + requestId = execution.getVariable("mso-request-id") + } + execution.setVariable(Prefix + "requestId", requestId) + + // get/set 'requestId' + if (execution.getVariable("requestId") == null) { + execution.setVariable("requestId", requestId) + } + + //Place holder for additional code. + + // TODO ??? + // userParams??? 1) pre-loads indicator, 2) 'auto-activation' + // Tag/Value parameters + // + // Map: 'networkInputParams': 'auto-activation'' + // Sample format? + // "requestParameters": { + // "userParams": [ + // { + // "name": "someUserParam1", + // "value": "someValue1" + // } + // ] + // } + // + // String userParams = //use json util to extract "userParams"// + // execution.setVariable("networkInputParams", userParams) + // else: execution.setVariable("networkInputParams", null) + // + + } catch (BpmnError e) { + throw e; + + } catch (Exception ex){ + sendSyncError(execution) + // caught exception + String exceptionMessage = "Exception Encountered in UpdateNetworkInstance, PreProcessRequest() - " + ex.getMessage() + utils.log("DEBUG", exceptionMessage, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + + } + } + + public void sendSyncResponse (Execution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix",Prefix) + + utils.log("DEBUG", " ***** Inside sendSyncResponse() of UpdateNetworkInstance ***** ", isDebugEnabled) + + try { + String requestId = execution.getVariable("mso-request-id") + String serviceInstanceId = execution.getVariable("serviceInstanceId") + + // RESTResponse (for API Handler (APIH) Reply Task) + String updateNetworkRestRequest = """{"requestReferences":{"instanceId":"${serviceInstanceId}","requestId":"${requestId}"}}""".trim() + + utils.log("DEBUG", " sendSyncResponse to APIH - " + "\n" + updateNetworkRestRequest, isDebugEnabled) + sendWorkflowResponse(execution, 202, updateNetworkRestRequest) + + } catch (Exception ex) { + String exceptionMessage = "Bpmn error encountered in UpdateNetworkInstance flow. sendSyncResponse() - " + ex.getMessage() + utils.log("DEBUG", exceptionMessage, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + } + + } + + + public void getNetworkModelInfo (Execution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix", Prefix) + + utils.log("DEBUG", " ***** Inside getNetworkModelInfo() of UpdateNetworkInstance ***** ", isDebugEnabled) + + try { + + // "networkModelInfo" is expected to be sent + String networkModelInfo = execution.getVariable("networkModelInfo") + utils.log("DEBUG", " networkModelInfo - " + networkModelInfo, isDebugEnabled) + + // "serviceModelInfo" is expected to be sent + String serviceModelInfo = execution.getVariable("serviceModelInfo") + utils.log("DEBUG", " serviceModelInfo - " + serviceModelInfo, isDebugEnabled) + + + } catch (Exception ex) { + sendSyncError(execution) + String exceptionMessage = "Bpmn error encountered in UpdateNetworkInstance flow. getNetworkModelInfo() - " + ex.getMessage() + utils.log("DEBUG", exceptionMessage, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + + } + + } + + + public void sendSyncError (Execution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix", Prefix) + + utils.log("DEBUG", " ***** Inside sendSyncError() of UpdateNetworkInstance ***** ", isDebugEnabled) + + try { + + String requestId = execution.getVariable("mso-request-id") + String serviceInstanceId = execution.getVariable("serviceInstanceId") + + // REST Error (for API Handler (APIH) Reply Task) + String syncError = """{"requestReferences":{"instanceId":"${serviceInstanceId}","requestId":"${requestId}"}}""".trim() + + sendWorkflowResponse(execution, 500, syncError) + + } catch (Exception ex) { + utils.log("DEBUG", " Bpmn error encountered in UpdateNetworkInstance flow. sendSyncError() - " + ex.getMessage(), isDebugEnabled) + } + + } + + public void prepareDBRequestError (Execution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix",Prefix) + + try { + utils.log("DEBUG", " ***** Inside prepareDBRequestError() of UpdateNetworkInstance ***** ", isDebugEnabled) + + String statusMessage = "" + WorkflowException wfe = null + if (execution.getVariable("WorkflowException") instanceof WorkflowException) { + wfe = execution.getVariable("WorkflowException") + statusMessage = wfe.getErrorMessage() + } + + String requestId = execution.getVariable(Prefix + "requestId") + String networkName = execution.getVariable("networkName") !=null ? execution.getVariable("networkName") : "" + String networkId = execution.getVariable("networkId") !=null ? execution.getVariable("networkId") : "" + String dbRequest = + """ + + + + ${requestId} + BPMN + ${statusMessage} + + FAILED + <network-id>${networkId}</network-id><network-name>${networkName}</network-names> + + + """ + + execution.setVariable(Prefix + "createDBRequest", dbRequest) + utils.log("DEBUG", " DB Adapter Request - " + "\n" + dbRequest, isDebugEnabled) + utils.logAudit(dbRequest) + + } catch (Exception ex) { + String exceptionMessage = " Bpmn error encountered in UpdateNetworkInstance flow. prepareDBRequestError() - " + ex.getMessage() + utils.log("DEBUG", exceptionMessage, isDebugEnabled) + exceptionUtil.buildWorkflowException(execution, 7000, exceptionMessage) + + } + + } + + public void prepareCompletion (Execution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix",Prefix) + + utils.log("DEBUG", " ***** Inside prepareCompletion() of UpdateNetworkInstance ***** ", isDebugEnabled) + + try { + + String requestId = execution.getVariable("mso-request-id") + String source = execution.getVariable(Prefix + "source") + + String msoCompletionRequest = + """ + + ${requestId} + UPDATE + VID + + Network has been updated successfully. + BPMN Network action: UPDATE + """ + + // Format Response + String xmlMsoCompletionRequest = utils.formatXml(msoCompletionRequest) + + // normal path + execution.setVariable(Prefix + "Success", true) + execution.setVariable(Prefix + "CompleteMsoProcessRequest", xmlMsoCompletionRequest) + utils.log("DEBUG", " Overall SUCCESS Response going to CompleteMsoProcess - " + "\n" + xmlMsoCompletionRequest, isDebugEnabled) + + } catch (Exception ex) { + String exceptionMessage = " Bpmn error encountered in UpdateNetworkInstance flow. prepareCompletion() - " + ex.getMessage() + utils.log("DEBUG", exceptionMessage, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + + } + + + } + + + + + // ************************************************** + // Post or Validate Response Section + // ************************************************** + + public void postProcessResponse (Execution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix", Prefix) + + utils.log("DEBUG", " ***** Inside postProcessResponse() of UpdateNetworkInstance ***** ", isDebugEnabled) + + try { + + if (execution.getVariable("CMSO_ResponseCode") == "200") { + execution.setVariable(Prefix + "Success", true) + utils.log("DEBUG", " ***** UpdateNetworkInstance Success ***** ", isDebugEnabled) + // Place holder for additional code. + + } else { + execution.setVariable(Prefix + "Success", false) + utils.log("DEBUG", " ***** UpdateNetworkInstance Failed in CompletionMsoProces flow!. ***** ", isDebugEnabled) + + } + + + } catch (Exception ex) { + String exceptionMessage = " Bpmn error encountered in UpdateNetworkInstance flow. postProcessResponse() - " + ex.getMessage() + utils.log("DEBUG", exceptionMessage, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + + } + + } + + + // ******************************* + // Build Error Section + // ******************************* + + public void processRollbackData (Execution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix", Prefix) + + utils.log("DEBUG", " ***** Inside processRollbackData() of UpdateNetworkInstance ***** ", isDebugEnabled) + + try { + //execution.getVariable("orchestrationStatus") + //execution.getVariable("networkId") + //execution.getVariable("networkName") + //networkOutputParams + //rollbackData + //rolledBack + + } catch (Exception ex) { + utils.log("DEBUG", " Bpmn error encountered in UpdateNetworkInstance flow. callDBCatalog() - " + ex.getMessage(), isDebugEnabled) + } + + } + + // Prepare for FalloutHandler + public void buildErrorResponse (Execution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix", Prefix) + + utils.log("DEBUG", " ***** Prepare for FalloutHandler. FAILURE - prepare request for sub-process FalloutHandler. *****", isDebugEnabled) + + String falloutHandlerRequest = "" + String requestId = execution.getVariable("mso-request-id") + + try { + WorkflowException wfe = execution.getVariable("WorkflowException") + String errorCode = String.valueOf(wfe.getErrorCode()) + String errorMessage = wfe.getErrorMessage() + falloutHandlerRequest = + """ + + ${requestId} + UPDATE + VID + + + ${errorMessage} + ${errorCode} + + """ + + utils.logAudit(falloutHandlerRequest) + execution.setVariable(Prefix + "FalloutHandlerRequest", falloutHandlerRequest) + utils.log("DEBUG", " Overall Error Response going to FalloutHandler: " + "\n" + falloutHandlerRequest, isDebugEnabled) + + } catch (Exception ex) { + String errorException = " Bpmn error encountered in UpdateNetworkInstance flow. FalloutHandlerRequest, buildErrorResponse() - " + ex.getMessage() + utils.log("DEBUG", errorException, isDebugEnabled) + falloutHandlerRequest = + """ + + ${requestId} + UPDATE + VID + + + ${errorException} + 7000 + + """ + + execution.setVariable(Prefix + "FalloutHandlerRequest", falloutHandlerRequest) + utils.log("DEBUG", " Overall Error Response going to FalloutHandler: " + "\n" + falloutHandlerRequest, isDebugEnabled) + + } + + } + + public void processJavaException(Execution execution){ + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix",Prefix) + try{ + utils.log("DEBUG", "Caught a Java Exception in " + Prefix, isDebugEnabled) + utils.log("DEBUG", "Started processJavaException Method", isDebugEnabled) + utils.log("DEBUG", "Variables List: " + execution.getVariables(), isDebugEnabled) + execution.setVariable("UnexpectedError", "Caught a Java Lang Exception - " + Prefix) // Adding this line temporarily until this flows error handling gets updated + exceptionUtil.buildWorkflowException(execution, 500, "Caught a Java Lang Exception") + + }catch(Exception e){ + utils.log("DEBUG", "Caught Exception during processJavaException Method: " + e, isDebugEnabled) + execution.setVariable("UnexpectedError", "Exception in processJavaException method - " + Prefix) // Adding this line temporarily until this flows error handling gets updated + exceptionUtil.buildWorkflowException(execution, 500, "Exception in processJavaException method" + Prefix) + } + utils.log("DEBUG", "Completed processJavaException Method in " + Prefix, isDebugEnabled) + } + +} diff --git a/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/UpdateNetworkInstanceInfra.groovy b/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/UpdateNetworkInstanceInfra.groovy index a682c4d463..5f0f65bd85 100644 --- a/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/UpdateNetworkInstanceInfra.groovy +++ b/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/UpdateNetworkInstanceInfra.groovy @@ -1,37 +1,37 @@ -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - MSO - * ================================================================================ - * 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========================================================= +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.bpmn.infrastructure.scripts; + +package org.openecomp.mso.bpmn.infrastructure.scripts; import groovy.xml.XmlUtil import groovy.json.* -import org.openecomp.mso.bpmn.common.scripts.AaiUtil; -import org.openecomp.mso.bpmn.common.scripts.AbstractServiceTaskProcessor; -import org.openecomp.mso.bpmn.common.scripts.ExceptionUtil; -import org.openecomp.mso.bpmn.common.scripts.NetworkUtils; -import org.openecomp.mso.bpmn.common.scripts.SDNCAdapterUtils; -import org.openecomp.mso.bpmn.common.scripts.VidUtils; -import org.openecomp.mso.bpmn.core.WorkflowException -import org.openecomp.mso.bpmn.core.json.JsonUtils; -import org.openecomp.mso.rest.APIResponse +import org.openecomp.mso.bpmn.common.scripts.AaiUtil; +import org.openecomp.mso.bpmn.common.scripts.AbstractServiceTaskProcessor; +import org.openecomp.mso.bpmn.common.scripts.ExceptionUtil; +import org.openecomp.mso.bpmn.common.scripts.NetworkUtils; +import org.openecomp.mso.bpmn.common.scripts.SDNCAdapterUtils; +import org.openecomp.mso.bpmn.common.scripts.VidUtils; +import org.openecomp.mso.bpmn.core.WorkflowException +import org.openecomp.mso.bpmn.core.json.JsonUtils; +import org.openecomp.mso.rest.APIResponse import java.util.UUID; @@ -195,19 +195,19 @@ public class UpdateNetworkInstanceInfra extends AbstractServiceTaskProcessor { } try { - // Catalog DB headers Authorization - String basicAuthValueDB = execution.getVariable("URN_mso_adapters_db_auth") - utils.log("DEBUG", " Obtained BasicAuth userid password for Catalog DB adapter: " + basicAuthValueDB, isDebugEnabled) - - def encodedString = utils.getBasicAuth(basicAuthValueDB, execution.getVariable("URN_mso_msoKey")) - execution.setVariable("BasicAuthHeaderValueDB",encodedString) - } catch (IOException ex) { - String dataErrorMessage = " Unable to encode Catalog DB user/password string - " + ex.getMessage() - utils.log("DEBUG", dataErrorMessage, isDebugEnabled) - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) - } - - try { + // Catalog DB headers Authorization + String basicAuthValueDB = execution.getVariable("URN_mso_adapters_db_auth") + utils.log("DEBUG", " Obtained BasicAuth userid password for Catalog DB adapter: " + basicAuthValueDB, isDebugEnabled) + + def encodedString = utils.getBasicAuth(basicAuthValueDB, execution.getVariable("URN_mso_msoKey")) + execution.setVariable("BasicAuthHeaderValueDB",encodedString) + } catch (IOException ex) { + String dataErrorMessage = " Unable to encode Catalog DB user/password string - " + ex.getMessage() + utils.log("DEBUG", dataErrorMessage, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) + } + + try { execution.setVariable("UPDNETI_UpdateNetworkInstanceInfraJsonRequest", updateNetworkJsonIncoming) @@ -230,7 +230,7 @@ public class UpdateNetworkInstanceInfra extends AbstractServiceTaskProcessor { execution.setVariable("UPDNETI_networkOutputs", networkOutputs) utils.log("DEBUG", " networkOutputs - " + '\n' + networkOutputs, isDebugEnabled) - String requestId = execution.getVariable("mso-request-id") + String requestId = execution.getVariable("mso-request-id") if (requestId == null || requestId == "") { requestId = execution.getVariable("requestId") } @@ -309,7 +309,7 @@ public class UpdateNetworkInstanceInfra extends AbstractServiceTaskProcessor { try { String serviceInstanceId = execution.getVariable("UPDNETI_serviceInstanceId") - String requestId = execution.getVariable("mso-request-id") + String requestId = execution.getVariable("mso-request-id") // RESTResponse (for API Handler (APIH) Reply Task) String updateNetworkRestRequest = """{"requestReferences":{"instanceId":"${serviceInstanceId}","requestId":"${requestId}"}}""".trim() @@ -1094,6 +1094,19 @@ public class UpdateNetworkInstanceInfra extends AbstractServiceTaskProcessor { execution.setVariable("prefix", Prefix) try { + // Catalog DB headers Authorization + String basicAuthValueDB = execution.getVariable("URN_mso_adapters_db_auth") + utils.log("DEBUG", " Obtained BasicAuth userid password for Catalog DB adapter: " + basicAuthValueDB, isDebugEnabled) + + def encodedString = utils.getBasicAuth(basicAuthValueDB, execution.getVariable("URN_mso_msoKey")) + execution.setVariable("BasicAuthHeaderValueDB",encodedString) + } catch (IOException ex) { + String dataErrorMessage = " Unable to encode Catalog DB user/password string - " + ex.getMessage() + utils.log("DEBUG", dataErrorMessage, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) + } + + try { utils.log("DEBUG", " ***** Inside prepareDBRequest of UpdateNetworkInstanceInfra ***** ", isDebugEnabled) String networkOutputs = execution.getVariable("UPDNETI_networkOutputs") @@ -1121,7 +1134,7 @@ public class UpdateNetworkInstanceInfra extends AbstractServiceTaskProcessor { """ - + ${requestId} BPMN ${statusMessage} @@ -1153,6 +1166,19 @@ public class UpdateNetworkInstanceInfra extends AbstractServiceTaskProcessor { execution.setVariable("prefix", Prefix) try { + // Catalog DB headers Authorization + String basicAuthValueDB = execution.getVariable("URN_mso_adapters_db_auth") + utils.log("DEBUG", " Obtained BasicAuth userid password for Catalog DB adapter: " + basicAuthValueDB, isDebugEnabled) + + def encodedString = utils.getBasicAuth(basicAuthValueDB, execution.getVariable("URN_mso_msoKey")) + execution.setVariable("BasicAuthHeaderValueDB",encodedString) + } catch (IOException ex) { + String dataErrorMessage = " Unable to encode Catalog DB user/password string - " + ex.getMessage() + utils.log("DEBUG", dataErrorMessage, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) + } + + try { utils.log("DEBUG", " ***** Inside prepareDBRequestError of UpdateNetworkInstanceInfra ***** ", isDebugEnabled) String statusMessage = "" @@ -1190,7 +1216,7 @@ public class UpdateNetworkInstanceInfra extends AbstractServiceTaskProcessor { """ - + ${requestId} BPMN ${statusMessage} @@ -1244,7 +1270,7 @@ public class UpdateNetworkInstanceInfra extends AbstractServiceTaskProcessor { // prepare rollback data String rollbackData = utils.getNodeXml(networkResponse, "rollback", false).replace("tag0:","").replace(":tag0","") String rollbackNetwork = - """ + """ ${rollbackData} """ String rollbackNetworkXml = utils.formatXml(rollbackNetwork) @@ -1345,9 +1371,9 @@ public class UpdateNetworkInstanceInfra extends AbstractServiceTaskProcessor { String requestId = execution.getVariable("UPDNETI_requestId") String msoCompletionRequest = - """ - + """ + ${requestId} UPDATE ${source} @@ -1528,15 +1554,15 @@ public class UpdateNetworkInstanceInfra extends AbstractServiceTaskProcessor { String errorCode = String.valueOf(wfe.getErrorCode()) String errorMessage = wfe.getErrorMessage() falloutHandlerRequest = - """ - + """ + ${requestId} UPDATE ${source} - + ${errorMessage} ${errorCode} @@ -1550,15 +1576,15 @@ public class UpdateNetworkInstanceInfra extends AbstractServiceTaskProcessor { String errorException = " Bpmn error encountered in UpdateNetworkInstanceInfra flow. FalloutHandlerRequest, buildErrorResponse() - " + ex.getMessage() utils.log("DEBUG", errorException, isDebugEnabled) falloutHandlerRequest = - """ - + """ + ${requestId} UPDATE ${source} - + ${errorException} 7000 @@ -1578,7 +1604,7 @@ public class UpdateNetworkInstanceInfra extends AbstractServiceTaskProcessor { try { - String requestId = execution.getVariable("mso-request-id") + String requestId = execution.getVariable("mso-request-id") // REST Error (for API Handler (APIH) Reply Task) String syncError = """{"requestReferences":{"instanceId":"","requestId":"${requestId}"}}""".trim() diff --git a/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/UpdateVfModule.groovy b/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/UpdateVfModule.groovy index 8f2eb27b91..d428cc33dd 100644 --- a/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/UpdateVfModule.groovy +++ b/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/UpdateVfModule.groovy @@ -1,24 +1,24 @@ -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - MSO - * ================================================================================ - * 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.openecomp.mso.bpmn.infrastructure.scripts +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.bpmn.infrastructure.scripts import groovy.util.Node import groovy.util.XmlParser; @@ -28,19 +28,21 @@ import java.io.Serializable; import org.camunda.bpm.engine.delegate.BpmnError import org.camunda.bpm.engine.runtime.Execution - -import org.openecomp.mso.bpmn.core.WorkflowException -import org.openecomp.mso.bpmn.core.json.JsonUtils; -import org.openecomp.mso.rest.APIResponse -import org.openecomp.mso.bpmn.common.scripts.AbstractServiceTaskProcessor -import org.openecomp.mso.bpmn.core.RollbackData +import org.openecomp.mso.bpmn.common.scripts.ExceptionUtil +import org.openecomp.mso.bpmn.core.WorkflowException +import org.openecomp.mso.bpmn.core.json.JsonUtils; +import org.openecomp.mso.rest.APIResponse +import org.openecomp.mso.bpmn.common.scripts.AbstractServiceTaskProcessor +import org.openecomp.mso.bpmn.core.RollbackData public class UpdateVfModule extends AbstractServiceTaskProcessor { - + + ExceptionUtil exceptionUtil = new ExceptionUtil() + /** * Initialize the flow's variables. - * + * * @param execution The flow's execution instance. */ public void initProcessVariables(Execution execution) { @@ -57,11 +59,11 @@ public class UpdateVfModule extends AbstractServiceTaskProcessor { execution.setVariable('UPDVfMod_vnfParams', null) execution.setVariable('UPDVfMod_updateInfraRequest', null) execution.setVariable('UpdateVfModuleSuccessIndicator', false) - } - + } + /** * Check for missing elements in the received request. - * + * * @param execution The flow's execution instance. */ public void preProcessRequest(Execution execution) { @@ -74,13 +76,13 @@ public class UpdateVfModule extends AbstractServiceTaskProcessor { try { initProcessVariables(execution) String request = validateRequest(execution) - + utils.logAudit("UpdateVfModule request: " + request) def requestInfo = getRequiredNodeXml(execution, request, 'request-info') execution.setVariable('UPDVfMod_requestInfo', requestInfo) execution.setVariable('UPDVfMod_requestId', getRequiredNodeText(execution, requestInfo, 'request-id')) execution.setVariable('UPDVfMod_source', getNodeTextForce(requestInfo, 'source')) - + def vnfInputs = getRequiredNodeXml(execution, request, 'vnf-inputs') execution.setVariable('UPDVfMod_vnfInputs', vnfInputs) execution.setVariable('UPDVfMod_vnfId', getRequiredNodeText(execution, vnfInputs, 'vnf-id')) @@ -96,13 +98,13 @@ public class UpdateVfModule extends AbstractServiceTaskProcessor { throw e; } catch (Exception e) { logError('Caught exception in ' + method, e) - createWorkflowException(execution, 1002, 'Error in preProcessRequest(): ' + e.getMessage()) + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in preProcessRequest(): ' + e.getMessage()) } } - + /** * Prepare and send the synchronous response for this flow. - * + * * @param execution The flow's execution instance. */ public void sendSynchResponse(Execution execution) { @@ -125,7 +127,7 @@ public class UpdateVfModule extends AbstractServiceTaskProcessor { startTime = System.currentTimeMillis() } def vnfInputs = execution.getVariable('UPDVfMod_vnfInputs') - + String synchResponse = """ @@ -142,25 +144,25 @@ public class UpdateVfModule extends AbstractServiceTaskProcessor { synchResponse = utils.formatXml(synchResponse) sendWorkflowResponse(execution, 200, synchResponse) - + utils.logAudit("UpdateVfModule Synch Response: " + synchResponse) logDebug('Exited ' + method, isDebugLogEnabled) } catch (BpmnError e) { throw e; } catch (Exception e) { logError('Caught exception in ' + method, e) - createWorkflowException(execution, 1002, 'Error in sendSynchResponse(): ' + e.getMessage()) + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in sendSynchResponse(): ' + e.getMessage()) } } - + /** * Prepare the Request for invoking the DoUpdateVfModule subflow. - * + * * NOTE: Currently, the method just logs passing through as the * incoming Request to this main flow is used as the Request to * the DoUpdateVfModule subflow. No preparation processing is * necessary. - * + * * @param execution The flow's execution instance. */ public void prepDoUpdateVfModule(Execution execution) { @@ -171,19 +173,19 @@ public class UpdateVfModule extends AbstractServiceTaskProcessor { logDebug('Entered ' + method, isDebugLogEnabled) try { - + logDebug('Exited ' + method, isDebugLogEnabled) } catch (BpmnError e) { throw e; } catch (Exception e) { logError('Caught exception in ' + method, e) - createWorkflowException(execution, 1002, 'Error in prepDoUpdateVfModule(): ' + e.getMessage()) + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in prepDoUpdateVfModule(): ' + e.getMessage()) } } - + /** * Prepare the Request for updating the DB for this Infra Request. - * + * * @param execution The flow's execution instance. */ public void prepUpdateInfraRequest(Execution execution) { @@ -199,10 +201,10 @@ public class UpdateVfModule extends AbstractServiceTaskProcessor { def vfModuleId = execution.getVariable('UPDVfMod_vfModuleId') def tenantId = execution.getVariable('UPDVfMod_tenantId') def volumeGroupId = execution.getVariable('UPDVfMod_volumeGroupId') - + String updateInfraRequest = """ + xmlns:req="http://org.openecomp.mso/requestsdb"> @@ -231,13 +233,13 @@ public class UpdateVfModule extends AbstractServiceTaskProcessor { throw e; } catch (Exception e) { logError('Caught exception in ' + method, e) - createWorkflowException(execution, 1002, 'Error in prepUpdateInfraRequest(): ' + e.getMessage()) + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in prepUpdateInfraRequest(): ' + e.getMessage()) } } - + /** * Builds a "CompletionHandler" 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 */ @@ -251,10 +253,10 @@ public class UpdateVfModule extends AbstractServiceTaskProcessor { try { def requestInfo = getVariable(execution, 'UPDVfMod_requestInfo') - + String content = """ - + ${requestInfo} MSO_ACTIVATE_BPEL @@ -270,13 +272,13 @@ public class UpdateVfModule extends AbstractServiceTaskProcessor { throw e; } catch (Exception e) { logError('Caught exception in ' + method, e) - createWorkflowException(execution, 2000, 'Internal Error') + exceptionUtil.buildAndThrowWorkflowException(execution, 2000, 'Internal Error') } } /** * Builds a "FalloutHandler" 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 */ @@ -287,12 +289,12 @@ public class UpdateVfModule extends AbstractServiceTaskProcessor { ')' def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') logDebug('Entered ' + method, isDebugLogEnabled) - + try { def prefix = execution.getVariable('prefix') def request = getVariable(execution, prefix+'Request') def requestInformation = utils.getNodeXml(request, 'request-information', false) - + def WorkflowException workflowException = execution.getVariable("WorkflowException") def errorResponseCode = workflowException.getErrorCode() def errorResponseMsg = workflowException.getErrorMessage() @@ -302,15 +304,15 @@ public class UpdateVfModule extends AbstractServiceTaskProcessor { } String content = """ - + ${requestInformation} ${encErrorResponseMsg} ${errorResponseCode} - + """ content = utils.formatXml(content) @@ -323,7 +325,7 @@ public class UpdateVfModule extends AbstractServiceTaskProcessor { throw e; } catch (Exception e) { logError('Caught exception in ' + method, e) - createWorkflowException(execution, 2000, 'Internal Error') + exceptionUtil.buildWorkflowException(execution, 2000, 'Internal Error') } } } diff --git a/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/UpdateVfModuleInfra.groovy b/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/UpdateVfModuleInfra.groovy index 8d05f41774..d0949ae4d1 100644 --- a/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/UpdateVfModuleInfra.groovy +++ b/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/UpdateVfModuleInfra.groovy @@ -26,7 +26,7 @@ import groovy.util.XmlParser; import groovy.xml.QName import java.io.Serializable; - +import org.openecomp.mso.bpmn.common.scripts.ExceptionUtil import org.camunda.bpm.engine.delegate.BpmnError import org.camunda.bpm.engine.runtime.Execution import org.openecomp.mso.rest.APIResponse @@ -39,10 +39,12 @@ import org.openecomp.mso.bpmn.core.WorkflowException public class UpdateVfModuleInfra extends AbstractServiceTaskProcessor { - + + ExceptionUtil exceptionUtil = new ExceptionUtil() + /** * Initialize the flow's variables. - * + * * @param execution The flow's execution instance. */ public void initProcessVariables(Execution execution) { @@ -59,11 +61,11 @@ public class UpdateVfModuleInfra extends AbstractServiceTaskProcessor { execution.setVariable('UPDVfModI_vnfParams', null) execution.setVariable('UPDVfModI_updateInfraRequest', null) execution.setVariable('UpdateVfModuleSuccessIndicator', false) - } - + } + /** * Check for missing elements in the received request. - * + * * @param execution The flow's execution instance. */ public void preProcessRequest(Execution execution) { @@ -72,58 +74,58 @@ public class UpdateVfModuleInfra extends AbstractServiceTaskProcessor { ')' def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') logDebug('Entered ' + method, isDebugLogEnabled) - + initProcessVariables(execution) - + def prefix = "UPDVfModI_" - + execution.setVariable("isVidRequest", "false") - + def incomingRequest = execution.getVariable('bpmnRequest') - + utils.log("DEBUG", "Incoming Infra Request: " + incomingRequest, isDebugLogEnabled) - + // check if request is xml or json try { def jsonSlurper = new JsonSlurper() Map reqMap = jsonSlurper.parseText(incomingRequest) utils.log("DEBUG", " Request is in JSON format.", isDebugLogEnabled) - + def serviceInstanceId = execution.getVariable('serviceInstanceId') def vnfId = execution.getVariable('vnfId') - + def vidUtils = new VidUtils(this) - + String requestInXmlFormat = vidUtils.createXmlVfModuleRequest(execution, reqMap, 'UPDATE_VF_MODULE', serviceInstanceId) - + utils.log("DEBUG", " Request in XML format: " + requestInXmlFormat, isDebugLogEnabled) - + execution.setVariable(prefix + 'Request', requestInXmlFormat) execution.setVariable(prefix+'vnfId', vnfId) - execution.setVariable("isVidRequest", "true") - + execution.setVariable("isVidRequest", "true") + } catch(groovy.json.JsonException je) { utils.log("DEBUG", " Request is not in JSON format.", isDebugLogEnabled) - workflowException(execution, "Invalid request format", 400) - + exceptionUtil.buildAndThrowWorkflowException(execution, 5000, "Invalid request format") + } catch(Exception e) { - String restFaultMessage = e.getMessage() + String restFaultMessage = e.getMessage() utils.log("ERROR", " Exception Encountered - " + "\n" + restFaultMessage, isDebugLogEnabled) - workflowException(execution, restFaultMessage, 400) + exceptionUtil.buildAndThrowWorkflowException(execution, 5000, restFaultMessage) } - + try { - + String request = validateInfraRequest(execution) - + def requestInfo = getRequiredNodeXml(execution, request, 'request-info') execution.setVariable('UPDVfModI_requestInfo', requestInfo) execution.setVariable('UPDVfModI_requestId', getRequiredNodeText(execution, requestInfo, 'request-id')) execution.setVariable('UPDVfModI_source', getNodeTextForce(requestInfo, 'source')) - + def vnfInputs = getRequiredNodeXml(execution, request, 'vnf-inputs') execution.setVariable('UPDVfModI_vnfInputs', vnfInputs) execution.setVariable('UPDVfModI_vnfId', getRequiredNodeText(execution, vnfInputs, 'vnf-id')) @@ -139,13 +141,13 @@ public class UpdateVfModuleInfra extends AbstractServiceTaskProcessor { throw e; } catch (Exception e) { logError('Caught exception in ' + method, e) - createWorkflowException(execution, 1002, 'Error in preProcessRequest(): ' + e.getMessage()) + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in preProcessRequest(): ' + e.getMessage()) } } - + /** * Prepare and send the sychronous response for this flow. - * + * * @param execution The flow's execution instance. */ public void sendSynchResponse(Execution execution) { @@ -155,7 +157,7 @@ public class UpdateVfModuleInfra extends AbstractServiceTaskProcessor { def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') logDebug('Entered ' + method, isDebugLogEnabled) - + try { def requestInfo = execution.getVariable('UPDVfModI_requestInfo') def requestId = execution.getVariable('UPDVfModI_requestId') @@ -167,12 +169,12 @@ public class UpdateVfModuleInfra extends AbstractServiceTaskProcessor { def startTime = getNodeTextForce(requestInfo, 'start-time') if (startTime.isEmpty()) { startTime = System.currentTimeMillis() - } - + } + // RESTResponse (for API Handler (APIH) Reply Task) def vfModuleId = execution.getVariable("vfModuleId") String synchResponse = """{"requestReferences":{"instanceId":"${vfModuleId}","requestId":"${requestId}"}}""".trim() - + sendWorkflowResponse(execution, 200, synchResponse) logDebug('Exited ' + method, isDebugLogEnabled) @@ -180,18 +182,18 @@ public class UpdateVfModuleInfra extends AbstractServiceTaskProcessor { throw e; } catch (Exception e) { logError('Caught exception in ' + method, e) - createWorkflowException(execution, 1002, 'Error in sendResponse(): ' + e.getMessage()) + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in sendResponse(): ' + e.getMessage()) } } - + /** * Prepare the Request for invoking the DoUpdateVfModule subflow. - * + * * NOTE: Currently, the method just logs passing through as the * incoming Request to this main flow is used as the Request to * the DoUpdateVfModule subflow. No preparation processing is * necessary. - * + * * @param execution The flow's execution instance. */ public void prepDoUpdateVfModule(Execution execution) { @@ -202,19 +204,19 @@ public class UpdateVfModuleInfra extends AbstractServiceTaskProcessor { logDebug('Entered ' + method, isDebugLogEnabled) try { - + logDebug('Exited ' + method, isDebugLogEnabled) } catch (BpmnError e) { throw e; } catch (Exception e) { logError('Caught exception in ' + method, e) - createWorkflowException(execution, 1002, 'Error in prepDoUpdateVfModule(): ' + e.getMessage()) + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in prepDoUpdateVfModule(): ' + e.getMessage()) } } - + /** * Prepare the Request for updating the DB for this Infra Request. - * + * * @param execution The flow's execution instance. */ public void prepUpdateInfraRequest(Execution execution) { @@ -230,7 +232,7 @@ public class UpdateVfModuleInfra extends AbstractServiceTaskProcessor { def vfModuleId = execution.getVariable('UPDVfModI_vfModuleId') def tenantId = execution.getVariable('UPDVfModI_tenantId') def volumeGroupId = execution.getVariable('UPDVfModI_volumeGroupId') - + String updateInfraRequest = """ @@ -261,13 +263,13 @@ public class UpdateVfModuleInfra extends AbstractServiceTaskProcessor { throw e; } catch (Exception e) { logError('Caught exception in ' + method, e) - createWorkflowException(execution, 1002, 'Error in prepUpdateInfraRequest(): ' + e.getMessage()) + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in prepUpdateInfraRequest(): ' + e.getMessage()) } } - + /** * Builds a "CompletionHandler" 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 */ @@ -281,7 +283,7 @@ public class UpdateVfModuleInfra extends AbstractServiceTaskProcessor { try { def requestInfo = getVariable(execution, 'UPDVfModI_requestInfo') - + String content = """ @@ -299,13 +301,13 @@ public class UpdateVfModuleInfra extends AbstractServiceTaskProcessor { throw e; } catch (Exception e) { logError('Caught exception in ' + method, e) - createWorkflowException(execution, 2000, 'Internal Error') + exceptionUtil.buildAndThrowWorkflowException(execution, 2000, 'Internal Error') } } /** * Builds a "FalloutHandler" 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 */ @@ -316,12 +318,12 @@ public class UpdateVfModuleInfra extends AbstractServiceTaskProcessor { ')' def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') logDebug('Entered ' + method, isDebugLogEnabled) - + try { def prefix = execution.getVariable('prefix') def request = getVariable(execution, prefix+'Request') def requestInformation = utils.getNodeXml(request, 'request-info', false) - + def WorkflowException workflowException = execution.getVariable("WorkflowException") def errorResponseCode = workflowException.getErrorCode() def errorResponseMsg = workflowException.getErrorMessage() @@ -339,7 +341,7 @@ public class UpdateVfModuleInfra extends AbstractServiceTaskProcessor { ${encErrorResponseMsg} ${errorResponseCode} - + """ content = utils.formatXml(content) @@ -351,10 +353,10 @@ public class UpdateVfModuleInfra extends AbstractServiceTaskProcessor { throw e; } catch (Exception e) { logError('Caught exception in ' + method, e) - createWorkflowException(execution, 2000, 'Internal Error') + exceptionUtil.buildWorkflowException(execution, 2000, 'Internal Error') } } - + /** * Validates the request, request id and service instance id. If a problem is found, * a WorkflowException is generated and an MSOWorkflowException event is thrown. This @@ -373,7 +375,7 @@ public class UpdateVfModuleInfra extends AbstractServiceTaskProcessor { def prefix = execution.getVariable("prefix") if (prefix == null) { - createWorkflowException(execution, 1002, processKey + " prefix is null") + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, processKey + " prefix is null") } try { @@ -381,34 +383,34 @@ public class UpdateVfModuleInfra extends AbstractServiceTaskProcessor { 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) { - createWorkflowException(execution, 1002, processKey + " request is null") + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, processKey + " request is null") } - + /* def requestId = execution.getVariable("mso-request-id") - + if (requestId == null) { - createWorkflowException(execution, 1002, processKey + " request has no mso-request-id") + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, processKey + " request has no mso-request-id") } - + setVariable(execution, prefix + 'requestId', requestId) def serviceInstanceId = execution.getVariable("mso-service-instance-id") if (serviceInstanceId == null) { - createWorkflowException(execution, 1002, processKey + " request message has no mso-service-instance-id") + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, processKey + " request message has no mso-service-instance-id") } utils.logContext(requestId, serviceInstanceId) @@ -420,8 +422,8 @@ public class UpdateVfModuleInfra extends AbstractServiceTaskProcessor { throw e; } catch (Exception e) { logError('Caught exception in ' + method, e) - createWorkflowException(execution, 1002, "Invalid Message") + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Invalid Message") } } - + } diff --git a/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/UpdateVfModuleVolume.groovy b/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/UpdateVfModuleVolume.groovy index 996fd56e0d..6d532527d0 100644 --- a/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/UpdateVfModuleVolume.groovy +++ b/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/UpdateVfModuleVolume.groovy @@ -1,24 +1,24 @@ -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - MSO - * ================================================================================ - * 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.openecomp.mso.bpmn.infrastructure.scripts +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.bpmn.infrastructure.scripts import java.util.concurrent.ExecutionException; @@ -26,17 +26,20 @@ import org.camunda.bpm.engine.delegate.BpmnError import org.camunda.bpm.engine.runtime.Execution import org.apache.commons.lang3.* import org.springframework.web.util.UriUtils -import org.openecomp.mso.bpmn.common.scripts.AaiUtil -import org.openecomp.mso.bpmn.common.scripts.VfModuleBase -import org.openecomp.mso.bpmn.core.WorkflowException -import org.openecomp.mso.bpmn.core.json.JsonUtils; -import org.openecomp.mso.rest.APIResponse +import org.openecomp.mso.bpmn.common.scripts.AaiUtil +import org.openecomp.mso.bpmn.common.scripts.VfModuleBase +import org.openecomp.mso.bpmn.core.WorkflowException +import org.openecomp.mso.bpmn.core.json.JsonUtils; +import org.openecomp.mso.rest.APIResponse +import org.openecomp.mso.bpmn.common.scripts.ExceptionUtil class UpdateVfModuleVolume extends VfModuleBase { - + + ExceptionUtil exceptionUtil = new ExceptionUtil() + /** * Initialize the flow's variables. - * + * * @param execution The flow's execution instance. */ private void initProcessVariables(Execution execution) { @@ -56,10 +59,10 @@ class UpdateVfModuleVolume extends VfModuleBase { execution.setVariable('UPDVfModVol_volumeGroupTenantId', null) execution.setVariable('UpdateVfModuleVolumeSuccessIndicator', false) } - + /** * Check for missing elements in the received request. - * + * * @param execution The flow's execution instance. */ @Override @@ -69,16 +72,16 @@ class UpdateVfModuleVolume extends VfModuleBase { ')' def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') logDebug('Entered ' + method, isDebugLogEnabled) - + try { initProcessVariables(execution) String request = validateRequest(execution) - + def requestInfo = getRequiredNodeXml(execution, request, 'request-info') execution.setVariable('UPDVfModVol_requestInfo', requestInfo) execution.setVariable('UPDVfModVol_requestId', getRequiredNodeText(execution, requestInfo, 'request-id')) execution.setVariable('UPDVfModVol_source', getNodeTextForce(requestInfo, 'source')) - + def volumeInputs = getRequiredNodeXml(execution, request, 'volume-inputs') execution.setVariable('UPDVfModVol_volumeInputs', volumeInputs) execution.setVariable('UPDVfModVol_volumeGroupId', getRequiredNodeText(execution, volumeInputs, 'volume-group-id')) @@ -96,13 +99,13 @@ class UpdateVfModuleVolume extends VfModuleBase { throw bpmnError } catch (Exception e) { logError('Caught exception in ' + method, e) - createWorkflowException(execution, 1002, 'Error in preProcessRequest(): ' + e.getMessage()) + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in preProcessRequest(): ' + e.getMessage()) } } /** * Prepare and send the synchronous response. - * + * * @param execution The flow's execution instance. */ public void sendSynchResponse(Execution execution) { @@ -111,7 +114,7 @@ class UpdateVfModuleVolume extends VfModuleBase { ')' def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') logDebug('Entered ' + method, isDebugLogEnabled) - + try { def requestInfo = execution.getVariable('UPDVfModVol_requestInfo') def requestId = execution.getVariable('UPDVfModVol_requestId') @@ -125,9 +128,9 @@ class UpdateVfModuleVolume extends VfModuleBase { startTime = System.currentTimeMillis() } def volumeInputs = execution.getVariable('UPDVfModVol_volumeInputs') - + String synchResponse = """ - + ${requestId} UPDATE_VF_MODULE_VOL @@ -147,14 +150,14 @@ class UpdateVfModuleVolume extends VfModuleBase { throw e; } catch (Exception e) { logError('Caught exception in ' + method, e) - createWorkflowException(execution, 1002, 'Error in sendSynchResponse(): ' + e.getMessage()) - } + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in sendSynchResponse(): ' + e.getMessage()) + } } - + /** * Prepare a Request for querying AAI for Volume Group information using the * Volume Group Id and Aic Cloud Region. - * + * * @param execution The flow's execution instance. */ public void queryAAIForVolumeGroup(Execution execution) { @@ -173,7 +176,7 @@ class UpdateVfModuleVolume extends VfModuleBase { logDebug('Sending GET to AAI endpoint \'' + endPoint + '\'', isDebugLogEnabled) utils.logAudit("UpdateVfModuleVolume sending GET for quering AAI endpoint: " + endPoint) - + AaiUtil aaiUtil = new AaiUtil(this) APIResponse response = aaiUtil.executeAAIGetCall(execution, endPoint) def int statusCode = response.getStatusCode() @@ -181,7 +184,7 @@ class UpdateVfModuleVolume extends VfModuleBase { logDebug('Response code:' + statusCode, isDebugLogEnabled) logDebug('Response:' + System.lineSeparator() + responseData, isDebugLogEnabled) utils.logAudit("UpdateVfModuleVolume response data: " + responseData) - + def volumeGroup = responseData def heatStackId = getNodeTextForce(volumeGroup, 'heat-stack-id') execution.setVariable('UPDVfModVol_volumeGroupHeatStackId', heatStackId) @@ -205,10 +208,10 @@ class UpdateVfModuleVolume extends VfModuleBase { throw e; } catch (Exception e) { logError('Caught exception in ' + method, e) - createWorkflowException(execution, 1002, 'Error in queryAAIForVolumeGroup(): ' + e.getMessage()) + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in queryAAIForVolumeGroup(): ' + e.getMessage()) } } - + /** * Prepare a Request for invoking the VnfAdapterRest subflow to do * a Volume Group update. @@ -221,22 +224,22 @@ class UpdateVfModuleVolume extends VfModuleBase { ')' def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') logDebug('Entered ' + method, isDebugLogEnabled) - + try { def aicCloudRegion = execution.getVariable('UPDVfModVol_aicCloudRegion') def tenantId = execution.getVariable('UPDVfModVol_tenantId') def volumeGroupId = execution.getVariable('UPDVfModVol_volumeGroupId') def volumeGroupHeatStackId = execution.getVariable('UPDVfModVol_volumeGroupHeatStackId') def vnfType = execution.getVariable('UPDVfModVol_vnfType') - + def volumeParamsXml = execution.getVariable('UPDVfModVol_volumeParams') def volumeGroupParams = transformParamsToEntries(volumeParamsXml) - + def requestId = execution.getVariable('UPDVfModVol_requestId') def serviceId = execution.getVariable('UPDVfModVol_serviceId') - - def messageId = execution.getVariable('mso-request-id') + '-' + System.currentTimeMillis() - def notificationUrl = createCallbackURL(execution, "VNFAResponse", messageId) + + def messageId = execution.getVariable('mso-request-id') + '-' + System.currentTimeMillis() + def notificationUrl = createCallbackURL(execution, "VNFAResponse", messageId) def useQualifiedHostName = execution.getVariable("URN_mso_use_qualified_host") if ('true'.equals(useQualifiedHostName)) { notificationUrl = utils.getQualifiedHostNameForCallback(notificationUrl) @@ -266,17 +269,17 @@ class UpdateVfModuleVolume extends VfModuleBase { vnfAdapterRestRequest = utils.formatXml(vnfAdapterRestRequest) execution.setVariable('UPDVfModVol_vnfAdapterRestRequest', vnfAdapterRestRequest) logDebug('Request for VNFAdapter Rest:\n' + vnfAdapterRestRequest, isDebugLogEnabled) - + utils.logAudit("UpdateVfModuleVolume Request for VNFAdapter Rest: " + vnfAdapterRestRequest) logDebug('Exited ' + method, isDebugLogEnabled) } catch (BpmnError e) { throw e; } catch (Exception e) { logError('Caught exception in ' + method, e) - createWorkflowException(execution, 1002, 'Error in prepVnfAdapterRest(): ' + e.getMessage()) + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in prepVnfAdapterRest(): ' + e.getMessage()) } } - + /** * Prepare a Request for updating the DB for this Infra request. * @@ -291,10 +294,10 @@ class UpdateVfModuleVolume extends VfModuleBase { try { def requestId = execution.getVariable('UPDVfMod_requestId') - + String updateInfraRequest = """ + xmlns:req="http://org.openecomp.mso/requestsdb"> @@ -310,20 +313,20 @@ class UpdateVfModuleVolume extends VfModuleBase { updateInfraRequest = utils.formatXml(updateInfraRequest) execution.setVariable('UPDVfModVol_updateInfraRequest', updateInfraRequest) logDebug('Request for Update Infra Request:\n' + updateInfraRequest, isDebugLogEnabled) - + utils.logAudit("UpdateVfModuleVolume Request for Updating DB for Infra: " + updateInfraRequest) logDebug('Exited ' + method, isDebugLogEnabled) } catch (BpmnError e) { throw e; } catch (Exception e) { logError('Caught exception in ' + method, e) - createWorkflowException(execution, 1002, 'Error in prepDbInfraDbRequest(): ' + e.getMessage()) + exceptionUtil.buildWorkflowException(execution, 1002, 'Error in prepDbInfraDbRequest(): ' + e.getMessage()) } } - + /** * Build a "CompletionHandler" request. - * + * * @param execution The flow's execution instance. */ public void prepCompletionHandlerRequest(Execution execution) { @@ -332,13 +335,13 @@ class UpdateVfModuleVolume extends VfModuleBase { ')' def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') logDebug('Entered ' + method, isDebugLogEnabled) - + try { def requestInfo = execution.getVariable('UPDVfModVol_requestInfo') String content = """ - + ${requestInfo} MSO_ACTIVATE_BPEL @@ -348,19 +351,19 @@ class UpdateVfModuleVolume extends VfModuleBase { logDebug('Request for Completion Handler:\n' + content, isDebugLogEnabled) utils.logAudit("UpdateVfModuleVolume Completion Handler request: " + content) execution.setVariable('UPDVfModVol_CompletionHandlerRequest', content) - + logDebug('Exited ' + method, isDebugLogEnabled) } catch (BpmnError e) { throw e; } catch (Exception e) { logError('Caught exception in ' + method, e) - createWorkflowException(execution, 1002, 'Error in prepCompletionHandlerRequest(): ' + e.getMessage()) + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in prepCompletionHandlerRequest(): ' + e.getMessage()) } } - + /** * Build a "FalloutHandler" request. - * + * * @param execution The flow's execution instance. */ public void prepFalloutHandler(Execution execution) { @@ -372,7 +375,7 @@ class UpdateVfModuleVolume extends VfModuleBase { try { def requestInfo = execution.getVariable('UPDVfModVol_requestInfo') - + def WorkflowException workflowException = execution.getVariable("WorkflowException") def errorResponseCode = workflowException.getErrorCode() def errorResponseMsg = workflowException.getErrorMessage() @@ -382,35 +385,35 @@ class UpdateVfModuleVolume extends VfModuleBase { } String content = """ - + ${requestInfo} ${encErrorResponseMsg} ${errorResponseCode} - + """ content = utils.formatXml(content) logDebug('Request for Fallout Handler:\n' + content, isDebugLogEnabled) utils.logAudit("UpdateVfModuleVolume Fallout request: " + content) execution.setVariable('UPDVfModVol_FalloutHandlerRequest', content) - + logDebug('Exited ' + method, isDebugLogEnabled) } catch (BpmnError e) { throw e; } catch (Exception e) { logError('Caught exception in ' + method, e) - createWorkflowException(execution, 1002, 'Error in prepFalloutHandler(): ' + e.getMessage()) + exceptionUtil.buildWorkflowException(execution, 1002, 'Error in prepFalloutHandler(): ' + e.getMessage()) } } - + /** * Create a WorkflowException for the error case where the Tenant Id from * AAI did not match the Tenant Id in the incoming request. - * + * * @param execution The flow's execution instance. */ public void handleTenantIdMismatch(Execution execution) { @@ -419,21 +422,21 @@ class UpdateVfModuleVolume extends VfModuleBase { ')' def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') logDebug('Entered ' + method, isDebugLogEnabled) - + String processKey = getProcessKey(execution); def volumeGroupId = execution.getVariable('UPDVfModVol_volumeGroupId') def aicCloudRegion = execution.getVariable('UPDVfModVol_aicCloudRegion') def tenantId = execution.getVariable('UPDVfModVol_tenantId') def volumeGroupTenantId = execution.getVariable('UPDVfModVol_volumeGroupTenantId') - + def String errorMessage = 'TenantId \'' + tenantId + '\' in incoming request does not match Tenant Id \'' + volumeGroupTenantId + '\' retrieved from AAI for Volume Group Id \'' + volumeGroupId + '\', AIC Cloud Region \'' + aicCloudRegion + '\'' - + logError('Error in UpdateVfModuleVol: ' + errorMessage) - + WorkflowException exception = new WorkflowException(processKey, 5000, errorMessage); execution.setVariable("WorkflowException", exception); - + logDebug('Exited ' + method, isDebugLogEnabled) utils.logAudit("UpdateVfModuleVolume workflowException in Tenant Mismatch: " + errorMessage) } diff --git a/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/UpdateVfModuleVolumeInfraV1.groovy b/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/UpdateVfModuleVolumeInfraV1.groovy index 2f716f5668..ffe122aed6 100644 --- a/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/UpdateVfModuleVolumeInfraV1.groovy +++ b/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/UpdateVfModuleVolumeInfraV1.groovy @@ -1,549 +1,549 @@ -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - MSO - * ================================================================================ - * 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.openecomp.mso.bpmn.infrastructure.scripts - -import groovy.json.JsonSlurper - -import java.util.concurrent.ExecutionException; - -import org.camunda.bpm.engine.delegate.BpmnError -import org.camunda.bpm.engine.runtime.Execution -import org.apache.commons.lang3.* -import org.springframework.web.util.UriUtils -import org.openecomp.mso.bpmn.common.scripts.AaiUtil; -import org.openecomp.mso.bpmn.common.scripts.ExceptionUtil; -import org.openecomp.mso.bpmn.common.scripts.VfModuleBase; -import org.openecomp.mso.bpmn.common.scripts.VidUtils; -import org.openecomp.mso.bpmn.core.WorkflowException -import org.openecomp.mso.rest.APIResponse -import org.openecomp.mso.rest.RESTClient -import org.openecomp.mso.rest.RESTConfig - -class UpdateVfModuleVolumeInfraV1 extends VfModuleBase { - - /** - * Initialize the flow's variables. - * - * @param execution The flow's execution instance. - */ - private void initProcessVariables(Execution execution) { - execution.setVariable('prefix', 'UPDVfModVol_') - execution.setVariable('UPDVfModVol_Request', null) - execution.setVariable('UPDVfModVol_requestInfo', null) - execution.setVariable('UPDVfModVol_requestId', null) - execution.setVariable('UPDVfModVol_source', null) - execution.setVariable('UPDVfModVol_volumeInputs', null) - execution.setVariable('UPDVfModVol_volumeGroupId', null) - execution.setVariable('UPDVfModVol_vnfType', null) - execution.setVariable('UPDVfModVol_serviceId', null) - execution.setVariable('UPDVfModVol_aicCloudRegion', null) - execution.setVariable('UPDVfModVol_tenantId', null) - execution.setVariable('UPDVfModVol_volumeParams', null) - execution.setVariable('UPDVfModVol_volumeGroupHeatStackId', null) - execution.setVariable('UPDVfModVol_volumeGroupTenantId', null) - execution.setVariable('UpdateVfModuleVolumeSuccessIndicator', false) - } - - - /** - * Perform initial processing, such as request validation, initialization of variables, etc. - * * @param execution - */ - public void preProcessRequest (Execution execution) { - def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - preProcessRequest(execution, isDebugEnabled) - } - - public void preProcessRequest(Execution execution, isDebugLogEnabled) { - - initProcessVariables(execution) - String jsonRequest = validateRequest(execution) - - def request = "" - - try { - def jsonSlurper = new JsonSlurper() - Map reqMap = jsonSlurper.parseText(jsonRequest) - - def serviceInstanceId = execution.getVariable('serviceInstanceId') - def volumeGroupId = execution.getVariable('volumeGroupId') - //def vnfId = execution.getVariable('vnfId') - - def vidUtils = new VidUtils(this) - request = vidUtils.createXmlVolumeRequest(reqMap, 'UPDATE_VF_MODULE_VOL', serviceInstanceId, volumeGroupId) - - execution.setVariable('UPDVfModVol_Request', request) - execution.setVariable("UPDVfModVol_isVidRequest", true) - - //need to get persona-model-id aka model-invariantId to use later to validate vf-module relation in AAI - - def modelInvariantId = reqMap.requestDetails.modelInfo.modelInvariantId ?: '' - execution.setVariable('UPDVfModVol_modelInvariantId', modelInvariantId) - - utils.log("DEBUG", "XML request:\n" + request, isDebugLogEnabled) - } - catch(groovy.json.JsonException je) { - utils.log("DEBUG", " Request is in XML format.", isDebugLogEnabled) - // assume request is in XML format - proceed as usual to process XML request - } - - def requestId = execution.getVariable('mso-request-id') - - def requestInfo = getRequiredNodeXml(execution, request, 'request-info') - execution.setVariable('UPDVfModVol_requestInfo', requestInfo) - execution.setVariable('UPDVfModVol_requestId', requestId) - //execution.setVariable('UPDVfModVol_requestId', getRequiredNodeText(execution, requestInfo, 'request-id')) - execution.setVariable('UPDVfModVol_source', getNodeTextForce(requestInfo, 'source')) - - def volumeInputs = getRequiredNodeXml(execution, request, 'volume-inputs') - execution.setVariable('UPDVfModVol_volumeInputs', volumeInputs) - execution.setVariable('UPDVfModVol_volumeGroupId', getRequiredNodeText(execution, volumeInputs, 'volume-group-id')) - execution.setVariable('UPDVfModVol_vnfType', getRequiredNodeText(execution, volumeInputs, 'vnf-type')) - execution.setVariable('UPDVfModVol_vnfVersion', getRequiredNodeText(execution, volumeInputs, 'asdc-service-model-version')) - execution.setVariable('UPDVfModVol_serviceId', getRequiredNodeText(execution, volumeInputs, 'service-id')) - execution.setVariable('UPDVfModVol_aicCloudRegion', getRequiredNodeText(execution, volumeInputs, 'aic-cloud-region')) - execution.setVariable('UPDVfModVol_tenantId', getRequiredNodeText(execution, volumeInputs, 'tenant-id')) - //execution.setVariable('UPDVfModVol_modelCustomizationId', getRequiredNodeText(execution, volumeInputs, 'model-customization-id')) - - try { - // Catalog DB headers Authorization - String basicAuthValueDB = execution.getVariable("URN_mso_adapters_db_auth") - utils.log("DEBUG", " Obtained BasicAuth userid password for Catalog DB adapter: " + basicAuthValueDB, isDebugLogEnabled) - - def encodedString = utils.getBasicAuth(basicAuthValueDB, execution.getVariable("URN_mso_msoKey")) - execution.setVariable("BasicAuthHeaderValueDB",encodedString) - } catch (IOException ex) { - String dataErrorMessage = " Unable to encode Catalog DB user/password string - " + ex.getMessage() - utils.log("DEBUG", dataErrorMessage, isDebugLogEnabled) - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) - } - def volumeParams = utils.getNodeXml(request, 'volume-params') - execution.setVariable('UPDVfModVol_volumeParams', volumeParams) - } - - /** - * Prepare and send the synchronous response. - * - * @param execution The flow's execution instance. - */ - public void sendSynchResponse(Execution execution, isDebugLogEnabled) { - - def requestInfo = execution.getVariable('UPDVfModVol_requestInfo') - def requestId = execution.getVariable('UPDVfModVol_requestId') - def source = execution.getVariable('UPDVfModVol_source') - def progress = getNodeTextForce(requestInfo, 'progress') - if (progress.isEmpty()) { - progress = '0' - } - def startTime = getNodeTextForce(requestInfo, 'start-time') - if (startTime.isEmpty()) { - startTime = System.currentTimeMillis() - } - def volumeInputs = execution.getVariable('UPDVfModVol_volumeInputs') - - String xmlSyncResponse = """ - - - ${requestId} - UPDATE_VF_MODULE_VOL - IN_PROGRESS - ${progress} - ${startTime} - ${source} - - ${volumeInputs} - - """ - - def syncResponse = '' - def isVidRequest = execution.getVariable('UPDVfModVol_isVidRequest') - - if(isVidRequest) { - def volumeGroupId = execution.getVariable('volumeGroupId') - syncResponse = """{"requestReferences":{"instanceId":"${volumeGroupId}","requestId":"${requestId}"}}""".trim() - } - else { - syncResponse = utils.formatXml(xmlSyncResponse) - } - - logDebug('Sync response: ' + syncResponse, isDebugLogEnabled) - execution.setVariable('UPDVfModVol_syncResponseSent', true) - sendWorkflowResponse(execution, 200, syncResponse) - } - - /** - * Prepare a Request for querying AAI for Volume Group information using the - * Volume Group Id and Aic Cloud Region. - * @param execution The flow's execution instance. - */ - public void queryAAIForVolumeGroup(Execution execution, isDebugLogEnabled) { - - def volumeGroupId = execution.getVariable('UPDVfModVol_volumeGroupId') - def aicCloudRegion = execution.getVariable('UPDVfModVol_aicCloudRegion') - - AaiUtil aaiUtil = new AaiUtil(this) - String aaiEndpoint = aaiUtil.getCloudInfrastructureCloudRegionEndpoint(execution) - String queryAAIVolumeGroupRequest = aaiEndpoint + '/' + URLEncoder.encode(aicCloudRegion, "UTF-8") + "/volume-groups/volume-group/" + UriUtils.encode(volumeGroupId, "UTF-8") - - utils.logAudit('Query AAI volume group by ID: ' + queryAAIVolumeGroupRequest) - logDebug('Query AAI volume group by ID: ' + queryAAIVolumeGroupRequest, isDebugLogEnabled) - - APIResponse response = aaiUtil.executeAAIGetCall(execution, queryAAIVolumeGroupRequest) - - String returnCode = response.getStatusCode() - String aaiResponseAsString = response.getResponseBodyAsString() - aaiResponseAsString = StringEscapeUtils.unescapeXml(aaiResponseAsString) - - utils.logAudit("AAI query volume group by id return code: " + returnCode) - utils.logAudit("AAI query volume group by id response: " + aaiResponseAsString) - - logDebug("AAI Volume Group return code: " + returnCode, isDebugLogEnabled) - logDebug("AAI Volume Group response: " + aaiResponseAsString, isDebugLogEnabled) - - ExceptionUtil exceptionUtil = new ExceptionUtil() - - if ((returnCode == '200') || (returnCode == '204')) { - - execution.setVariable('UPDVfModVol_aaiVolumeGroupResponse', aaiResponseAsString) - //def heatStackId = getNodeTextForce(aaiResponseAsString, 'heat-stack-id') - //execution.setVariable('UPDVfModVol_volumeGroupHeatStackId', heatStackId) - - def volumeGroupTenantId = getTenantIdFromVolumeGroup(aaiResponseAsString) - if (volumeGroupTenantId == null) { - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Could not find Tenant Id element in Volume Group with Volume Group Id " + volumeGroupId - + ", AIC Cloud Region " + aicCloudRegion) - } - execution.setVariable('UPDVfModVol_volumeGroupTenantId', volumeGroupTenantId) - logDebug("Received Tenant Id " + volumeGroupTenantId + " from AAI for Volume Group with Volume Group Id " + volumeGroupId + ", AIC Cloud Region " + aicCloudRegion, isDebugLogEnabled) - - def relatedVfModuleLink = getRelatedVfModuleRelatedLink(aaiResponseAsString) - logDebug("Related VF Module link: " + relatedVfModuleLink, isDebugLogEnabled) - execution.setVariable('UPDVfModVol_relatedVfModuleLink', relatedVfModuleLink) - - } - else if (returnCode == '404') { - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Volume Group " + volumeGroupId + " not found at AAI") - } - else { - WorkflowException aWorkflowException = exceptionUtil.MapAAIExceptionToWorkflowException(aaiResponseAsString, execution) - throw new BpmnError("MSOWorkflowException") - } - } - - /** - * Query AAI service instance - * @param execution - * @param isDebugEnabled - */ - public void queryAAIForGenericVnf(Execution execution, isDebugEnabled) { - - def vnfId = execution.getVariable('vnfId') - - AaiUtil aaiUtil = new AaiUtil(this) - String aaiEndpoint = aaiUtil.getNetworkGenericVnfEndpoint(execution) - def String queryAAIRequest = aaiEndpoint + "/" + UriUtils.encode(vnfId, "UTF-8") - - utils.logAudit("AAI query generic vnf request: " + queryAAIRequest) - - APIResponse response = aaiUtil.executeAAIGetCall(execution, queryAAIRequest) - - String returnCode = response.getStatusCode() - String aaiResponseAsString = response.getResponseBodyAsString() - aaiResponseAsString = StringEscapeUtils.unescapeXml(aaiResponseAsString) - - utils.logAudit("AAI query generic vnf return code: " + returnCode) - utils.logAudit("AAI query generic vnf response: " + aaiResponseAsString) - - ExceptionUtil exceptionUtil = new ExceptionUtil() - - if (returnCode=='200') { - utils.log("DEBUG", 'Generic vnf ' + vnfId + ' found in AAI.', isDebugEnabled) - execution.setVariable('UPDVfModVol_AAIQueryGenericVfnResponse', aaiResponseAsString) - } else { - if (returnCode=='404') { - def message = 'Generic vnf ' + vnfId + ' was not found in AAI. Return code: 404.' - utils.log("DEBUG", message, isDebugEnabled) - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, message) - } else { - WorkflowException aWorkflowException = exceptionUtil.MapAAIExceptionToWorkflowException(aaiResponseAsString, execution) - throw new BpmnError("MSOWorkflowException") - } - } - } - - /** - * Query AAI for VF Module using vf-module-id - * @param execution - * @param isDebugLogEnabled - */ - public void queryAAIForVfModule(Execution execution, isDebugLogEnabled) { - - AaiUtil aaiUtil = new AaiUtil(this) - String queryAAIVfModuleRequest = execution.getVariable('UPDVfModVol_relatedVfModuleLink') - execution.setVariable('UPDVfModVol_personaModelId', '') - - utils.logAudit('Query AAI VF Module: ' + queryAAIVfModuleRequest) - logDebug('Query AAI VF Module: ' + queryAAIVfModuleRequest, isDebugLogEnabled) - - APIResponse response = aaiUtil.executeAAIGetCall(execution, queryAAIVfModuleRequest) - - String returnCode = response.getStatusCode() - String aaiResponseAsString = response.getResponseBodyAsString() - aaiResponseAsString = StringEscapeUtils.unescapeXml(aaiResponseAsString) - - utils.logAudit("AAI query vf-module: " + returnCode) - utils.logAudit("AAI query vf-module response: " + aaiResponseAsString) - - logDebug("AAI query vf-module:: " + returnCode, isDebugLogEnabled) - logDebug("AAI query vf-module response: " + aaiResponseAsString, isDebugLogEnabled) - - ExceptionUtil exceptionUtil = new ExceptionUtil() - - if ((returnCode == '200') || (returnCode == '204')) { - def personaModelId = utils.getNodeText1(aaiResponseAsString, 'persona-model-id') - execution.setVariable('UPDVfModVol_personaModelId', personaModelId) - } - else if (returnCode == '404') { - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "VF Module not found at AAI") - } - else { - WorkflowException aWorkflowException = exceptionUtil.MapAAIExceptionToWorkflowException(aaiResponseAsString, execution) - throw new BpmnError("MSOWorkflowException") - } - } - /** - * - */ - public String getRelatedVfModuleRelatedLink(xml) { - def list = new XmlSlurper().parseText(xml) - def vfModuleRelationship = list.'**'.find { node -> node.'related-to'.text() == 'vf-module' } - return vfModuleRelationship?.'related-link'?.text() ?: '' - } - - /** - * Prepare a Request for invoking the VnfAdapterRest subflow to do - * a Volume Group update. - * - * @param execution The flow's execution instance. - */ - public void prepVnfAdapterRest(Execution execution, isDebugLogEnabled) { - - def aicCloudRegion = execution.getVariable('UPDVfModVol_aicCloudRegion') - def tenantId = execution.getVariable('UPDVfModVol_tenantId') - def volumeGroupId = execution.getVariable('UPDVfModVol_volumeGroupId') - - def aaiVolumeGroupResponse = execution.getVariable('UPDVfModVol_aaiVolumeGroupResponse') - def volumeGroupHeatStackId = getNodeTextForce(aaiVolumeGroupResponse, 'heat-stack-id') - def volumeGroupName = getNodeTextForce(aaiVolumeGroupResponse, 'volume-group-name') - def modelCustomizationId = getNodeTextForce(aaiVolumeGroupResponse, 'vf-module-persona-model-customization-id') - - def vnfType = execution.getVariable('UPDVfModVol_vnfType') - def vnfVersion = execution.getVariable('UPDVfModVol_vnfVersion') - - def aaiGenericVnfResponse = execution.getVariable('UPDVfModVol_AAIQueryGenericVfnResponse') - def vnfId = utils.getNodeText1(aaiGenericVnfResponse, 'vnf-id') - def vnfName = utils.getNodeText1(aaiGenericVnfResponse, 'vnf-name') - - - def volumeParamsXml = execution.getVariable('UPDVfModVol_volumeParams') - def volumeGroupParams = transformVolumeParamsToEntries(volumeParamsXml) - - def requestId = execution.getVariable('UPDVfModVol_requestId') - def serviceId = execution.getVariable('UPDVfModVol_serviceId') - - def messageId = execution.getVariable('mso-request-id') + '-' + System.currentTimeMillis() - def notificationUrl = createCallbackURL(execution, "VNFAResponse", messageId) - def useQualifiedHostName = execution.getVariable("URN_mso_use_qualified_host") - if ('true'.equals(useQualifiedHostName)) { - notificationUrl = utils.getQualifiedHostNameForCallback(notificationUrl) - } - - String vnfAdapterRestRequest = """ - - ${aicCloudRegion} - ${tenantId} - ${vnfId} - ${vnfName} - ${volumeGroupId} - ${volumeGroupName} - ${volumeGroupHeatStackId} - ${vnfType} - ${vnfVersion} - - ${modelCustomizationId} - - - vnf_id - ${vnfId} - - - vnf_name - ${vnfName} - - - vf_module_id - ${volumeGroupId} - - - vf_module_name - ${volumeGroupName} - - ${volumeGroupParams} - - true - - ${requestId} - ${serviceId} - - ${messageId} - ${notificationUrl} - - """ - vnfAdapterRestRequest = utils.formatXml(vnfAdapterRestRequest) - execution.setVariable('UPDVfModVol_vnfAdapterRestRequest', vnfAdapterRestRequest) - logDebug('Request for VNFAdapter Rest:\n' + vnfAdapterRestRequest, isDebugLogEnabled) - } - - /** - * Prepare a Request for updating the DB for this Infra request. - * - * @param execution The flow's execution instance. - */ - public void prepDbInfraDbRequest(Execution execution, isDebugLogEnabled) { - - def requestId = execution.getVariable('UPDVfModVol_requestId') - - String updateInfraRequest = """ - - - - - ${requestId} - BPEL - COMPLETE - 100 - - - - """ - - updateInfraRequest = utils.formatXml(updateInfraRequest) - execution.setVariable('UPDVfModVol_updateInfraRequest', updateInfraRequest) - logDebug('Request for Update Infra Request:\n' + updateInfraRequest, isDebugLogEnabled) - } - - /** - * Build a "CompletionHandler" request. - * @param execution The flow's execution instance. - */ - public void prepCompletionHandlerRequest(Execution execution, requestId, action, source, isDebugLogEnabled) { - - String content = """ - - - ${requestId} - CREATE - ${source} - - BPMN VF Module Volume action: UPDATE - - """ - - content = utils.formatXml(content) - logDebug('Request for Completion Handler:\n' + content, isDebugLogEnabled) - execution.setVariable('UPDVfModVol_CompletionHandlerRequest', content) - } - - - /** - * Build a "FalloutHandler" request. - * @param execution The flow's execution instance. - */ - public void prepFalloutHandler(Execution execution, isDebugLogEnabled) { - - def requestInfo = execution.getVariable('UPDVfModVol_requestInfo') - - def WorkflowException workflowException = execution.getVariable("WorkflowException") - def errorResponseCode = workflowException.getErrorCode() - def errorResponseMsg = workflowException.getErrorMessage() - def encErrorResponseMsg = "" - if (errorResponseMsg != null) { - encErrorResponseMsg = errorResponseMsg.replace("&", "&").replace("<", "<").replace(">", ">") - } - - String content = """ - - ${requestInfo} - - ${encErrorResponseMsg} - ${errorResponseCode} - - - """ - content = utils.formatXml(content) - logDebug('Request for Fallout Handler:\n' + content, isDebugLogEnabled) - execution.setVariable('UPDVfModVol_FalloutHandlerRequest', content) - } - - /** - * Create a WorkflowException for the error case where the Tenant Id from - * AAI did not match the Tenant Id in the incoming request. - * @param execution The flow's execution instance. - */ - public void handleTenantIdMismatch(Execution execution, isDebugLogEnabled) { - - def volumeGroupId = execution.getVariable('UPDVfModVol_volumeGroupId') - def aicCloudRegion = execution.getVariable('UPDVfModVol_aicCloudRegion') - def tenantId = execution.getVariable('UPDVfModVol_tenantId') - def volumeGroupTenantId = execution.getVariable('UPDVfModVol_volumeGroupTenantId') - - def String errorMessage = "TenantId " + tenantId + " in incoming request does not match Tenant Id " + volumeGroupTenantId + - " retrieved from AAI for Volume Group Id " + volumeGroupId + ", AIC Cloud Region " + aicCloudRegion - - ExceptionUtil exceptionUtil = new ExceptionUtil() - logError('Error in UpdateVfModuleVol: ' + errorMessage) - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, errorMessage) - } - - /** - * Create a WorkflowException for the error case where the Personal Model Id from - * AAI did not match the model invariant ID in the incoming request. - * @param execution The flow's execution instance. - */ - public void handlePersonaModelIdMismatch(Execution execution, isDebugLogEnabled) { - - def modelInvariantId = execution.getVariable('UPDVfModVol_modelInvariantId') - def personaModelId = execution.getVariable('UPDVfModVol_personaModelId') - - def String errorMessage = "Model Invariant ID " + modelInvariantId + " in incoming request does not match persona model ID " + personaModelId + - " retrieved from AAI for Volume Group Id " - - ExceptionUtil exceptionUtil = new ExceptionUtil() - logError('Error in UpdateVfModuleVol: ' + errorMessage) - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, errorMessage) - } - -} +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.bpmn.infrastructure.scripts + +import groovy.json.JsonSlurper + +import java.util.concurrent.ExecutionException; + +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.runtime.Execution +import org.apache.commons.lang3.* +import org.springframework.web.util.UriUtils +import org.openecomp.mso.bpmn.common.scripts.AaiUtil; +import org.openecomp.mso.bpmn.common.scripts.ExceptionUtil; +import org.openecomp.mso.bpmn.common.scripts.VfModuleBase; +import org.openecomp.mso.bpmn.common.scripts.VidUtils; +import org.openecomp.mso.bpmn.core.WorkflowException +import org.openecomp.mso.rest.APIResponse +import org.openecomp.mso.rest.RESTClient +import org.openecomp.mso.rest.RESTConfig + +class UpdateVfModuleVolumeInfraV1 extends VfModuleBase { + + /** + * Initialize the flow's variables. + * + * @param execution The flow's execution instance. + */ + private void initProcessVariables(Execution execution) { + execution.setVariable('prefix', 'UPDVfModVol_') + execution.setVariable('UPDVfModVol_Request', null) + execution.setVariable('UPDVfModVol_requestInfo', null) + execution.setVariable('UPDVfModVol_requestId', null) + execution.setVariable('UPDVfModVol_source', null) + execution.setVariable('UPDVfModVol_volumeInputs', null) + execution.setVariable('UPDVfModVol_volumeGroupId', null) + execution.setVariable('UPDVfModVol_vnfType', null) + execution.setVariable('UPDVfModVol_serviceId', null) + execution.setVariable('UPDVfModVol_aicCloudRegion', null) + execution.setVariable('UPDVfModVol_tenantId', null) + execution.setVariable('UPDVfModVol_volumeParams', null) + execution.setVariable('UPDVfModVol_volumeGroupHeatStackId', null) + execution.setVariable('UPDVfModVol_volumeGroupTenantId', null) + execution.setVariable('UpdateVfModuleVolumeSuccessIndicator', false) + } + + + /** + * Perform initial processing, such as request validation, initialization of variables, etc. + * * @param execution + */ + public void preProcessRequest (Execution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + preProcessRequest(execution, isDebugEnabled) + } + + public void preProcessRequest(Execution execution, isDebugLogEnabled) { + + initProcessVariables(execution) + String jsonRequest = validateRequest(execution) + + def request = "" + + try { + def jsonSlurper = new JsonSlurper() + Map reqMap = jsonSlurper.parseText(jsonRequest) + + def serviceInstanceId = execution.getVariable('serviceInstanceId') + def volumeGroupId = execution.getVariable('volumeGroupId') + //def vnfId = execution.getVariable('vnfId') + + def vidUtils = new VidUtils(this) + request = vidUtils.createXmlVolumeRequest(reqMap, 'UPDATE_VF_MODULE_VOL', serviceInstanceId, volumeGroupId) + + execution.setVariable('UPDVfModVol_Request', request) + execution.setVariable("UPDVfModVol_isVidRequest", true) + + //need to get persona-model-id aka model-invariantId to use later to validate vf-module relation in AAI + + def modelInvariantId = reqMap.requestDetails.modelInfo.modelInvariantId ?: '' + execution.setVariable('UPDVfModVol_modelInvariantId', modelInvariantId) + + utils.log("DEBUG", "XML request:\n" + request, isDebugLogEnabled) + } + catch(groovy.json.JsonException je) { + utils.log("DEBUG", " Request is in XML format.", isDebugLogEnabled) + // assume request is in XML format - proceed as usual to process XML request + } + + def requestId = execution.getVariable('mso-request-id') + + def requestInfo = getRequiredNodeXml(execution, request, 'request-info') + execution.setVariable('UPDVfModVol_requestInfo', requestInfo) + execution.setVariable('UPDVfModVol_requestId', requestId) + //execution.setVariable('UPDVfModVol_requestId', getRequiredNodeText(execution, requestInfo, 'request-id')) + execution.setVariable('UPDVfModVol_source', getNodeTextForce(requestInfo, 'source')) + + def volumeInputs = getRequiredNodeXml(execution, request, 'volume-inputs') + execution.setVariable('UPDVfModVol_volumeInputs', volumeInputs) + execution.setVariable('UPDVfModVol_volumeGroupId', getRequiredNodeText(execution, volumeInputs, 'volume-group-id')) + execution.setVariable('UPDVfModVol_vnfType', getRequiredNodeText(execution, volumeInputs, 'vnf-type')) + execution.setVariable('UPDVfModVol_vnfVersion', getRequiredNodeText(execution, volumeInputs, 'asdc-service-model-version')) + execution.setVariable('UPDVfModVol_serviceId', utils.getNodeText1(volumeInputs, 'service-id')) + execution.setVariable('UPDVfModVol_aicCloudRegion', getRequiredNodeText(execution, volumeInputs, 'aic-cloud-region')) + execution.setVariable('UPDVfModVol_tenantId', getRequiredNodeText(execution, volumeInputs, 'tenant-id')) + //execution.setVariable('UPDVfModVol_modelCustomizationId', getRequiredNodeText(execution, volumeInputs, 'model-customization-id')) + + try { + // Catalog DB headers Authorization + String basicAuthValueDB = execution.getVariable("URN_mso_adapters_db_auth") + utils.log("DEBUG", " Obtained BasicAuth userid password for Catalog DB adapter: " + basicAuthValueDB, isDebugLogEnabled) + + def encodedString = utils.getBasicAuth(basicAuthValueDB, execution.getVariable("URN_mso_msoKey")) + execution.setVariable("BasicAuthHeaderValueDB",encodedString) + } catch (IOException ex) { + String dataErrorMessage = " Unable to encode Catalog DB user/password string - " + ex.getMessage() + utils.log("DEBUG", dataErrorMessage, isDebugLogEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) + } + def volumeParams = utils.getNodeXml(request, 'volume-params') + execution.setVariable('UPDVfModVol_volumeParams', volumeParams) + } + + /** + * Prepare and send the synchronous response. + * + * @param execution The flow's execution instance. + */ + public void sendSynchResponse(Execution execution, isDebugLogEnabled) { + + def requestInfo = execution.getVariable('UPDVfModVol_requestInfo') + def requestId = execution.getVariable('UPDVfModVol_requestId') + def source = execution.getVariable('UPDVfModVol_source') + def progress = getNodeTextForce(requestInfo, 'progress') + if (progress.isEmpty()) { + progress = '0' + } + def startTime = getNodeTextForce(requestInfo, 'start-time') + if (startTime.isEmpty()) { + startTime = System.currentTimeMillis() + } + def volumeInputs = execution.getVariable('UPDVfModVol_volumeInputs') + + String xmlSyncResponse = """ + + + ${requestId} + UPDATE_VF_MODULE_VOL + IN_PROGRESS + ${progress} + ${startTime} + ${source} + + ${volumeInputs} + + """ + + def syncResponse = '' + def isVidRequest = execution.getVariable('UPDVfModVol_isVidRequest') + + if(isVidRequest) { + def volumeGroupId = execution.getVariable('volumeGroupId') + syncResponse = """{"requestReferences":{"instanceId":"${volumeGroupId}","requestId":"${requestId}"}}""".trim() + } + else { + syncResponse = utils.formatXml(xmlSyncResponse) + } + + logDebug('Sync response: ' + syncResponse, isDebugLogEnabled) + execution.setVariable('UPDVfModVol_syncResponseSent', true) + sendWorkflowResponse(execution, 200, syncResponse) + } + + /** + * Prepare a Request for querying AAI for Volume Group information using the + * Volume Group Id and Aic Cloud Region. + * @param execution The flow's execution instance. + */ + public void queryAAIForVolumeGroup(Execution execution, isDebugLogEnabled) { + + def volumeGroupId = execution.getVariable('UPDVfModVol_volumeGroupId') + def aicCloudRegion = execution.getVariable('UPDVfModVol_aicCloudRegion') + + AaiUtil aaiUtil = new AaiUtil(this) + String aaiEndpoint = aaiUtil.getCloudInfrastructureCloudRegionEndpoint(execution) + String queryAAIVolumeGroupRequest = aaiEndpoint + '/' + URLEncoder.encode(aicCloudRegion, "UTF-8") + "/volume-groups/volume-group/" + UriUtils.encode(volumeGroupId, "UTF-8") + + utils.logAudit('Query AAI volume group by ID: ' + queryAAIVolumeGroupRequest) + logDebug('Query AAI volume group by ID: ' + queryAAIVolumeGroupRequest, isDebugLogEnabled) + + APIResponse response = aaiUtil.executeAAIGetCall(execution, queryAAIVolumeGroupRequest) + + String returnCode = response.getStatusCode() + String aaiResponseAsString = response.getResponseBodyAsString() + aaiResponseAsString = StringEscapeUtils.unescapeXml(aaiResponseAsString) + + utils.logAudit("AAI query volume group by id return code: " + returnCode) + utils.logAudit("AAI query volume group by id response: " + aaiResponseAsString) + + logDebug("AAI Volume Group return code: " + returnCode, isDebugLogEnabled) + logDebug("AAI Volume Group response: " + aaiResponseAsString, isDebugLogEnabled) + + ExceptionUtil exceptionUtil = new ExceptionUtil() + + if ((returnCode == '200') || (returnCode == '204')) { + + execution.setVariable('UPDVfModVol_aaiVolumeGroupResponse', aaiResponseAsString) + //def heatStackId = getNodeTextForce(aaiResponseAsString, 'heat-stack-id') + //execution.setVariable('UPDVfModVol_volumeGroupHeatStackId', heatStackId) + + def volumeGroupTenantId = getTenantIdFromVolumeGroup(aaiResponseAsString) + if (volumeGroupTenantId == null) { + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Could not find Tenant Id element in Volume Group with Volume Group Id " + volumeGroupId + + ", AIC Cloud Region " + aicCloudRegion) + } + execution.setVariable('UPDVfModVol_volumeGroupTenantId', volumeGroupTenantId) + logDebug("Received Tenant Id " + volumeGroupTenantId + " from AAI for Volume Group with Volume Group Id " + volumeGroupId + ", AIC Cloud Region " + aicCloudRegion, isDebugLogEnabled) + + def relatedVfModuleLink = getRelatedVfModuleRelatedLink(aaiResponseAsString) + logDebug("Related VF Module link: " + relatedVfModuleLink, isDebugLogEnabled) + execution.setVariable('UPDVfModVol_relatedVfModuleLink', relatedVfModuleLink) + + } + else if (returnCode == '404') { + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Volume Group " + volumeGroupId + " not found at AAI") + } + else { + WorkflowException aWorkflowException = exceptionUtil.MapAAIExceptionToWorkflowException(aaiResponseAsString, execution) + throw new BpmnError("MSOWorkflowException") + } + } + + /** + * Query AAI service instance + * @param execution + * @param isDebugEnabled + */ + public void queryAAIForGenericVnf(Execution execution, isDebugEnabled) { + + def vnfId = execution.getVariable('vnfId') + + AaiUtil aaiUtil = new AaiUtil(this) + String aaiEndpoint = aaiUtil.getNetworkGenericVnfEndpoint(execution) + def String queryAAIRequest = aaiEndpoint + "/" + UriUtils.encode(vnfId, "UTF-8") + + utils.logAudit("AAI query generic vnf request: " + queryAAIRequest) + + APIResponse response = aaiUtil.executeAAIGetCall(execution, queryAAIRequest) + + String returnCode = response.getStatusCode() + String aaiResponseAsString = response.getResponseBodyAsString() + aaiResponseAsString = StringEscapeUtils.unescapeXml(aaiResponseAsString) + + utils.logAudit("AAI query generic vnf return code: " + returnCode) + utils.logAudit("AAI query generic vnf response: " + aaiResponseAsString) + + ExceptionUtil exceptionUtil = new ExceptionUtil() + + if (returnCode=='200') { + utils.log("DEBUG", 'Generic vnf ' + vnfId + ' found in AAI.', isDebugEnabled) + execution.setVariable('UPDVfModVol_AAIQueryGenericVfnResponse', aaiResponseAsString) + } else { + if (returnCode=='404') { + def message = 'Generic vnf ' + vnfId + ' was not found in AAI. Return code: 404.' + utils.log("DEBUG", message, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, message) + } else { + WorkflowException aWorkflowException = exceptionUtil.MapAAIExceptionToWorkflowException(aaiResponseAsString, execution) + throw new BpmnError("MSOWorkflowException") + } + } + } + + /** + * Query AAI for VF Module using vf-module-id + * @param execution + * @param isDebugLogEnabled + */ + public void queryAAIForVfModule(Execution execution, isDebugLogEnabled) { + + AaiUtil aaiUtil = new AaiUtil(this) + String queryAAIVfModuleRequest = execution.getVariable('UPDVfModVol_relatedVfModuleLink') + execution.setVariable('UPDVfModVol_personaModelId', '') + + utils.logAudit('Query AAI VF Module: ' + queryAAIVfModuleRequest) + logDebug('Query AAI VF Module: ' + queryAAIVfModuleRequest, isDebugLogEnabled) + + APIResponse response = aaiUtil.executeAAIGetCall(execution, queryAAIVfModuleRequest) + + String returnCode = response.getStatusCode() + String aaiResponseAsString = response.getResponseBodyAsString() + aaiResponseAsString = StringEscapeUtils.unescapeXml(aaiResponseAsString) + + utils.logAudit("AAI query vf-module: " + returnCode) + utils.logAudit("AAI query vf-module response: " + aaiResponseAsString) + + logDebug("AAI query vf-module:: " + returnCode, isDebugLogEnabled) + logDebug("AAI query vf-module response: " + aaiResponseAsString, isDebugLogEnabled) + + ExceptionUtil exceptionUtil = new ExceptionUtil() + + if ((returnCode == '200') || (returnCode == '204')) { + def personaModelId = utils.getNodeText1(aaiResponseAsString, 'persona-model-id') + execution.setVariable('UPDVfModVol_personaModelId', personaModelId) + } + else if (returnCode == '404') { + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "VF Module not found at AAI") + } + else { + WorkflowException aWorkflowException = exceptionUtil.MapAAIExceptionToWorkflowException(aaiResponseAsString, execution) + throw new BpmnError("MSOWorkflowException") + } + } + /** + * + */ + public String getRelatedVfModuleRelatedLink(xml) { + def list = new XmlSlurper().parseText(xml) + def vfModuleRelationship = list.'**'.find { node -> node.'related-to'.text() == 'vf-module' } + return vfModuleRelationship?.'related-link'?.text() ?: '' + } + + /** + * Prepare a Request for invoking the VnfAdapterRest subflow to do + * a Volume Group update. + * + * @param execution The flow's execution instance. + */ + public void prepVnfAdapterRest(Execution execution, isDebugLogEnabled) { + + def aicCloudRegion = execution.getVariable('UPDVfModVol_aicCloudRegion') + def tenantId = execution.getVariable('UPDVfModVol_tenantId') + def volumeGroupId = execution.getVariable('UPDVfModVol_volumeGroupId') + + def aaiVolumeGroupResponse = execution.getVariable('UPDVfModVol_aaiVolumeGroupResponse') + def volumeGroupHeatStackId = getNodeTextForce(aaiVolumeGroupResponse, 'heat-stack-id') + def volumeGroupName = getNodeTextForce(aaiVolumeGroupResponse, 'volume-group-name') + def modelCustomizationId = getNodeTextForce(aaiVolumeGroupResponse, 'vf-module-persona-model-customization-id') + + def vnfType = execution.getVariable('UPDVfModVol_vnfType') + def vnfVersion = execution.getVariable('UPDVfModVol_vnfVersion') + + def aaiGenericVnfResponse = execution.getVariable('UPDVfModVol_AAIQueryGenericVfnResponse') + def vnfId = utils.getNodeText1(aaiGenericVnfResponse, 'vnf-id') + def vnfName = utils.getNodeText1(aaiGenericVnfResponse, 'vnf-name') + + + def volumeParamsXml = execution.getVariable('UPDVfModVol_volumeParams') + def volumeGroupParams = transformVolumeParamsToEntries(volumeParamsXml) + + def requestId = execution.getVariable('UPDVfModVol_requestId') + def serviceId = execution.getVariable('UPDVfModVol_serviceId') + + def messageId = execution.getVariable('mso-request-id') + '-' + System.currentTimeMillis() + def notificationUrl = createCallbackURL(execution, "VNFAResponse", messageId) + def useQualifiedHostName = execution.getVariable("URN_mso_use_qualified_host") + if ('true'.equals(useQualifiedHostName)) { + notificationUrl = utils.getQualifiedHostNameForCallback(notificationUrl) + } + + String vnfAdapterRestRequest = """ + + ${aicCloudRegion} + ${tenantId} + ${vnfId} + ${vnfName} + ${volumeGroupId} + ${volumeGroupName} + ${volumeGroupHeatStackId} + ${vnfType} + ${vnfVersion} + + ${modelCustomizationId} + + + vnf_id + ${vnfId} + + + vnf_name + ${vnfName} + + + vf_module_id + ${volumeGroupId} + + + vf_module_name + ${volumeGroupName} + + ${volumeGroupParams} + + true + + ${requestId} + ${serviceId} + + ${messageId} + ${notificationUrl} + + """ + vnfAdapterRestRequest = utils.formatXml(vnfAdapterRestRequest) + execution.setVariable('UPDVfModVol_vnfAdapterRestRequest', vnfAdapterRestRequest) + logDebug('Request for VNFAdapter Rest:\n' + vnfAdapterRestRequest, isDebugLogEnabled) + } + + /** + * Prepare a Request for updating the DB for this Infra request. + * + * @param execution The flow's execution instance. + */ + public void prepDbInfraDbRequest(Execution execution, isDebugLogEnabled) { + + def requestId = execution.getVariable('UPDVfModVol_requestId') + + String updateInfraRequest = """ + + + + + ${requestId} + BPEL + COMPLETE + 100 + + + + """ + + updateInfraRequest = utils.formatXml(updateInfraRequest) + execution.setVariable('UPDVfModVol_updateInfraRequest', updateInfraRequest) + logDebug('Request for Update Infra Request:\n' + updateInfraRequest, isDebugLogEnabled) + } + + /** + * Build a "CompletionHandler" request. + * @param execution The flow's execution instance. + */ + public void prepCompletionHandlerRequest(Execution execution, requestId, action, source, isDebugLogEnabled) { + + String content = """ + + + ${requestId} + CREATE + ${source} + + BPMN VF Module Volume action: UPDATE + + """ + + content = utils.formatXml(content) + logDebug('Request for Completion Handler:\n' + content, isDebugLogEnabled) + execution.setVariable('UPDVfModVol_CompletionHandlerRequest', content) + } + + + /** + * Build a "FalloutHandler" request. + * @param execution The flow's execution instance. + */ + public void prepFalloutHandler(Execution execution, isDebugLogEnabled) { + + def requestInfo = execution.getVariable('UPDVfModVol_requestInfo') + + def WorkflowException workflowException = execution.getVariable("WorkflowException") + def errorResponseCode = workflowException.getErrorCode() + def errorResponseMsg = workflowException.getErrorMessage() + def encErrorResponseMsg = "" + if (errorResponseMsg != null) { + encErrorResponseMsg = errorResponseMsg.replace("&", "&").replace("<", "<").replace(">", ">") + } + + String content = """ + + ${requestInfo} + + ${encErrorResponseMsg} + ${errorResponseCode} + + + """ + content = utils.formatXml(content) + logDebug('Request for Fallout Handler:\n' + content, isDebugLogEnabled) + execution.setVariable('UPDVfModVol_FalloutHandlerRequest', content) + } + + /** + * Create a WorkflowException for the error case where the Tenant Id from + * AAI did not match the Tenant Id in the incoming request. + * @param execution The flow's execution instance. + */ + public void handleTenantIdMismatch(Execution execution, isDebugLogEnabled) { + + def volumeGroupId = execution.getVariable('UPDVfModVol_volumeGroupId') + def aicCloudRegion = execution.getVariable('UPDVfModVol_aicCloudRegion') + def tenantId = execution.getVariable('UPDVfModVol_tenantId') + def volumeGroupTenantId = execution.getVariable('UPDVfModVol_volumeGroupTenantId') + + def String errorMessage = "TenantId " + tenantId + " in incoming request does not match Tenant Id " + volumeGroupTenantId + + " retrieved from AAI for Volume Group Id " + volumeGroupId + ", AIC Cloud Region " + aicCloudRegion + + ExceptionUtil exceptionUtil = new ExceptionUtil() + logError('Error in UpdateVfModuleVol: ' + errorMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, errorMessage) + } + + /** + * Create a WorkflowException for the error case where the Personal Model Id from + * AAI did not match the model invariant ID in the incoming request. + * @param execution The flow's execution instance. + */ + public void handlePersonaModelIdMismatch(Execution execution, isDebugLogEnabled) { + + def modelInvariantId = execution.getVariable('UPDVfModVol_modelInvariantId') + def personaModelId = execution.getVariable('UPDVfModVol_personaModelId') + + def String errorMessage = "Model Invariant ID " + modelInvariantId + " in incoming request does not match persona model ID " + personaModelId + + " retrieved from AAI for Volume Group Id " + + ExceptionUtil exceptionUtil = new ExceptionUtil() + logError('Error in UpdateVfModuleVol: ' + errorMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, errorMessage) + } + +} diff --git a/bpmn/MSOInfrastructureBPMN/src/main/java/org/openecomp/mso/bpmn/infrastructure/MSOInfrastructureApplication.java b/bpmn/MSOInfrastructureBPMN/src/main/java/org/openecomp/mso/bpmn/infrastructure/MSOInfrastructureApplication.java index 2f1ca17c0d..07ec8ff5dc 100644 --- a/bpmn/MSOInfrastructureBPMN/src/main/java/org/openecomp/mso/bpmn/infrastructure/MSOInfrastructureApplication.java +++ b/bpmn/MSOInfrastructureBPMN/src/main/java/org/openecomp/mso/bpmn/infrastructure/MSOInfrastructureApplication.java @@ -1,58 +1,58 @@ -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - MSO - * ================================================================================ - * 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.openecomp.mso.bpmn.infrastructure; - -import java.util.List; - -import org.camunda.bpm.application.PostDeploy; -import org.camunda.bpm.application.PreUndeploy; -import org.camunda.bpm.application.ProcessApplication; -import org.camunda.bpm.application.ProcessApplicationInfo; -import org.camunda.bpm.application.impl.ServletProcessApplication; -import org.camunda.bpm.engine.ProcessEngine; - -import org.openecomp.mso.logger.MsoLogger; - -/** - * @since Version 1.0 - * - */ -@ProcessApplication("MSO Infrastructure Application") -public class MSOInfrastructureApplication extends ServletProcessApplication { - - private MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL); - - @PostDeploy - public void postDeploy(ProcessEngine processEngineInstance) { - long startTime = System.currentTimeMillis(); - - msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Post deployment complete..."); - } - - @PreUndeploy - public void cleanup(ProcessEngine processEngine, ProcessApplicationInfo processApplicationInfo, List processEngines) { - long startTime = System.currentTimeMillis(); - - msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Pre Undeploy complete..."); - - } - -} +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.bpmn.infrastructure; + +import java.util.List; + +import org.camunda.bpm.application.PostDeploy; +import org.camunda.bpm.application.PreUndeploy; +import org.camunda.bpm.application.ProcessApplication; +import org.camunda.bpm.application.ProcessApplicationInfo; +import org.camunda.bpm.application.impl.ServletProcessApplication; +import org.camunda.bpm.engine.ProcessEngine; + +import org.openecomp.mso.logger.MsoLogger; + +/** + * @since Version 1.0 + * + */ +@ProcessApplication("MSO Infrastructure Application") +public class MSOInfrastructureApplication extends ServletProcessApplication { + + private MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL); + + @PostDeploy + public void postDeploy(ProcessEngine processEngineInstance) { + long startTime = System.currentTimeMillis(); + + msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Post deployment complete..."); + } + + @PreUndeploy + public void cleanup(ProcessEngine processEngine, ProcessApplicationInfo processApplicationInfo, List processEngines) { + long startTime = System.currentTimeMillis(); + + msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Pre Undeploy complete..."); + + } + +} diff --git a/bpmn/MSOInfrastructureBPMN/src/main/java/org/openecomp/mso/bpmn/infrastructure/workflow/service/WorkflowAsyncInfrastructureResource.java b/bpmn/MSOInfrastructureBPMN/src/main/java/org/openecomp/mso/bpmn/infrastructure/workflow/service/WorkflowAsyncInfrastructureResource.java index 0a35f5220f..09454f0876 100644 --- a/bpmn/MSOInfrastructureBPMN/src/main/java/org/openecomp/mso/bpmn/infrastructure/workflow/service/WorkflowAsyncInfrastructureResource.java +++ b/bpmn/MSOInfrastructureBPMN/src/main/java/org/openecomp/mso/bpmn/infrastructure/workflow/service/WorkflowAsyncInfrastructureResource.java @@ -1,50 +1,50 @@ -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - MSO - * ================================================================================ - * 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.openecomp.mso.bpmn.infrastructure.workflow.service; - -import javax.ws.rs.Path; - -import org.camunda.bpm.engine.ProcessEngineServices; -import org.camunda.bpm.engine.ProcessEngines; -import org.openecomp.mso.bpmn.common.workflow.service.WorkflowAsyncResource; - - -/** - * - * @version 1.0 - * Asynchronous Workflow processing using JAX RS RESTeasy implementation - * Both Synchronous and Asynchronous BPMN process can benefit from this implementation since the workflow gets executed in the background - * and the server thread is freed up, server scales better to process more incoming requests - * - * Usage: For synchronous process, when you are ready to send the response invoke the callback to write the response - * For asynchronous process - the activity may send a acknowledgement response and then proceed further on executing the process - */ -@Path("/async") -public class WorkflowAsyncInfrastructureResource extends WorkflowAsyncResource { - - protected ProcessEngineServices getProcessEngineServices() { - if (pes4junit == null) { - return ProcessEngines.getProcessEngine("infrastructure"); - } else { - return pes4junit; - } - } -} +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.bpmn.infrastructure.workflow.service; + +import javax.ws.rs.Path; + +import org.camunda.bpm.engine.ProcessEngineServices; +import org.camunda.bpm.engine.ProcessEngines; +import org.openecomp.mso.bpmn.common.workflow.service.WorkflowAsyncResource; + + +/** + * + * @version 1.0 + * Asynchronous Workflow processing using JAX RS RESTeasy implementation + * Both Synchronous and Asynchronous BPMN process can benefit from this implementation since the workflow gets executed in the background + * and the server thread is freed up, server scales better to process more incoming requests + * + * Usage: For synchronous process, when you are ready to send the response invoke the callback to write the response + * For asynchronous process - the activity may send a acknowledgement response and then proceed further on executing the process + */ +@Path("/async") +public class WorkflowAsyncInfrastructureResource extends WorkflowAsyncResource { + + protected ProcessEngineServices getProcessEngineServices() { + if (pes4junit == null) { + return ProcessEngines.getProcessEngine("infrastructure"); + } else { + return pes4junit; + } + } +} diff --git a/bpmn/MSOInfrastructureBPMN/src/main/java/org/openecomp/mso/bpmn/infrastructure/workflow/service/WorkflowResourceApplication.java b/bpmn/MSOInfrastructureBPMN/src/main/java/org/openecomp/mso/bpmn/infrastructure/workflow/service/WorkflowResourceApplication.java index 79eafbe5d8..84a9bae051 100644 --- a/bpmn/MSOInfrastructureBPMN/src/main/java/org/openecomp/mso/bpmn/infrastructure/workflow/service/WorkflowResourceApplication.java +++ b/bpmn/MSOInfrastructureBPMN/src/main/java/org/openecomp/mso/bpmn/infrastructure/workflow/service/WorkflowResourceApplication.java @@ -1,57 +1,57 @@ -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - MSO - * ================================================================================ - * 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.openecomp.mso.bpmn.infrastructure.workflow.service; - -import java.util.HashSet; -import java.util.Set; - -import javax.ws.rs.ApplicationPath; -import javax.ws.rs.core.Application; - -import org.openecomp.mso.bpmn.common.workflow.service.WorkflowMessageResource; -import org.openecomp.mso.bpmn.common.workflow.service.WorkflowResource; - -/** - * @version 1.0 - * RESTeasy workflow application which wires synchronous and asynchronous response - * - */ -@ApplicationPath("/") -public class WorkflowResourceApplication extends Application { - private Set singletons = new HashSet(); - private Set> classes = new HashSet>(); - - public WorkflowResourceApplication() { - singletons.add(new WorkflowResource()); - singletons.add(new WorkflowAsyncInfrastructureResource()); - singletons.add(new WorkflowMessageResource()); - } - - @Override - public Set> getClasses() { - return classes; - } - - @Override - public Set getSingletons() { - return singletons; - } -} +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.bpmn.infrastructure.workflow.service; + +import java.util.HashSet; +import java.util.Set; + +import javax.ws.rs.ApplicationPath; +import javax.ws.rs.core.Application; + +import org.openecomp.mso.bpmn.common.workflow.service.WorkflowMessageResource; +import org.openecomp.mso.bpmn.common.workflow.service.WorkflowResource; + +/** + * @version 1.0 + * RESTeasy workflow application which wires synchronous and asynchronous response + * + */ +@ApplicationPath("/") +public class WorkflowResourceApplication extends Application { + private Set singletons = new HashSet(); + private Set> classes = new HashSet>(); + + public WorkflowResourceApplication() { + singletons.add(new WorkflowResource()); + singletons.add(new WorkflowAsyncInfrastructureResource()); + singletons.add(new WorkflowMessageResource()); + } + + @Override + public Set> getClasses() { + return classes; + } + + @Override + public Set getSingletons() { + return singletons; + } +} diff --git a/bpmn/MSOInfrastructureBPMN/src/main/resources/META-INF/persistence.xml b/bpmn/MSOInfrastructureBPMN/src/main/resources/META-INF/persistence.xml index 62fcfadca7..8e87f47ddc 100644 --- a/bpmn/MSOInfrastructureBPMN/src/main/resources/META-INF/persistence.xml +++ b/bpmn/MSOInfrastructureBPMN/src/main/resources/META-INF/persistence.xml @@ -1,37 +1,37 @@ - - - - - - - java:jboss/datasources/ProcessEngine - - - - - - - - + + + + + + + java:jboss/datasources/ProcessEngine + + + + + + + + diff --git a/bpmn/MSOInfrastructureBPMN/src/main/resources/META-INF/processes.xml b/bpmn/MSOInfrastructureBPMN/src/main/resources/META-INF/processes.xml index 511ba0ae3d..4053de8e28 100644 --- a/bpmn/MSOInfrastructureBPMN/src/main/resources/META-INF/processes.xml +++ b/bpmn/MSOInfrastructureBPMN/src/main/resources/META-INF/processes.xml @@ -1,81 +1,81 @@ - - - - - - - org.camunda.bpm.engine.impl.cfg.StandaloneProcessEngineConfiguration - java:jboss/datasources/ProcessEngine - - full - true - true - true - true - - - - - - org.camunda.bpm.application.impl.event.ProcessApplicationEventListenerPlugin - - - - - org.camunda.spin.plugin.impl.SpinProcessEnginePlugin - - - - - org.camunda.connect.plugin.impl.ConnectProcessEnginePlugin - - - - org.openecomp.mso.bpmn.core.plugins.LoggingAndURNMappingPlugin - - - - - org.openecomp.mso.bpmn.core.plugins.WorkflowExceptionPlugin - - - - - - - - - - infrastructure - - false - true - - - - + + + + + + + org.camunda.bpm.engine.impl.cfg.StandaloneProcessEngineConfiguration + java:jboss/datasources/ProcessEngine + + full + true + true + true + true + + + + + + org.camunda.bpm.application.impl.event.ProcessApplicationEventListenerPlugin + + + + + org.camunda.spin.plugin.impl.SpinProcessEnginePlugin + + + + + org.camunda.connect.plugin.impl.ConnectProcessEnginePlugin + + + + org.openecomp.mso.bpmn.core.plugins.LoggingAndURNMappingPlugin + + + + + org.openecomp.mso.bpmn.core.plugins.WorkflowExceptionPlugin + + + + + + + + + + infrastructure + + false + true + + + + diff --git a/bpmn/MSOInfrastructureBPMN/src/main/resources/logback.xml b/bpmn/MSOInfrastructureBPMN/src/main/resources/logback.xml index 133fa54003..7c9e0282d4 100644 --- a/bpmn/MSOInfrastructureBPMN/src/main/resources/logback.xml +++ b/bpmn/MSOInfrastructureBPMN/src/main/resources/logback.xml @@ -1,159 +1,159 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ${logDirectory}/${auditLogName}${jboss.server.name}.log - - ${logDirectory}/${auditLogName}${jboss.server.name}.log.%d - - - - ${auditPattern} - - - - 256 - - - - - ${logDirectory}/${metricsLogName}${jboss.server.name}.log - - ${logDirectory}/${metricsLogName}${jboss.server.name}.log.%d - - - - - ${metricPattern} - - - - - - 256 - - - - - ${logDirectory}/${errorLogName}${jboss.server.name}.log - - ${logDirectory}/${errorLogName}${jboss.server.name}.log.%d - - - - INFO - - - ${errorPattern} - - - - - 256 - - - - - ${debugLogDirectory}/${debugLogName}${jboss.server.name}.log - - ${debugLogDirectory}/${debugLogName}${jboss.server.name}.log.%d - - - - ${debugPattern} - - - - - 256 - - true - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ${logDirectory}/${auditLogName}${jboss.server.name}.log + + ${logDirectory}/${auditLogName}${jboss.server.name}.log.%d + + + + ${auditPattern} + + + + 256 + + + + + ${logDirectory}/${metricsLogName}${jboss.server.name}.log + + ${logDirectory}/${metricsLogName}${jboss.server.name}.log.%d + + + + + ${metricPattern} + + + + + + 256 + + + + + ${logDirectory}/${errorLogName}${jboss.server.name}.log + + ${logDirectory}/${errorLogName}${jboss.server.name}.log.%d + + + + INFO + + + ${errorPattern} + + + + + 256 + + + + + ${debugLogDirectory}/${debugLogName}${jboss.server.name}.log + + ${debugLogDirectory}/${debugLogName}${jboss.server.name}.log.%d + + + + ${debugPattern} + + + + + 256 + + true + + + + + + + + + + + + + + + + + + + + + + + diff --git a/bpmn/MSOInfrastructureBPMN/src/main/resources/process/CreateGenericMacroServiceNetworkVnf.bpmn b/bpmn/MSOInfrastructureBPMN/src/main/resources/process/CreateGenericMacroServiceNetworkVnf.bpmn index 1f5318224b..7b9b8212e5 100644 --- a/bpmn/MSOInfrastructureBPMN/src/main/resources/process/CreateGenericMacroServiceNetworkVnf.bpmn +++ b/bpmn/MSOInfrastructureBPMN/src/main/resources/process/CreateGenericMacroServiceNetworkVnf.bpmn @@ -1,1203 +1,1203 @@ - - - - - SequenceFlow_7 - SequenceFlow_3 - - - - - SequenceFlow_1 - - - - SequenceFlow_1 - SequenceFlow_7 - - - - - SequenceFlow_10o22u2 - - - - SequenceFlow_0afe2pg - SequenceFlow_29 - - - - - - - - - - - - - - - SequenceFlow_29 - SequenceFlow_8 - - - - SequenceFlow_8 - SequenceFlow_6 - - - - - SequenceFlow_6 - - - - - SequenceFlow_2 - - - - SequenceFlow_5 - - - - SequenceFlow_2 - SequenceFlow_5 - - - - - - SequenceFlow_12ilko1 - - - - - - - - - - - - - - - - - - - - - - - - - - SequenceFlow_1bwbn7r - SequenceFlow_12ag2bk - - - SequenceFlow_0cmebdc - SequenceFlow_0dfkfh1 - SequenceFlow_1bwbn7r - - - - - - - - - - - - - - - - - - - - - - - SequenceFlow_0j6sjye - SequenceFlow_1ky2sv9 - - - - - - - - - - - - - - - - - - - - SequenceFlow_1h77psn - SequenceFlow_0qi5uxg - - - SequenceFlow_0bvecvm - SequenceFlow_1h77psn - - - - SequenceFlow_0xowenu - - - - SequenceFlow_3 - - - - - SequenceFlow_0zq7i3q - SequenceFlow_0zpbskl - SequenceFlow_0dhf2js - - - SequenceFlow_0zq7i3q - - - - SequenceFlow_0zpbskl - SequenceFlow_1sx5llu - SequenceFlow_02o4yqx - - - SequenceFlow_0sdb3on - SequenceFlow_05lo85t - SequenceFlow_0xtr1g5 - - - SequenceFlow_05lo85t - SequenceFlow_09xerwk - SequenceFlow_19mxskt - SequenceFlow_0tmepzk - - - - - - - - - - - SequenceFlow_0807ukc - SequenceFlow_19yywk8 - - - SequenceFlow_19yywk8 - - - SequenceFlow_19mxskt - SequenceFlow_1brxd2r - SequenceFlow_08s0ew2 - - - SequenceFlow_0jg47xm - SequenceFlow_0807ukc - - - - - - - - - - - - - - - - - - - - - - - - SequenceFlow_0xtr1g5 - SequenceFlow_09xerwk - - - - - - - - - - - SequenceFlow_0136s37 - SequenceFlow_1fqmrda - SequenceFlow_1dmsx0d - - - SequenceFlow_1ieiew4 - SequenceFlow_1os9x7w - SequenceFlow_0g7scsg - - - - - - - - - - SequenceFlow_1os9x7w - SequenceFlow_1f1hd3l - - - SequenceFlow_1sx5llu - SequenceFlow_0dhf2js - SequenceFlow_1rabks0 - SequenceFlow_0jg47xm - - - - - - - - - - - SequenceFlow_1dmsx0d - SequenceFlow_1otyild - - - - SequenceFlow_1otyild - SequenceFlow_0136s37 - SequenceFlow_12u8ufr - - - - - 0 }]]> - - - - SequenceFlow_0tmepzk - SequenceFlow_1fqmrda - SequenceFlow_1brxd2r - - - - - - - - - - SequenceFlow_12u8ufr - SequenceFlow_08s0ew2 - SequenceFlow_1ieiew4 - SequenceFlow_0sezboq - - - - - - - - - SequenceFlow_1f1hd3l - SequenceFlow_0g7scsg - SequenceFlow_0sezboq - SequenceFlow_0f4u373 - - - SequenceFlow_02o4yqx - SequenceFlow_0sdb3on - - - - SequenceFlow_0f4u373 - SequenceFlow_1rabks0 - - - - - - - - SequenceFlow_1vwssu7 - SequenceFlow_19etqmx - - - - SequenceFlow_10o22u2 - SequenceFlow_0j6sjye - - - - - SequenceFlow_12ilko1 - SequenceFlow_0afe2pg - - - - - - - - - SequenceFlow_1vwssu7 - - - - SequenceFlow_13uceka - - - - SequenceFlow_19etqmx - SequenceFlow_0cmebdc - SequenceFlow_1f26zbk - - - SequenceFlow_04vlq8r - SequenceFlow_1n7r495 - SequenceFlow_0dfkfh1 - - - - - - 0}]]> - - - SequenceFlow_1n7r495 - SequenceFlow_1f26zbk - SequenceFlow_1j7n6qx - - - - SequenceFlow_1j7n6qx - - - - - - - SequenceFlow_10tbv62 - - - - SequenceFlow_10tbv62 - SequenceFlow_0bvecvm - SequenceFlow_0w7328u - - - SequenceFlow_0qi5uxg - SequenceFlow_0w7328u - SequenceFlow_0xowenu - - - - 0}]]> - - - in 1702 scope only one VNF will be created - - - - - SequenceFlow_12ag2bk - SequenceFlow_04vlq8r - - - - - - - - - - ${URN_mso_adapters_db_endpoint} - - - - application/soap+xml - - - POST - - soap-http-connector - - - SequenceFlow_0vj46ej - SequenceFlow_13uceka - - - - SequenceFlow_1ky2sv9 - SequenceFlow_0vj46ej - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + SequenceFlow_7 + SequenceFlow_3 + + + + + SequenceFlow_1 + + + + SequenceFlow_1 + SequenceFlow_7 + + + + + SequenceFlow_10o22u2 + + + + SequenceFlow_0afe2pg + SequenceFlow_29 + + + + + + + + + + + + + + + SequenceFlow_29 + SequenceFlow_8 + + + + SequenceFlow_8 + SequenceFlow_6 + + + + + SequenceFlow_6 + + + + + SequenceFlow_2 + + + + SequenceFlow_5 + + + + SequenceFlow_2 + SequenceFlow_5 + + + + + + SequenceFlow_12ilko1 + + + + + + + + + + + + + + + + + + + + + + + + + + SequenceFlow_1bwbn7r + SequenceFlow_12ag2bk + + + SequenceFlow_0cmebdc + SequenceFlow_0dfkfh1 + SequenceFlow_1bwbn7r + + + + + + + + + + + + + + + + + + + + + + + SequenceFlow_0j6sjye + SequenceFlow_1ky2sv9 + + + + + + + + + + + + + + + + + + + + SequenceFlow_1h77psn + SequenceFlow_0qi5uxg + + + SequenceFlow_0bvecvm + SequenceFlow_1h77psn + + + + SequenceFlow_0xowenu + + + + SequenceFlow_3 + + + + + SequenceFlow_0zq7i3q + SequenceFlow_0zpbskl + SequenceFlow_0dhf2js + + + SequenceFlow_0zq7i3q + + + + SequenceFlow_0zpbskl + SequenceFlow_1sx5llu + SequenceFlow_02o4yqx + + + SequenceFlow_0sdb3on + SequenceFlow_05lo85t + SequenceFlow_0xtr1g5 + + + SequenceFlow_05lo85t + SequenceFlow_09xerwk + SequenceFlow_19mxskt + SequenceFlow_0tmepzk + + + + + + + + + + + SequenceFlow_0807ukc + SequenceFlow_19yywk8 + + + SequenceFlow_19yywk8 + + + SequenceFlow_19mxskt + SequenceFlow_1brxd2r + SequenceFlow_08s0ew2 + + + SequenceFlow_0jg47xm + SequenceFlow_0807ukc + + + + + + + + + + + + + + + + + + + + + + + + SequenceFlow_0xtr1g5 + SequenceFlow_09xerwk + + + + + + + + + + + SequenceFlow_0136s37 + SequenceFlow_1fqmrda + SequenceFlow_1dmsx0d + + + SequenceFlow_1ieiew4 + SequenceFlow_1os9x7w + SequenceFlow_0g7scsg + + + + + + + + + + SequenceFlow_1os9x7w + SequenceFlow_1f1hd3l + + + SequenceFlow_1sx5llu + SequenceFlow_0dhf2js + SequenceFlow_1rabks0 + SequenceFlow_0jg47xm + + + + + + + + + + + SequenceFlow_1dmsx0d + SequenceFlow_1otyild + + + + SequenceFlow_1otyild + SequenceFlow_0136s37 + SequenceFlow_12u8ufr + + + + + 0 }]]> + + + + SequenceFlow_0tmepzk + SequenceFlow_1fqmrda + SequenceFlow_1brxd2r + + + + + + + + + + SequenceFlow_12u8ufr + SequenceFlow_08s0ew2 + SequenceFlow_1ieiew4 + SequenceFlow_0sezboq + + + + + + + + + SequenceFlow_1f1hd3l + SequenceFlow_0g7scsg + SequenceFlow_0sezboq + SequenceFlow_0f4u373 + + + SequenceFlow_02o4yqx + SequenceFlow_0sdb3on + + + + SequenceFlow_0f4u373 + SequenceFlow_1rabks0 + + + + + + + + SequenceFlow_1vwssu7 + SequenceFlow_19etqmx + + + + SequenceFlow_10o22u2 + SequenceFlow_0j6sjye + + + + + SequenceFlow_12ilko1 + SequenceFlow_0afe2pg + + + + + + + + + SequenceFlow_1vwssu7 + + + + SequenceFlow_13uceka + + + + SequenceFlow_19etqmx + SequenceFlow_0cmebdc + SequenceFlow_1f26zbk + + + SequenceFlow_04vlq8r + SequenceFlow_1n7r495 + SequenceFlow_0dfkfh1 + + + + + + 0}]]> + + + SequenceFlow_1n7r495 + SequenceFlow_1f26zbk + SequenceFlow_1j7n6qx + + + + SequenceFlow_1j7n6qx + + + + + + + SequenceFlow_10tbv62 + + + + SequenceFlow_10tbv62 + SequenceFlow_0bvecvm + SequenceFlow_0w7328u + + + SequenceFlow_0qi5uxg + SequenceFlow_0w7328u + SequenceFlow_0xowenu + + + + 0}]]> + + + in 1702 scope only one VNF will be created + + + + + SequenceFlow_12ag2bk + SequenceFlow_04vlq8r + + + + + + + + + + ${URN_mso_adapters_db_endpoint} + + + + application/soap+xml + + + POST + + soap-http-connector + + + SequenceFlow_0vj46ej + SequenceFlow_13uceka + + + + SequenceFlow_1ky2sv9 + SequenceFlow_0vj46ej + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/bpmn/MSOInfrastructureBPMN/src/main/resources/process/CreateNetworkInstance.bpmn b/bpmn/MSOInfrastructureBPMN/src/main/resources/process/CreateNetworkInstance.bpmn index e86d287e27..52627a5e33 100644 --- a/bpmn/MSOInfrastructureBPMN/src/main/resources/process/CreateNetworkInstance.bpmn +++ b/bpmn/MSOInfrastructureBPMN/src/main/resources/process/CreateNetworkInstance.bpmn @@ -121,6 +121,7 @@ CreateNetworkInstance.prepareDBRequestError(execution)]]> application/soap+xml + #{BasicAuthHeaderValueDB} POST @@ -369,4 +370,4 @@ CreateNetworkInstance.sendSyncResponse(execution)]]> - + \ No newline at end of file diff --git a/bpmn/MSOInfrastructureBPMN/src/main/resources/process/CreateServiceInstance.bpmn b/bpmn/MSOInfrastructureBPMN/src/main/resources/process/CreateServiceInstance.bpmn index d8e8dfda30..fa114c5e76 100644 --- a/bpmn/MSOInfrastructureBPMN/src/main/resources/process/CreateServiceInstance.bpmn +++ b/bpmn/MSOInfrastructureBPMN/src/main/resources/process/CreateServiceInstance.bpmn @@ -8,7 +8,7 @@ SequenceFlow_10 SequenceFlow_14 - diff --git a/bpmn/MSOInfrastructureBPMN/src/main/resources/process/CreateVfModuleInfra.bpmn b/bpmn/MSOInfrastructureBPMN/src/main/resources/process/CreateVfModuleInfra.bpmn index 7e5a1cd497..7a8133ec7f 100644 --- a/bpmn/MSOInfrastructureBPMN/src/main/resources/process/CreateVfModuleInfra.bpmn +++ b/bpmn/MSOInfrastructureBPMN/src/main/resources/process/CreateVfModuleInfra.bpmn @@ -1,22 +1,22 @@ - + SequenceFlow_1 - + - - - - - - - - - - + + + + + + + + + + SequenceFlow_7 SequenceFlow_4 @@ -28,17 +28,17 @@ def createVfModule = new CreateVfModuleInfra() createVfModule.sendResponse(execution)]]> - + SequenceFlow_4 - + - + SequenceFlow_5 - + - + SequenceFlow_5 SequenceFlow_6 @@ -49,12 +49,12 @@ createVfModule.prepareUpdateInfraRequest(execution)]]> + http-connector ${URN_mso_adapters_db_endpoint} application/soap+xml - #{BasicAuthHeaderValueDB} ${CVFMI_updateInfraRequest} @@ -62,14 +62,13 @@ createVfModule.prepareUpdateInfraRequest(execution)]]> ${statusCode} ${response} - http-connector SequenceFlow_6 SequenceFlow_8 - - + + updateInfraRequestResponseGood SequenceFlow_12 @@ -77,15 +76,15 @@ createVfModule.prepareUpdateInfraRequest(execution)]]> def createVfModule = new CreateVfModuleInfra() createVfModule.postProcessResponse(execution)]]> - + - - - - - - + + + + + + SequenceFlow_12 SequenceFlow_14 @@ -95,13 +94,13 @@ createVfModule.postProcessResponse(execution)]]> updateInfraRequestResponseBad updateInfraRequestResponseGood - + updateInfraRequestResponseBad - + @@ -111,37 +110,37 @@ createVfModule.postProcessResponse(execution)]]> def createVfModule = new CreateVfModuleInfra() createVfModule.validateRollbackResponse(execution)]]> - + - - - - + + + + SequenceFlow_19 SequenceFlow_17 - + SequenceFlow_13 - + - + - - - - + + + + SequenceFlow_10 SequenceFlow_11 - + SequenceFlow_11 - + SequenceFlow_22 @@ -150,19 +149,19 @@ createVfModule.validateRollbackResponse(execution)]]> def cvfm = new CreateVfModuleInfra() cvfm.falloutHandlerPrep(execution, 'CVFMI_FalloutHandlerRequest')]]> - + SequenceFlow_21 isRollbackOnNoSequenceFlow SequenceFlow_22 - + SequenceFlow_13 isRollbackOnNoSequenceFlow IsRollbackOnYesSequenceFlow - + IsRollbackOnYesSequenceFlow SequenceFlow_19 @@ -173,7 +172,7 @@ cvfm.logAndSaveOriginalException(execution)]]> - + SequenceFlow_14 @@ -182,18 +181,18 @@ cvfm.logAndSaveOriginalException(execution)]]> SequenceFlow_16 - + - - + + SequenceFlow_15 - + - + SequenceFlow_15 - + SequenceFlow_1 @@ -202,272 +201,272 @@ cvfm.logAndSaveOriginalException(execution)]]> def createVfModule = new CreateVfModuleInfra() createVfModule.preProcessRequest(execution)]]> - + - - + + - + - - + + - + - + - + - - + + - + - + - - + + - + - + - - + + - + - + - + - + - + - + - + - + - + - + - + - + - - + + - + - - + + - - - - + + + + - + - - - - + + + + - + - - - - + + + + - + - - + + - + - + - + - + - + - + - + - + - + - + - + - + - - + + - + - - + + - + - - + + - + - + - - + + - - + + - + - + - + - + - + - - - - + + + + - + - - - - + + + + - + - - - + + + - + - - - - + + + + - + - + - - + + - + - + - - + + - + - - + + - + \ No newline at end of file diff --git a/bpmn/MSOInfrastructureBPMN/src/main/resources/process/CreateVfModuleVolumeInfraV1.bpmn b/bpmn/MSOInfrastructureBPMN/src/main/resources/process/CreateVfModuleVolumeInfraV1.bpmn index 5c8074e01e..0fc889bfd6 100644 --- a/bpmn/MSOInfrastructureBPMN/src/main/resources/process/CreateVfModuleVolumeInfraV1.bpmn +++ b/bpmn/MSOInfrastructureBPMN/src/main/resources/process/CreateVfModuleVolumeInfraV1.bpmn @@ -1,16 +1,16 @@ - + SequenceFlow_1 - + SequenceFlow_14 - + - + SequenceFlow_14 SequenceFlow_syncResponseSent @@ -26,8 +26,8 @@ def createVfModuleVolumeInfraV1 = new CreateVfModuleVolumeInfraV1() createVfModuleVolumeInfraV1.executeMethod('sendSyncError', execution, isDebugLogEnabled)]]> - - + + SequenceFlow_22 SequenceFlow_syncResponseSent @@ -37,24 +37,24 @@ def createVfModuleVolumeInfraV1 = new CreateVfModuleVolumeInfraV1() createVfModuleVolumeInfraV1.executeMethod('prepareFalloutHandlerRequest', execution, isDebugLogEnabled) ]]> - + - - - - - - - + + + + + + + SequenceFlow_18 SequenceFlow_19 - + SequenceFlow_19 - + @@ -64,7 +64,7 @@ createVfModuleVolumeInfraV1.executeMethod('prepareFalloutHandlerRequest', execut def createVfModuleVolumeInfraV1 = new CreateVfModuleVolumeInfraV1() createVfModuleVolumeInfraV1.executeMethod('preProcessRequest', execution, isDebugLogEnabled)]]> - + SequenceFlow_4 SequenceFlow_3 @@ -72,7 +72,7 @@ createVfModuleVolumeInfraV1.executeMethod('preProcessRequest', execution, isDebu def createVfModuleVolumeInfraV1 = new CreateVfModuleVolumeInfraV1() createVfModuleVolumeInfraV1.executeMethod('sendSyncResponse', execution, isDebugLogEnabled)]]> - + SequenceFlow_3 SequenceFlow_volGrpNamePresent @@ -81,7 +81,7 @@ createVfModuleVolumeInfraV1.executeMethod('sendSyncResponse', execution, isDebug - + SequenceFlow_volGrpNameMissing SequenceFlow_7 @@ -89,40 +89,40 @@ createVfModuleVolumeInfraV1.executeMethod('sendSyncResponse', execution, isDebug def createVfModuleVolumeInfraV1 = new CreateVfModuleVolumeInfraV1() createVfModuleVolumeInfraV1.executeMethod('buildWorkflowException', execution, 2500, "Volume group name not present in request.", isDebugLogEnabled)]]> - + SequenceFlow_7 - + - - - - - + + + + + SequenceFlow_volGrpNamePresent SequenceFlow_5 - - - - - - - - - - - + + + + + + + + + + + SequenceFlow_serviceInstanceFound SequenceFlow_2 - + SequenceFlow_12 SequenceFlow_13 @@ -130,20 +130,20 @@ createVfModuleVolumeInfraV1.executeMethod('buildWorkflowException', execution, 2 def createVfModuleVolumeInfraV1 = new CreateVfModuleVolumeInfraV1() createVfModuleVolumeInfraV1.executeMethod('setSuccessIndicator', execution, true)]]> - + - - - - - - + + + + + + SequenceFlow_11 SequenceFlow_12 - + SequenceFlow_8 SequenceFlow_11 @@ -151,33 +151,32 @@ createVfModuleVolumeInfraV1.executeMethod('setSuccessIndicator', execution, true def createVfModuleVolumeInfraV1 = new CreateVfModuleVolumeInfraV1() createVfModuleVolumeInfraV1.executeMethod('postProcessResponse', execution, isDebugLogEnabled)]]> - + + http-connector ${URN_mso_adapters_db_endpoint} ${CVMVINFRAV1_createDBRequest} application/soap+xml - #{BasicAuthHeaderValueDB} POST ${response} ${statusCode} - http-connector SequenceFlow_6 SequenceFlow_8 - + SequenceFlow_13 - + SequenceFlow_2 @@ -186,20 +185,20 @@ createVfModuleVolumeInfraV1.executeMethod('postProcessResponse', execution, isDe def createVfModuleVolumeInfraV1 = new CreateVfModuleVolumeInfraV1() createVfModuleVolumeInfraV1.executeMethod('prepareDbInfraSuccessRequest', execution, isDebugLogEnabled)]]> - + SequenceFlow_5 SequenceFlow_serviceInstanceFound SequenceFlow_serviceInstanceNotFound - + - + SequenceFlow_16 - + SequenceFlow_serviceInstanceNotFound @@ -208,274 +207,274 @@ createVfModuleVolumeInfraV1.executeMethod('prepareDbInfraSuccessRequest', execut def createVfModuleVolumeInfraV1 = new CreateVfModuleVolumeInfraV1() createVfModuleVolumeInfraV1.executeMethod('buildWorkflowException', execution, 2500, "Service instance id not found in AAI: $CVMVINFRAV1_serviceInstanceId.", isDebugLogEnabled)]]> - + - + - + - + - - + + - + - + - + - + - + - + - + - - - - + + + + - + - - + + - + - - + + - + - - + + - + - + - + - - + + - + - + - + - + - + - + - + - + - + - + - + - + - - + + - + - - + + - + - - + + - + - - + + - + - + - - + + - + - - - - + + + + - + - - - - + + + + - + - + - + - - + + - + - - + + - + - + - + - - - - + + + + - + - + - - - - + + + + - + - - - - + + + + - + - + - + - + - - - - + + + + - - - - + + + + - + - + - - + + - + - + - - + + - + - + \ No newline at end of file diff --git a/bpmn/MSOInfrastructureBPMN/src/main/resources/process/CreateVnfInfra.bpmn b/bpmn/MSOInfrastructureBPMN/src/main/resources/process/CreateVnfInfra.bpmn index f98f8eda03..e8d27b6014 100644 --- a/bpmn/MSOInfrastructureBPMN/src/main/resources/process/CreateVnfInfra.bpmn +++ b/bpmn/MSOInfrastructureBPMN/src/main/resources/process/CreateVnfInfra.bpmn @@ -45,7 +45,7 @@ createVnf.sendSyncResponse(execution)]]> SequenceFlow_8 SequenceFlow_9 - @@ -60,7 +60,7 @@ exceptionUtil.processJavaException(execution)]]> - + @@ -109,7 +109,7 @@ createVnf.prepareCompletionHandlerRequest(execution)]]> SequenceFlow_17 - + diff --git a/bpmn/MSOInfrastructureBPMN/src/main/resources/process/DelServiceInstance.bpmn b/bpmn/MSOInfrastructureBPMN/src/main/resources/process/DelServiceInstance.bpmn index 6d47b1a9ba..4488e8de1c 100644 --- a/bpmn/MSOInfrastructureBPMN/src/main/resources/process/DelServiceInstance.bpmn +++ b/bpmn/MSOInfrastructureBPMN/src/main/resources/process/DelServiceInstance.bpmn @@ -8,7 +8,7 @@ SequenceFlow_10 SequenceFlow_14 - diff --git a/bpmn/MSOInfrastructureBPMN/src/main/resources/process/DeleteGenericMacroServiceNetworkVnf.bpmn b/bpmn/MSOInfrastructureBPMN/src/main/resources/process/DeleteGenericMacroServiceNetworkVnf.bpmn index 3bd8b91abd..eeb32599d3 100644 --- a/bpmn/MSOInfrastructureBPMN/src/main/resources/process/DeleteGenericMacroServiceNetworkVnf.bpmn +++ b/bpmn/MSOInfrastructureBPMN/src/main/resources/process/DeleteGenericMacroServiceNetworkVnf.bpmn @@ -1,771 +1,771 @@ - - - - - SequenceFlow_7 - SequenceFlow_3 - - - - - SequenceFlow_1 - - - - SequenceFlow_1 - SequenceFlow_7 - - - - - SequenceFlow_10o22u2 - - - - SequenceFlow_12ilko1 - SequenceFlow_29 - - - - - - - - - - - - - - - SequenceFlow_29 - SequenceFlow_8 - - - - SequenceFlow_8 - SequenceFlow_6 - - - - - SequenceFlow_6 - - - - - SequenceFlow_2 - - - - SequenceFlow_5 - - - - SequenceFlow_2 - SequenceFlow_5 - - - - - - SequenceFlow_12ilko1 - - - - - - - - - - - - - - - - - - - SequenceFlow_1bwbn7r - SequenceFlow_12ag2bk - - - SequenceFlow_0cmebdc - SequenceFlow_0dfkfh1 - SequenceFlow_1bwbn7r - - - - - - - - - - - - - - - SequenceFlow_10o22u2 - SequenceFlow_04ao07f - - - - - - - - - - - - - - SequenceFlow_1h77psn - SequenceFlow_1dmn40p - - - SequenceFlow_0bvecvm - SequenceFlow_0mr8jgt - SequenceFlow_1h77psn - - - - SequenceFlow_0xowenu - - - - SequenceFlow_3 - - - - - SequenceFlow_06llof4 - - - - - - - - - - - - SequenceFlow_0807ukc - SequenceFlow_19yywk8 - - - SequenceFlow_19yywk8 - - - SequenceFlow_06llof4 - SequenceFlow_0807ukc - - - - - - - - - - - - - SequenceFlow_1vwssu7 - - - - SequenceFlow_04ao07f - - - - SequenceFlow_1vwssu7 - SequenceFlow_0cmebdc - SequenceFlow_1f26zbk - - - SequenceFlow_04vlq8r - SequenceFlow_1n7r495 - SequenceFlow_0dfkfh1 - - - - - - 0}]]> - - - SequenceFlow_1n7r495 - SequenceFlow_1f26zbk - SequenceFlow_1j7n6qx - - - - SequenceFlow_1j7n6qx - - - - - - SequenceFlow_10tbv62 - - - - SequenceFlow_10tbv62 - SequenceFlow_0bvecvm - SequenceFlow_0w7328u - - - SequenceFlow_0w7328u - SequenceFlow_1wc8h5g - SequenceFlow_0xowenu - - - - 0}]]> - - - - - SequenceFlow_12ag2bk - SequenceFlow_04vlq8r - - - - - - - - - - - - - - - - SequenceFlow_0jek18q - SequenceFlow_1ttswdr - - - SequenceFlow_1ttswdr - SequenceFlow_18103ca - - - - SequenceFlow_0jek18q - - - - SequenceFlow_18103ca - - - - - - - - SequenceFlow_1dmn40p - SequenceFlow_0g2cw86 - - - - SequenceFlow_0g2cw86 - SequenceFlow_0mr8jgt - SequenceFlow_1wc8h5g - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + SequenceFlow_7 + SequenceFlow_3 + + + + + SequenceFlow_1 + + + + SequenceFlow_1 + SequenceFlow_7 + + + + + SequenceFlow_10o22u2 + + + + SequenceFlow_12ilko1 + SequenceFlow_29 + + + + + + + + + + + + + + + SequenceFlow_29 + SequenceFlow_8 + + + + SequenceFlow_8 + SequenceFlow_6 + + + + + SequenceFlow_6 + + + + + SequenceFlow_2 + + + + SequenceFlow_5 + + + + SequenceFlow_2 + SequenceFlow_5 + + + + + + SequenceFlow_12ilko1 + + + + + + + + + + + + + + + + + + + SequenceFlow_1bwbn7r + SequenceFlow_12ag2bk + + + SequenceFlow_0cmebdc + SequenceFlow_0dfkfh1 + SequenceFlow_1bwbn7r + + + + + + + + + + + + + + + SequenceFlow_10o22u2 + SequenceFlow_04ao07f + + + + + + + + + + + + + + SequenceFlow_1h77psn + SequenceFlow_1dmn40p + + + SequenceFlow_0bvecvm + SequenceFlow_0mr8jgt + SequenceFlow_1h77psn + + + + SequenceFlow_0xowenu + + + + SequenceFlow_3 + + + + + SequenceFlow_06llof4 + + + + + + + + + + + + SequenceFlow_0807ukc + SequenceFlow_19yywk8 + + + SequenceFlow_19yywk8 + + + SequenceFlow_06llof4 + SequenceFlow_0807ukc + + + + + + + + + + + + + SequenceFlow_1vwssu7 + + + + SequenceFlow_04ao07f + + + + SequenceFlow_1vwssu7 + SequenceFlow_0cmebdc + SequenceFlow_1f26zbk + + + SequenceFlow_04vlq8r + SequenceFlow_1n7r495 + SequenceFlow_0dfkfh1 + + + + + + 0}]]> + + + SequenceFlow_1n7r495 + SequenceFlow_1f26zbk + SequenceFlow_1j7n6qx + + + + SequenceFlow_1j7n6qx + + + + + + SequenceFlow_10tbv62 + + + + SequenceFlow_10tbv62 + SequenceFlow_0bvecvm + SequenceFlow_0w7328u + + + SequenceFlow_0w7328u + SequenceFlow_1wc8h5g + SequenceFlow_0xowenu + + + + 0}]]> + + + + + SequenceFlow_12ag2bk + SequenceFlow_04vlq8r + + + + + + + + + + + + + + + + SequenceFlow_0jek18q + SequenceFlow_1ttswdr + + + SequenceFlow_1ttswdr + SequenceFlow_18103ca + + + + SequenceFlow_0jek18q + + + + SequenceFlow_18103ca + + + + + + + + SequenceFlow_1dmn40p + SequenceFlow_0g2cw86 + + + + SequenceFlow_0g2cw86 + SequenceFlow_0mr8jgt + SequenceFlow_1wc8h5g + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/bpmn/MSOInfrastructureBPMN/src/main/resources/process/DeleteNetworkInstance.bpmn b/bpmn/MSOInfrastructureBPMN/src/main/resources/process/DeleteNetworkInstance.bpmn index 8c37d212c3..951ae3c0b5 100644 --- a/bpmn/MSOInfrastructureBPMN/src/main/resources/process/DeleteNetworkInstance.bpmn +++ b/bpmn/MSOInfrastructureBPMN/src/main/resources/process/DeleteNetworkInstance.bpmn @@ -1,370 +1,371 @@ - - - - - SequenceFlow_0lp2z7l - - - - SequenceFlow_10 - SequenceFlow_14 - - - - - SequenceFlow_10 - - - - - SequenceFlow_14 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - SequenceFlow_0eto8sn - SequenceFlow_1lj31zp - - - SequenceFlow_0x3znm5 - - - SequenceFlow_095crcd - SequenceFlow_0x3znm5 - - - - - - SequenceFlow_0lp2z7l - SequenceFlow_1ablr60 - - - - - - SequenceFlow_1lj31zp - SequenceFlow_0xxvjxq - - - - - - - - - - - - SequenceFlow_0xxvjxq - SequenceFlow_095crcd - - - - - SequenceFlow_0n4umjf - - - - SequenceFlow_1ghqolv - - - SequenceFlow_0n4umjf - SequenceFlow_1s5niqb - - - - - - - ${URN_mso_adapters_db_endpoint} - ${DELNI_deleteDBRequest} - - - application/soap+xml - - - POST - ${response} - ${statusCode} - - http-connector - - - SequenceFlow_1s5niqb - SequenceFlow_06s5eu4 - - - SequenceFlow_06s5eu4 - SequenceFlow_1reso2f - - - - - - - - - - - - SequenceFlow_1reso2f - SequenceFlow_1ghqolv - - - - - - - - - - - - SequenceFlow_1ablr60 - SequenceFlow_0rt8wax - - - - SequenceFlow_0rt8wax - SequenceFlow_0eto8sn - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + SequenceFlow_0lp2z7l + + + + SequenceFlow_10 + SequenceFlow_14 + + + + + SequenceFlow_10 + + + + + SequenceFlow_14 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + SequenceFlow_0eto8sn + SequenceFlow_1lj31zp + + + SequenceFlow_0x3znm5 + + + SequenceFlow_095crcd + SequenceFlow_0x3znm5 + + + + + + SequenceFlow_0lp2z7l + SequenceFlow_1ablr60 + + + + + + SequenceFlow_1lj31zp + SequenceFlow_0xxvjxq + + + + + + + + + + + + SequenceFlow_0xxvjxq + SequenceFlow_095crcd + + + + + SequenceFlow_0n4umjf + + + + SequenceFlow_1ghqolv + + + SequenceFlow_0n4umjf + SequenceFlow_1s5niqb + + + + + + + ${URN_mso_adapters_db_endpoint} + ${DELNI_deleteDBRequest} + + + application/soap+xml + #{BasicAuthHeaderValueDB} + + + POST + ${response} + ${statusCode} + + http-connector + + + SequenceFlow_1s5niqb + SequenceFlow_06s5eu4 + + + SequenceFlow_06s5eu4 + SequenceFlow_1reso2f + + + + + + + + + + + + SequenceFlow_1reso2f + SequenceFlow_1ghqolv + + + + + + + + + + + + SequenceFlow_1ablr60 + SequenceFlow_0rt8wax + + + + SequenceFlow_0rt8wax + SequenceFlow_0eto8sn + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/bpmn/MSOInfrastructureBPMN/src/main/resources/process/DeleteVfModuleInfra.bpmn b/bpmn/MSOInfrastructureBPMN/src/main/resources/process/DeleteVfModuleInfra.bpmn index b974bd01aa..04369acba0 100644 --- a/bpmn/MSOInfrastructureBPMN/src/main/resources/process/DeleteVfModuleInfra.bpmn +++ b/bpmn/MSOInfrastructureBPMN/src/main/resources/process/DeleteVfModuleInfra.bpmn @@ -83,7 +83,6 @@ dvfm.completionHandlerPrep(execution, 'DELVfModI_CompletionHandlerRequest') POST - #{BasicAuthHeaderValueDB} application/soap+xml @@ -327,4 +326,4 @@ dvfm.falloutHandlerPrep(execution, 'DELVfModI_FalloutHandlerRequest') - \ No newline at end of file + diff --git a/bpmn/MSOInfrastructureBPMN/src/main/resources/process/DeleteVfModuleVolumeInfraV1.bpmn b/bpmn/MSOInfrastructureBPMN/src/main/resources/process/DeleteVfModuleVolumeInfraV1.bpmn index 163e50be23..d0051de976 100644 --- a/bpmn/MSOInfrastructureBPMN/src/main/resources/process/DeleteVfModuleVolumeInfraV1.bpmn +++ b/bpmn/MSOInfrastructureBPMN/src/main/resources/process/DeleteVfModuleVolumeInfraV1.bpmn @@ -203,7 +203,6 @@ execution.setVariable("DELVfModVol_TransactionSuccessIndicator", true)]]>${DELVfModVol_updateInfraRequest} - #{BasicAuthHeaderValueDB} application/soap+xml diff --git a/bpmn/MSOInfrastructureBPMN/src/main/resources/process/DeleteVnfInfra.bpmn b/bpmn/MSOInfrastructureBPMN/src/main/resources/process/DeleteVnfInfra.bpmn index 765bb1ffa6..b5b10a0fda 100644 --- a/bpmn/MSOInfrastructureBPMN/src/main/resources/process/DeleteVnfInfra.bpmn +++ b/bpmn/MSOInfrastructureBPMN/src/main/resources/process/DeleteVnfInfra.bpmn @@ -33,7 +33,7 @@ String falloutHandlerRequest = ex.processMainflowsBPMNException(execution, reque execution.setVariable("DELVI_falloutHandlerRequest", falloutHandlerRequest )]]> - + @@ -87,7 +87,7 @@ DeleteVnfInfra deleteVnf = new DeleteVnfInfra() deleteVnf.prepareCompletionHandlerRequest(execution)]]> - + diff --git a/bpmn/MSOInfrastructureBPMN/src/main/resources/process/UpdateNetworkInstance.bpmn b/bpmn/MSOInfrastructureBPMN/src/main/resources/process/UpdateNetworkInstance.bpmn new file mode 100644 index 0000000000..a19e0c632b --- /dev/null +++ b/bpmn/MSOInfrastructureBPMN/src/main/resources/process/UpdateNetworkInstance.bpmn @@ -0,0 +1,372 @@ + + + + + SequenceFlow_0lp2z7l + + + + SequenceFlow_10 + SequenceFlow_14 + + + + + SequenceFlow_10 + + + + + SequenceFlow_14 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + SequenceFlow_0eto8sn + SequenceFlow_1lj31zp + + + SequenceFlow_0x3znm5 + + + SequenceFlow_095crcd + SequenceFlow_0x3znm5 + + + + + + SequenceFlow_0lp2z7l + SequenceFlow_1ablr60 + + + + + + SequenceFlow_1lj31zp + SequenceFlow_0xxvjxq + + + + + + + + + + + + SequenceFlow_0xxvjxq + SequenceFlow_095crcd + + + + + SequenceFlow_0n4umjf + + + + SequenceFlow_1ghqolv + + + SequenceFlow_0n4umjf + SequenceFlow_1s5niqb + + + + + + + ${URN_mso_adapters_db_endpoint} + ${UPDNI_createDBRequest} + + + application/soap+xml + + + POST + ${response} + ${statusCode} + + http-connector + + + SequenceFlow_1s5niqb + SequenceFlow_06s5eu4 + + + SequenceFlow_06s5eu4 + SequenceFlow_1reso2f + + + + + + + + + + + + SequenceFlow_1reso2f + SequenceFlow_1ghqolv + + + + + + + + + + + + SequenceFlow_1ablr60 + SequenceFlow_0rt8wax + + + + SequenceFlow_0rt8wax + SequenceFlow_0eto8sn + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/bpmn/MSOInfrastructureBPMN/src/main/resources/process/UpdateNetworkInstanceInfra.bpmn b/bpmn/MSOInfrastructureBPMN/src/main/resources/process/UpdateNetworkInstanceInfra.bpmn index bba8b6f7a7..f49149b709 100644 --- a/bpmn/MSOInfrastructureBPMN/src/main/resources/process/UpdateNetworkInstanceInfra.bpmn +++ b/bpmn/MSOInfrastructureBPMN/src/main/resources/process/UpdateNetworkInstanceInfra.bpmn @@ -1,10 +1,10 @@ - + SequenceFlow_1 - + SequenceFlow_32 SequenceFlow_11 @@ -13,7 +13,7 @@ def UpdateNetworkInstanceInfra = new UpdateNetworkInstanceInfra() UpdateNetworkInstanceInfra.prepareSDNCRequest(execution) ]]> - + SequenceFlow_12 SequenceFlow_5 @@ -26,56 +26,56 @@ UpdateNetworkInstanceInfra.validateSDNCResponse(execution)]]> sdncTopoNo_SequenceFlow sdncTopoYes_SequenceFlow - + - + SequenceFlow_34 - + - + sdncTopoNo_SequenceFlow SequenceFlow_34 - + - - - - - + + + + + - + - - - - - - - - + + + + + + + + SequenceFlow_11 SequenceFlow_12 - - + + SequenceFlow_27 SequenceFlow_29 - + SequenceFlow_23 @@ -85,12 +85,12 @@ UpdateNetworkInstanceInfra.postProcessResponse(execution)]]> - + SequenceFlow_23 - + - + isRollbackOn_YesNetwork_SequenceFlow isPONR_Yes_SequenceFlow @@ -99,13 +99,13 @@ UpdateNetworkInstanceInfra.postProcessResponse(execution)]]> - + isPONR_No_SequenceFlow isNetworkOk_No_SequenceFlow isNetworkOk_Yes_SequenceFlow - + @@ -118,7 +118,7 @@ UpdateNetworkInstanceInfra.postProcessResponse(execution)]]> - + sdncOk_Yeso_ExclusiveGateway SequenceFlow_53 @@ -126,13 +126,13 @@ UpdateNetworkInstanceInfra.postProcessResponse(execution)]]> def UpdateNetworkInstanceInfra = new UpdateNetworkInstanceInfra() UpdateNetworkInstanceInfra.prepareSDNCRollbackRequest(execution)]]> - + SequenceFlow_53 SequenceFlow_55 - + - + SequenceFlow_47 SequenceFlow_22 @@ -140,16 +140,16 @@ UpdateNetworkInstanceInfra.prepareSDNCRollbackRequest(execution)]]> - + + http-connector ${URN_mso_adapters_db_endpoint} ${UPDNETI_updateDBRequest} - #{BasicAuthHeaderValueDB} application/soap+xml @@ -157,28 +157,27 @@ UpdateNetworkInstanceInfra.prepareDBRequestError(execution)]]> ${response} ${statusCode} - http-connector SequenceFlow_22 SequenceFlow_19 - + - - - - - - - - + + + + + + + + SequenceFlow_25 SequenceFlow_18 - + SequenceFlow_18 @@ -190,14 +189,14 @@ UpdateNetworkInstanceInfra.prepareDBRequestError(execution)]]> def UpdateNetworkInstanceInfra = new UpdateNetworkInstanceInfra() UpdateNetworkInstanceInfra.validateRollbackResponses(execution)]]> - + isRollbackOn_NoNetwork_SequenceFlow isPONR_Yes_SequenceFlow SequenceFlow_4 SequenceFlow_47 - + SequenceFlow_19 SequenceFlow_25 @@ -206,7 +205,7 @@ def buildErrorResponse = new UpdateNetworkInstanceInfra() buildErrorResponse.buildErrorResponse(execution) ]]> - + SequenceFlow_13 @@ -215,7 +214,7 @@ buildErrorResponse.buildErrorResponse(execution) def UpdateNetworkInstanceInfra = new UpdateNetworkInstanceInfra() UpdateNetworkInstanceInfra.callRESTReQueryAAINetworkId(execution)]]> - + SequenceFlow_35 SequenceFlow_46 @@ -223,7 +222,7 @@ UpdateNetworkInstanceInfra.callRESTReQueryAAINetworkId(execution)]]> - + SequenceFlow_46 SequenceFlow_37 @@ -233,16 +232,16 @@ UpdateNetworkInstanceInfra.prepareDBRequest(execution) ]]> - + + http-connector ${URN_mso_adapters_db_endpoint} ${UPDNETI_updateDBRequest} - #{BasicAuthHeaderValueDB} application/soap+xml @@ -250,28 +249,27 @@ UpdateNetworkInstanceInfra.prepareDBRequest(execution) ${response} ${statusCode} - http-connector SequenceFlow_37 SequenceFlow_27 - + - - - - - - - - + + + + + + + + SequenceFlow_29 SequenceFlow_17 - + SequenceFlow_17 @@ -283,12 +281,12 @@ UpdateNetworkInstanceInfra.prepareDBRequest(execution) def UpdateNetworkInstanceInfra = new UpdateNetworkInstanceInfra() UpdateNetworkInstanceInfra.processJavaException(execution)]]> - + SequenceFlow_10 - + - + SequenceFlow_14 @@ -301,7 +299,7 @@ def UpdateNetworkInstanceInfra = new UpdateNetworkInstanceInfra() UpdateNetworkInstanceInfra.preProcessRequest(execution) ]]> - + SequenceFlow_24 SequenceFlow_32 @@ -309,7 +307,7 @@ UpdateNetworkInstanceInfra.preProcessRequest(execution) def UpdateNetworkInstanceInfra = new UpdateNetworkInstanceInfra() UpdateNetworkInstanceInfra.callRESTQueryAAICloudRegion(execution)]]> - + siFoundYes SequenceFlow_24 @@ -317,19 +315,19 @@ UpdateNetworkInstanceInfra.callRESTQueryAAICloudRegion(execution)]]> - + SequenceFlow_30 - + siFoundNo SequenceFlow_30 - - + SequenceFlow_3 siFoundYes @@ -338,21 +336,21 @@ exceptionUtil.buildWorkflowException(execution, 404, "Service Instance Not Found - - + + - - - - - - - + + + + + + + SequenceFlow_28 SequenceFlow_3 - + SequenceFlow_7 SequenceFlow_28 @@ -360,7 +358,7 @@ exceptionUtil.buildWorkflowException(execution, 404, "Service Instance Not Found def UpdateNetworkInstanceInfra = new UpdateNetworkInstanceInfra() UpdateNetworkInstanceInfra.sendSyncResponse(execution)]]> - + SequenceFlow_59 SequenceFlow_13 @@ -368,10 +366,11 @@ UpdateNetworkInstanceInfra.sendSyncResponse(execution)]]> def UpdateNetworkInstanceInfra = new UpdateNetworkInstanceInfra() UpdateNetworkInstanceInfra.validateUpdateNetworkResponse(execution)]]> - + + http-connector ${UPDNETI_updateNetworkRequest} ${URN_mso_adapters_network_rest_endpoint}/${UPDNETI_networkId} @@ -385,13 +384,12 @@ UpdateNetworkInstanceInfra.validateUpdateNetworkResponse(execution)]]>${statusCode} ${response} - http-connector SequenceFlow_61 SequenceFlow_59 - + SequenceFlow_2 SequenceFlow_61 @@ -400,7 +398,7 @@ def UpdateNetworkInstanceInfra = new UpdateNetworkInstanceInfra() UpdateNetworkInstanceInfra.prepareUpdateNetworkRequest(execution) ]]> - + SequenceFlow_38 SequenceFlow_2 @@ -408,7 +406,7 @@ UpdateNetworkInstanceInfra.prepareUpdateNetworkRequest(execution) def UpdateNetworkInstanceInfra = new UpdateNetworkInstanceInfra() UpdateNetworkInstanceInfra.callRESTQueryAAINetworkTableRef(execution)]]> - + sdncTopoYes_SequenceFlow SequenceFlow_6 @@ -416,7 +414,7 @@ UpdateNetworkInstanceInfra.callRESTQueryAAINetworkTableRef(execution)]]> - + SequenceFlow_6 SequenceFlow_15 @@ -424,7 +422,7 @@ UpdateNetworkInstanceInfra.callRESTReQueryAAINetworkId(execution)]]> - + SequenceFlow_15 SequenceFlow_38 @@ -432,585 +430,585 @@ UpdateNetworkInstanceInfra.callRESTQueryAAINetworkVpnBinding(execution)]]> - - + + - - + + - + - + - + - - + + - + - + - + - + - + - + - + - + - + - + - + - + - - + + - + - - - + + + - + - + - + - + - + - + - + - + - + - - - - + + + + - + - - + + - + - - + + - - + + - + - + - - - - + + + + - + - + - + - - + + - + - + - - - - + + + + - + - - - - + + + + - + - - - - + + + + - + - + - + - + - + - - - - + + + + - + - - - - + + + + - + - - - - + + + + - + - + - - + + - + - - + + - + - + - - + + - + - + - + - - + + - + - - - + + + - + - + - - + + - + - + - + - + - + - - + + - + - - + + - + - + - + - - - - + + + + - + - - - - + + + + - + - + - + - - + + - + - - + + - + - + - + - - + + - + - + - + - - + + - + - - + + - + - + - + - - + + - + - + - - - - + + + + - + - + - - - + + + - + - + - + - - - - + + + + - + - - + + - + - - - - + + + + - + - - + + - + - - - - + + + + - + - + - + - + - + - + - + - - + + - + - - + + - + - + - + - + - - - - + + + + - + - - - - + + + + - + - + - + - + - - - + + + - + - - + + - + - - + + - + - - + + - + - + - - + + - + - + - - - - + + + + - + - + \ No newline at end of file diff --git a/bpmn/MSOInfrastructureBPMN/src/main/resources/process/UpdateVfModuleVolumeInfraV1.bpmn b/bpmn/MSOInfrastructureBPMN/src/main/resources/process/UpdateVfModuleVolumeInfraV1.bpmn index 75b88b2e8d..96c0681c48 100644 --- a/bpmn/MSOInfrastructureBPMN/src/main/resources/process/UpdateVfModuleVolumeInfraV1.bpmn +++ b/bpmn/MSOInfrastructureBPMN/src/main/resources/process/UpdateVfModuleVolumeInfraV1.bpmn @@ -26,7 +26,6 @@ ${UPDVfModVol_updateInfraRequest} - #{BasicAuthHeaderValueDB} aapplication/soap+xml diff --git a/bpmn/MSOInfrastructureBPMN/src/main/resources/subprocess/DoCreateNetworkInstance.bpmn b/bpmn/MSOInfrastructureBPMN/src/main/resources/subprocess/DoCreateNetworkInstance.bpmn index 59f82013b1..ecd23f0ca9 100644 --- a/bpmn/MSOInfrastructureBPMN/src/main/resources/subprocess/DoCreateNetworkInstance.bpmn +++ b/bpmn/MSOInfrastructureBPMN/src/main/resources/subprocess/DoCreateNetworkInstance.bpmn @@ -297,10 +297,9 @@ WorkflowException SequenceFlow_59 - + - isSdncRpc2No_SequenceFlow2 - SequenceFlow_1jia57e + SequenceFlow_13 SequenceFlow_35 siFoundNo SequenceFlow_30 - @@ -454,7 +453,7 @@ DoCreateNetworkInstance.prepareRpcSDNCActivateRequest(execution)]]> - + @@ -500,14 +499,14 @@ DoCreateNetworkInstance.validateRpcSDNCActivateResponse(execution)]]> - SequenceFlow_13 + SequenceFlow_1ipz2ze isSdncRpc2Yes_SequenceFlow2 isSdncRpc2No_SequenceFlow2 - + isSdncRpc1Yes_SequenceFlow1 SequenceFlow_0j8bxnb @@ -524,13 +523,14 @@ DoCreateNetworkInstance.prepareRpcSDNCRequest(execution) - SequenceFlow_1ipz2ze + SequenceFlow_1jia57e + isSdncRpc2No_SequenceFlow2 SequenceFlow_1s8b1m1 - + isNetworkActiveYes_SequenceFlow SequenceFlow_18ylufb @@ -730,16 +730,16 @@ DoCreateNetworkInstance.postProcessResponse(execution)]]> - + - + - - + + - + @@ -865,11 +865,9 @@ DoCreateNetworkInstance.postProcessResponse(execution)]]> - - - + - + @@ -1006,77 +1004,73 @@ DoCreateNetworkInstance.postProcessResponse(execution)]]> - + - + - + - + - - + + - + - - - - + + - + - - - - + + - + - - + + - + - - + + - + - + - + - + - - - + + + - + - + - + @@ -1160,25 +1154,24 @@ DoCreateNetworkInstance.postProcessResponse(execution)]]> - + - + - - - - + + - + - - + + + - + @@ -1188,9 +1181,9 @@ DoCreateNetworkInstance.postProcessResponse(execution)]]> - + - + @@ -1206,16 +1199,16 @@ DoCreateNetworkInstance.postProcessResponse(execution)]]> - - - - + + + + - + - + @@ -1231,10 +1224,12 @@ DoCreateNetworkInstance.postProcessResponse(execution)]]> - - + + + + - + @@ -1382,4 +1377,4 @@ DoCreateNetworkInstance.postProcessResponse(execution)]]> - \ No newline at end of file + diff --git a/bpmn/MSOInfrastructureBPMN/src/main/resources/subprocess/DoCreateServiceInstance.bpmn b/bpmn/MSOInfrastructureBPMN/src/main/resources/subprocess/DoCreateServiceInstance.bpmn index 302620fdaf..a770c8c11a 100644 --- a/bpmn/MSOInfrastructureBPMN/src/main/resources/subprocess/DoCreateServiceInstance.bpmn +++ b/bpmn/MSOInfrastructureBPMN/src/main/resources/subprocess/DoCreateServiceInstance.bpmn @@ -1,390 +1,390 @@ - - - - - SequenceFlow_1 - - - - SequenceFlow_2 - SequenceFlow_3 - - - - - SequenceFlow_1 - SequenceFlow_2 - - - - - SequenceFlow_156ih25 - SequenceFlow_14 - - - - SequenceFlow_9 - SequenceFlow_10 - - - - - - - - - - - - SequenceFlow_14 - SequenceFlow_9 - - - SequenceFlow_10 - - - - - - - - - - - - - - - SequenceFlow_11fnnkb - SequenceFlow_4 - - - - - - - - - - - - - SequenceFlow_1uw2p9a - SequenceFlow_1w01tqs - SequenceFlow_129ih1g - - - - SequenceFlow_3 - SequenceFlow_11fnnkb - SequenceFlow_1uw2p9a - - - - - - - - SequenceFlow_0tgrn11 - - - - SequenceFlow_1xzgv5k - - - - - - - - - - SequenceFlow_1lqktwf - SequenceFlow_0eumzpf - - - - - SequenceFlow_0tgrn11 - SequenceFlow_1lqktwf - - - - - SequenceFlow_0eumzpf - SequenceFlow_1xzgv5k - - - - - - SequenceFlow_1dd86x8 - SequenceFlow_156ih25 - SequenceFlow_00v4npo - - - - SequenceFlow_00v4npo - - - - - - SequenceFlow_4 - SequenceFlow_1w01tqs - - - - - SequenceFlow_129ih1g - SequenceFlow_1dd86x8 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + SequenceFlow_1 + + + + SequenceFlow_2 + SequenceFlow_3 + + + + + SequenceFlow_1 + SequenceFlow_2 + + + + + SequenceFlow_156ih25 + SequenceFlow_14 + + + + SequenceFlow_9 + SequenceFlow_10 + + + + + + + + + + + + SequenceFlow_14 + SequenceFlow_9 + + + SequenceFlow_10 + + + + + + + + + + + + + + + SequenceFlow_11fnnkb + SequenceFlow_4 + + + + + + + + + + + + + SequenceFlow_1uw2p9a + SequenceFlow_1w01tqs + SequenceFlow_129ih1g + + + + SequenceFlow_3 + SequenceFlow_11fnnkb + SequenceFlow_1uw2p9a + + + + + + + + SequenceFlow_0tgrn11 + + + + SequenceFlow_1xzgv5k + + + + + + + + + + SequenceFlow_1lqktwf + SequenceFlow_0eumzpf + + + + + SequenceFlow_0tgrn11 + SequenceFlow_1lqktwf + + + + + SequenceFlow_0eumzpf + SequenceFlow_1xzgv5k + + + + + + SequenceFlow_1dd86x8 + SequenceFlow_156ih25 + SequenceFlow_00v4npo + + + + SequenceFlow_00v4npo + + + + + + SequenceFlow_4 + SequenceFlow_1w01tqs + + + + + SequenceFlow_129ih1g + SequenceFlow_1dd86x8 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/bpmn/MSOInfrastructureBPMN/src/main/resources/subprocess/DoCreateServiceInstanceRollback.bpmn b/bpmn/MSOInfrastructureBPMN/src/main/resources/subprocess/DoCreateServiceInstanceRollback.bpmn index e73c79d953..80ace28ae7 100644 --- a/bpmn/MSOInfrastructureBPMN/src/main/resources/subprocess/DoCreateServiceInstanceRollback.bpmn +++ b/bpmn/MSOInfrastructureBPMN/src/main/resources/subprocess/DoCreateServiceInstanceRollback.bpmn @@ -1,338 +1,338 @@ - - - - - SequenceFlow_1 - - - - SequenceFlow_1 - SequenceFlow_2 - - - - SequenceFlow_01l4ssl - - - - SequenceFlow_8 - - - - SequenceFlow_7 - - - - SequenceFlow_8 - SequenceFlow_7 - - - - - - - - - - - - - - - - - SequenceFlow_1x9eh33 - SequenceFlow_05wu9i7 - - - SequenceFlow_06aasqh - SequenceFlow_11fnnkb - SequenceFlow_1uw2p9a - - - - - - - rollback AAI - SequenceFlow_1uw2p9a - SequenceFlow_0khjo7l - SequenceFlow_1n7wade - SequenceFlow_1x9eh33 - - - - - - - - - - - - - - - - - SequenceFlow_11fnnkb - SequenceFlow_0k28xib - - - SequenceFlow_0k28xib - SequenceFlow_0khjo7l - - - - - SequenceFlow_2 - SequenceFlow_06aasqh - SequenceFlow_1rzlaoy - - - SequenceFlow_05wu9i7 - SequenceFlow_1n7wade - SequenceFlow_1rzlaoy - SequenceFlow_01l4ssl - - - - - - - - - - SequenceFlow_1ch4xrf - - - - SequenceFlow_1ch4xrf - SequenceFlow_1pjk2ff - - - - SequenceFlow_1pjk2ff - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + SequenceFlow_1 + + + + SequenceFlow_1 + SequenceFlow_2 + + + + SequenceFlow_01l4ssl + + + + SequenceFlow_8 + + + + SequenceFlow_7 + + + + SequenceFlow_8 + SequenceFlow_7 + + + + + + + + + + + + + + + + + SequenceFlow_1x9eh33 + SequenceFlow_05wu9i7 + + + SequenceFlow_06aasqh + SequenceFlow_11fnnkb + SequenceFlow_1uw2p9a + + + + + + + rollback AAI + SequenceFlow_1uw2p9a + SequenceFlow_0khjo7l + SequenceFlow_1n7wade + SequenceFlow_1x9eh33 + + + + + + + + + + + + + + + + + SequenceFlow_11fnnkb + SequenceFlow_0k28xib + + + SequenceFlow_0k28xib + SequenceFlow_0khjo7l + + + + + SequenceFlow_2 + SequenceFlow_06aasqh + SequenceFlow_1rzlaoy + + + SequenceFlow_05wu9i7 + SequenceFlow_1n7wade + SequenceFlow_1rzlaoy + SequenceFlow_01l4ssl + + + + + + + + + + SequenceFlow_1ch4xrf + + + + SequenceFlow_1ch4xrf + SequenceFlow_1pjk2ff + + + + SequenceFlow_1pjk2ff + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/bpmn/MSOInfrastructureBPMN/src/main/resources/subprocess/DoCreateVfModule.bpmn b/bpmn/MSOInfrastructureBPMN/src/main/resources/subprocess/DoCreateVfModule.bpmn index 62eb91810f..fecb720666 100644 --- a/bpmn/MSOInfrastructureBPMN/src/main/resources/subprocess/DoCreateVfModule.bpmn +++ b/bpmn/MSOInfrastructureBPMN/src/main/resources/subprocess/DoCreateVfModule.bpmn @@ -1,1006 +1,1167 @@ - - - - - SequenceFlow_1 - - - - SequenceFlow_15 - - - - - SequenceFlow_15 - SequenceFlow_11 - SequenceFlow_40 - - - - - - - - - - - - - - SequenceFlow_43 - SequenceFlow_17 - - - - SequenceFlow_17 - SequenceFlow_19 - SequenceFlow_21 - - - - - - - - - - - - - - - SequenceFlow_19 - SequenceFlow_35 - - - - SequenceFlow_11 - SequenceFlow_21 - SequenceFlow_35 - SequenceFlow_6 - - - - - - - - - - - - - SequenceFlow_18 - SequenceFlow_20 - - - SequenceFlow_20 - SequenceFlow_22 - - - - SequenceFlow_8 - SequenceFlow_18 - - - - - - SequenceFlow_22 - SequenceFlow_23 - - - - - - - - - - - - - SequenceFlow_23 - SequenceFlow_24 - - - - - - SequenceFlow_24 - SequenceFlow_31 - - - - - - - - - - SequenceFlow_5 - SequenceFlow_10 - - - SequenceFlow_1avfxsz - SequenceFlow_5 - - - - SequenceFlow_10 - SequenceFlow_12 - - - - - - - - - - - - - SequenceFlow_12 - SequenceFlow_13 - - - SequenceFlow_13 - SequenceFlow_14 - - - - SequenceFlow_14 - SequenceFlow_28 - SequenceFlow_30 - - - - - - - - - - - - SequenceFlow_0363dz7 - - - - SequenceFlow_8 - - - - - SequenceFlow_28 - SequenceFlow_3 - - - - - - - - - - SequenceFlow_3 - SequenceFlow_29 - - - - - SequenceFlow_30 - SequenceFlow_29 - SequenceFlow_16 - - - - SequenceFlow_31 - SequenceFlow_32 - - - - - - - - - - - - SequenceFlow_32 - SequenceFlow_33 - - - SequenceFlow_33 - SequenceFlow_1ushk1d - - - - SequenceFlow_0xfanpi - SequenceFlow_0abffyj - - - - - - - SequenceFlow_41 - - - - SequenceFlow_39 - SequenceFlow_37 - SequenceFlow_41 - - - SequenceFlow_25 - SequenceFlow_27 - - - - - SequenceFlow_27 - SequenceFlow_36 - SequenceFlow_39 - - - - - - - SequenceFlow_36 - SequenceFlow_37 - - - - - - SequenceFlow_16 - SequenceFlow_7 - - - - - SequenceFlow_7 - - - - SequenceFlow_40 - SequenceFlow_43 - - - - - - - - - SequenceFlow_9 - SequenceFlow_38 - - - - - SequenceFlow_9 - - - - - SequenceFlow_38 - - - - SequenceFlow_1 - SequenceFlow_4 - - - - - SequenceFlow_4 - - - - - - - - - - - - - - - - - - - - - SequenceFlow_6 - SequenceFlow_25 - - - - SequenceFlow_1ushk1d - SequenceFlow_0ery1pk - SequenceFlow_0xfanpi - - - - - - - - - SequenceFlow_0ery1pk - SequenceFlow_0abffyj - - - - SequenceFlow_0363dz7 - SequenceFlow_0bi38s7 - SequenceFlow_1k5uku2 - - - SequenceFlow_112los9 - SequenceFlow_1k5uku2 - SequenceFlow_1avfxsz - - - - - - - - - - - SequenceFlow_0bi38s7 - SequenceFlow_1qm81ym - - - - - - - - - - - SequenceFlow_1qm81ym - SequenceFlow_112los9 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + SequenceFlow_1 + + + + SequenceFlow_15 + + + + + SequenceFlow_15 + SequenceFlow_11 + SequenceFlow_40 + + + + + + + + + + + + + + SequenceFlow_43 + SequenceFlow_17 + + + + SequenceFlow_17 + SequenceFlow_19 + SequenceFlow_21 + + + + + + + + + + + + + + + SequenceFlow_19 + SequenceFlow_35 + + + + SequenceFlow_11 + SequenceFlow_21 + SequenceFlow_35 + SequenceFlow_6 + + + + + + + + + + + + + SequenceFlow_18 + SequenceFlow_20 + + + SequenceFlow_20 + SequenceFlow_22 + + + + SequenceFlow_8 + SequenceFlow_18 + + + + + + SequenceFlow_22 + SequenceFlow_23 + + + + + + + + + + + + + SequenceFlow_23 + SequenceFlow_24 + + + + + + SequenceFlow_24 + SequenceFlow_31 + + + + + + + + + + SequenceFlow_5 + SequenceFlow_10 + + + SequenceFlow_1avfxsz + SequenceFlow_5 + + + + SequenceFlow_10 + SequenceFlow_12 + + + + + + + + + + + + + SequenceFlow_12 + SequenceFlow_13 + + + SequenceFlow_13 + SequenceFlow_14 + + + + SequenceFlow_14 + SequenceFlow_28 + SequenceFlow_30 + + + + + + + + + + + + SequenceFlow_0363dz7 + + + + SequenceFlow_8 + + + + + SequenceFlow_28 + SequenceFlow_3 + + + + + + + + + + SequenceFlow_3 + SequenceFlow_29 + + + + + SequenceFlow_30 + SequenceFlow_29 + SequenceFlow_16 + + + + SequenceFlow_31 + SequenceFlow_32 + + + + + + + + + + + + SequenceFlow_32 + SequenceFlow_33 + + + SequenceFlow_33 + SequenceFlow_1ushk1d + + + + SequenceFlow_0xfanpi + SequenceFlow_0abffyj + + + + + + + SequenceFlow_0zcfn2x + SequenceFlow_170kw7h + + + + SequenceFlow_39 + SequenceFlow_37 + SequenceFlow_0zcfn2x + SequenceFlow_0m382su + + + SequenceFlow_25 + SequenceFlow_27 + + + + + SequenceFlow_27 + SequenceFlow_36 + SequenceFlow_39 + + + + + + + SequenceFlow_36 + SequenceFlow_37 + + + + + SequenceFlow_16 + SequenceFlow_7 + + + + + SequenceFlow_7 + + + + SequenceFlow_40 + SequenceFlow_43 + + + + + + + + + SequenceFlow_9 + SequenceFlow_38 + + + + + SequenceFlow_9 + + + + + SequenceFlow_38 + + + + SequenceFlow_1 + SequenceFlow_4 + + + + + SequenceFlow_1f53tby + SequenceFlow_0270n5c + + + + + + + + + + + + + + + + + + + + + SequenceFlow_6 + SequenceFlow_25 + + + + SequenceFlow_1ushk1d + SequenceFlow_0ery1pk + SequenceFlow_0xfanpi + + + + + + + + + SequenceFlow_0ery1pk + SequenceFlow_0abffyj + + + + SequenceFlow_0363dz7 + SequenceFlow_0bi38s7 + SequenceFlow_1k5uku2 + + + SequenceFlow_112los9 + SequenceFlow_1k5uku2 + SequenceFlow_1avfxsz + + + + + + + + + + + SequenceFlow_0bi38s7 + SequenceFlow_1qm81ym + + + + + + + + + + + SequenceFlow_1qm81ym + SequenceFlow_112los9 + + + + + + + + + SequenceFlow_0d00zqi + SequenceFlow_0g270u0 + + + + + + + + + + + + + SequenceFlow_0g270u0 + SequenceFlow_1yrlvgb + + + SequenceFlow_1yrlvgb + SequenceFlow_170kw7h + + + + + + + + + + + + + SequenceFlow_0m382su + SequenceFlow_0d00zqi + + + + SequenceFlow_4 + SequenceFlow_0270n5c + SequenceFlow_05og7iw + + + + + + + + + + + + + + + + SequenceFlow_05og7iw + SequenceFlow_1f53tby + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/bpmn/MSOInfrastructureBPMN/src/main/resources/subprocess/DoCreateVfModuleRollback.bpmn b/bpmn/MSOInfrastructureBPMN/src/main/resources/subprocess/DoCreateVfModuleRollback.bpmn index 0444b69633..7a7f369e42 100644 --- a/bpmn/MSOInfrastructureBPMN/src/main/resources/subprocess/DoCreateVfModuleRollback.bpmn +++ b/bpmn/MSOInfrastructureBPMN/src/main/resources/subprocess/DoCreateVfModuleRollback.bpmn @@ -17,8 +17,7 @@ def dcvfmr = new DoCreateVfModuleRollback() dcvfmr.preProcessRequest(execution)]]> - + @@ -40,8 +39,7 @@ dcvfmr.preProcessRequest(execution)]]> SequenceFlow_10 SequenceFlow_15 - + SequenceFlow_1p0v6yk SequenceFlow_16 - + @@ -67,8 +64,7 @@ dcvfmr.prepVNFAdapterRequest(execution)]]> - + SequenceFlow_13 SequenceFlow_14 - + @@ -107,8 +102,7 @@ dcvfmr.prepUpdateAAIVfModule(execution)]]> - + SequenceFlow_19 SequenceFlow_32 - + @@ -140,8 +133,7 @@ dcvfmr.prepSDNCAdapterRequest(execution)]]> - + @@ -156,8 +148,7 @@ dcvfmr.prepSDNCAdapterRequest(execution)]]> SequenceFlow_35 SequenceFlow_21 - + SequenceFlow_24 SequenceFlow_34 - \ No newline at end of file + diff --git a/bpmn/MSOInfrastructureBPMN/src/main/resources/subprocess/DoCreateVnf.bpmn b/bpmn/MSOInfrastructureBPMN/src/main/resources/subprocess/DoCreateVnf.bpmn index 91fca3d213..5e88527676 100644 --- a/bpmn/MSOInfrastructureBPMN/src/main/resources/subprocess/DoCreateVnf.bpmn +++ b/bpmn/MSOInfrastructureBPMN/src/main/resources/subprocess/DoCreateVnf.bpmn @@ -1,5 +1,5 @@ - + SequenceFlow_1 @@ -8,8 +8,8 @@ SequenceFlow_1 SequenceFlow_2 - @@ -87,8 +87,8 @@ exceptionUtil.buildWorkflowException(execution, 5000, "Generic Vnf Already Exist vnfExistNo SequenceFlow_11 - @@ -102,7 +102,7 @@ createVnf.prepareCreateGenericVnf(execution)]]> SequenceFlow_11 - SequenceFlow_1acnwwu + SequenceFlow_0seif8n @@ -133,12 +133,11 @@ exceptionUtil.processJavaException(execution)]]> - SequenceFlow_0ttqcwx SequenceFlow_1q6udwm - @@ -157,18 +156,18 @@ createVnf.preProcessSDNCAssignRequest(execution)]]> SequenceFlow_15knw0q SequenceFlow_0c5h00o - SequenceFlow_0c5h00o SequenceFlow_1lalmvp - @@ -187,22 +186,31 @@ createVnf.preProcessSDNCActivateRequest(execution)]]> SequenceFlow_0eb41vb SequenceFlow_15z3gpq - - SequenceFlow_1acnwwu + SequenceFlow_1gc18ih SequenceFlow_0ttqcwx SequenceFlow_0ay5l4b - + + + + + SequenceFlow_0seif8n + SequenceFlow_1gc18ih + + @@ -420,13 +428,6 @@ createVnfInfra.validateSDNCResponse(execution, response, "activate")]]> - - - - - - - @@ -446,30 +447,46 @@ createVnfInfra.validateSDNCResponse(execution, response, "activate")]]> - + - + - - + + - + - - - + + - + + + + + + + + + + + + + + + + + + diff --git a/bpmn/MSOInfrastructureBPMN/src/main/resources/subprocess/DoCreateVnfAndModules.bpmn b/bpmn/MSOInfrastructureBPMN/src/main/resources/subprocess/DoCreateVnfAndModules.bpmn index 58a88c2b56..433957572d 100644 --- a/bpmn/MSOInfrastructureBPMN/src/main/resources/subprocess/DoCreateVnfAndModules.bpmn +++ b/bpmn/MSOInfrastructureBPMN/src/main/resources/subprocess/DoCreateVnfAndModules.bpmn @@ -29,12 +29,16 @@ doCreateVnfAndModules.preProcessRequest(execution)]]> - + + + + + SequenceFlow_1hf7k7q - SequenceFlow_02oe9wx + SequenceFlow_1ixcnb6 @@ -56,9 +60,13 @@ doCreateVnfAndModules.preProcessRequest(execution)]]> - + + + + + SequenceFlow_1lh21yl SequenceFlow_1llbx0k @@ -81,8 +89,8 @@ doCreateVnfAndModules.validateAddOnModule(execution)]]> - SequenceFlow_02oe9wx SequenceFlow_07gl6gw + SequenceFlow_1a6wyuu SequenceFlow_132bohl SequenceFlow_0jz6bqn @@ -104,6 +112,9 @@ doCreateVnfAndModules.validateAddOnModule(execution)]]> + + + SequenceFlow_1xd3ri5 SequenceFlow_08i3uo6 @@ -165,7 +176,6 @@ doCreateVnfAndModules.queryCatalogDB(execution)]]> SequenceFlow_1lh21yl - SequenceFlow_1vrogpr @@ -174,6 +184,15 @@ doCreateVnfAndModules.queryCatalogDB(execution)]]> def doCreateVnfAndModules = new DoCreateVnfAndModules() doCreateVnfAndModules.finisthProcessingInitialCountDeployment(execution)]]> + + + + SequenceFlow_1ixcnb6 + SequenceFlow_1a6wyuu + + @@ -204,44 +223,44 @@ doCreateVnfAndModules.finisthProcessingInitialCountDeployment(execution)]]> - + - + - + - + - - + + - + - + - + - - - - + + + + - + - + @@ -254,51 +273,51 @@ doCreateVnfAndModules.finisthProcessingInitialCountDeployment(execution)]]> - + - + - - - - + + + + - + - - - + + + - + - - - + + + - + - - - - + + + + - + - - - + + + - + @@ -319,33 +338,41 @@ doCreateVnfAndModules.finisthProcessingInitialCountDeployment(execution)]]> - + - - + + - + - + + + + + + + + + + + - - - + - + - - - + + + - + - - + + diff --git a/bpmn/MSOInfrastructureBPMN/src/main/resources/subprocess/DoCreateVnfAndModulesRollback.bpmn b/bpmn/MSOInfrastructureBPMN/src/main/resources/subprocess/DoCreateVnfAndModulesRollback.bpmn new file mode 100644 index 0000000000..2fba166dc4 --- /dev/null +++ b/bpmn/MSOInfrastructureBPMN/src/main/resources/subprocess/DoCreateVnfAndModulesRollback.bpmn @@ -0,0 +1,282 @@ + + + + + + SequenceFlow_12 + + + + SequenceFlow_22 + + + + SequenceFlow_12 + SequenceFlow_22 + + + + + + SequenceFlow_23 + + + + SequenceFlow_23 + + + + SequenceFlow_1537b7m + + + SequenceFlow_0bmsi5h + SequenceFlow_1srw52v + SequenceFlow_1r6wyy6 + SequenceFlow_0v85t87 + + + SequenceFlow_1r6wyy6 + SequenceFlow_1kr0r4a + SequenceFlow_1yas9ol + + + SequenceFlow_04yd2yr + SequenceFlow_1yas9ol + + + + SequenceFlow_1537b7m + SequenceFlow_0bmsi5h + + + + + + SequenceFlow_0v85t87 + SequenceFlow_1ycq005 + + + + + + + + + + + SequenceFlow_1ycq005 + SequenceFlow_181hb2a + + + + 0}]]> + + + + + + + + + + + + + SequenceFlow_1kr0r4a + SequenceFlow_04yd2yr + + + + SequenceFlow_181hb2a + SequenceFlow_1srw52v + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/bpmn/MSOInfrastructureBPMN/src/main/resources/subprocess/DoDeleteNetworkInstance.bpmn b/bpmn/MSOInfrastructureBPMN/src/main/resources/subprocess/DoDeleteNetworkInstance.bpmn index 84b6d68149..3c581865cc 100644 --- a/bpmn/MSOInfrastructureBPMN/src/main/resources/subprocess/DoDeleteNetworkInstance.bpmn +++ b/bpmn/MSOInfrastructureBPMN/src/main/resources/subprocess/DoDeleteNetworkInstance.bpmn @@ -65,7 +65,6 @@ validateSDNCResponse.validateSDNCResponse(execution) SequenceFlow_1yvnovn - SequenceFlow_1loz6nk SequenceFlow_1nl99y6 SequenceFlow_1yvnovn - SequenceFlow_0jb7rws SequenceFlow_1wif0e5 SequenceFlow_147vc14 - SequenceFlow_1loz6nk - SequenceFlow_0tiz0kk SequenceFlow_0jb7rws SequenceFlow_1raa09h - + SequenceFlow_1suj1nc SequenceFlow_1raa09h + SequenceFlow_0jb7rws SequenceFlow_1nl99y6 @@ -142,6 +139,9 @@ DoDeleteNetworkInstance.prepareRollbackData(execution)]]> def DoDeleteNetworkInstance = new DoDeleteNetworkInstance() DoDeleteNetworkInstance.setExceptionFlag(execution)]]> + Rollback Not Needed for Delete. + + isRelationshipExistNo_SequenceFlow @@ -858,13 +858,6 @@ DoDeleteNetworkInstance.validateRpcSDNCDeactivateResponse(execution)]]> - - - - - - - @@ -874,10 +867,10 @@ DoDeleteNetworkInstance.validateRpcSDNCDeactivateResponse(execution)]]> - - + + - + @@ -928,6 +921,13 @@ DoDeleteNetworkInstance.validateRpcSDNCDeactivateResponse(execution)]]> + + + + + + + diff --git a/bpmn/MSOInfrastructureBPMN/src/main/resources/subprocess/DoDeleteNetworkInstanceRollback.bpmn b/bpmn/MSOInfrastructureBPMN/src/main/resources/subprocess/DoDeleteNetworkInstanceRollback.bpmn index 17f5ce4a40..2c5fa5ae4b 100644 --- a/bpmn/MSOInfrastructureBPMN/src/main/resources/subprocess/DoDeleteNetworkInstanceRollback.bpmn +++ b/bpmn/MSOInfrastructureBPMN/src/main/resources/subprocess/DoDeleteNetworkInstanceRollback.bpmn @@ -84,7 +84,7 @@ DoDeleteNetworkInstanceRollback.processJavaException(execution)]]> ${DELNWKIR_rollbackNetworkRequest} - CRENWKIR_urlRollbackPoNetwork + ${URN_mso_adapters_network_rest_endpoint} #{BasicAuthHeaderValuePO} diff --git a/bpmn/MSOInfrastructureBPMN/src/main/resources/subprocess/DoDeleteServiceInstance.bpmn b/bpmn/MSOInfrastructureBPMN/src/main/resources/subprocess/DoDeleteServiceInstance.bpmn index c40f73d059..9d21cc8301 100644 --- a/bpmn/MSOInfrastructureBPMN/src/main/resources/subprocess/DoDeleteServiceInstance.bpmn +++ b/bpmn/MSOInfrastructureBPMN/src/main/resources/subprocess/DoDeleteServiceInstance.bpmn @@ -1,332 +1,332 @@ - - - - - SequenceFlow_0jfgn05 - - - SequenceFlow_0jfgn05 - SequenceFlow_1jqc16k - - - - SequenceFlow_1wyvxwi - - - - - - - - - - - - - SequenceFlow_1w8ao21 - SequenceFlow_0riudmc - SequenceFlow_05wu9i7 - - - - - - - - - - - - - SequenceFlow_0rtflal - SequenceFlow_0k28xib - - - SequenceFlow_0k28xib - SequenceFlow_1w8ao21 - - - - - SequenceFlow_1dwch0k - SequenceFlow_0rtflal - - - - - SequenceFlow_1up0j5r - SequenceFlow_1hcfvcj - SequenceFlow_05jfuko - - - - - - SequenceFlow_05jfuko - - - - - SequenceFlow_1hcfvcj - SequenceFlow_0riudmc - SequenceFlow_1dwch0k - - - - - - - - - - - - - - - - SequenceFlow_1jqc16k - SequenceFlow_1grea1r - - - - SequenceFlow_1grea1r - SequenceFlow_1up0j5r - - - - - - SequenceFlow_05wu9i7 - SequenceFlow_1wyvxwi - - - - - - SequenceFlow_0u33vy6 - - - - SequenceFlow_0hevfee - - - SequenceFlow_0u33vy6 - SequenceFlow_0hevfee - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + SequenceFlow_0jfgn05 + + + SequenceFlow_0jfgn05 + SequenceFlow_1jqc16k + + + + SequenceFlow_1wyvxwi + + + + + + + + + + + + + SequenceFlow_1w8ao21 + SequenceFlow_0riudmc + SequenceFlow_05wu9i7 + + + + + + + + + + + + + SequenceFlow_0rtflal + SequenceFlow_0k28xib + + + SequenceFlow_0k28xib + SequenceFlow_1w8ao21 + + + + + SequenceFlow_1dwch0k + SequenceFlow_0rtflal + + + + + SequenceFlow_1up0j5r + SequenceFlow_1hcfvcj + SequenceFlow_05jfuko + + + + + + SequenceFlow_05jfuko + + + + + SequenceFlow_1hcfvcj + SequenceFlow_0riudmc + SequenceFlow_1dwch0k + + + + + + + + + + + + + + + + SequenceFlow_1jqc16k + SequenceFlow_1grea1r + + + + SequenceFlow_1grea1r + SequenceFlow_1up0j5r + + + + + + SequenceFlow_05wu9i7 + SequenceFlow_1wyvxwi + + + + + + SequenceFlow_0u33vy6 + + + + SequenceFlow_0hevfee + + + SequenceFlow_0u33vy6 + SequenceFlow_0hevfee + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/bpmn/MSOInfrastructureBPMN/src/main/resources/subprocess/DoDeleteVnfAndModules.bpmn b/bpmn/MSOInfrastructureBPMN/src/main/resources/subprocess/DoDeleteVnfAndModules.bpmn new file mode 100644 index 0000000000..127030d789 --- /dev/null +++ b/bpmn/MSOInfrastructureBPMN/src/main/resources/subprocess/DoDeleteVnfAndModules.bpmn @@ -0,0 +1,263 @@ + + + + + SequenceFlow_1 + + + + SequenceFlow_1 + SequenceFlow_08nd69s + + + + + SequenceFlow_19 + + + SequenceFlow_18 + + + + + SequenceFlow_18 + SequenceFlow_19 + + + + + + SequenceFlow_1uqlr6b + + + + SequenceFlow_0t4yszi + SequenceFlow_0lu7b1v + SequenceFlow_1qrkdn3 + SequenceFlow_1936oc0 + + + + + + + + SequenceFlow_05ujwz8 + SequenceFlow_1uqlr6b + + + + + + + + + + + + + + + + + + + SequenceFlow_1qoor0l + SequenceFlow_1p4ycii + + + SequenceFlow_1936oc0 + SequenceFlow_05ujwz8 + + + + + + + + SequenceFlow_08nd69s + SequenceFlow_0lu7b1v + + + + SequenceFlow_1qrkdn3 + SequenceFlow_1qoor0l + + + + + + SequenceFlow_1p4ycii + SequenceFlow_0t4yszi + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/bpmn/MSOInfrastructureBPMN/src/main/resources/subprocess/DoUpdateNetworkInstance.bpmn b/bpmn/MSOInfrastructureBPMN/src/main/resources/subprocess/DoUpdateNetworkInstance.bpmn new file mode 100644 index 0000000000..45e1a49f8a --- /dev/null +++ b/bpmn/MSOInfrastructureBPMN/src/main/resources/subprocess/DoUpdateNetworkInstance.bpmn @@ -0,0 +1,847 @@ + + + + + SequenceFlow_1 + + + + SequenceFlow_32 + SequenceFlow_11 + + + + + SequenceFlow_12 + SequenceFlow_5 + + + + SequenceFlow_5 + sdncTopoNo_SequenceFlow + sdncTopoYes_SequenceFlow + + + + + + + + SequenceFlow_34 + + + + + sdncTopoNo_SequenceFlow + SequenceFlow_34 + + + + + + + + + + + + + + SequenceFlow_11 + SequenceFlow_12 + + + + SequenceFlow_46 + SequenceFlow_29 + + + + + + SequenceFlow_053re4q + isRollbackOn_YesNetwork_SequenceFlow + isRollbackOn_NoNetwork_SequenceFlow + + + + + + + SequenceFlow_23 + + + + + isRollbackOn_YesNetwork_SequenceFlow + isPONR_Yes_SequenceFlow + isPONR_No_SequenceFlow + + + + + + + SequenceFlow_0nrc66n + sdncOk_Yeso_ExclusiveGateway + sdncOk_No_ExclusiveGateway + + + + + + + sdncOk_Yeso_ExclusiveGateway + SequenceFlow_53 + + + + + SequenceFlow_04rdjfi + + + SequenceFlow_53 + sdncOk_No_ExclusiveGateway + SequenceFlow_0srdlf3 + SequenceFlow_47 + + + + SequenceFlow_47 + SequenceFlow_0qr4es6 + + + + + + + + + + + + + + + + + + + SequenceFlow_0qr4es6 + + + SequenceFlow_0ze5k6c + SequenceFlow_04rdjfi + + + + + + SequenceFlow_0nrc66n + SequenceFlow_0srdlf3 + + + + + + + SequenceFlow_23 + SequenceFlow_053re4q + + + + + isPONR_Yes_SequenceFlow + isRollbackOn_NoNetwork_SequenceFlow + isPONR_No_SequenceFlow + SequenceFlow_0ze5k6c + + + Note: Rollback is not needed for UpdateNetwork, + + + + + SequenceFlow_13 + SequenceFlow_35 + + + + + SequenceFlow_35 + SequenceFlow_46 + + + + + SequenceFlow_29 + + + + SequenceFlow_10 + SequenceFlow_14 + + + + + SequenceFlow_10 + + + + + SequenceFlow_14 + + + + SequenceFlow_1 + SequenceFlow_7 + + + + + SequenceFlow_24 + SequenceFlow_32 + + + + + siFoundYes + SequenceFlow_24 + + + + + SequenceFlow_30 + + + + siFoundNo + SequenceFlow_30 + + + + + SequenceFlow_3 + siFoundYes + siFoundNo + + + + + + + + + + + + + + + + SequenceFlow_7 + SequenceFlow_3 + + + + SequenceFlow_59 + SequenceFlow_13 + + + + + + + + ${UPDNETI_updateNetworkRequest} + ${URN_mso_adapters_network_rest_endpoint}/${UPDNETI_networkId} + + + #{BasicAuthHeaderValuePO} + application/xml + + + PUT + ${statusCode} + ${response} + + http-connector + + + SequenceFlow_61 + SequenceFlow_59 + + + + SequenceFlow_2 + SequenceFlow_61 + + + + + SequenceFlow_38 + SequenceFlow_2 + + + + + sdncTopoYes_SequenceFlow + SequenceFlow_6 + + + + + SequenceFlow_6 + SequenceFlow_15 + + + + + SequenceFlow_15 + SequenceFlow_38 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/bpmn/MSOInfrastructureBPMN/src/main/resources/subprocess/DoUpdateNetworkInstanceRollback.bpmn b/bpmn/MSOInfrastructureBPMN/src/main/resources/subprocess/DoUpdateNetworkInstanceRollback.bpmn new file mode 100644 index 0000000000..6fd0565f3a --- /dev/null +++ b/bpmn/MSOInfrastructureBPMN/src/main/resources/subprocess/DoUpdateNetworkInstanceRollback.bpmn @@ -0,0 +1,373 @@ + + + + + SequenceFlow_1krl2dg + + + SequenceFlow_1krl2dg + SequenceFlow_0u41iz2 + + + + + + + + + ${UPDNETIR_rollbackNetworkRequest} + ${URN_mso_adapters_network_rest_endpoint} + + + #{BasicAuthHeaderValuePO} + application/xml + + + PUT + ${statusCode} + ${response} + + http-connector + + + SequenceFlow_0e1uixp + SequenceFlow_17o4w67 + + + SequenceFlow_0u41iz2 + SequenceFlow_0e1uixp + SequenceFlow_1lteduj + + + + + + + + + + + + SequenceFlow_101y57s + SequenceFlow_0790olb + + + SequenceFlow_0virkpu + SequenceFlow_101y57s + SequenceFlow_0mw0dgd + + + SequenceFlow_0qc4v9t + SequenceFlow_0el8yzs + SequenceFlow_0yto4gz + + + + SequenceFlow_1lteduj + SequenceFlow_17o4w67 + SequenceFlow_0virkpu + SequenceFlow_0qc4v9t + + + + + + + + + + + + + + + SequenceFlow_0yto4gz + + + + + + SequenceFlow_0xktw7v + SequenceFlow_0soe5t3 + + + + SequenceFlow_0xktw7v + + + + SequenceFlow_0soe5t3 + + + + + + SequenceFlow_0790olb + SequenceFlow_0mw0dgd + SequenceFlow_0el8yzs + + + + + + SequenceFlow_07kf49j + SequenceFlow_01syg1x + + + + SequenceFlow_07kf49j + + + + SequenceFlow_01syg1x + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/bpmn/MSOInfrastructureBPMN/src/main/resources/urn.properties b/bpmn/MSOInfrastructureBPMN/src/main/resources/urn.properties index b3fee32765..ccbeaa6e38 100644 --- a/bpmn/MSOInfrastructureBPMN/src/main/resources/urn.properties +++ b/bpmn/MSOInfrastructureBPMN/src/main/resources/urn.properties @@ -1,29 +1,29 @@ -### -# ============LICENSE_START======================================================= -# ECOMP MSO -# ================================================================================ -# 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========================================================= -### - -# URN mappings for this project. - -# TODO: Remove all the non-URN stuff that's in here. -# TODO: Implement a real URN mapping capability. - -#AAIEndPoint= http://localhost:8080/SoapUIMocks -AAIEndPoint= http://localhost:28090/ -SDNCEndPoint=http://localhost:28090/SDNCAdapter/ -msoRollback = true +### +# ============LICENSE_START======================================================= +# ECOMP MSO +# ================================================================================ +# 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========================================================= +### + +# URN mappings for this project. + +# TODO: Remove all the non-URN stuff that's in here. +# TODO: Implement a real URN mapping capability. + +#AAIEndPoint= http://localhost:8080/SoapUIMocks +AAIEndPoint= http://localhost:28090/ +SDNCEndPoint=http://localhost:28090/SDNCAdapter/ +msoRollback = true diff --git a/bpmn/MSOInfrastructureBPMN/src/main/webapp/WEB-INF/jboss-deployment-structure.xml b/bpmn/MSOInfrastructureBPMN/src/main/webapp/WEB-INF/jboss-deployment-structure.xml index 130f95e171..3dbfcce36f 100644 --- a/bpmn/MSOInfrastructureBPMN/src/main/webapp/WEB-INF/jboss-deployment-structure.xml +++ b/bpmn/MSOInfrastructureBPMN/src/main/webapp/WEB-INF/jboss-deployment-structure.xml @@ -1,31 +1,31 @@ - - - - - - - - - - - - - + + + + + + + + + + + + + diff --git a/bpmn/MSOInfrastructureBPMN/src/main/webapp/WEB-INF/jboss-web.xml b/bpmn/MSOInfrastructureBPMN/src/main/webapp/WEB-INF/jboss-web.xml index 42717c5a76..a39a02178a 100644 --- a/bpmn/MSOInfrastructureBPMN/src/main/webapp/WEB-INF/jboss-web.xml +++ b/bpmn/MSOInfrastructureBPMN/src/main/webapp/WEB-INF/jboss-web.xml @@ -1,26 +1,26 @@ - - - - - - other - /mso - + + + + + + other + /mso + diff --git a/bpmn/MSOInfrastructureBPMN/src/main/webapp/WEB-INF/web.xml b/bpmn/MSOInfrastructureBPMN/src/main/webapp/WEB-INF/web.xml index 3bdba77999..eb5df6038e 100644 --- a/bpmn/MSOInfrastructureBPMN/src/main/webapp/WEB-INF/web.xml +++ b/bpmn/MSOInfrastructureBPMN/src/main/webapp/WEB-INF/web.xml @@ -1,74 +1,74 @@ - - - - MSO Infrastructure BPMN Workflow Servlet - - resteasy-servlet - org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher - - javax.ws.rs.Application - org.openecomp.mso.bpmn.infrastructure.workflow.service.WorkflowResourceApplication - - - - resteasy-servlet - /* - - - mso.configuration - MSO_PROP_TOPOLOGY=topology.properties - - - log.configuration - logback.bpmn.xml - - - resteasy.resources - org.openecomp.mso.logger.MsoLoggingServlet,org.openecomp.mso.bpmn.core.HealthCheckHandler - - - LogFilter - org.openecomp.mso.logger.LogFilter - - - LogFilter - /* - - - - HTTPBasicAuth - Authentication for Client Apps - /workflow/* - GET - POST - - - BPMN-Client - - - - BASIC - ApplicationRealm - - - BPMN-Client - + + + + MSO Infrastructure BPMN Workflow Servlet + + resteasy-servlet + org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher + + javax.ws.rs.Application + org.openecomp.mso.bpmn.infrastructure.workflow.service.WorkflowResourceApplication + + + + resteasy-servlet + /* + + + mso.configuration + MSO_PROP_TOPOLOGY=topology.properties + + + log.configuration + logback.bpmn.xml + + + resteasy.resources + org.openecomp.mso.logger.MsoLoggingServlet,org.openecomp.mso.bpmn.core.HealthCheckHandler + + + LogFilter + org.openecomp.mso.logger.LogFilter + + + LogFilter + /* + + + + HTTPBasicAuth + Authentication for Client Apps + /workflow/* + GET + POST + + + BPMN-Client + + + + BASIC + ApplicationRealm + + + BPMN-Client + \ No newline at end of file diff --git a/bpmn/MSOInfrastructureBPMN/src/test/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/DoCreateVfModuleVolumeV1Test.groovy b/bpmn/MSOInfrastructureBPMN/src/test/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/DoCreateVfModuleVolumeV1Test.groovy index cf95ed3085..e9c27b040a 100644 --- a/bpmn/MSOInfrastructureBPMN/src/test/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/DoCreateVfModuleVolumeV1Test.groovy +++ b/bpmn/MSOInfrastructureBPMN/src/test/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/DoCreateVfModuleVolumeV1Test.groovy @@ -1,218 +1,218 @@ -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - MSO - * ================================================================================ - * 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.openecomp.mso.bpmn.infrastructure.scripts; - -import static org.junit.Assert.* -import static org.mockito.Mockito.* - -import org.apache.commons.lang3.* -import org.camunda.bpm.engine.impl.persistence.entity.ExecutionEntity -import org.junit.Assert -import org.junit.Before -import org.junit.Test -import org.junit.runner.RunWith -import org.mockito.ArgumentCaptor -import org.mockito.MockitoAnnotations -import org.mockito.runners.MockitoJUnitRunner -import org.openecomp.mso.bpmn.common.scripts.MsoGroovyTest - - -@RunWith(MockitoJUnitRunner.class) -class DoCreateVfModuleVolumeV1Test extends MsoGroovyTest { - - def volumeRequest = -""" - - 123abc - d8d4fcfa-fd7e-4413-b19d-c95aa67291b8 - CREATE_VF_MODULE_VOL - SoapUI-bns-create-base-vol-1001-1 - - - Test/vSAMP12 - vSAMP12::base::module-0 - true - 2.0 - a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb - MDTWNJ21 - 897deadc2b954a6bac6d3c197fb3525e - MSOTESTVOL101a-vSAMP12_base_vol_module-0 - - - - value1" - value2" - value3" - -""" - - def genericVnfResponseXml = """ - - TEST-VNF-ID-0123 - STMTN5MMSC20 - pcrf-capacity - SDN-MOBILITY - vPCRF - pending-create - false - false - introvert - 2.0 - 0000020 - - - lukewarm - PCRF::module-0-0 - introvert - 2.0 - true - fastburn - pending-create - 0000074 - - - supercool - PCRF::module-1-0 - extrovert - 2.0 - false - slowburn - pending-create - 0000075 - - - - - - -""" - def String expectedCreateVnfRequestXml = """ - MDTWNJ21 - 897deadc2b954a6bac6d3c197fb3525e - TEST-VNF-ID-0123 - STMTN5MMSC20 - test-vol-group-id-123 - MSOTESTVOL101a-vSAMP12_base_vol_module-0 - Test/vSAMP12 - 2.0 - vSAMP12::base::module-0 - - - - vnf_id - TEST-VNF-ID-0123 - - - vnf_name - STMTN5MMSC20 - - - vf_module_id - test-vol-group-id-123 - - - vf_module_name - MSOTESTVOL101a-vSAMP12_base_vol_module-0 - - - param1 - value1 - - - param2 - value2 - - - param3 - value3 - - - true - true - true - - d8d4fcfa-fd7e-4413-b19d-c95aa67291b8 - a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb - - 111 - http://localhost:28080/mso/WorkflowMessage/12345678 - -""" - - @Before - public void init() - { - MockitoAnnotations.initMocks(this) - - } - - @Test - public void TestPreProcessRequest() { - - ExecutionEntity mockExecution = setupMock('DoCreateVfModuleVolumeV1') - - when(mockExecution.getVariable("DoCreateVfModuleVolumeV1Request")).thenReturn(volumeRequest) - when(mockExecution.getVariable("vnf-id")).thenReturn('test-vnf-id-123') - when(mockExecution.getVariable("volume-group-id")).thenReturn('test-volume-group-id-123') - when(mockExecution.getVariable("mso-request-id")).thenReturn('test-request-id-123') - - DoCreateVfModuleVolumeV1 myprocess = new DoCreateVfModuleVolumeV1() - myprocess.preProcessRequest(mockExecution, 'true') - - verify(mockExecution).setVariable('DCVFMODVOLV1_serviceId', 'a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb') - verify(mockExecution).setVariable('DCVFMODVOLV1_source', 'SoapUI-bns-create-base-vol-1001-1') - verify(mockExecution, times(7)).setVariable(anyString(), anyString()) - } - - @Test - public void TestPrepareVnfAdapterCreateRequest() { - - ExecutionEntity mockExecution = setupMock('DoCreateVfModuleVolumeV1') - - when(mockExecution.getVariable("DCVFMODVOLV1_Request")).thenReturn(volumeRequest) - when(mockExecution.getVariable("DCVFMODVOLV1_requestId")).thenReturn('d8d4fcfa-fd7e-4413-b19d-c95aa67291b8') - when(mockExecution.getVariable("DCVFMODVOLV1_serviceId")).thenReturn('a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb') - when(mockExecution.getVariable("DCVFMODVOLV1_AAIQueryGenericVfnResponse")).thenReturn(genericVnfResponseXml) - when(mockExecution.getVariable("DCVFMODVOLV1_rollbackEnabled")).thenReturn(true) - when(mockExecution.getVariable("volume-group-id")).thenReturn('test-vol-group-id-123') - when(mockExecution.getVariable("URN_mso_workflow_message_endpoint")).thenReturn('http://localhost:28080/mso/WorkflowMessage') - when(mockExecution.getVariable("URN_mso_use_qualified_host")).thenReturn(true) - - DoCreateVfModuleVolumeV1 myprocess = new DoCreateVfModuleVolumeV1() - myprocess.prepareVnfAdapterCreateRequest(mockExecution, 'true') - - // Capture the arguments to setVariable - ArgumentCaptor captor1 = ArgumentCaptor.forClass(String.class); - ArgumentCaptor captor2 = ArgumentCaptor.forClass(String.class); - - verify(mockExecution, times(2)).setVariable(captor1.capture(), captor2.capture()) - - List arg2List = captor2.getAllValues() - String createVnfRequestXml = arg2List.get(0) - - //replace messageID value because it is random generated - createVnfRequestXml = createVnfRequestXml.replaceAll("(.+?)", "111") - .replaceAll("(.+?)", "http://localhost:28080/mso/WorkflowMessage/12345678") - - Assert.assertEquals(expectedCreateVnfRequestXml.trim(), createVnfRequestXml.trim()) - } - -} +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.bpmn.infrastructure.scripts; + +import static org.junit.Assert.* +import static org.mockito.Mockito.* + +import org.apache.commons.lang3.* +import org.camunda.bpm.engine.impl.persistence.entity.ExecutionEntity +import org.junit.Assert +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.mockito.ArgumentCaptor +import org.mockito.MockitoAnnotations +import org.mockito.runners.MockitoJUnitRunner +import org.openecomp.mso.bpmn.common.scripts.MsoGroovyTest + + +@RunWith(MockitoJUnitRunner.class) +class DoCreateVfModuleVolumeV1Test extends MsoGroovyTest { + + def volumeRequest = +""" + + 123abc + d8d4fcfa-fd7e-4413-b19d-c95aa67291b8 + CREATE_VF_MODULE_VOL + SoapUI-bns-create-base-vol-1001-1 + + + Test/vSAMP12 + vSAMP12::base::module-0 + true + 2.0 + a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb + MDTWNJ21 + 897deadc2b954a6bac6d3c197fb3525e + MSOTESTVOL101a-vSAMP12_base_vol_module-0 + + + + value1" + value2" + value3" + +""" + + def genericVnfResponseXml = """ + + TEST-VNF-ID-0123 + STMTN5MMSC20 + pcrf-capacity + SDN-MOBILITY + vPCRF + pending-create + false + false + introvert + 2.0 + 0000020 + + + lukewarm + PCRF::module-0-0 + introvert + 2.0 + true + fastburn + pending-create + 0000074 + + + supercool + PCRF::module-1-0 + extrovert + 2.0 + false + slowburn + pending-create + 0000075 + + + + + + +""" + def String expectedCreateVnfRequestXml = """ + MDTWNJ21 + 897deadc2b954a6bac6d3c197fb3525e + TEST-VNF-ID-0123 + STMTN5MMSC20 + test-vol-group-id-123 + MSOTESTVOL101a-vSAMP12_base_vol_module-0 + Test/vSAMP12 + 2.0 + vSAMP12::base::module-0 + + + + vnf_id + TEST-VNF-ID-0123 + + + vnf_name + STMTN5MMSC20 + + + vf_module_id + test-vol-group-id-123 + + + vf_module_name + MSOTESTVOL101a-vSAMP12_base_vol_module-0 + + + param1 + value1 + + + param2 + value2 + + + param3 + value3 + + + true + true + true + + d8d4fcfa-fd7e-4413-b19d-c95aa67291b8 + a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb + + 111 + http://localhost:28080/mso/WorkflowMessage/12345678 + +""" + + @Before + public void init() + { + MockitoAnnotations.initMocks(this) + + } + + @Test + public void TestPreProcessRequest() { + + ExecutionEntity mockExecution = setupMock('DoCreateVfModuleVolumeV1') + + when(mockExecution.getVariable("DoCreateVfModuleVolumeV1Request")).thenReturn(volumeRequest) + when(mockExecution.getVariable("vnf-id")).thenReturn('test-vnf-id-123') + when(mockExecution.getVariable("volume-group-id")).thenReturn('test-volume-group-id-123') + when(mockExecution.getVariable("mso-request-id")).thenReturn('test-request-id-123') + + DoCreateVfModuleVolumeV1 myprocess = new DoCreateVfModuleVolumeV1() + myprocess.preProcessRequest(mockExecution, 'true') + + verify(mockExecution).setVariable('DCVFMODVOLV1_serviceId', 'a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb') + verify(mockExecution).setVariable('DCVFMODVOLV1_source', 'SoapUI-bns-create-base-vol-1001-1') + verify(mockExecution, times(7)).setVariable(anyString(), anyString()) + } + + @Test + public void TestPrepareVnfAdapterCreateRequest() { + + ExecutionEntity mockExecution = setupMock('DoCreateVfModuleVolumeV1') + + when(mockExecution.getVariable("DCVFMODVOLV1_Request")).thenReturn(volumeRequest) + when(mockExecution.getVariable("DCVFMODVOLV1_requestId")).thenReturn('d8d4fcfa-fd7e-4413-b19d-c95aa67291b8') + when(mockExecution.getVariable("DCVFMODVOLV1_serviceId")).thenReturn('a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb') + when(mockExecution.getVariable("DCVFMODVOLV1_AAIQueryGenericVfnResponse")).thenReturn(genericVnfResponseXml) + when(mockExecution.getVariable("DCVFMODVOLV1_rollbackEnabled")).thenReturn(true) + when(mockExecution.getVariable("volume-group-id")).thenReturn('test-vol-group-id-123') + when(mockExecution.getVariable("URN_mso_workflow_message_endpoint")).thenReturn('http://localhost:28080/mso/WorkflowMessage') + when(mockExecution.getVariable("URN_mso_use_qualified_host")).thenReturn(true) + + DoCreateVfModuleVolumeV1 myprocess = new DoCreateVfModuleVolumeV1() + myprocess.prepareVnfAdapterCreateRequest(mockExecution, 'true') + + // Capture the arguments to setVariable + ArgumentCaptor captor1 = ArgumentCaptor.forClass(String.class); + ArgumentCaptor captor2 = ArgumentCaptor.forClass(String.class); + + verify(mockExecution, times(2)).setVariable(captor1.capture(), captor2.capture()) + + List arg2List = captor2.getAllValues() + String createVnfRequestXml = arg2List.get(0) + + //replace messageID value because it is random generated + createVnfRequestXml = createVnfRequestXml.replaceAll("(.+?)", "111") + .replaceAll("(.+?)", "http://localhost:28080/mso/WorkflowMessage/12345678") + + Assert.assertEquals(expectedCreateVnfRequestXml.trim(), createVnfRequestXml.trim()) + } + +} diff --git a/bpmn/MSOInfrastructureBPMN/src/test/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/UpdateNetworkInstanceInfraTest.groovy b/bpmn/MSOInfrastructureBPMN/src/test/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/UpdateNetworkInstanceInfraTest.groovy index d19081c766..a90cf12ecb 100644 --- a/bpmn/MSOInfrastructureBPMN/src/test/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/UpdateNetworkInstanceInfraTest.groovy +++ b/bpmn/MSOInfrastructureBPMN/src/test/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/UpdateNetworkInstanceInfraTest.groovy @@ -1,3094 +1,3055 @@ -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - MSO - * ================================================================================ - * 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.openecomp.mso.bpmn.infrastructure.scripts; - -import static org.junit.Assert.* -import static org.mockito.Mockito.* -import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockGetCloudRegion -import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockGetNetwork -import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockPutNetwork -import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockGetNetworkPolicy -import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockGetNetworkRouteTable -import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockGetNetworkVpnBinding - -import org.apache.commons.lang3.* -import org.camunda.bpm.engine.ProcessEngineServices -import org.camunda.bpm.engine.RepositoryService -import org.camunda.bpm.engine.impl.persistence.entity.ExecutionEntity -import org.camunda.bpm.engine.repository.ProcessDefinition -import org.camunda.bpm.engine.runtime.Execution -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.runner.RunWith -import org.mockito.ArgumentCaptor -import org.mockito.MockitoAnnotations -import org.mockito.runners.MockitoJUnitRunner -import org.openecomp.mso.bpmn.common.scripts.MsoUtils -import org.openecomp.mso.bpmn.core.WorkflowException - -import com.github.tomakehurst.wiremock.client.WireMock -import com.github.tomakehurst.wiremock.junit.WireMockRule - - -@RunWith(MockitoJUnitRunner.class) -class UpdateNetworkInstanceInfraTest { - - @Rule - public WireMockRule wireMockRule = new WireMockRule(28090); - - def utils = new MsoUtils() - - String jsonIncomingRequest = - """{ "requestDetails": { - "modelInfo": { - "modelType": "networkTyp", - "modelId": "modelId", - "modelNameVersionId": "modelNameVersionId", - "modelName": "CONTRAIL_EXTERNAL", - "modelVersion": "1" - }, - "cloudConfiguration": { - "lcpCloudRegionId": "RDM2WAGPLCP", - "tenantId": "7dd5365547234ee8937416c65507d266" - }, - "requestInfo": { - "instanceName": "MNS-25180-L-01-dmz_direct_net_1", - "source": "VID", - "callbackUrl": "", - "suppressRollback": true, - "productFamilyId": "a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb" - }, - "relatedInstanceList": [ - { - "relatedInstance": { - "instanceId": "f70e927b-6087-4974-9ef8-c5e4d5847ca4", - "modelInfo": { - "modelType": "serviceT", - "modelId": "modelI", - "modelNameVersionId": "modelNameVersionI", - "modelName": "modleNam", - "modelVersion": "1" - } - } - } - ], - "requestParameters": { - "userParams": [ - { - "name": "someUserParam1", - "value": "someValue1" - } - ] - } - }}""" - - String jsonIncomingRequest_Missingname = - """{ "requestDetails": { - "modelInfo": { - "modelType": "networkTyp", - "modelId": "modelId", - "modelNameVersionId": "modelNameVersionId", - "modelName": "CONTRAIL_EXTERNAL", - "modelVersion": "1" - }, - "cloudConfiguration": { - "lcpCloudRegionId": "RDM2WAGPLCP", - "tenantId": "7dd5365547234ee8937416c65507d266" - }, - "requestInfo": { - "source": "VID", - "callbackUrl": "", - "suppressRollback": true, - "productFamilyId": "a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb" - }, - "relatedInstanceList": [ - { - "relatedInstance": { - "instanceId": "f70e927b-6087-4974-9ef8-c5e4d5847ca4", - "modelInfo": { - "modelType": "serviceT", - "modelId": "modelI", - "modelNameVersionId": "modelNameVersionI", - "modelName": "modleNam", - "modelVersion": "1" - } - } - } - ], - "requestParameters": { - "userParams": [] - } - }}""" - - String jsonIncomingRequest_MissingCloudRegion = - """{ "requestDetails": { - "modelInfo": { - "modelType": "networkTyp", - "modelId": "modelId", - "modelNameVersionId": "modelNameVersionId", - "modelName": "CONTRAIL_EXTERNAL", - "modelVersion": "1" - }, - "cloudConfiguration": { - "tenantId": "7dd5365547234ee8937416c65507d266" - }, - "requestInfo": { - "instanceName": "MNS-25180-L-01-dmz_direct_net_1", - "source": "VID", - "callbackUrl": "", - "suppressRollback": true, - "productFamilyId": "a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb" - }, - "relatedInstanceList": [ - { - "relatedInstance": { - "instanceId": "f70e927b-6087-4974-9ef8-c5e4d5847ca4", - "modelInfo": { - "modelType": "serviceT", - "modelId": "modelI", - "modelNameVersionId": "modelNameVersionI", - "modelName": "modleNam", - "modelVersion": "1" - } - } - } - ], - "requestParameters": { - "userParams": [] - } - }}""" - - - - String expectedNetworkRequestMissingNetworkId = - """ - - 88f65519-9a38-4c4b-8445-9eb4a5a5af56 - UPDATE - VID - f70e927b-6087-4974-9ef8-c5e4d5847ca4 - - - - MNS-25180-L-01-dmz_direct_net_1 - CONTRAIL_EXTERNAL - RDM2WAGPLCP - 7dd5365547234ee8937416c65507d266 - a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb - true - - - someValue1 - - -""" - - -String expectedNetworkRequestMissingCloudRegion = -""" - - 88f65519-9a38-4c4b-8445-9eb4a5a5af56 - UPDATE - PORTAL - - - HSL_direct_net_2 - CONTRAIL_EXTERNAL - a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb - - e81d842d3e8b45c5a59f57cd76af3aaf - - - 1 - -""" - - // vnfRESTRequest - String networkRESTRequest = -""" - - - - 1ef47428-cade-45bd-a103-0751e8b2deb0 - UPDATE - PORTAL - - - MNS-25180-L-01-dmz_direct_net_1 - CONTRAIL_EXTERNAL - a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb - RDM2WAGPLCP - 7dd5365547234ee8937416c65507d266 - dvs-slcp3-01 - 3008 - - - 1 - 0 - - - - """ - - String networkInputsMissingName = - """ - - CONTRAIL_EXTERNAL - a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb - RDM2WAGPLCP - e81d842d3e8b45c5a59f57cd76af3aaf - """ - -String networkInputsMissingCloudRegion = -""" - HSL_direct_net_2 - CONTRAIL_EXTERNAL - a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb - - e81d842d3e8b45c5a59f57cd76af3aaf -""" - - String expectedUpdateNetworkInstanceInfraRequest = - """ - - - 1ef47428-cade-45bd-a103-0751e8b2deb0 - UPDATE - PORTAL - - - MNS-25180-L-01-dmz_direct_net_1 - CONTRAIL_EXTERNAL - a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb - RDM2WAGPLCP - 7dd5365547234ee8937416c65507d266 - dvs-slcp3-01 - 3008 - - - 1 - 0 - - -""" - - String expectedUpdateNetworkInstanceInfraRequest_Output = - """ - - - 1ef47428-cade-45bd-a103-0751e8b2deb0 - UPDATE - PORTAL - - - MNS-25180-L-01-dmz_direct_net_1 - CONTRAIL_EXTERNAL - a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb - RDM2WAGPLCP - 7dd5365547234ee8937416c65507d266 - - - MNS-25180-L-01-dmz_direct_net_1 - bdc5efe8-404a-409b-85f6-0dcc9eebae30 - - - 1 - 0 - - -""" - - // expectedNetworkRequest - String expectedNetworkRequest = - """ - - UPDATE - VID - f70e927b-6087-4974-9ef8-c5e4d5847ca4 - - - 49c86598-f766-46f8-84f8-8d1c1b10f9b4 - MNS-25180-L-01-dmz_direct_net_1 - CONTRAIL_EXTERNAL - RDM2WAGPLCP - 7dd5365547234ee8937416c65507d266 - a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb - true - - - true - a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb - true - true - 10.10.125.1 - -""" - -String expectedNetworkInputs = -""" - - MNS-25180-L-01-dmz_direct_net_1 - CONTRAIL_EXTERNAL - RDM2WAGPLCP - 7dd5365547234ee8937416c65507d266 - a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb - true -""" - - - String NetworkRequest_noPhysicalName = - """ - - 1ef47428-cade-45bd-a103-0751e8b2deb0 - UPDATE - PORTAL - - - MNS-25180-L-01-dmz_direct_net_1 - CONTRAIL_EXTERNAL - a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb - RDM2WAGPLCP - 7dd5365547234ee8937416c65507d266 - 3008 - - - - true - a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb - true - true - 10.10.125.1 - - -""" - - String vnfRequestFakeRegion = - """ - - 1ef47428-cade-45bd-a103-0751e8b2deb0 - UPDATE - PORTAL - - - MNS-25180-L-01-dmz_direct_net_1 - CONTRAIL_EXTERNAL - a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb - MDTWNJ21 - 7dd5365547234ee8937416c65507d266 - - - 1 - 0 - -""" - - // expectedNetworkRequest - String expectedNetworkRequest_Outputs = - """ - - 1ef47428-cade-45bd-a103-0751e8b2deb0 - UPDATE - PORTAL - - - MNS-25180-L-01-dmz_direct_net_1 - CONTRAIL_EXTERNAL - a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb - RDM2WAGPLCP - 7dd5365547234ee8937416c65507d266 - - - MNS-25180-L-01-dmz_direct_net_1 - bdc5efe8-404a-409b-85f6-0dcc9eebae30 - - - 1 - 0 - -""" - - - // expectedNetworkRequest - String networkInputs_404 = - """ - myOwn_Network - CONTRAIL_EXTERNAL - a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb - RDM2WAGPLCP - e81d842d3e8b45c5a59f57cd76af3aaf - """ - - String networkInputs = - """ - bdc5efe8-404a-409b-85f6-0dcc9eebae30 - MNS-25180-L-01-dmz_direct_net_1 - CONTRAIL_EXTERNAL - a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb - RDM2WAGPLCP - e81d842d3e8b45c5a59f57cd76af3aaf -""" - - String networkOutputs = - """ - 49c86598-f766-46f8-84f8-8d1c1b10f9b4 - MNS-25180-L-01-dmz_direct_net_1 - """ - - String queryAAIResponse = - """ - - - - - - - - - - - - bdc5efe8-404a-409b-85f6-0dcc9eebae30 - HSL_direct_net_2 - CONTRAIL_EXTERNAL - dmz_direct - contrail - a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb - 0 - pending-delete - - - 57e9a1ff-d14f-4071-a828-b19ae98eb2fc - 107.239.52.1 - 107.239.52.0 - 24 - 4 - pending-delete - true - - - - - - vpn-binding - https://aai-app-e2e.test.com:8443/aai/v8/network/vpn-bindings/vpn-binding/85f015d0-2e32-4c30-96d2-87a1a27f8017/ - - vpn-binding.vpn-id - 85f015d0-2e32-4c30-96d2-87a1a27f8017 - - - - vpn-binding - https://aai-app-e2e.test.com:8443/aai/v8/network/vpn-bindings/vpn-binding/c980a6ef-3b88-49f0-9751-dbad8608d0a6/ - - vpn-binding.vpn-id - c980a6ef-3b88-49f0-9751-dbad8608d0a6 - - - - tenant - https://aai-app-e2e.test.com:8443/aai/v8/cloud-infrastructure/tenants/tenant/7dd5365547234ee8937416c65507d266/ - - tenant.tenant-id - 7dd5365547234ee8937416c65507d266 - - - - - -""" - - String queryIdAIIResponse = - """ - - - - - - - - - - - - 49c86598-f766-46f8-84f8-8d1c1b10f9b4 - MNS-25180-L-01-dmz_direct_net_1 - CONTRAIL_EXTERNAL - dmz_direct - contrail - a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb - 0 - l3-version - pending-delete - ST_2Bindings_6006/55288ef0-595c-47d3-819e-cf93aaac6326 - networkName - false - true - false - - - 57e9a1ff-d14f-4071-a828-b19ae98eb2fc - 107.239.52.1 - 107.239.52.0 - 24 - 4 - pending-delete - true - subnetName - - - - 57e9a1ff-d14f-4071-a828-b19ae98eb2fc - 107.239.52.1 - 107.239.52.0 - 24 - 4 - pending-delete - true - subnetName - - - - - 414 - 4132176 - - - 415 - 4132176 - - - - inner - ctag-version - - - tenant - https://aai-ext1.test.com:8443/aai/v8/cloud-infrastructure/tenants/tenant/897deadc2b954a6bac6d3c197fb3525e/ - - tenant.tenant-id - 897deadc2b954a6bac6d3c197fb3525e - - - tenant.tenant-name - MSOTest1 - - - - vpn-binding - https://aai-ext1.test.com:8443/aai/v8/network/vpn-bindings/vpn-binding/a290b841-f672-44dd-b9cd-6f8c20d7d8c8/ - - vpn-binding.vpn-id - a290b841-f672-44dd-b9cd-6f8c20d7d8c8 - - - vpn-binding.vpn-name - oam_protected_net_6_MTN5_msotest2 - - - - vpn-binding - https://aai-ext1.test.com:8443/aai/v8/network/vpn-bindings/vpn-binding/24a4b507-853a-4a38-99aa-05fcc54be24d/ - - vpn-binding.vpn-id - 24a4b507-853a-4a38-99aa-05fcc54be24d - - - vpn-binding.vpn-name - oam_protected_net_6_MTN5_msotest1 - - - - - - - - vpn-binding - https://aai-app-e2e.test.com:8443/aai/v8/network/vpn-bindings/vpn-binding/85f015d0-2e32-4c30-96d2-87a1a27f8017/ - - vpn-binding.vpn-id - 85f015d0-2e32-4c30-96d2-87a1a27f8017 - - - - vpn-binding - https://aai-app-e2e.test.com:8443/aai/v8/network/vpn-bindings/vpn-binding/c980a6ef-3b88-49f0-9751-dbad8608d0a6/ - - vpn-binding.vpn-id - c980a6ef-3b88-49f0-9751-dbad8608d0a6 - - - - tenant - https://aai-app-e2e.test.com:8443/aai/v8/cloud-infrastructure/tenants/tenant/7dd5365547234ee8937416c65507d266/ - - tenant.tenant-id - 7dd5365547234ee8937416c65507d266 - - - - network-policy - https://aai-app-e2e.test.com:8443/aai/v8/network/network-policies/network-policy/cee6d136-e378-4678-a024-2cd15f0ee0cg - - network-policy.network-policy-id - cee6d136-e378-4678-a024-2cd15f0ee0cg - - - - route-table-reference - https://aai-app-e2e.test.com:8443/aai/v8/network/route-table-references/route-table-reference/refFQDN1 - - route-table-reference.route-table-reference-id - cee6d136-e378-4678-a024-2cd15f0ee0hi - - - - route-table-reference - https://aai-app-e2e.test.com:8443/aai/v8/network/route-table-references/route-table-reference/refFQDN2 - - route-table-reference.route-table-reference-id - cee6d136-e378-4678-a024-2cd15f0ee0hi - - - - - -""" - - String queryIdAIIResponseTestScenario01 = - """ - - 4da55fe4-7a9e-478c-a434-8a98d62265ab - GN_EVPN_direct_net_0_ST1 - CONTRAIL30_BASIC - GN_EVPN_direct - contrail - false - 9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb - 0 - 1465398611 - pending-delete - networkName - false - true - false - - - cb1a7b47-5428-44c9-89c2-8b17541c3228 - 108.239.40.1 - 108.239.40.0 - 28 - 4 - pending-delete - true - 108.239.40.0 - 108.239.40.0 - 1465398611 - subnetName - - - - e2cc7c14-90f0-4205-840d-b4e07f04e621 - 2606:ae00:2e01:604::1 - 2606:ae00:2e01:604:: - 64 - 6 - pending-delete - true - 2606:ae00:2e01:604:: - 2606:ae00:2e01:604:: - 1465398611 - subnetName - - - - - - 416 - 4132176 - - - - cloud-region - https://mtanjv9aaas03.aic.cip.com:8443/aai/v8/cloud-infrastructure/cloud-regions/cloud-region/att-aic/AAIAIC25/ - - - cloud-region.cloud-region-id - AAIAIC25 - - - cloud-region.cloud-owner - att-aic - - - cloud-region.owner-defined-type - - - - - tenant - https://mtanjv9aaas03.aic.cip.com:8443/aai/v8/cloud-infrastructure/cloud-regions/cloud-region/att-aic/AAIAIC25/tenants/tenant/4ae1d3446a4c48b2bec44b6cfba06d68/ - - tenant.tenant-id - 4ae1d3446a4c48b2bec44b6cfba06d68 - - - - cloud-region.cloud-owner - att-aic - - - cloud-region.cloud-region-id - AAIAIC25 - - - tenant.tenant-name - Ruchira Contrail 3.0 test - - - - vpn-binding - https://mtanjv9aaas03.aic.cip.com:8443/aai/v8/network/vpn-bindings/vpn-binding/85f015d0-2e32-4c30-96d2-87a1a27f8017/ - - vpn-binding.vpn-id - 9a7b327d9-287aa00-82c4b0-100001 - - - vpn-binding.vpn-name - GN_EVPN_direct_net_0_ST1 - - - - route-table-reference - - route-table-reference.route-table-reference-id - cee6d136-e378-4678-a024-2cd15f0ee0hi - - - -""" - - String queryIdAIIResponseVpnNotPresent = - """ - - - - - - - - - - - - 49c86598-f766-46f8-84f8-8d1c1b10f9b4 - MNS-25180-L-01-dmz_direct_net_1 - CONTRAIL_EXTERNAL - dmz_direct - contrail - a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb - 0 - pending-delete - networkName - false - true - false - - - 57e9a1ff-d14f-4071-a828-b19ae98eb2fc - 107.239.52.1 - 107.239.52.0 - 24 - 4 - pending-delete - true - subnetName - - - - - - -""" - - String queryNameAIIResponse = - """ - - - - - - - - - - - - 49c86598-f766-46f8-84f8-8d1c1b10f9b4 - MNS-25180-L-01-dmz_direct_net_1 - CONTRAIL_EXTERNAL - dmz_direct - contrail - a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb - 0 - pending-delete - - - 57e9a1ff-d14f-4071-a828-b19ae98eb2fc - 107.239.52.1 - 107.239.52.0 - 24 - 4 - pending-delete - true - - - - - - vpn-binding - https://aai-app-e2e.test.com:8443/aai/v8/network/vpn-bindings/vpn-binding/85f015d0-2e32-4c30-96d2-87a1a27f8017/ - - vpn-binding.vpn-id - 85f015d0-2e32-4c30-96d2-87a1a27f8017 - - - - vpn-binding - https://aai-app-e2e.test.com:8443/aai/v8/network/vpn-bindings/vpn-binding/c980a6ef-3b88-49f0-9751-dbad8608d0a6/ - - vpn-binding.vpn-id - c980a6ef-3b88-49f0-9751-dbad8608d0a6 - - - - tenant - https://aai-app-e2e.test.com:8443/aai/v8/cloud-infrastructure/tenants/tenant/7dd5365547234ee8937416c65507d266/ - - tenant.tenant-id - 7dd5365547234ee8937416c65507d266 - - - - - - """ - - String queryNameAIIResponseVpnNotPresent = - """ - - - - - - - - - - - - - - -""" - - String queryVpnBindingAAIResponse = - """ - - - - - - - - - - - - 9a7b327d9-287aa00-82c4b0-105757 - GN_EVPN_Test - 13979:105757 - - - l3-network - https://aai-app-e2e.test.com:8443/aai/v3/network/l3-networks/l3-network/689ec39e-c5fc-4462-8db2-4f760763ad28/ - - l3-network.network-id - 689ec39e-c5fc-4462-8db2-4f760763ad28 - - - - l3-network - https://aai-app-e2e.test.com:8443/aai/v3/network/l3-networks/l3-network/1a49396b-19b3-40a4-8792-aa2fbd0f0704/ - - l3-network.network-id - 1a49396b-19b3-40a4-8792-aa2fbd0f0704 - - - - l3-network - https://aai-app-e2e.test.com:8443/aai/v3/network/l3-networks/l3-network/774f3329-3c83-4771-86c7-9e6207cd50fd/ - - l3-network.network-id - 774f3329-3c83-4771-86c7-9e6207cd50fd - - - - - -""" - - String updateDBRequest_Active = - """ - - - - 88f65519-9a38-4c4b-8445-9eb4a5a5af56 - BPMN - Network MNS-25180-L-01-dmz_direct_net_1 already exists. Silent success. - - COMPLETED - 100 - <network-id>49c86598-f766-46f8-84f8-8d1c1b10f9b4</network-id><network-name>MNS-25180-L-01-dmz_direct_net_1</network-names> - 49c86598-f766-46f8-84f8-8d1c1b10f9b4 - - -""" - - String updateDBRequest = - """ - - - - 88f65519-9a38-4c4b-8445-9eb4a5a5af56 - BPMN - Network successfully updated. - - COMPLETED - 100 - <network-id></network-id><network-name></network-names> - - - -""" - - String updateDBRequestError = - """ - - - - 88f65519-9a38-4c4b-8445-9eb4a5a5af56 - BPMN - Received error from SDN-C: No availability zone available - - FAILED - <network-id></network-id><network-name></network-names> - - - """ - - String updateDBRequestError01 = - """ - - - - 88f65519-9a38-4c4b-8445-9eb4a5a5af56 - BPMN - Received error unexpectedly from SDN-C. - - FAILED - <network-id></network-id><network-name></network-names> - - - """ - - String updateDBRequest_Outputs = - """ - - - - 88f65519-9a38-4c4b-8445-9eb4a5a5af56 - BPMN - Network successfully updated. - - COMPLETED - 100 - <network-id>49c86598-f766-46f8-84f8-8d1c1b10f9b4</network-id><network-name>MNS-25180-L-01-dmz_direct_net_1</network-names> - 49c86598-f766-46f8-84f8-8d1c1b10f9b4 - - -""" - - String updateNetworkRequest = - """ - RDM2WAGPLCP - 7dd5365547234ee8937416c65507d266 - 49c86598-f766-46f8-84f8-8d1c1b10f9b4 - ST_2Bindings_6006/55288ef0-595c-47d3-819e-cf93aaac6326 - MNS-25180-L-01-dmz_direct_net_1 - CONTRAIL_EXTERNAL - - CONTRAIL - - networkName - 414,415 - - - true - false - 13979:105757 - 13979:105757 - GN_EVPN_Test - refFQDN1 - refFQDN2 - - - - - - - 107.239.52.0/24 - true - 107.239.52.1 - 4 - 57e9a1ff-d14f-4071-a828-b19ae98eb2fc - subnetName - - - - - - - 107.239.52.0/24 - true - 107.239.52.1 - 4 - 57e9a1ff-d14f-4071-a828-b19ae98eb2fc - subnetName - - true - true - false - - true - a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb - true - true - 10.10.125.1 - - - 88f65519-9a38-4c4b-8445-9eb4a5a5af56 - f70e927b-6087-4974-9ef8-c5e4d5847ca4 - - messageId_generated - -""" - - - String updateNetworkRequest_noPhysicalName = - """ - RDM2WAGPLCP - 7dd5365547234ee8937416c65507d266 - 49c86598-f766-46f8-84f8-8d1c1b10f9b4 - ST_2Bindings_6006/55288ef0-595c-47d3-819e-cf93aaac6326 - MNS-25180-L-01-dmz_direct_net_1 - CONTRAIL_EXTERNAL - - CONTRAIL - - networkName - 414,415 - - - true - false - 13979:105757 - 13979:105757 - GN_EVPN_Test - - - - - - - 107.239.52.0/24 - true - 107.239.52.1 - 4 - 57e9a1ff-d14f-4071-a828-b19ae98eb2fc - subnetName - - - - - - - 107.239.52.0/24 - true - 107.239.52.1 - 4 - 57e9a1ff-d14f-4071-a828-b19ae98eb2fc - subnetName - - true - true - false - - true - a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb - true - true - 10.10.125.1 - - - 88f65519-9a38-4c4b-8445-9eb4a5a5af56 - null - - messageId_generated - -""" - - String updateNetworkResponseREST = - """ - MNS-25180-L-01-dmz_direct_net_1/2c88a3a9-69b9-43a7-ada6-1aca577c3641 - c4f4e878-cde0-4b15-ae9a-bda857759cea - default-domain:MSOTest:GN_EVPN_direct_net_0_ST1 - - - - 57e9a1ff-d14f-4071-a828-b19ae98eb2fc - bd8e87c6-f4e2-41b8-b0bc-9596aa00cd73 - - - 57e9a1ff-d14f-4071-a828-b19ae98eb2fc - bd8e87c6-f4e2-41b8-b0bc-9596aa00cd73 - - - - MNS-25180-L-01-dmz_direct_net_1/2c88a3a9-69b9-43a7-ada6-1aca577c3641 - c4f4e878-cde0-4b15-ae9a-bda857759cea - - CONTRAIL_EXTERNAL - true - 7dd5365547234ee8937416c65507d266 - RDM2WAGPLCP - - 1ef47428-cade-45bd-a103-0751e8b2deb0 - - - - messageId_generated -""" - - String updateRollbackNetworkRequest = - """ - - MNS-25180-L-01-dmz_direct_net_1/2c88a3a9-69b9-43a7-ada6-1aca577c3641 - c4f4e878-cde0-4b15-ae9a-bda857759cea - - CONTRAIL_EXTERNAL - true - 7dd5365547234ee8937416c65507d266 - RDM2WAGPLCP - - 1ef47428-cade-45bd-a103-0751e8b2deb0 - - - -""" - - String updateNetworkResponse = - """ - MNS-25180-L-01-dmz_direct_net_1/2c88a3a9-69b9-43a7-ada6-1aca577c3641 - c4f4e878-cde0-4b15-ae9a-bda857759cea - MNS-25180-L-01-dmz_direct_net_1/2c88a3a9-69b9-43a7-ada6-1aca577c3641 - default-domain:MSOTest:GN_EVPN_direct_net_0_ST1 - - - 57e9a1ff-d14f-4071-a828-b19ae98eb2fc - bd8e87c6-f4e2-41b8-b0bc-9596aa00cd73 - - - - RDM2WAGPLCP - - 1ef47428-cade-45bd-a103-0751e8b2deb0 - - - true - MNS-25180-L-01-dmz_direct_net_1/2c88a3a9-69b9-43a7-ada6-1aca577c3641 - CONTRAIL_EXTERNAL - false - c4f4e878-cde0-4b15-ae9a-bda857759cea - 7dd5365547234ee8937416c65507d266 - -""" - - String updateContrailAAIPayloadRequest = - """ - 49c86598-f766-46f8-84f8-8d1c1b10f9b4 - MNS-25180-L-01-dmz_direct_net_1 - CONTRAIL_EXTERNAL - dmz_direct - contrail - c4f4e878-cde0-4b15-ae9a-bda857759cea - a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb - 0 - l3-version - active - ST_2Bindings_6006/55288ef0-595c-47d3-819e-cf93aaac6326 - default-domain:MSOTest:GN_EVPN_direct_net_0_ST1 - networkName - false - true - false - - - 57e9a1ff-d14f-4071-a828-b19ae98eb2fc - bd8e87c6-f4e2-41b8-b0bc-9596aa00cd73 - 107.239.52.1 - 107.239.52.0 - 24 - 4 - active - true - subnetName - - - 57e9a1ff-d14f-4071-a828-b19ae98eb2fc - bd8e87c6-f4e2-41b8-b0bc-9596aa00cd73 - 107.239.52.1 - 107.239.52.0 - 24 - 4 - active - true - subnetName - - - - 414 - - - 415 - - - - inner - ctag-version - - - tenant - https://aai-ext1.test.com:8443/aai/v8/cloud-infrastructure/tenants/tenant/897deadc2b954a6bac6d3c197fb3525e/ - - tenant.tenant-id - 897deadc2b954a6bac6d3c197fb3525e - - - tenant.tenant-name - MSOTest1 - - - - vpn-binding - https://aai-ext1.test.com:8443/aai/v8/network/vpn-bindings/vpn-binding/a290b841-f672-44dd-b9cd-6f8c20d7d8c8/ - - vpn-binding.vpn-id - a290b841-f672-44dd-b9cd-6f8c20d7d8c8 - - - vpn-binding.vpn-name - oam_protected_net_6_MTN5_msotest2 - - - - vpn-binding - https://aai-ext1.test.com:8443/aai/v8/network/vpn-bindings/vpn-binding/24a4b507-853a-4a38-99aa-05fcc54be24d/ - - vpn-binding.vpn-id - 24a4b507-853a-4a38-99aa-05fcc54be24d - - - vpn-binding.vpn-name - oam_protected_net_6_MTN5_msotest1 - - - - - - - - vpn-binding - https://aai-app-e2e.test.com:8443/aai/v8/network/vpn-bindings/vpn-binding/85f015d0-2e32-4c30-96d2-87a1a27f8017/ - - vpn-binding.vpn-id - 85f015d0-2e32-4c30-96d2-87a1a27f8017 - - - - vpn-binding - https://aai-app-e2e.test.com:8443/aai/v8/network/vpn-bindings/vpn-binding/c980a6ef-3b88-49f0-9751-dbad8608d0a6/ - - vpn-binding.vpn-id - c980a6ef-3b88-49f0-9751-dbad8608d0a6 - - - - tenant - https://aai-app-e2e.test.com:8443/aai/v8/cloud-infrastructure/tenants/tenant/7dd5365547234ee8937416c65507d266/ - - tenant.tenant-id - 7dd5365547234ee8937416c65507d266 - - - - network-policy - https://aai-app-e2e.test.com:8443/aai/v8/network/network-policies/network-policy/cee6d136-e378-4678-a024-2cd15f0ee0cg - - network-policy.network-policy-id - cee6d136-e378-4678-a024-2cd15f0ee0cg - - - - route-table-reference - https://aai-app-e2e.test.com:8443/aai/v8/network/route-table-references/route-table-reference/refFQDN1 - - route-table-reference.route-table-reference-id - cee6d136-e378-4678-a024-2cd15f0ee0hi - - - - route-table-reference - https://aai-app-e2e.test.com:8443/aai/v8/network/route-table-references/route-table-reference/refFQDN2 - - route-table-reference.route-table-reference-id - cee6d136-e378-4678-a024-2cd15f0ee0hi - - - -""" - - String updateContrailAAIResponse = - """ - - - - - - - - -""" - - String updateNetworkErrorResponse = - """ - 680bd458-5ec1-4a16-b77c-509022e53450INTERNAL - 400 Bad Request: The server could not comply with the request since it is either malformed or otherwise incorrect., error.type=StackValidationFailed, error.message=Property error: : resources.network.properties: : Unknown Property network_ipam_refs_data - true - """ - - - String networkException500 = - """soap:VersionMismatch"http://org.openecomp.mso/network", the namespace on the "updateNetworkContrail" element, is not a valid SOAP version.""" - - String aaiResponse = - """ - - - - - - - - - - - - bdc5efe8-404a-409b-85f6-0dcc9eebae30 - HSL_direct_net_2 - CONTRAIL_BASIC - HSL_direct - contrail - 8bbd3edf-b835-4610-96a2-a5cafa029042 - a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb - active - HSL_direct_net_2/57594a56-1c92-4a38-9caa-641c1fa3d4b6 - - - ea5f2a2c-604f-47ff-a9c5-253ee4f0ef0a - 5a77fdc2-7789-4649-a1b9-6eaf1db1813a - 172.16.34.1 - 172.16.34.0 - 28 - 4 - active - true - - - - - - tenant - https://aai-app-e2e.test.com:8443/aai/v3/cloud-infrastructure/tenants/tenant/e81d842d3e8b45c5a59f57cd76af3aaf/ - - tenant.tenant-id - e81d842d3e8b45c5a59f57cd76af3aaf - - - - - - """ - - String changeAssignSDNCRequest = - """ - - 88f65519-9a38-4c4b-8445-9eb4a5a5af56 - f70e927b-6087-4974-9ef8-c5e4d5847ca4 - changeassign - network-topology-operation - sdncCallback - - - - 88f65519-9a38-4c4b-8445-9eb4a5a5af56 - NetworkActivateRequest - VID - - - - - - a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb - MSO-dev-service-type - f70e927b-6087-4974-9ef8-c5e4d5847ca4 - MSO_1610_dev - - - 49c86598-f766-46f8-84f8-8d1c1b10f9b4 - CONTRAIL_EXTERNAL - MNS-25180-L-01-dmz_direct_net_1 - 7dd5365547234ee8937416c65507d266 - RDM2WAGPLCP - - -""" - -String assignResponse = -""" 006927ca-f5a3-47fd-880c-dfcbcd81a093 200 OK 200006927ca-f5a3-47fd-880c-dfcbcd81a093Ynotsurewecarea9a77d5a-123e-4ca2-9eb9-0b015d2ee0fbGN_EVPN_direct_net_0_ST_noGW8abc633a-810b-4ca5-8b3a-09511d13a2ce """ - - String sdncRollbackRequest = - """ - - 88f65519-9a38-4c4b-8445-9eb4a5a5af56 - f70e927b-6087-4974-9ef8-c5e4d5847ca4 - rollback - network-topology-operation - sdncCallback - - - - 88f65519-9a38-4c4b-8445-9eb4a5a5af56 - NetworkActivateRequest - VID - - - - - - a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb - MSO-dev-service-type - f70e927b-6087-4974-9ef8-c5e4d5847ca4 - MSO_1610_dev - - - 8abc633a-810b-4ca5-8b3a-09511d13a2ce - CONTRAIL_EXTERNAL - MNS-25180-L-01-dmz_direct_net_1 - 7dd5365547234ee8937416c65507d266 - RDM2WAGPLCP - - -""" - - String sdncAdapterWorkflowResponse = - """ - - - 745b1b50-e39e-4685-9cc8-c71f0bde8bf0 - 200 - OK - - <output xmlns="org:openecomp:sdnctl:vnf"><svc-request-id>00703dc8-71ff-442d-a4a8-3adc5beef6a9</svc-request-id><response-code>200</response-code><ack-final-indicator>Y</ack-final-indicator><network-information><network-id>49c86598-f766-46f8-84f8-8d1c1b10f9b4</network-id></network-information><service-information><service-type>a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb</service-type><service-instance-id>MNS-25180-L-01-dmz_direct_net_1</service-instance-id><subscriber-name>notsurewecare</subscriber-name></service-information></output> - -""" - - - String sdncAdapterWorkflowResponse_Error = - """ - - - - 400 - Error writing to l3-netework - Y - c79240d8-34b5-4853-af69-2021928dba00 - - - -""" - - String expected_sdncAdapterWorkflowResponse_Error = - """ - - - - 400 - Error writing to l3-netework - Y - c79240d8-34b5-4853-af69-2021928dba00 - - - -""" - - String sdncAdapterWorkflowFormattedResponse = - """ - - - 00703dc8-71ff-442d-a4a8-3adc5beef6a9 - 200 - Y - - 49c86598-f766-46f8-84f8-8d1c1b10f9b4 - - - a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb - f70e927b-6087-4974-9ef8-c5e4d5847ca4 - notsurewecare - - - -""" - - String falloutHandlerRequest = - """ - - b69c9054-da09-4a2c-adf5-51042b62bfac - UPDATE - PORTAL - - - Received error from SDN-C: No availability zone available. - 5300 - - """ - - String falloutHandlerRequestObject = - """ - - b69c9054-da09-4a2c-adf5-51042b62bfac - UPDATE - VID - - - Received error from SDN-C: No availability zone available - 7000 - - """ - - - String falloutHandlerRequest_Scenario01 = - """ - - b69c9054-da09-4a2c-adf5-51042b62bfac - UPDATE - VID - - - Unexpected Response from AAI - 400 - 7020 - - """ - - String completeMsoProcessRequest = - """ - - 88f65519-9a38-4c4b-8445-9eb4a5a5af56 - UPDATE - PORTAL - - BPMN Network action: UPDATE -""" - -// - - - - - - - - - - - @Before - public void init() - { - MockitoAnnotations.initMocks(this) - - } - - public void initializeVariables (Execution mockExecution) { - - verify(mockExecution).setVariable("UPDNETI_messageId", "") - verify(mockExecution).setVariable("BasicAuthHeaderValuePO", "") - verify(mockExecution).setVariable("BasicAuthHeaderValueSDNC", "") - verify(mockExecution).setVariable("UPDNETI_UpdateNetworkInstanceInfraJsonRequest", "") - verify(mockExecution).setVariable("UPDNETI_networkRequest", "") - verify(mockExecution).setVariable("UPDNETI_networkInputs", "") - verify(mockExecution).setVariable("UPDNETI_networkOutputs", "") - verify(mockExecution).setVariable("UPDNETI_requestId", "") - verify(mockExecution).setVariable("UPDNETI_source", "") - verify(mockExecution).setVariable("UPDNETI_networkId", "") - - verify(mockExecution).setVariable("UPDNETI_CompleteMsoProcessRequest", "") - verify(mockExecution).setVariable("UPDNETI_FalloutHandlerRequest", "") - verify(mockExecution).setVariable("UPDNETI_isSilentSuccess", false) - verify(mockExecution).setVariable("UPDNETI_isPONR", false) - - // AAI query Cloud Region - verify(mockExecution).setVariable("UPDNETI_queryCloudRegionRequest","") - verify(mockExecution).setVariable("UPDNETI_queryCloudRegionReturnCode","") - verify(mockExecution).setVariable("UPDNETI_queryCloudRegionResponse","") - verify(mockExecution).setVariable("UPDNETI_cloudRegionPo","") - verify(mockExecution).setVariable("UPDNETI_cloudRegionSdnc","") - verify(mockExecution).setVariable("UPDNETI_isCloudRegionGood", false) - - // AAI query Id - verify(mockExecution).setVariable("UPDNETI_queryIdAAIRequest","") - verify(mockExecution).setVariable("UPDNETI_queryIdAAIResponse", "") - verify(mockExecution).setVariable("UPDNETI_aaiIdReturnCode", "") - - // AAI query vpn binding - verify(mockExecution).setVariable("UPDNETI_queryVpnBindingAAIRequest","") - verify(mockExecution).setVariable("UPDNETI_queryVpnBindingAAIResponse", "") - verify(mockExecution).setVariable("UPDNETI_aaiQqueryVpnBindingReturnCode", "") - verify(mockExecution).setVariable("UPDNETI_vpnBindings", null) - verify(mockExecution).setVariable("UPDNETI_vpnCount", 0) - verify(mockExecution).setVariable("UPDNETI_routeCollection", "") - - // AAI query network policy - verify(mockExecution).setVariable("UPDNETI_queryNetworkPolicyAAIRequest","") - verify(mockExecution).setVariable("UPDNETI_queryNetworkPolicyAAIResponse", "") - verify(mockExecution).setVariable("UPDNETI_aaiQqueryNetworkPolicyReturnCode", "") - verify(mockExecution).setVariable("UPDNETI_networkPolicyUriList", null) - verify(mockExecution).setVariable("UPDNETI_networkPolicyCount", 0) - verify(mockExecution).setVariable("UPDNETI_networkCollection", "") - - // AAI query route table reference - verify(mockExecution).setVariable("UPDNETI_queryNetworkTableRefAAIRequest","") - verify(mockExecution).setVariable("UPDNETI_queryNetworkTableRefAAIResponse", "") - verify(mockExecution).setVariable("UPDNETI_aaiQqueryNetworkTableRefReturnCode", "") - verify(mockExecution).setVariable("UPDNETI_networkTableRefUriList", null) - verify(mockExecution).setVariable("UPDNETI_networkTableRefCount", 0) - verify(mockExecution).setVariable("UPDNETI_tableRefCollection", "") - - - // AAI requery Id - verify(mockExecution).setVariable("UPDNETI_requeryIdAAIRequest","") - verify(mockExecution).setVariable("UPDNETI_requeryIdAAIResponse", "") - verify(mockExecution).setVariable("UPDNETI_aaiRequeryIdReturnCode", "") - - // AAI update contrail - verify(mockExecution).setVariable("UPDNETI_updateContrailAAIUrlRequest","") - verify(mockExecution).setVariable("UPDNETI_updateContrailAAIPayloadRequest","") - verify(mockExecution).setVariable("UPDNETI_updateContrailAAIResponse", "") - verify(mockExecution).setVariable("UPDNETI_aaiUpdateContrailReturnCode", "") - - verify(mockExecution).setVariable("UPDNETI_updateNetworkRequest", "") - verify(mockExecution).setVariable("UPDNETI_updateNetworkResponse", "") - verify(mockExecution).setVariable("UPDNETI_rollbackNetworkRequest", "") - verify(mockExecution).setVariable("UPDNETI_rollbackNetworkResponse", "") - verify(mockExecution).setVariable("UPDNETI_networkReturnCode", "") - verify(mockExecution).setVariable("UPDNETI_rollbackNetworkReturnCode", "") - verify(mockExecution).setVariable("UPDNETI_isNetworkRollbackNeeded", false) - - verify(mockExecution).setVariable("UPDNETI_changeAssignSDNCRequest", "") - verify(mockExecution).setVariable("UPDNETI_changeAssignSDNCResponse", "") - verify(mockExecution).setVariable("UPDNETI_rollbackSDNCRequest", "") - verify(mockExecution).setVariable("UPDNETI_rollbackSDNCResponse", "") - verify(mockExecution).setVariable("UPDNETI_sdncReturnCode", "") - verify(mockExecution).setVariable("UPDNETI_rollbackSDNCReturnCode", "") - verify(mockExecution).setVariable("UPDNETI_isSdncRollbackNeeded", false) - verify(mockExecution).setVariable("UPDNETI_sdncResponseSuccess", false) - - verify(mockExecution).setVariable("UPDNETI_updateDBRequest", "") - verify(mockExecution).setVariable("UPDNETI_updateDBResponse", "") - verify(mockExecution).setVariable("UPDNETI_dbReturnCode", "") - - verify(mockExecution).setVariable("UPDNETI_isVnfBindingPresent", false) - verify(mockExecution).setVariable("UPDNETI_Success", false) - verify(mockExecution).setVariable("UPDNETI_serviceInstanceId", "") - verify(mockExecution).setVariable("GENGS_type", "service-instance") // Setting for Generic Sub Flow use - - - } - - @Test - //@Ignore - public void preProcessRequest_NetworkRequest() { - - println "************ preProcessRequest_Payload ************* " - ExecutionEntity mockExecution = setupMock() - // Initialize prerequisite variables - when(mockExecution.getVariable("mso-request-id")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56") - when(mockExecution.getVariable("requestId")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56") - when(mockExecution.getVariable("isBaseVfModule")).thenReturn(true) - when(mockExecution.getVariable("recipeTimeout")).thenReturn(0) - when(mockExecution.getVariable("requestAction")).thenReturn("UPDATE") - when(mockExecution.getVariable("serviceInstanceId")).thenReturn("f70e927b-6087-4974-9ef8-c5e4d5847ca4") - when(mockExecution.getVariable("vnfId")).thenReturn("") - when(mockExecution.getVariable("volumeGroupId")).thenReturn("") - when(mockExecution.getVariable("networkId")).thenReturn("49c86598-f766-46f8-84f8-8d1c1b10f9b4") - when(mockExecution.getVariable("serviceType")).thenReturn("MOG") - when(mockExecution.getVariable("networkType")).thenReturn("modelName") - when(mockExecution.getVariable("bpmnRequest")).thenReturn(jsonIncomingRequest) - - when(mockExecution.getVariable("UPDNETI_messageId")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56") - when(mockExecution.getVariable("URN_mso_adapters_po_auth")).thenReturn("3141634BF7E070AA289CF2892C986C0B") - when(mockExecution.getVariable("URN_mso_adapters_db_auth")).thenReturn("757A94191D685FD2092AC1490730A4FC") - when(mockExecution.getVariable("URN_mso_msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7") - when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") - when(mockExecution.getVariable("URN_mso_rollback")).thenReturn("true") - - // preProcessRequest(Execution execution) - UpdateNetworkInstanceInfra UpdateNetworkInstanceInfra = new UpdateNetworkInstanceInfra() - UpdateNetworkInstanceInfra.preProcessRequest(mockExecution) - - // check the sequence of variable invocation - //MockitoDebuggerImpl preDebugger = new MockitoDebuggerImpl() - //preDebugger.printInvocations(mockExecution) - - verify(mockExecution).getVariable("isDebugLogEnabled") - verify(mockExecution).setVariable("prefix", "UPDNETI_") - - //verify variable initialization - initializeVariables(mockExecution) - - // Authentications - verify(mockExecution).setVariable("BasicAuthHeaderValuePO", "Basic cGFzc3dvcmQ=") - verify(mockExecution).setVariable("BasicAuthHeaderValueSDNC", "Basic cGFzc3dvcmQ=") - - verify(mockExecution).setVariable("UPDNETI_UpdateNetworkInstanceInfraJsonRequest", jsonIncomingRequest) - //verify(mockExecution).setVariable("UPDNETI_networkRequest", expectedNetworkRequest) - //verify(mockExecution).setVariable("UPDNETI_networkInputs", expectedNetworkInputs) - //verify(mockExecution, atLeast(3)).setVariable("UPDNETI_networkOutputs", "") - - //verify(mockExecution).setVariable("UPDNETI_requestId", "88f65519-9a38-4c4b-8445-9eb4a5a5af56") - //verify(mockExecution).setVariable("UPDNETI_source", "VID") - //verify(mockExecution).setVariable("UPDNETI_messageId", "88f65519-9a38-4c4b-8445-9eb4a5a5af56") - //verify(mockExecution, atLeast(1)).setVariable("GENGS_type", "service-instance") - - } - - - @Test - //@Ignore - public void preProcessRequest_MissingNetworkId() { - - println "************ preProcessRequest_MissingName() ************* " - - WorkflowException missingNameWorkflowException = new WorkflowException("UpdateNetworkInstanceInfra", 2500, "Variable 'network-id' value/element is missing.") - - ExecutionEntity mockExecution = setupMock() - // Initialize prerequisite variables - when(mockExecution.getVariable("mso-request-id")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56") - when(mockExecution.getVariable("requestId")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56") - when(mockExecution.getVariable("isBaseVfModule")).thenReturn(true) - when(mockExecution.getVariable("recipeTimeout")).thenReturn(0) - when(mockExecution.getVariable("requestAction")).thenReturn("UPDATE") - when(mockExecution.getVariable("serviceInstanceId")).thenReturn("f70e927b-6087-4974-9ef8-c5e4d5847ca4") - when(mockExecution.getVariable("vnfId")).thenReturn("") - when(mockExecution.getVariable("volumeGroupId")).thenReturn("") - //when(mockExecution.getVariable("networkId")).thenReturn("49c86598-f766-46f8-84f8-8d1c1b10f9b4") - when(mockExecution.getVariable("serviceType")).thenReturn("MOG") - when(mockExecution.getVariable("networkType")).thenReturn("modelName") - when(mockExecution.getVariable("bpmnRequest")).thenReturn(jsonIncomingRequest) - - when(mockExecution.getVariable("UPDNETI_messageId")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56") - when(mockExecution.getVariable("URN_mso_adapters_po_auth")).thenReturn("3141634BF7E070AA289CF2892C986C0B") - when(mockExecution.getVariable("URN_mso_adapters_db_auth")).thenReturn("757A94191D685FD2092AC1490730A4FC") - when(mockExecution.getVariable("URN_mso_msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7") - when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") - when(mockExecution.getVariable("URN_mso_rollback")).thenReturn("true") - - // preProcessRequest(Execution execution) - UpdateNetworkInstanceInfra UpdateNetworkInstanceInfra = new UpdateNetworkInstanceInfra() - try { - UpdateNetworkInstanceInfra.preProcessRequest(mockExecution) - } catch (Exception ex) { - println " Test End - Handle catch-throw BpmnError()! " - } - - // check the sequence of variable invocation - //MockitoDebuggerImpl preDebugger = new MockitoDebuggerImpl() - //preDebugger.printInvocations(mockExecution) - - verify(mockExecution, atLeast(1)).getVariable("isDebugLogEnabled") - verify(mockExecution, atLeast(1)).setVariable("prefix", "UPDNETI_") - - //verify variable initialization - initializeVariables(mockExecution) - - // Authentications - verify(mockExecution).setVariable("BasicAuthHeaderValuePO", "Basic cGFzc3dvcmQ=") - verify(mockExecution).setVariable("BasicAuthHeaderValueSDNC", "Basic cGFzc3dvcmQ=") - - verify(mockExecution).setVariable("UPDNETI_UpdateNetworkInstanceInfraJsonRequest", jsonIncomingRequest) - //verify(mockExecution, atLeast(1)).setVariable("UPDNETI_networkOutputs", networkOutputs) - //verify(mockExecution).setVariable("UPDNETI_networkRequest", expectedNetworkRequestMissingNetworkId) - //verify(mockExecution).setVariable("UPDNETI_networkInputs", expectedNetworkInputs) - - //verify(mockExecution).setVariable("UPDNETI_requestId", "88f65519-9a38-4c4b-8445-9eb4a5a5af56") - //verify(mockExecution).setVariable("UPDNETI_source", "VID") - //verify(mockExecution).setVariable("UPDNETI_messageId", "88f65519-9a38-4c4b-8445-9eb4a5a5af56") - - verify(mockExecution).setVariable(eq("WorkflowException"), refEq(missingNameWorkflowException)) - - } - - @Test - //@Ignore - public void preProcessRequest_MissingCloudRegion() { - - println "************ preProcessRequest_MissingCloudRegion() ************* " - - WorkflowException missingCloudRegionWorkflowException = new WorkflowException("UpdateNetworkInstanceInfra", 2500, "requestDetails has missing 'aic-cloud-region' value/element.") - - ExecutionEntity mockExecution = setupMock() - // Initialize prerequisite variables - when(mockExecution.getVariable("mso-request-id")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56") - when(mockExecution.getVariable("requestId")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56") - when(mockExecution.getVariable("isBaseVfModule")).thenReturn(true) - when(mockExecution.getVariable("recipeTimeout")).thenReturn(0) - when(mockExecution.getVariable("requestAction")).thenReturn("UPDATE") - when(mockExecution.getVariable("serviceInstanceId")).thenReturn("f70e927b-6087-4974-9ef8-c5e4d5847ca4") - when(mockExecution.getVariable("vnfId")).thenReturn("") - when(mockExecution.getVariable("volumeGroupId")).thenReturn("") - when(mockExecution.getVariable("networkId")).thenReturn("networkId") - when(mockExecution.getVariable("serviceType")).thenReturn("MOG") - when(mockExecution.getVariable("networkType")).thenReturn("modelName") - - when(mockExecution.getVariable("bpmnRequest")).thenReturn(jsonIncomingRequest_MissingCloudRegion) - when(mockExecution.getVariable("UPDNETI_messageId")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56") - when(mockExecution.getVariable("URN_mso_adapters_po_auth")).thenReturn("3141634BF7E070AA289CF2892C986C0B") - when(mockExecution.getVariable("URN_mso_adapters_db_auth")).thenReturn("757A94191D685FD2092AC1490730A4FC") - when(mockExecution.getVariable("URN_mso_msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7") - when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") - when(mockExecution.getVariable("URN_mso_rollback")).thenReturn("true") - - - // preProcessRequest(Execution execution) - UpdateNetworkInstanceInfra UpdateNetworkInstanceInfra = new UpdateNetworkInstanceInfra() - try { - UpdateNetworkInstanceInfra.preProcessRequest(mockExecution) - } catch (Exception ex) { - println " Test End - Handle catch-throw BpmnError()! " - } - // check the sequence of variable invocation - //MockitoDebuggerImpl preDebugger = new MockitoDebuggerImpl() - //preDebugger.printInvocations(mockExecution) - - verify(mockExecution, atLeast(1)).getVariable("isDebugLogEnabled") - verify(mockExecution, atLeast(1)).setVariable("prefix", "UPDNETI_") - - //verify variable initialization - initializeVariables(mockExecution) - - verify(mockExecution).setVariable("UPDNETI_messageId", "88f65519-9a38-4c4b-8445-9eb4a5a5af56") - // Authentications - verify(mockExecution).setVariable("BasicAuthHeaderValuePO", "Basic cGFzc3dvcmQ=") - verify(mockExecution).setVariable("BasicAuthHeaderValueSDNC", "Basic cGFzc3dvcmQ=") - - verify(mockExecution).setVariable("UPDNETI_UpdateNetworkInstanceInfraJsonRequest", jsonIncomingRequest_MissingCloudRegion) - //verify(mockExecution).setVariable("UPDNETI_networkRequest", "") - //verify(mockExecution).setVariable("UPDNETI_networkInputs", "") - //verify(mockExecution, atLeast(1)).setVariable("UPDNETI_networkOutputs", "") - - //verify(mockExecution).setVariable("UPDNETI_requestId", "88f65519-9a38-4c4b-8445-9eb4a5a5af56") - //verify(mockExecution).setVariable("UPDNETI_source", "VID") - - verify(mockExecution).setVariable(eq("WorkflowException"), refEq(missingCloudRegionWorkflowException)) - - } - - @Test - //@Ignore - public void sendSyncResponse() { - - println "************ sendSyncResponse ************* " - - ExecutionEntity mockExecution = setupMock() - when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") - when(mockExecution.getVariable("isAsyncProcess")).thenReturn(true) - when(mockExecution.getVariable("mso-request-id")).thenReturn("e8ebf6a0-f8ea-4dc0-8b99-fe98a87722d6") - //when(mockExecution.getVariable("serviceInstanceId")).thenReturn("f70e927b-6087-4974-9ef8-c5e4d5847ca4") - - // preProcessRequest(Execution execution) - UpdateNetworkInstanceInfra UpdateNetworkInstanceInfra = new UpdateNetworkInstanceInfra() - UpdateNetworkInstanceInfra.sendSyncResponse(mockExecution) - - verify(mockExecution).setVariable("prefix", "UPDNETI_") - verify(mockExecution).setVariable("UpdateNetworkInstanceInfraResponseCode", "202") - - - } - - @Test - //@Ignore - public void sendSyncError() { - - println "************ sendSyncError ************* " - - ExecutionEntity mockExecution = setupMock() - when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") - when(mockExecution.getVariable("isAsyncProcess")).thenReturn(true) - when(mockExecution.getVariable("mso-request-id")).thenReturn("e8ebf6a0-f8ea-4dc0-8b99-fe98a87722d6") - //when(mockExecution.getVariable("serviceInstanceId")).thenReturn("f70e927b-6087-4974-9ef8-c5e4d5847ca4") - - - // preProcessRequest(Execution execution) - UpdateNetworkInstanceInfra UpdateNetworkInstanceInfra = new UpdateNetworkInstanceInfra() - UpdateNetworkInstanceInfra.sendSyncError(mockExecution) - - verify(mockExecution).setVariable("prefix", "UPDNETI_") - verify(mockExecution).setVariable("UpdateNetworkInstanceInfraResponseCode", "500") - - } - - - @Test - //@Ignore - public void prepareDBRequest() { - - println "************ prepareDBRequest ************* " - ExecutionEntity mockExecution = mock(ExecutionEntity.class) - // Initialize prerequisite variables - when(mockExecution.getVariable("UPDNETI_networkOutputs")).thenReturn("") - when(mockExecution.getVariable("UPDNETI_requestId")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56") - when(mockExecution.getVariable("UPDNETI_orchestrationStatus")).thenReturn("") - when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") - - // preProcessRequest(Execution execution) - UpdateNetworkInstanceInfra UpdateNetworkInstanceInfra = new UpdateNetworkInstanceInfra() - UpdateNetworkInstanceInfra.prepareDBRequest(mockExecution) - - verify(mockExecution).setVariable("prefix", "UPDNETI_") - verify(mockExecution).setVariable("UPDNETI_updateDBRequest", updateDBRequest) - - } - - @Test - //@Ignore - public void prepareDBRequestErro_ExceptionObject() { - - println "************ prepareDBRequest ************* " - - WorkflowException sndcWorkflowException = new WorkflowException("UpdateNetworkInstanceInfra", 500, "Received error from SDN-C: No availability zone available") - - ExecutionEntity mockExecution = mock(ExecutionEntity.class) - // Initialize prerequisite variables - when(mockExecution.getVariable("UPDNETI_networkOutputs")).thenReturn("") - when(mockExecution.getVariable("UPDNETI_requestId")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56") - when(mockExecution.getVariable("UPDNETI_networkOutputs")).thenReturn("") - when(mockExecution.getVariable("UPDNETI_orchestrationStatus")).thenReturn("") - when(mockExecution.getVariable("WorkflowException")).thenReturn(sndcWorkflowException) - when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") - - // preProcessRequest(Execution execution) - UpdateNetworkInstanceInfra UpdateNetworkInstanceInfra = new UpdateNetworkInstanceInfra() - UpdateNetworkInstanceInfra.prepareDBRequestError(mockExecution) - - verify(mockExecution).setVariable("prefix", "UPDNETI_") - verify(mockExecution).setVariable("UPDNETI_updateDBRequest", updateDBRequestError) - - } - - @Test - //@Ignore - public void prepareDBRequest_Outputs() { - - println "************ prepareDBRequest ************* " - ExecutionEntity mockExecution = mock(ExecutionEntity.class) - // Initialize prerequisite variables - when(mockExecution.getVariable("UPDNETI_networkOutputs")).thenReturn(networkOutputs) - when(mockExecution.getVariable("UPDNETI_requestId")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56") - when(mockExecution.getVariable("UPDNETI_orchestrationStatus")).thenReturn("") - when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") - - // preProcessRequest(Execution execution) - UpdateNetworkInstanceInfra UpdateNetworkInstanceInfra = new UpdateNetworkInstanceInfra() - UpdateNetworkInstanceInfra.prepareDBRequest(mockExecution) - - verify(mockExecution).setVariable("prefix", "UPDNETI_") - verify(mockExecution).setVariable("UPDNETI_updateDBRequest", updateDBRequest_Outputs) - - } - - @Test - //@Ignore - public void prepareUpdateNetworkRequest() { - - println "************ prepareNetworkRequest ************* " - ExecutionEntity mockExecution = setupMock() - // Initialize prerequisite variables - when(mockExecution.getVariable("UPDNETI_networkRequest")).thenReturn(expectedNetworkRequest) - when(mockExecution.getVariable("UPDNETI_requeryIdAAIResponse")).thenReturn(queryIdAIIResponse) - when(mockExecution.getVariable("UPDNETI_cloudRegionPo")).thenReturn("RDM2WAGPLCP") - when(mockExecution.getVariable("UPDNETI_messageId")).thenReturn("messageId_generated") - when(mockExecution.getVariable("UPDNETI_source")).thenReturn("VID") - //when(mockExecution.getVariable("UPDNETI_queryVpnBindingAAIResponse")).thenReturn(queryVpnBindingAAIResponse) - when(mockExecution.getVariable("UPDNETI_routeCollection")).thenReturn("13979:10575713979:105757") - when(mockExecution.getVariable("UPDNETI_networkCollection")).thenReturn("GN_EVPN_Test") - when(mockExecution.getVariable("UPDNETI_tableRefCollection")).thenReturn("refFQDN1refFQDN2") - when(mockExecution.getVariable("UPDNETI_requestId")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56") - //when(mockExecution.getVariable("URN_?????")).thenReturn("") // notificationUrl, //TODO - is this coming from URN? What variable/value to use? - when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") - when(mockExecution.getVariable("UPDNETI_rollbackEnabled")).thenReturn("true") - - // preProcessRequest(Execution execution) - UpdateNetworkInstanceInfra UpdateNetworkInstanceInfra = new UpdateNetworkInstanceInfra() - UpdateNetworkInstanceInfra.prepareUpdateNetworkRequest(mockExecution) - - // check the sequence of variable invocation - //MockitoDebuggerImpl preDebugger = new MockitoDebuggerImpl() - //preDebugger.printInvocations(mockExecution) - - // verify set prefix = "UPDNETI_" - verify(mockExecution).setVariable("prefix", "UPDNETI_") - - verify(mockExecution).setVariable("UPDNETI_updateNetworkRequest", updateNetworkRequest) - - } - - - @Test - //@Ignore - public void prepareUpdateNetworkRequest_NoPhysicalname() { - - println "************ prepareNetworkRequest ************* " - ExecutionEntity mockExecution = mock(ExecutionEntity.class) - // Initialize prerequisite variables - when(mockExecution.getVariable("UPDNETI_networkRequest")).thenReturn(NetworkRequest_noPhysicalName) - when(mockExecution.getVariable("UPDNETI_requeryIdAAIResponse")).thenReturn(queryIdAIIResponse) - when(mockExecution.getVariable("UPDNETI_cloudRegionPo")).thenReturn("RDM2WAGPLCP") - when(mockExecution.getVariable("UPDNETI_messageId")).thenReturn("messageId_generated") - when(mockExecution.getVariable("UPDNETI_source")).thenReturn("VID") - //when(mockExecution.getVariable("UPDNETI_queryVpnBindingAAIResponse")).thenReturn(queryVpnBindingAAIResponse) - when(mockExecution.getVariable("UPDNETI_routeCollection")).thenReturn("13979:10575713979:105757") - when(mockExecution.getVariable("UPDNETI_networkCollection")).thenReturn("GN_EVPN_Test") - when(mockExecution.getVariable("UPDNETI_tableRefCollection")).thenReturn("") - when(mockExecution.getVariable("UPDNETI_requestId")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56") - //when(mockExecution.getVariable("URN_?????")).thenReturn("") // notificationUrl, //TODO - is this coming from URN? What variable/value to use? - when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") - when(mockExecution.getVariable("UPDNETI_rollbackEnabled")).thenReturn("true") - - // preProcessRequest(Execution execution) - UpdateNetworkInstanceInfra UpdateNetworkInstanceInfra = new UpdateNetworkInstanceInfra() - UpdateNetworkInstanceInfra.prepareUpdateNetworkRequest(mockExecution) - - // check the sequence of variable invocation - //MockitoDebuggerImpl preDebugger = new MockitoDebuggerImpl() - //preDebugger.printInvocations(mockExecution) - - // verify set prefix = "UPDNETI_" - verify(mockExecution).setVariable("prefix", "UPDNETI_") - - verify(mockExecution).setVariable("UPDNETI_updateNetworkRequest", updateNetworkRequest_noPhysicalName) - - } - - @Test - //@Ignore - public void prepareSDNCRequest() { - - println "************ prepareSDNCRequest ************* " - - ExecutionEntity mockExecution = mock(ExecutionEntity.class) - // Initialize prerequisite variables - when(mockExecution.getVariable("UPDNETI_networkRequest")).thenReturn(expectedNetworkRequest) - when(mockExecution.getVariable("UPDNETI_cloudRegionSdnc")).thenReturn("RDM2WAGPLCP") - when(mockExecution.getVariable("UPDNETI_serviceInstanceId")).thenReturn("f70e927b-6087-4974-9ef8-c5e4d5847ca4") - when(mockExecution.getVariable("openecomp-mso-request-id")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56") - when(mockExecution.getVariable("URN_mso_workflow_sdncadapter_callback")).thenReturn("http://localhost:28090/SDNCAdapterCallback") - when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") - when(mockExecution.getVariable("GENGSI_siResourceLink")).thenReturn("https://aai-int1.test.com:8443/aai/v8/business/customers/customer/MSO_1610_dev/service-subscriptions/service-subscription/MSO-dev-service-type/service-instances/service-instance/6d4eb22a-82f1-4257-9f80-4176262cfe69/") - - - // preProcessRequest(Execution execution) - UpdateNetworkInstanceInfra UpdateNetworkInstanceInfra = new UpdateNetworkInstanceInfra() - UpdateNetworkInstanceInfra.prepareSDNCRequest(mockExecution) - - // verify set prefix = "UPDNETI_" - verify(mockExecution).setVariable("prefix", "UPDNETI_") - verify(mockExecution).setVariable("UPDNETI_changeAssignSDNCRequest", changeAssignSDNCRequest) - - } - - @Test - //@Ignore - public void prepareSDNCRollbackRequest() { - - println "************ prepareSDNCRollbackRequest ************* " - - - - ExecutionEntity mockExecution = mock(ExecutionEntity.class) - // Initialize prerequisite variables - when(mockExecution.getVariable("UPDNETI_networkRequest")).thenReturn(expectedNetworkRequest) - when(mockExecution.getVariable("UPDNETI_cloudRegionSdnc")).thenReturn("RDM2WAGPLCP") - when(mockExecution.getVariable("UPDNETI_serviceInstanceId")).thenReturn("f70e927b-6087-4974-9ef8-c5e4d5847ca4") - when(mockExecution.getVariable("UPDNETI_changeAssignSDNCResponse")).thenReturn(assignResponse) - when(mockExecution.getVariable("openecomp-mso-request-id")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56") - when(mockExecution.getVariable("URN_mso_workflow_sdncadapter_callback")).thenReturn("http://localhost:28090/SDNCAdapterCallback") - when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") - when(mockExecution.getVariable("GENGSI_siResourceLink")).thenReturn("https://aai-int1.test.com:8443/aai/v8/business/customers/customer/MSO_1610_dev/service-subscriptions/service-subscription/MSO-dev-service-type/service-instances/service-instance/6d4eb22a-82f1-4257-9f80-4176262cfe69/") - - // preProcessRequest(Execution execution) - UpdateNetworkInstanceInfra UpdateNetworkInstanceInfra = new UpdateNetworkInstanceInfra() - UpdateNetworkInstanceInfra.prepareSDNCRollbackRequest(mockExecution) - - // verify set prefix = "UPDNETI_" - verify(mockExecution).setVariable("prefix", "UPDNETI_") - verify(mockExecution).setVariable("UPDNETI_rollbackSDNCRequest", sdncRollbackRequest) - - } - - @Test - //@Ignore - public void callRESTQueryAAINetworkId_200() { - - println "************ callRESTQueryAAINetworkId ************* " - - WireMock.reset(); - - MockGetNetwork("49c86598-f766-46f8-84f8-8d1c1b10f9b4", "UpdateNetworkV2/updateNetwork_queryNetworkId_AAIResponse_Success.xml", 200); - - ExecutionEntity mockExecution = setupMock() - when(mockExecution.getVariable("UPDNETI_networkRequest")).thenReturn(expectedNetworkRequest) - when(mockExecution.getVariable("UPDNETI_messageId")).thenReturn("e8ebf6a0-f8ea-4dc0-8b99-fe98a87722d6") - when(mockExecution.getVariable("URN_aai_endpoint")).thenReturn("http://localhost:28090") - when(mockExecution.getVariable("URN_mso_workflow_global_default_aai_version")).thenReturn("8") - when(mockExecution.getVariable("URN_mso_workflow_default_aai_v8_l3_network_uri")).thenReturn("/aai/v8/network/l3-networks/l3-network") - when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") - when(mockExecution.getVariable("URN_aai_auth")).thenReturn("757A94191D685FD2092AC1490730A4FC") - when(mockExecution.getVariable("URN_mso_msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7") - - // preProcessRequest(Execution execution) - UpdateNetworkInstanceInfra UpdateNetworkInstanceInfra = new UpdateNetworkInstanceInfra() - UpdateNetworkInstanceInfra.callRESTQueryAAINetworkId(mockExecution) - - // check the sequence of variable invocation - //MockitoDebuggerImpl preDebugger = new MockitoDebuggerImpl() - //preDebugger.printInvocations(mockExecution) - - verify(mockExecution).setVariable("prefix", "UPDNETI_") - verify(mockExecution).setVariable("UPDNETI_queryIdAAIRequest", "http://localhost:28090/aai/v8/network/l3-networks/l3-network/49c86598-f766-46f8-84f8-8d1c1b10f9b4") - verify(mockExecution).setVariable("UPDNETI_aaiIdReturnCode", "200") - - } - - @Test - //@Ignore - public void callRESTQueryAAICloudRegion30_200() { - - println "************ callRESTQueryAAICloudRegion30_200 ************* " - - WireMock.reset(); - MockGetCloudRegion("RDM2WAGPLCP", 200, "CreateNetworkV2/cloudRegion30_AAIResponse_Success.xml") - - ExecutionEntity mockExecution = setupMock() - when(mockExecution.getVariable("prefix")).thenReturn("UPDNETI_") - when(mockExecution.getVariable("UPDNETI_networkInputs")).thenReturn(expectedNetworkRequest) - when(mockExecution.getVariable("URN_aai_endpoint")).thenReturn("http://localhost:28090") - when(mockExecution.getVariable("URN_mso_workflow_global_default_aai_version")).thenReturn("8") - when(mockExecution.getVariable("URN_mso_workflow_default_aai_v8_cloud_region_uri")).thenReturn("/aai/v8/cloud-infrastructure/cloud-regions/cloud-region/att-aic") - when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") - when(mockExecution.getVariable("URN_aai_auth")).thenReturn("757A94191D685FD2092AC1490730A4FC") - when(mockExecution.getVariable("URN_mso_msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7") - - // preProcessRequest(Execution execution) - UpdateNetworkInstanceInfra UpdateNetworkInstanceInfra = new UpdateNetworkInstanceInfra() - UpdateNetworkInstanceInfra.callRESTQueryAAICloudRegion(mockExecution) - - // check the sequence of variable invocation - //MockitoDebuggerImpl preDebugger = new MockitoDebuggerImpl() - //preDebugger.printInvocations(mockExecution) - - verify(mockExecution, atLeast(1)).setVariable("prefix", "UPDNETI_") - verify(mockExecution).setVariable("UPDNETI_queryCloudRegionRequest", "http://localhost:28090/aai/v8/cloud-infrastructure/cloud-regions/cloud-region/att-aic/RDM2WAGPLCP") - verify(mockExecution, atLeast(2)).setVariable("UPDNETI_queryCloudRegionReturnCode", "200") - verify(mockExecution).setVariable("UPDNETI_isCloudRegionGood", true) - - } - - @Test - //@Ignore - public void callRESTQueryAAICloudRegion25_200() { - - println "************ callRESTQueryAAICloudRegion25_200 ************* " - - WireMock.reset(); - MockGetCloudRegion("RDM2WAGPLCP", 200, "CreateNetworkV2/cloudRegion25_AAIResponse_Success.xml") - - ExecutionEntity mockExecution = setupMock() - when(mockExecution.getVariable("prefix")).thenReturn("UPDNETI_") - when(mockExecution.getVariable("UPDNETI_networkInputs")).thenReturn(expectedNetworkRequest) - when(mockExecution.getVariable("URN_aai_endpoint")).thenReturn("http://localhost:28090") - when(mockExecution.getVariable("URN_mso_workflow_global_default_aai_version")).thenReturn("8") - when(mockExecution.getVariable("URN_mso_workflow_default_aai_v8_cloud_region_uri")).thenReturn("/aai/v8/cloud-infrastructure/cloud-regions/cloud-region/att-aic") - when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") - when(mockExecution.getVariable("URN_aai_auth")).thenReturn("757A94191D685FD2092AC1490730A4FC") - when(mockExecution.getVariable("URN_mso_msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7") - - // preProcessRequest(Execution execution) - UpdateNetworkInstanceInfra UpdateNetworkInstanceInfra = new UpdateNetworkInstanceInfra() - UpdateNetworkInstanceInfra.callRESTQueryAAICloudRegion(mockExecution) - - // check the sequence of variable invocation - //MockitoDebuggerImpl preDebugger = new MockitoDebuggerImpl() - //preDebugger.printInvocations(mockExecution) - - verify(mockExecution, atLeast(1)).setVariable("prefix", "UPDNETI_") - verify(mockExecution).setVariable("UPDNETI_queryCloudRegionRequest", "http://localhost:28090/aai/v8/cloud-infrastructure/cloud-regions/cloud-region/att-aic/RDM2WAGPLCP") - verify(mockExecution, atLeast(2)).setVariable("UPDNETI_queryCloudRegionReturnCode", "200") - verify(mockExecution).setVariable("UPDNETI_isCloudRegionGood", true) - - } - - @Test - //@Ignore - public void callRESTQueryAAICloudRegion_NotFound() { - - println "************ callRESTQueryAAICloudRegionFake ************* " - - WireMock.reset(); - MockGetCloudRegion("MDTWNJ21", 404, "") - - ExecutionEntity mockExecution = setupMock() - when(mockExecution.getVariable("prefix")).thenReturn("UPDNETI_") - when(mockExecution.getVariable("UPDNETI_networkInputs")).thenReturn(vnfRequestFakeRegion) - when(mockExecution.getVariable("URN_aai_endpoint")).thenReturn("http://localhost:28090") - when(mockExecution.getVariable("URN_mso_workflow_global_default_aai_version")).thenReturn("8") - when(mockExecution.getVariable("URN_mso_workflow_default_aai_v8_cloud_region_uri")).thenReturn("/aai/v8/cloud-infrastructure/cloud-regions/cloud-region/att-aic") - when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") - when(mockExecution.getVariable("URN_aai_auth")).thenReturn("757A94191D685FD2092AC1490730A4FC") - when(mockExecution.getVariable("URN_mso_msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7") - - // preProcessRequest(Execution execution) - UpdateNetworkInstanceInfra UpdateNetworkInstanceInfra = new UpdateNetworkInstanceInfra() - UpdateNetworkInstanceInfra.callRESTQueryAAICloudRegion(mockExecution) - - // check the sequence of variable invocation - //MockitoDebuggerImpl preDebugger = new MockitoDebuggerImpl() - //preDebugger.printInvocations(mockExecution) - - verify(mockExecution, atLeast(1)).setVariable("prefix", "UPDNETI_") - verify(mockExecution).setVariable("UPDNETI_queryCloudRegionRequest", "http://localhost:28090/aai/v8/cloud-infrastructure/cloud-regions/cloud-region/att-aic/MDTWNJ21") - verify(mockExecution, atLeast(1)).setVariable("UPDNETI_queryCloudRegionReturnCode", "404") - verify(mockExecution).setVariable("UPDNETI_cloudRegionPo", "MDTWNJ21") - verify(mockExecution).setVariable("UPDNETI_cloudRegionSdnc", "AAIAIC25") - verify(mockExecution).setVariable("UPDNETI_isCloudRegionGood", true) - - } - - @Test - //@Ignore - public void callRESTQueryAAINetworkVpnBinding_200() { - - println "************ callRESTQueryAAINetworkVpnBinding_200 ************* " - - WireMock.reset(); - MockGetNetworkVpnBinding("85f015d0-2e32-4c30-96d2-87a1a27f8017", "UpdateNetworkV2/updateNetwork_queryVpnBinding_AAIResponse_Success.xml", 200) - MockGetNetworkVpnBinding("c980a6ef-3b88-49f0-9751-dbad8608d0a6", "UpdateNetworkV2/updateNetwork_queryVpnBinding_AAIResponse_Success.xml", 200); - - ExecutionEntity mockExecution = setupMock() - when(mockExecution.getVariable("UPDNETI_requeryIdAAIResponse")).thenReturn(queryIdAIIResponse) // v6 - when(mockExecution.getVariable("UPDNETI_messageId")).thenReturn("e8ebf6a0-f8ea-4dc0-8b99-fe98a87722d6") - when(mockExecution.getVariable("URN_aai_endpoint")).thenReturn("http://localhost:28090") - when(mockExecution.getVariable("URN_mso_workflow_global_default_aai_version")).thenReturn("8") - when(mockExecution.getVariable("URN_mso_workflow_default_aai_v8_vpn_binding_uri")).thenReturn("/aai/v8/network/vpn-bindings/vpn-binding") -// when(mockExecution.getVariable("URN_mso_workflow_UpdateNetworkInstanceInfra_aai_network_vpn-binding_uri")).thenReturn("") - when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") - when(mockExecution.getVariable("URN_aai_auth")).thenReturn("757A94191D685FD2092AC1490730A4FC") - when(mockExecution.getVariable("URN_mso_msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7") - - // preProcessRequest(Execution execution) - UpdateNetworkInstanceInfra UpdateNetworkInstanceInfra = new UpdateNetworkInstanceInfra() - UpdateNetworkInstanceInfra.callRESTQueryAAINetworkVpnBinding(mockExecution) - - // check the sequence of variable invocation - //MockitoDebuggerImpl preDebugger = new MockitoDebuggerImpl() - //preDebugger.printInvocations(mockExecution) - - verify(mockExecution).setVariable("prefix", "UPDNETI_") - verify(mockExecution).setVariable("UPDNETI_vpnCount", 2) - verify(mockExecution).setVariable("UPDNETI_vpnBindings", ['/aai/v8/network/vpn-bindings/vpn-binding/85f015d0-2e32-4c30-96d2-87a1a27f8017/', '/aai/v8/network/vpn-bindings/vpn-binding/c980a6ef-3b88-49f0-9751-dbad8608d0a6/']) - // the last vpnBinding value is saved. - verify(mockExecution).setVariable("UPDNETI_queryVpnBindingAAIRequest", "http://localhost:28090/aai/v8/network/vpn-bindings/vpn-binding/85f015d0-2e32-4c30-96d2-87a1a27f8017") - verify(mockExecution, atLeast(2)).setVariable("UPDNETI_aaiQqueryVpnBindingReturnCode", "200") - - } - - @Test - //@Ignore - public void callRESTQueryAAINetworkVpnBinding_TestScenario01_200() { - - println "************ callRESTQueryAAINetworkVpnBinding_200 ************* " - - WireMock.reset(); - MockGetNetworkVpnBinding("85f015d0-2e32-4c30-96d2-87a1a27f8017", "UpdateNetworkV2/updateNetwork_queryVpnBinding_AAIResponse_Success.xml", 200) - - ExecutionEntity mockExecution = setupMock() - when(mockExecution.getVariable("UPDNETI_requeryIdAAIResponse")).thenReturn(queryIdAIIResponseTestScenario01) - when(mockExecution.getVariable("UPDNETI_messageId")).thenReturn("e8ebf6a0-f8ea-4dc0-8b99-fe98a87722d6") - when(mockExecution.getVariable("URN_aai_endpoint")).thenReturn("http://localhost:28090") - when(mockExecution.getVariable("URN_mso_workflow_global_default_aai_version")).thenReturn("8") - when(mockExecution.getVariable("URN_mso_workflow_default_aai_v8_vpn_binding_uri")).thenReturn("/aai/v8/network/vpn-bindings/vpn-binding") -// when(mockExecution.getVariable("URN_mso_workflow_UpdateNetworkInstanceInfra_aai_network_vpn-binding_uri")).thenReturn("") - when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") - when(mockExecution.getVariable("URN_aai_auth")).thenReturn("757A94191D685FD2092AC1490730A4FC") - when(mockExecution.getVariable("URN_mso_msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7") - - // preProcessRequest(Execution execution) - UpdateNetworkInstanceInfra UpdateNetworkInstanceInfra = new UpdateNetworkInstanceInfra() - UpdateNetworkInstanceInfra.callRESTQueryAAINetworkVpnBinding(mockExecution) - - // check the sequence of variable invocation - //MockitoDebuggerImpl preDebugger = new MockitoDebuggerImpl() - //preDebugger.printInvocations(mockExecution) - - verify(mockExecution).setVariable("prefix", "UPDNETI_") - verify(mockExecution).setVariable("UPDNETI_vpnCount", 1) - verify(mockExecution).setVariable("UPDNETI_vpnBindings", ['/aai/v8/network/vpn-bindings/vpn-binding/85f015d0-2e32-4c30-96d2-87a1a27f8017/']) - // the last vpnBinding value is saved. - verify(mockExecution).setVariable("UPDNETI_queryVpnBindingAAIRequest", "http://localhost:28090/aai/v8/network/vpn-bindings/vpn-binding/85f015d0-2e32-4c30-96d2-87a1a27f8017") - verify(mockExecution).setVariable("UPDNETI_aaiQqueryVpnBindingReturnCode", "200") - - } - - @Test - //@Ignore - public void callRESTQueryAAINetworkVpnBinding_200_URN_Uri() { - - println "************ callRESTQueryAAINetworkVpnBinding_200 ************* " - - WireMock.reset(); - MockGetNetworkVpnBinding("85f015d0-2e32-4c30-96d2-87a1a27f8017", "UpdateNetworkV2/updateNetwork_queryVpnBinding_AAIResponse_Success.xml", 200) - MockGetNetworkVpnBinding("c980a6ef-3b88-49f0-9751-dbad8608d0a6", "UpdateNetworkV2/updateNetwork_queryVpnBinding_AAIResponse_Success.xml", 200); - - ExecutionEntity mockExecution = setupMock() - when(mockExecution.getVariable("UPDNETI_requeryIdAAIResponse")).thenReturn(queryIdAIIResponse) - when(mockExecution.getVariable("UPDNETI_messageId")).thenReturn("e8ebf6a0-f8ea-4dc0-8b99-fe98a87722d6") - when(mockExecution.getVariable("URN_aai_endpoint")).thenReturn("http://localhost:28090") - when(mockExecution.getVariable("URN_mso_workflow_global_default_aai_version")).thenReturn("8") - when(mockExecution.getVariable("URN_mso_workflow_default_aai_v8_vpn_binding_uri")).thenReturn("/aai/v8/network/vpn-bindings/vpn-binding") - when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") - when(mockExecution.getVariable("URN_aai_auth")).thenReturn("757A94191D685FD2092AC1490730A4FC") - when(mockExecution.getVariable("URN_mso_msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7") - - // preProcessRequest(Execution execution) - UpdateNetworkInstanceInfra UpdateNetworkInstanceInfra = new UpdateNetworkInstanceInfra() - UpdateNetworkInstanceInfra.callRESTQueryAAINetworkVpnBinding(mockExecution) - - // check the sequence of variable invocation - //MockitoDebuggerImpl preDebugger = new MockitoDebuggerImpl() - //preDebugger.printInvocations(mockExecution) - - verify(mockExecution).setVariable("prefix", "UPDNETI_") - verify(mockExecution).setVariable("UPDNETI_vpnCount", 2) - verify(mockExecution).setVariable("UPDNETI_vpnBindings", ['/aai/v8/network/vpn-bindings/vpn-binding/85f015d0-2e32-4c30-96d2-87a1a27f8017/', '/aai/v8/network/vpn-bindings/vpn-binding/c980a6ef-3b88-49f0-9751-dbad8608d0a6/']) - // the last vpnBinding value is saved. - verify(mockExecution).setVariable("UPDNETI_queryVpnBindingAAIRequest", "http://localhost:28090/aai/v8/network/vpn-bindings/vpn-binding/85f015d0-2e32-4c30-96d2-87a1a27f8017") - verify(mockExecution, atLeast(2)).setVariable("UPDNETI_aaiQqueryVpnBindingReturnCode", "200") - - } - - @Test - //@Ignore - public void callRESTQueryAAINetworkVpnBinding_NotPresent() { - - println "************ callRESTQueryAAINetworkVpnBinding_NotPresent ************* " - - WireMock.reset(); - MockGetNetworkVpnBinding("85f015d0-2e32-4c30-96d2-87a1a27f8017", "UpdateNetworkV2/updateNetwork_queryVpnBinding_AAIResponse_Success.xml", 200) - - ExecutionEntity mockExecution = setupMock() - // Initialize prerequisite variables - - when(mockExecution.getVariable("UPDNETI_requeryIdAAIResponse")).thenReturn(queryIdAIIResponseVpnNotPresent) - when(mockExecution.getVariable("UPDNETI_messageId")).thenReturn("e8ebf6a0-f8ea-4dc0-8b99-fe98a87722d6") - when(mockExecution.getVariable("URN_aai_endpoint")).thenReturn("http://localhost:28090") - when(mockExecution.getVariable("URN_mso_workflow_global_default_aai_version")).thenReturn("8") - when(mockExecution.getVariable("URN_mso_workflow_default_aai_v8_l3_network_uri")).thenReturn("/aai/v8/network/l3-networks/l3-network") - when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") - - // preProcessRequest(Execution execution) - UpdateNetworkInstanceInfra UpdateNetworkInstanceInfra = new UpdateNetworkInstanceInfra() - UpdateNetworkInstanceInfra.callRESTQueryAAINetworkVpnBinding(mockExecution) - - // check the sequence of variable invocation - //MockitoDebuggerImpl preDebugger = new MockitoDebuggerImpl() - //preDebugger.printInvocations(mockExecution) - - verify(mockExecution).setVariable("prefix", "UPDNETI_") - verify(mockExecution).setVariable("UPDNETI_aaiQqueryVpnBindingReturnCode", "200") - verify(mockExecution).setVariable("UPDNETI_vpnCount", 0) - verify(mockExecution).setVariable("UPDNETI_queryVpnBindingAAIResponse", aaiVpnResponseStub) - - } - - @Test - //@Ignore - public void callRESTQueryAAINetworkTableRef_200() { - - println "************ callRESTQueryAAINetworkTableRef_200 ************* " - - WireMock.reset(); - MockGetNetworkRouteTable("refFQDN1", "CreateNetworkV2/createNetwork_queryNetworkTableRef1_AAIResponse_Success.xml", 200) - MockGetNetworkRouteTable("refFQDN2", "CreateNetworkV2/createNetwork_queryNetworkTableRef2_AAIResponse_Success.xml", 200) - - ExecutionEntity mockExecution = setupMock() - when(mockExecution.getVariable("UPDNETI_requeryIdAAIResponse")).thenReturn(queryIdAIIResponse) - when(mockExecution.getVariable("UPDNETI_messageId")).thenReturn("e8ebf6a0-f8ea-4dc0-8b99-fe98a87722d6") - when(mockExecution.getVariable("URN_aai_endpoint")).thenReturn("http://localhost:28090") - when(mockExecution.getVariable("URN_mso_workflow_global_default_aai_version")).thenReturn("8") - when(mockExecution.getVariable("URN_mso_workflow_default_aai_v8_route_table_reference_uri")).thenReturn("/aai/v8/network/route-table-references/route-table-reference") -// when(mockExecution.getVariable("URN_mso_workflow_CreateNetworkInstanceInfra_aai_network_table_reference_uri")).thenReturn("") - when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") - when(mockExecution.getVariable("URN_aai_auth")).thenReturn("757A94191D685FD2092AC1490730A4FC") - when(mockExecution.getVariable("URN_mso_msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7") - - // preProcessRequest(Execution execution) - UpdateNetworkInstanceInfra UpdateNetworkInstanceInfra = new UpdateNetworkInstanceInfra() - UpdateNetworkInstanceInfra.callRESTQueryAAINetworkTableRef(mockExecution) - - // check the sequence of variable invocation - //MockitoDebuggerImpl preDebugger = new MockitoDebuggerImpl() - //preDebugger.printInvocations(mockExecution) - - verify(mockExecution).setVariable("prefix", "UPDNETI_") - verify(mockExecution).setVariable("UPDNETI_networkTableRefCount", 2) - verify(mockExecution).setVariable("UPDNETI_networkTableRefUriList", ['/aai/v8/network/route-table-references/route-table-reference/refFQDN1','/aai/v8/network/route-table-references/route-table-reference/refFQDN2']) - // the last vpnBinding value is saved. - verify(mockExecution).setVariable("UPDNETI_queryNetworkTableRefAAIRequest", "http://localhost:28090/aai/v8/network/route-table-references/route-table-reference/refFQDN1") - verify(mockExecution, atLeast(2)).setVariable("UPDNETI_aaiQqueryNetworkTableRefReturnCode", "200") - - } - - @Test - //@Ignore - public void callRESTQueryAAINetworkPolicy_200() { - - println "************ callRESTQueryAAINetworkPolicy_200 ************* " - - WireMock.reset(); - MockGetNetworkPolicy("cee6d136-e378-4678-a024-2cd15f0ee0cg", "UpdateNetworkV2/updateNetwork_queryNetworkPolicy_AAIResponse_Success.xml", 200) - - ExecutionEntity mockExecution = setupMock() - when(mockExecution.getVariable("UPDNETI_requeryIdAAIResponse")).thenReturn(queryIdAIIResponse) - when(mockExecution.getVariable("UPDNETI_messageId")).thenReturn("e8ebf6a0-f8ea-4dc0-8b99-fe98a87722d6") - when(mockExecution.getVariable("URN_aai_endpoint")).thenReturn("http://localhost:28090") - when(mockExecution.getVariable("URN_mso_workflow_global_default_aai_version")).thenReturn("8") - when(mockExecution.getVariable("URN_mso_workflow_default_aai_v8_network_policy_uri")).thenReturn("/aai/v8/network/network-policies/network-policy") -// when(mockExecution.getVariable("URN_mso_workflow_UpdateNetworkInstanceInfra_aai_network_policy_uri")).thenReturn("") - when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") - when(mockExecution.getVariable("URN_aai_auth")).thenReturn("757A94191D685FD2092AC1490730A4FC") - when(mockExecution.getVariable("URN_mso_msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7") - - // preProcessRequest(Execution execution) - UpdateNetworkInstanceInfra UpdateNetworkInstanceInfra = new UpdateNetworkInstanceInfra() - UpdateNetworkInstanceInfra.callRESTQueryAAINetworkPolicy(mockExecution) - - // check the sequence of variable invocation - //MockitoDebuggerImpl preDebugger = new MockitoDebuggerImpl() - //preDebugger.printInvocations(mockExecution) - - verify(mockExecution).setVariable("prefix", "UPDNETI_") - verify(mockExecution).setVariable("UPDNETI_networkPolicyCount", 1) - verify(mockExecution).setVariable("UPDNETI_networkPolicyUriList", ['/aai/v8/network/network-policies/network-policy/cee6d136-e378-4678-a024-2cd15f0ee0cg']) - // the last vpnBinding value is saved. - verify(mockExecution).setVariable("UPDNETI_queryNetworkPolicyAAIRequest", "http://localhost:28090/aai/v8/network/network-policies/network-policy/cee6d136-e378-4678-a024-2cd15f0ee0cg") - verify(mockExecution).setVariable("UPDNETI_aaiQqueryNetworkPolicyReturnCode", "200") - - } - - - @Test - //@Ignore - public void callRESTReQueryAAINetworkId_200() { - - println "************ callRESTReQueryAAINetworkId ************* " - - WireMock.reset(); - MockGetNetwork("49c86598-f766-46f8-84f8-8d1c1b10f9b4", "UpdateNetworkV2/updateNetwork_queryNetworkId_AAIResponse_Success.xml", 200) - - ExecutionEntity mockExecution = setupMock() - when(mockExecution.getVariable("UPDNETI_changeAssignSDNCResponse")).thenReturn(sdncAdapterWorkflowFormattedResponse) - when(mockExecution.getVariable("UPDNETI_messageId")).thenReturn("e8ebf6a0-f8ea-4dc0-8b99-fe98a87722d6") - when(mockExecution.getVariable("URN_aai_endpoint")).thenReturn("http://localhost:28090") - when(mockExecution.getVariable("URN_mso_workflow_global_default_aai_version")).thenReturn("8") - when(mockExecution.getVariable("URN_mso_workflow_default_aai_v8_l3_network_uri")).thenReturn("/aai/v8/network/l3-networks/l3-network") - when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") - when(mockExecution.getVariable("URN_aai_auth")).thenReturn("757A94191D685FD2092AC1490730A4FC") - when(mockExecution.getVariable("URN_mso_msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7") - - // preProcessRequest(Execution execution) - UpdateNetworkInstanceInfra UpdateNetworkInstanceInfra = new UpdateNetworkInstanceInfra() - UpdateNetworkInstanceInfra.callRESTReQueryAAINetworkId(mockExecution) - - // check the sequence of variable invocation - //MockitoDebuggerImpl preDebugger = new MockitoDebuggerImpl() - //preDebugger.printInvocations(mockExecution) - - verify(mockExecution).setVariable("prefix", "UPDNETI_") - verify(mockExecution).setVariable("UPDNETI_requeryIdAAIRequest", "http://localhost:28090/aai/v8/network/l3-networks/l3-network/49c86598-f766-46f8-84f8-8d1c1b10f9b4") - verify(mockExecution).setVariable("UPDNETI_aaiRequeryIdReturnCode", "200") - - } - - - @Test - //@Ignore - public void callRESTUpdateContrailAAINetworkREST_200() { - - println "************ callRESTUpdateContrailAAINetwork ************* " - - WireMock.reset(); - MockPutNetwork("49c86598-f766-46f8-84f8-8d1c1b10f9b4", 200, "UpdateNetworkV2/updateNetwork_updateContrail_AAIResponse_Success.xml") - - ExecutionEntity mockExecution = setupMock() - when(mockExecution.getVariable("UPDNETI_changeAssignSDNCResponse")).thenReturn(sdncAdapterWorkflowFormattedResponse) - when(mockExecution.getVariable("UPDNETI_requeryIdAAIResponse")).thenReturn(queryIdAIIResponse) - when(mockExecution.getVariable("UPDNETI_updateNetworkResponse")).thenReturn(updateNetworkResponseREST) - when(mockExecution.getVariable("UPDNETI_messageId")).thenReturn("e8ebf6a0-f8ea-4dc0-8b99-fe98a87722d6") - when(mockExecution.getVariable("URN_aai_endpoint")).thenReturn("http://localhost:28090") - when(mockExecution.getVariable("URN_mso_workflow_global_default_aai_version")).thenReturn("8") - when(mockExecution.getVariable("URN_mso_workflow_default_aai_v8_l3_network_uri")).thenReturn("/aai/v8/network/l3-networks/l3-network") - when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") - when(mockExecution.getVariable("URN_aai_auth")).thenReturn("757A94191D685FD2092AC1490730A4FC") - when(mockExecution.getVariable("URN_mso_msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7") - - // preProcessRequest(Execution execution) - UpdateNetworkInstanceInfra UpdateNetworkInstanceInfra = new UpdateNetworkInstanceInfra() - UpdateNetworkInstanceInfra.callRESTUpdateContrailAAINetwork(mockExecution) - - // Capture the arguments to setVariable - ArgumentCaptor captor1 = ArgumentCaptor.forClass(String.class); - ArgumentCaptor captor2 = ArgumentCaptor.forClass(String.class); - - verify(mockExecution, times(6)).setVariable(captor1.capture(), captor2.capture()) - List arg2List = captor2.getAllValues() - String payloadResponseActual = arg2List.get(4) - - assertEquals(updateContrailAAIResponse.replaceAll("\\s+", ""), payloadResponseActual.replaceAll("\\s+", "")) - - verify(mockExecution).setVariable("prefix", "UPDNETI_") - verify(mockExecution).setVariable("UPDNETI_updateContrailAAIUrlRequest", "http://localhost:28090/aai/v8/network/l3-networks/l3-network/49c86598-f766-46f8-84f8-8d1c1b10f9b4") - verify(mockExecution).setVariable("UPDNETI_updateContrailAAIPayloadRequest", updateContrailAAIPayloadRequest) - verify(mockExecution).setVariable("UPDNETI_aaiUpdateContrailReturnCode", "200") - verify(mockExecution).setVariable("UPDNETI_isPONR", true) - - } - - - - @Test - //@Ignore - public void validateUpdateNetworkResponseREST() { - - println "************ validateNetworkResponse ************* " - - ExecutionEntity mockExecution = mock(ExecutionEntity.class) - // Initialize prerequisite variables - when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") - when(mockExecution.getVariable("UPDNETI_updateNetworkResponse")).thenReturn(updateNetworkResponseREST) - when(mockExecution.getVariable("UPDNETI_networkReturnCode")).thenReturn('200') - - UpdateNetworkInstanceInfra UpdateNetworkInstanceInfra = new UpdateNetworkInstanceInfra() - UpdateNetworkInstanceInfra.validateUpdateNetworkResponse(mockExecution) - - //MockitoDebuggerImpl debugger = new MockitoDebuggerImpl() - //debugger.printInvocations(mockExecution) - - verify(mockExecution).setVariable("prefix", "UPDNETI_") - verify(mockExecution).setVariable("UPDNETI_updateNetworkResponse", updateNetworkResponseREST) - verify(mockExecution).setVariable("UPDNETI_isNetworkRollbackNeeded", true) - verify(mockExecution).setVariable("UPDNETI_rollbackNetworkRequest", updateRollbackNetworkRequest) - - } - - @Test - //@Ignore - public void validateUpdateNetworkResponseREST_Error() { - - println "************ validateNetworkResponse ************* " - - WorkflowException workflowException = new WorkflowException("UpdateNetworkInstanceInfra", 2500, "Received error from Network Adapter: JBWEB000065: HTTP Status 500.") - - ExecutionEntity mockExecution = setupMock() - // Initialize prerequisite variables - when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") - when(mockExecution.getVariable("UPDNETI_updateNetworkResponse")).thenReturn(networkException500) - when(mockExecution.getVariable("UPDNETI_networkReturnCode")).thenReturn('500') - - UpdateNetworkInstanceInfra UpdateNetworkInstanceInfra = new UpdateNetworkInstanceInfra() - try { - UpdateNetworkInstanceInfra.validateUpdateNetworkResponse(mockExecution) - } catch (Exception ex) { - println " Test End - Handle catch-throw BpmnError()! " - } - - verify(mockExecution).setVariable("prefix", "UPDNETI_") - verify(mockExecution, atLeast(1)).setVariable("WorkflowException", refEq(workflowException, any(WorkflowException.class))) - - } - - @Test - //@Ignore - public void validateSDNCResponse() { - - println "************ validateSDNCResponse ************* " - - ExecutionEntity mockExecution = setupMock() - // Initialize prerequisite variables - when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") - when(mockExecution.getVariable("UPDNETI_changeAssignSDNCResponse")).thenReturn(sdncAdapterWorkflowResponse) - when(mockExecution.getVariable("prefix")).thenReturn("UPDNETI_") - when(mockExecution.getVariable("SDNCA_SuccessIndicator")).thenReturn(true) - when(mockExecution.getVariable("UPDNETI_sdncReturnCode")).thenReturn("200") - when(mockExecution.getVariable("UPDNETI_isResponseGood")).thenReturn(true) - - UpdateNetworkInstanceInfra UpdateNetworkInstanceInfra = new UpdateNetworkInstanceInfra() - try { - UpdateNetworkInstanceInfra.validateSDNCResponse(mockExecution) - verify(mockExecution).setVariable("UPDNETI_isSdncRollbackNeeded", true) - verify(mockExecution).setVariable("UPDNETI_rollbackSDNCRequest", "") - - } catch (Exception ex) { - println " Graceful Exit - " + ex.getMessage() - } - //MockitoDebuggerImpl debugger = new MockitoDebuggerImpl() - //debugger.printInvocations(mockExecution) - - //verify(mockExecution).setVariable("UPDNETI_isSdncRollbackNeeded", true) - - } - - @Test - //@Ignore - public void validateSDNCResponse_Error() { - - println "************ validateSDNCResponse ************* " - //ExecutionEntity mockExecution = mock(ExecutionEntity.class) - ExecutionEntity mockExecution = setupMock() - // Initialize prerequisite variables - when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") - when(mockExecution.getVariable("UPDNETI_changeAssignSDNCResponse")).thenReturn(sdncAdapterWorkflowResponse_Error) - when(mockExecution.getVariable("prefix")).thenReturn("UPDNETI_") - when(mockExecution.getVariable("SDNCA_SuccessIndicator")).thenReturn(false) - when(mockExecution.getVariable("UPDNETI_sdncReturnCode")).thenReturn("200") - when(mockExecution.getVariable("UPDNETI_isResponseGood")).thenReturn(true) - - UpdateNetworkInstanceInfra UpdateNetworkInstanceInfra = new UpdateNetworkInstanceInfra() - try { - UpdateNetworkInstanceInfra.validateSDNCResponse(mockExecution) - } catch (Exception ex) { - println " Graceful Exit! - " + ex.getMessage() - } - //MockitoDebuggerImpl debugger = new MockitoDebuggerImpl() - //debugger.printInvocations(mockExecution) - - // verify set prefix = "UPDNETI_" - //verify(mockExecution).setVariable("UPDNETI_sdncResponseSuccess", false) - - } - - - - @Test - //@Ignore - public void postProcessResponse() { - - println "************ postProcessResponse ************* " - ExecutionEntity mockExecution = mock(ExecutionEntity.class) - // Initialize prerequisite variables - when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") - when(mockExecution.getVariable("UPDNETI_source")).thenReturn("PORTAL") - when(mockExecution.getVariable("UPDNETI_requestId")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56") - when(mockExecution.getVariable("UPDNETI_dbReturnCode")).thenReturn("200") - - // postProcessResponse(Execution execution) - UpdateNetworkInstanceInfra UpdateNetworkInstanceInfra = new UpdateNetworkInstanceInfra() - UpdateNetworkInstanceInfra.postProcessResponse(mockExecution) - - // check the sequence of variable invocation - //MockitoDebuggerImpl preDebugger = new MockitoDebuggerImpl() - //preDebugger.printInvocations(mockExecution) - - verify(mockExecution).setVariable("prefix", "UPDNETI_") - verify(mockExecution).setVariable("UPDNETI_Success", true) - verify(mockExecution).setVariable("UPDNETI_CompleteMsoProcessRequest", completeMsoProcessRequest) - - } - - @Test - //@Ignore - public void validateRollbackResponses_Good() { - - WorkflowException workflowException = new WorkflowException("UpdateNetworkInstanceInfra", 2500, "AAI Update Contrail Failed. Error 404.") - WorkflowException expectedWorkflowException = new WorkflowException("UpdateNetworkInstanceInfra", 2500, "AAI Update Contrail Failed. Error 404. + PO Network rollback is not supported for Update. Submit another Update to restore/rollback. + SNDC rollback completed.") - - println "************ validateRollbackResponses_Good() ************* " - ExecutionEntity mockExecution = setupMock() - // Initialize prerequisite variables - when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") - when(mockExecution.getVariable("prefix")).thenReturn("UPDNETI_") - - when(mockExecution.getVariable("UPDNETI_isNetworkRollbackNeeded")).thenReturn(true) - when(mockExecution.getVariable("UPDNETI_rollbackNetworkReturnCode")).thenReturn("200") - when(mockExecution.getVariable("UPDNETI_rollbackNetworkResponse")).thenReturn("GoodResponse") - when(mockExecution.getVariable("UPDNETI_isSdncRollbackNeeded")).thenReturn(true) - when(mockExecution.getVariable("UPDNETI_rollbackSDNCReturnCode")).thenReturn("200") - when(mockExecution.getVariable("UPDNETI_rollbackSDNCResponse")).thenReturn("GoodResponse") - when(mockExecution.getVariable("WorkflowException")).thenReturn(workflowException) - - UpdateNetworkInstanceInfra UpdateNetworkInstanceInfra = new UpdateNetworkInstanceInfra() - UpdateNetworkInstanceInfra.validateRollbackResponses(mockExecution) - - // verify set prefix = "UPDNETI_" - verify(mockExecution, atLeast(1)).setVariable("prefix", "UPDNETI_") - verify(mockExecution).setVariable("WorkflowException", refEq(expectedWorkflowException, any(WorkflowException.class))) - - } - - @Test - //@Ignore - public void validateRollbackResponses_Failed() { - - WorkflowException workflowException = new WorkflowException("UpdateNetworkInstanceInfra", 7020, "AAI Update Contrail Failed. Error 404.") - WorkflowException expectedWorkflowException = new WorkflowException("UpdateNetworkInstanceInfra", 7020, "AAI Update Contrail Failed. Error 404. + PO Network rollback is not supported for Update. Submit another Update to restore/rollback. + SDNC rollback failed. ") - - println "************ validateRollbackResponses_Failed() ************* " - ExecutionEntity mockExecution = setupMock() - // Initialize prerequisite variables - when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") - when(mockExecution.getVariable("prefix")).thenReturn("UPDNETI_") - - when(mockExecution.getVariable("UPDNETI_isNetworkRollbackNeeded")).thenReturn(true) - when(mockExecution.getVariable("UPDNETI_rollbackNetworkReturnCode")).thenReturn("404") - when(mockExecution.getVariable("UPDNETI_rollbackNetworkResponse")).thenReturn("BadResponse") - when(mockExecution.getVariable("UPDNETI_isSdncRollbackNeeded")).thenReturn(true) - when(mockExecution.getVariable("UPDNETI_rollbackSDNCReturnCode")).thenReturn("500") - when(mockExecution.getVariable("UPDNETI_rollbackSDNCResponse")).thenReturn("BadResponse") - when(mockExecution.getVariable("WorkflowException")).thenReturn(workflowException) - - UpdateNetworkInstanceInfra UpdateNetworkInstanceInfra = new UpdateNetworkInstanceInfra() - UpdateNetworkInstanceInfra.validateRollbackResponses(mockExecution) - - // verify set prefix = "UPDNETI_" - verify(mockExecution, atLeast(1)).setVariable("prefix", "UPDNETI_") - verify(mockExecution, atLeast(1)).setVariable("WorkflowException", refEq(expectedWorkflowException, any(WorkflowException.class))) - - } - - @Test - //@Ignore - public void validateRollbackResponses_NetworkFailed() { - - WorkflowException workflowException = new WorkflowException("UpdateNetworkInstanceInfra", 7020, "AAI Update Contrail Failed. Error 404.") - WorkflowException expectedWorkflowExceptionFailed = new WorkflowException("UpdateNetworkInstanceInfra", 7020, "AAI Update Contrail Failed. Error 404. + PO Network rollback is not supported for Update. Submit another Update to restore/rollback. + SNDC rollback completed.") - - println "************ validateRollbackResponses_NetworkFailed() ************* " - ExecutionEntity mockExecution = setupMock() - // Initialize prerequisite variables - when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") - when(mockExecution.getVariable("prefix")).thenReturn("UPDNETI_") - - when(mockExecution.getVariable("UPDNETI_isNetworkRollbackNeeded")).thenReturn(true) - when(mockExecution.getVariable("UPDNETI_rollbackNetworkReturnCode")).thenReturn("404") - when(mockExecution.getVariable("UPDNETI_rollbackNetworkResponse")).thenReturn("BadResponse") - when(mockExecution.getVariable("UPDNETI_isSdncRollbackNeeded")).thenReturn(true) - when(mockExecution.getVariable("UPDNETI_rollbackSDNCReturnCode")).thenReturn("200") - when(mockExecution.getVariable("UPDNETI_rollbackSDNCResponse")).thenReturn("GoodResponse") - when(mockExecution.getVariable("WorkflowException")).thenReturn(workflowException) - - UpdateNetworkInstanceInfra UpdateNetworkInstanceInfra = new UpdateNetworkInstanceInfra() - UpdateNetworkInstanceInfra.validateRollbackResponses(mockExecution) - - // verify set prefix = "UPDNETI_" - verify(mockExecution, atLeast(1)).setVariable("prefix", "UPDNETI_") - verify(mockExecution, atLeast(1)).setVariable("WorkflowException", refEq(expectedWorkflowExceptionFailed , any(WorkflowException.class))) - - } - - @Test - //@Ignore - public void validateRollbackResponses_SdncFailed() { - - WorkflowException workflowException = new WorkflowException("UpdateNetworkInstanceInfra", 7020, "AAI Update Contrail Failed. Error 404.") - WorkflowException expectedWorkflowException = new WorkflowException("UpdateNetworkInstanceInfra", 7020, "AAI Update Contrail Failed. Error 404. + PO Network rollback is not supported for Update. Submit another Update to restore/rollback. + SDNC rollback failed. ") - - println "************ validateRollbackResponses_SdncFailed() ************* " - ExecutionEntity mockExecution = setupMock() - // Initialize prerequisite variables - when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") - when(mockExecution.getVariable("prefix")).thenReturn("UPDNETI_") - - when(mockExecution.getVariable("UPDNETI_isNetworkRollbackNeeded")).thenReturn(true) - when(mockExecution.getVariable("UPDNETI_rollbackNetworkReturnCode")).thenReturn("200") - when(mockExecution.getVariable("UPDNETI_rollbackNetworkResponse")).thenReturn("GoodResponse") - when(mockExecution.getVariable("UPDNETI_isSdncRollbackNeeded")).thenReturn(true) - when(mockExecution.getVariable("UPDNETI_rollbackSDNCReturnCode")).thenReturn("200") - when(mockExecution.getVariable("UPDNETI_rollbackSDNCResponse")).thenReturn("400") - when(mockExecution.getVariable("WorkflowException")).thenReturn(workflowException) - - UpdateNetworkInstanceInfra UpdateNetworkInstanceInfra = new UpdateNetworkInstanceInfra() - UpdateNetworkInstanceInfra.validateRollbackResponses(mockExecution) - - // verify set prefix = "UPDNETI_" - verify(mockExecution, atLeast(1)).setVariable("prefix", "UPDNETI_") - verify(mockExecution).setVariable("WorkflowException", refEq(expectedWorkflowException , any(WorkflowException.class))) - - } - - @Test - //@Ignore - public void validateRollbackResponses_NoRollbacks() { - - WorkflowException workflowException = new WorkflowException("UpdateNetworkInstanceInfra", 2500, " AAI Update Contrail Failed. Error 404") - WorkflowException expectedWorkflowException = new WorkflowException("UpdateNetworkInstanceInfra", 2500, " AAI Update Contrail Failed. Error 404") - - println "************ validateRollbackResponses_NoRollbacks() ************* " - ExecutionEntity mockExecution = setupMock() - // Initialize prerequisite variables - when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") - when(mockExecution.getVariable("prefix")).thenReturn("UPDNETI_") - - when(mockExecution.getVariable("UPDNETI_isNetworkRollbackNeeded")).thenReturn(false) - when(mockExecution.getVariable("UPDNETI_rollbackNetworkReturnCode")).thenReturn("200") - when(mockExecution.getVariable("UPDNETI_rollbackNetworkResponse")).thenReturn("GoodResponse") - when(mockExecution.getVariable("UPDNETI_isSdncRollbackNeeded")).thenReturn(false) - when(mockExecution.getVariable("UPDNETI_rollbackSDNCReturnCode")).thenReturn("200") - when(mockExecution.getVariable("UPDNETI_rollbackSDNCResponse")).thenReturn("GoodResponse") - when(mockExecution.getVariable("WorkflowException")).thenReturn(workflowException) - - UpdateNetworkInstanceInfra UpdateNetworkInstanceInfra = new UpdateNetworkInstanceInfra() - UpdateNetworkInstanceInfra.validateRollbackResponses(mockExecution) - - // verify set prefix = "UPDNETI_" - verify(mockExecution, atLeast(1)).setVariable("prefix", "UPDNETI_") - //verify(mockExecution, atLeast(1)).setVariable("WorkflowException", any(expectedWorkflowException)) - verify(mockExecution, atLeast(1)).setVariable("WorkflowException", refEq(expectedWorkflowException, any(WorkflowException.class))) - - } - - - @Test - //@Ignore - public void buildErrorResponse() { - - println "************ buildErrorResponse ************* " - - - WorkflowException sndcWorkflowException = new WorkflowException("UpdateNetworkInstanceInfra", 5300, "Received error from SDN-C: No availability zone available.") - - ExecutionEntity mockExecution = setupMock() - // Initialize prerequisite variables - when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") - when(mockExecution.getVariable("UPDNETI_requestId")).thenReturn("b69c9054-da09-4a2c-adf5-51042b62bfac") - when(mockExecution.getVariable("UPDNETI_source")).thenReturn("PORTAL") - when(mockExecution.getVariable("WorkflowException")).thenReturn(sndcWorkflowException) - - // buildErrorResponse(Execution execution) - UpdateNetworkInstanceInfra UpdateNetworkInstanceInfra = new UpdateNetworkInstanceInfra() - UpdateNetworkInstanceInfra.buildErrorResponse(mockExecution) - - // verify set prefix = "UPDNETI_" - verify(mockExecution, atLeast(1)).setVariable("prefix", "UPDNETI_") - verify(mockExecution).setVariable("UPDNETI_Success", false) - verify(mockExecution).setVariable("UPDNETI_FalloutHandlerRequest", falloutHandlerRequest) - - //MockitoDebuggerImpl debugger = new MockitoDebuggerImpl() - //debugger.printInvocations(mockExecution) - - } - - @Test - //@Ignore - public void buildErrorResponse_WorkflowExceptionObject() { - - println "************ buildErrorResponse ************* " - - WorkflowException sndcWorkflowException = new WorkflowException("UpdateNetworkInstanceInfra", 7000, "Received error from SDN-C: No availability zone available") - - ExecutionEntity mockExecution = setupMock() - // Initialize prerequisite variables - when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") - when(mockExecution.getVariable("UPDNETI_requestId")).thenReturn("b69c9054-da09-4a2c-adf5-51042b62bfac") - when(mockExecution.getVariable("UPDNETI_source")).thenReturn("VID") - when(mockExecution.getVariable("WorkflowException")).thenReturn(sndcWorkflowException) - - // buildErrorResponse(Execution execution) - UpdateNetworkInstanceInfra UpdateNetworkInstanceInfra = new UpdateNetworkInstanceInfra() - UpdateNetworkInstanceInfra.buildErrorResponse(mockExecution) - - // verify set prefix = "UPDNETI_" - verify(mockExecution).setVariable("prefix", "UPDNETI_") - verify(mockExecution).setVariable("UPDNETI_Success", false) - verify(mockExecution).setVariable("UPDNETI_FalloutHandlerRequest", falloutHandlerRequestObject) - - //MockitoDebuggerImpl debugger = new MockitoDebuggerImpl() - //debugger.printInvocations(mockExecution) - - } - - @Test - //@Ignore - public void buildErrorResponse_Scenario01() { - - WorkflowException aaiWorkflowException_Secnario01 = new WorkflowException("UpdateNetworkInstanceInfra", 7020, "Unexpected Response from AAI - 400") - - println "************ buildErrorResponse ************* " - ExecutionEntity mockExecution = setupMock() - // Initialize prerequisite variables - when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") - when(mockExecution.getVariable("UPDNETI_requestId")).thenReturn("b69c9054-da09-4a2c-adf5-51042b62bfac") - when(mockExecution.getVariable("UPDNETI_source")).thenReturn("VID") - when(mockExecution.getVariable("WorkflowException")).thenReturn(aaiWorkflowException_Secnario01) - when(mockExecution.getVariable("UPDNETI_dbReturnCode")).thenReturn("200") - when(mockExecution.getVariable("UPDNETI_updateDBResponse")).thenReturn("") - - when(mockExecution.getVariable("UPDNETI_aaiRequeryIdReturnCode")).thenReturn("400") - - // buildErrorResponse(Execution execution) - UpdateNetworkInstanceInfra UpdateNetworkInstanceInfra = new UpdateNetworkInstanceInfra() - UpdateNetworkInstanceInfra.buildErrorResponse(mockExecution) - - // verify set prefix = "UPDNETI_" - verify(mockExecution, atLeast(1)).setVariable("prefix", "UPDNETI_") - verify(mockExecution).setVariable("UPDNETI_Success", false) - verify(mockExecution).setVariable("UPDNETI_FalloutHandlerRequest", falloutHandlerRequest_Scenario01) - - //MockitoDebuggerImpl debugger = new MockitoDebuggerImpl() - //debugger.printInvocations(mockExecution) - - } - - - private ExecutionEntity setupMock() { - - ProcessDefinition mockProcessDefinition = mock(ProcessDefinition.class) - when(mockProcessDefinition.getKey()).thenReturn("UpdateNetworkInstanceInfra") - RepositoryService mockRepositoryService = mock(RepositoryService.class) - when(mockRepositoryService.getProcessDefinition()).thenReturn(mockProcessDefinition) - when(mockRepositoryService.getProcessDefinition().getKey()).thenReturn("UpdateNetworkInstanceInfra") - when(mockRepositoryService.getProcessDefinition().getId()).thenReturn("100") - ProcessEngineServices mockProcessEngineServices = mock(ProcessEngineServices.class) - when(mockProcessEngineServices.getRepositoryService()).thenReturn(mockRepositoryService) - - ExecutionEntity mockExecution = mock(ExecutionEntity.class) - // Initialize prerequisite variables - - when(mockExecution.getId()).thenReturn("100") - when(mockExecution.getProcessDefinitionId()).thenReturn("UpdateNetworkInstanceInfra") - when(mockExecution.getProcessInstanceId()).thenReturn("UpdateNetworkInstanceInfra") - when(mockExecution.getProcessEngineServices()).thenReturn(mockProcessEngineServices) - when(mockExecution.getProcessEngineServices().getRepositoryService().getProcessDefinition(mockExecution.getProcessDefinitionId())).thenReturn(mockProcessDefinition) - - return mockExecution - } - - -} +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.bpmn.infrastructure.scripts; + +import static org.junit.Assert.* +import static org.mockito.Mockito.* +import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockGetCloudRegion +import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockGetNetwork +import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockPutNetwork +import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockGetNetworkPolicy +import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockGetNetworkRouteTable +import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockGetNetworkVpnBinding + +import org.apache.commons.lang3.* +import org.camunda.bpm.engine.ProcessEngineServices +import org.camunda.bpm.engine.RepositoryService +import org.camunda.bpm.engine.impl.persistence.entity.ExecutionEntity +import org.camunda.bpm.engine.repository.ProcessDefinition +import org.camunda.bpm.engine.runtime.Execution +import org.junit.Before +import org.junit.Ignore; +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.mockito.ArgumentCaptor +import org.mockito.MockitoAnnotations +import org.mockito.runners.MockitoJUnitRunner +import org.openecomp.mso.bpmn.common.scripts.MsoUtils +import org.openecomp.mso.bpmn.core.WorkflowException + +import com.github.tomakehurst.wiremock.client.WireMock +import com.github.tomakehurst.wiremock.junit.WireMockRule + + +@RunWith(MockitoJUnitRunner.class) +class UpdateNetworkInstanceInfraTest { + + @Rule + public WireMockRule wireMockRule = new WireMockRule(28090); + + def utils = new MsoUtils() + + String jsonIncomingRequest = + """{ "requestDetails": { + "modelInfo": { + "modelType": "networkTyp", + "modelId": "modelId", + "modelNameVersionId": "modelNameVersionId", + "modelName": "CONTRAIL_EXTERNAL", + "modelVersion": "1" + }, + "cloudConfiguration": { + "lcpCloudRegionId": "RDM2WAGPLCP", + "tenantId": "7dd5365547234ee8937416c65507d266" + }, + "requestInfo": { + "instanceName": "MNS-25180-L-01-dmz_direct_net_1", + "source": "VID", + "callbackUrl": "", + "suppressRollback": true, + "productFamilyId": "a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb" + }, + "relatedInstanceList": [ + { + "relatedInstance": { + "instanceId": "f70e927b-6087-4974-9ef8-c5e4d5847ca4", + "modelInfo": { + "modelType": "serviceT", + "modelId": "modelI", + "modelNameVersionId": "modelNameVersionI", + "modelName": "modleNam", + "modelVersion": "1" + } + } + } + ], + "requestParameters": { + "userParams": [ + { + "name": "someUserParam1", + "value": "someValue1" + } + ] + } + }}""" + + String jsonIncomingRequest_Missingname = + """{ "requestDetails": { + "modelInfo": { + "modelType": "networkTyp", + "modelId": "modelId", + "modelNameVersionId": "modelNameVersionId", + "modelName": "CONTRAIL_EXTERNAL", + "modelVersion": "1" + }, + "cloudConfiguration": { + "lcpCloudRegionId": "RDM2WAGPLCP", + "tenantId": "7dd5365547234ee8937416c65507d266" + }, + "requestInfo": { + "source": "VID", + "callbackUrl": "", + "suppressRollback": true, + "productFamilyId": "a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb" + }, + "relatedInstanceList": [ + { + "relatedInstance": { + "instanceId": "f70e927b-6087-4974-9ef8-c5e4d5847ca4", + "modelInfo": { + "modelType": "serviceT", + "modelId": "modelI", + "modelNameVersionId": "modelNameVersionI", + "modelName": "modleNam", + "modelVersion": "1" + } + } + } + ], + "requestParameters": { + "userParams": [] + } + }}""" + + String jsonIncomingRequest_MissingCloudRegion = + """{ "requestDetails": { + "modelInfo": { + "modelType": "networkTyp", + "modelId": "modelId", + "modelNameVersionId": "modelNameVersionId", + "modelName": "CONTRAIL_EXTERNAL", + "modelVersion": "1" + }, + "cloudConfiguration": { + "tenantId": "7dd5365547234ee8937416c65507d266" + }, + "requestInfo": { + "instanceName": "MNS-25180-L-01-dmz_direct_net_1", + "source": "VID", + "callbackUrl": "", + "suppressRollback": true, + "productFamilyId": "a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb" + }, + "relatedInstanceList": [ + { + "relatedInstance": { + "instanceId": "f70e927b-6087-4974-9ef8-c5e4d5847ca4", + "modelInfo": { + "modelType": "serviceT", + "modelId": "modelI", + "modelNameVersionId": "modelNameVersionI", + "modelName": "modleNam", + "modelVersion": "1" + } + } + } + ], + "requestParameters": { + "userParams": [] + } + }}""" + + + + String expectedNetworkRequestMissingNetworkId = + """ + + 88f65519-9a38-4c4b-8445-9eb4a5a5af56 + UPDATE + VID + f70e927b-6087-4974-9ef8-c5e4d5847ca4 + + + + MNS-25180-L-01-dmz_direct_net_1 + CONTRAIL_EXTERNAL + RDM2WAGPLCP + 7dd5365547234ee8937416c65507d266 + a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb + true + + + someValue1 + + +""" + + +String expectedNetworkRequestMissingCloudRegion = +""" + + 88f65519-9a38-4c4b-8445-9eb4a5a5af56 + UPDATE + PORTAL + + + HSL_direct_net_2 + CONTRAIL_EXTERNAL + a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb + + e81d842d3e8b45c5a59f57cd76af3aaf + + + 1 + +""" + + // vnfRESTRequest + String networkRESTRequest = +""" + + + + 1ef47428-cade-45bd-a103-0751e8b2deb0 + UPDATE + PORTAL + + + MNS-25180-L-01-dmz_direct_net_1 + CONTRAIL_EXTERNAL + a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb + RDM2WAGPLCP + 7dd5365547234ee8937416c65507d266 + dvs-slcp3-01 + 3008 + + + 1 + 0 + + + + """ + + String networkInputsMissingName = + """ + + CONTRAIL_EXTERNAL + a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb + RDM2WAGPLCP + e81d842d3e8b45c5a59f57cd76af3aaf + """ + +String networkInputsMissingCloudRegion = +""" + HSL_direct_net_2 + CONTRAIL_EXTERNAL + a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb + + e81d842d3e8b45c5a59f57cd76af3aaf +""" + + String expectedUpdateNetworkInstanceInfraRequest = + """ + + + 1ef47428-cade-45bd-a103-0751e8b2deb0 + UPDATE + PORTAL + + + MNS-25180-L-01-dmz_direct_net_1 + CONTRAIL_EXTERNAL + a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb + RDM2WAGPLCP + 7dd5365547234ee8937416c65507d266 + dvs-slcp3-01 + 3008 + + + 1 + 0 + + +""" + + String expectedUpdateNetworkInstanceInfraRequest_Output = + """ + + + 1ef47428-cade-45bd-a103-0751e8b2deb0 + UPDATE + PORTAL + + + MNS-25180-L-01-dmz_direct_net_1 + CONTRAIL_EXTERNAL + a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb + RDM2WAGPLCP + 7dd5365547234ee8937416c65507d266 + + + MNS-25180-L-01-dmz_direct_net_1 + bdc5efe8-404a-409b-85f6-0dcc9eebae30 + + + 1 + 0 + + +""" + + // expectedNetworkRequest + String expectedNetworkRequest = + """ + + UPDATE + VID + f70e927b-6087-4974-9ef8-c5e4d5847ca4 + + + 49c86598-f766-46f8-84f8-8d1c1b10f9b4 + MNS-25180-L-01-dmz_direct_net_1 + CONTRAIL_EXTERNAL + RDM2WAGPLCP + 7dd5365547234ee8937416c65507d266 + a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb + true + + + true + a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb + true + true + 10.10.125.1 + +""" + +String expectedNetworkInputs = +""" + + MNS-25180-L-01-dmz_direct_net_1 + CONTRAIL_EXTERNAL + RDM2WAGPLCP + 7dd5365547234ee8937416c65507d266 + a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb + true +""" + + + String NetworkRequest_noPhysicalName = + """ + + 1ef47428-cade-45bd-a103-0751e8b2deb0 + UPDATE + PORTAL + + + MNS-25180-L-01-dmz_direct_net_1 + CONTRAIL_EXTERNAL + a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb + RDM2WAGPLCP + 7dd5365547234ee8937416c65507d266 + 3008 + + + + true + a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb + true + true + 10.10.125.1 + + +""" + + String vnfRequestFakeRegion = + """ + + 1ef47428-cade-45bd-a103-0751e8b2deb0 + UPDATE + PORTAL + + + MNS-25180-L-01-dmz_direct_net_1 + CONTRAIL_EXTERNAL + a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb + MDTWNJ21 + 7dd5365547234ee8937416c65507d266 + + + 1 + 0 + +""" + + // expectedNetworkRequest + String expectedNetworkRequest_Outputs = + """ + + 1ef47428-cade-45bd-a103-0751e8b2deb0 + UPDATE + PORTAL + + + MNS-25180-L-01-dmz_direct_net_1 + CONTRAIL_EXTERNAL + a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb + RDM2WAGPLCP + 7dd5365547234ee8937416c65507d266 + + + MNS-25180-L-01-dmz_direct_net_1 + bdc5efe8-404a-409b-85f6-0dcc9eebae30 + + + 1 + 0 + +""" + + + // expectedNetworkRequest + String networkInputs_404 = + """ + myOwn_Network + CONTRAIL_EXTERNAL + a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb + RDM2WAGPLCP + e81d842d3e8b45c5a59f57cd76af3aaf + """ + + String networkInputs = + """ + bdc5efe8-404a-409b-85f6-0dcc9eebae30 + MNS-25180-L-01-dmz_direct_net_1 + CONTRAIL_EXTERNAL + a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb + RDM2WAGPLCP + e81d842d3e8b45c5a59f57cd76af3aaf +""" + + String networkOutputs = + """ + 49c86598-f766-46f8-84f8-8d1c1b10f9b4 + MNS-25180-L-01-dmz_direct_net_1 + """ + + String queryAAIResponse = + """ + + + + + + + + + + + + bdc5efe8-404a-409b-85f6-0dcc9eebae30 + HSL_direct_net_2 + CONTRAIL_EXTERNAL + dmz_direct + contrail + a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb + 0 + pending-delete + + + 57e9a1ff-d14f-4071-a828-b19ae98eb2fc + 107.239.52.1 + 107.239.52.0 + 24 + 4 + pending-delete + true + + + + + + vpn-binding + https://aai-app-e2e.test.com:8443/aai/v8/network/vpn-bindings/vpn-binding/85f015d0-2e32-4c30-96d2-87a1a27f8017/ + + vpn-binding.vpn-id + 85f015d0-2e32-4c30-96d2-87a1a27f8017 + + + + vpn-binding + https://aai-app-e2e.test.com:8443/aai/v8/network/vpn-bindings/vpn-binding/c980a6ef-3b88-49f0-9751-dbad8608d0a6/ + + vpn-binding.vpn-id + c980a6ef-3b88-49f0-9751-dbad8608d0a6 + + + + tenant + https://aai-app-e2e.test.com:8443/aai/v8/cloud-infrastructure/tenants/tenant/7dd5365547234ee8937416c65507d266/ + + tenant.tenant-id + 7dd5365547234ee8937416c65507d266 + + + + + +""" + + String queryIdAIIResponse = + """ + + + + + + + + + + + + 49c86598-f766-46f8-84f8-8d1c1b10f9b4 + MNS-25180-L-01-dmz_direct_net_1 + CONTRAIL_EXTERNAL + dmz_direct + contrail + a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb + 0 + l3-version + pending-delete + ST_2Bindings_6006/55288ef0-595c-47d3-819e-cf93aaac6326 + networkName + false + true + false + + + 57e9a1ff-d14f-4071-a828-b19ae98eb2fc + 107.239.52.1 + 107.239.52.0 + 24 + 4 + pending-delete + true + subnetName + + + + 57e9a1ff-d14f-4071-a828-b19ae98eb2fc + 107.239.52.1 + 107.239.52.0 + 24 + 4 + pending-delete + true + subnetName + + + + + 414 + 4132176 + + + 415 + 4132176 + + + + inner + ctag-version + + + tenant + https://aai-ext1.test.com:8443/aai/v8/cloud-infrastructure/tenants/tenant/897deadc2b954a6bac6d3c197fb3525e/ + + tenant.tenant-id + 897deadc2b954a6bac6d3c197fb3525e + + + tenant.tenant-name + MSOTest1 + + + + vpn-binding + https://aai-ext1.test.com:8443/aai/v8/network/vpn-bindings/vpn-binding/a290b841-f672-44dd-b9cd-6f8c20d7d8c8/ + + vpn-binding.vpn-id + a290b841-f672-44dd-b9cd-6f8c20d7d8c8 + + + vpn-binding.vpn-name + oam_protected_net_6_MTN5_msotest2 + + + + vpn-binding + https://aai-ext1.test.com:8443/aai/v8/network/vpn-bindings/vpn-binding/24a4b507-853a-4a38-99aa-05fcc54be24d/ + + vpn-binding.vpn-id + 24a4b507-853a-4a38-99aa-05fcc54be24d + + + vpn-binding.vpn-name + oam_protected_net_6_MTN5_msotest1 + + + + + + + + vpn-binding + https://aai-app-e2e.test.com:8443/aai/v8/network/vpn-bindings/vpn-binding/85f015d0-2e32-4c30-96d2-87a1a27f8017/ + + vpn-binding.vpn-id + 85f015d0-2e32-4c30-96d2-87a1a27f8017 + + + + vpn-binding + https://aai-app-e2e.test.com:8443/aai/v8/network/vpn-bindings/vpn-binding/c980a6ef-3b88-49f0-9751-dbad8608d0a6/ + + vpn-binding.vpn-id + c980a6ef-3b88-49f0-9751-dbad8608d0a6 + + + + tenant + https://aai-app-e2e.test.com:8443/aai/v8/cloud-infrastructure/tenants/tenant/7dd5365547234ee8937416c65507d266/ + + tenant.tenant-id + 7dd5365547234ee8937416c65507d266 + + + + network-policy + https://aai-app-e2e.test.com:8443/aai/v8/network/network-policies/network-policy/cee6d136-e378-4678-a024-2cd15f0ee0cg + + network-policy.network-policy-id + cee6d136-e378-4678-a024-2cd15f0ee0cg + + + + route-table-reference + https://aai-app-e2e.test.com:8443/aai/v8/network/route-table-references/route-table-reference/refFQDN1 + + route-table-reference.route-table-reference-id + cee6d136-e378-4678-a024-2cd15f0ee0hi + + + + route-table-reference + https://aai-app-e2e.test.com:8443/aai/v8/network/route-table-references/route-table-reference/refFQDN2 + + route-table-reference.route-table-reference-id + cee6d136-e378-4678-a024-2cd15f0ee0hi + + + + + +""" + + String queryIdAIIResponseTestScenario01 = + """ + + 4da55fe4-7a9e-478c-a434-8a98d62265ab + GN_EVPN_direct_net_0_ST1 + CONTRAIL30_BASIC + GN_EVPN_direct + contrail + false + 9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb + 0 + 1465398611 + pending-delete + networkName + false + true + false + + + cb1a7b47-5428-44c9-89c2-8b17541c3228 + 108.239.40.1 + 108.239.40.0 + 28 + 4 + pending-delete + true + 108.239.40.0 + 108.239.40.0 + 1465398611 + subnetName + + + + e2cc7c14-90f0-4205-840d-b4e07f04e621 + 2606:ae00:2e01:604::1 + 2606:ae00:2e01:604:: + 64 + 6 + pending-delete + true + 2606:ae00:2e01:604:: + 2606:ae00:2e01:604:: + 1465398611 + subnetName + + + + + + 416 + 4132176 + + + + cloud-region + https://mtanjv9aaas03.aic.cip.com:8443/aai/v8/cloud-infrastructure/cloud-regions/cloud-region/att-aic/AAIAIC25/ + + + cloud-region.cloud-region-id + AAIAIC25 + + + cloud-region.cloud-owner + att-aic + + + cloud-region.owner-defined-type + + + + + tenant + https://mtanjv9aaas03.aic.cip.com:8443/aai/v8/cloud-infrastructure/cloud-regions/cloud-region/att-aic/AAIAIC25/tenants/tenant/4ae1d3446a4c48b2bec44b6cfba06d68/ + + tenant.tenant-id + 4ae1d3446a4c48b2bec44b6cfba06d68 + + + + cloud-region.cloud-owner + att-aic + + + cloud-region.cloud-region-id + AAIAIC25 + + + tenant.tenant-name + Ruchira Contrail 3.0 test + + + + vpn-binding + https://mtanjv9aaas03.aic.cip.com:8443/aai/v8/network/vpn-bindings/vpn-binding/85f015d0-2e32-4c30-96d2-87a1a27f8017/ + + vpn-binding.vpn-id + 9a7b327d9-287aa00-82c4b0-100001 + + + vpn-binding.vpn-name + GN_EVPN_direct_net_0_ST1 + + + + route-table-reference + + route-table-reference.route-table-reference-id + cee6d136-e378-4678-a024-2cd15f0ee0hi + + + +""" + + String queryIdAIIResponseVpnNotPresent = + """ + + + + + + + + + + + + 49c86598-f766-46f8-84f8-8d1c1b10f9b4 + MNS-25180-L-01-dmz_direct_net_1 + CONTRAIL_EXTERNAL + dmz_direct + contrail + a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb + 0 + pending-delete + networkName + false + true + false + + + 57e9a1ff-d14f-4071-a828-b19ae98eb2fc + 107.239.52.1 + 107.239.52.0 + 24 + 4 + pending-delete + true + subnetName + + + + + + +""" + + String queryNameAIIResponse = + """ + + + + + + + + + + + + 49c86598-f766-46f8-84f8-8d1c1b10f9b4 + MNS-25180-L-01-dmz_direct_net_1 + CONTRAIL_EXTERNAL + dmz_direct + contrail + a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb + 0 + pending-delete + + + 57e9a1ff-d14f-4071-a828-b19ae98eb2fc + 107.239.52.1 + 107.239.52.0 + 24 + 4 + pending-delete + true + + + + + + vpn-binding + https://aai-app-e2e.test.com:8443/aai/v8/network/vpn-bindings/vpn-binding/85f015d0-2e32-4c30-96d2-87a1a27f8017/ + + vpn-binding.vpn-id + 85f015d0-2e32-4c30-96d2-87a1a27f8017 + + + + vpn-binding + https://aai-app-e2e.test.com:8443/aai/v8/network/vpn-bindings/vpn-binding/c980a6ef-3b88-49f0-9751-dbad8608d0a6/ + + vpn-binding.vpn-id + c980a6ef-3b88-49f0-9751-dbad8608d0a6 + + + + tenant + https://aai-app-e2e.test.com:8443/aai/v8/cloud-infrastructure/tenants/tenant/7dd5365547234ee8937416c65507d266/ + + tenant.tenant-id + 7dd5365547234ee8937416c65507d266 + + + + + + """ + + String queryNameAIIResponseVpnNotPresent = + """ + + + + + + + + + + + + + + +""" + + String queryVpnBindingAAIResponse = + """ + + + + + + + + + + + + 9a7b327d9-287aa00-82c4b0-105757 + GN_EVPN_Test + 13979:105757 + + + l3-network + https://aai-app-e2e.test.com:8443/aai/v3/network/l3-networks/l3-network/689ec39e-c5fc-4462-8db2-4f760763ad28/ + + l3-network.network-id + 689ec39e-c5fc-4462-8db2-4f760763ad28 + + + + l3-network + https://aai-app-e2e.test.com:8443/aai/v3/network/l3-networks/l3-network/1a49396b-19b3-40a4-8792-aa2fbd0f0704/ + + l3-network.network-id + 1a49396b-19b3-40a4-8792-aa2fbd0f0704 + + + + l3-network + https://aai-app-e2e.test.com:8443/aai/v3/network/l3-networks/l3-network/774f3329-3c83-4771-86c7-9e6207cd50fd/ + + l3-network.network-id + 774f3329-3c83-4771-86c7-9e6207cd50fd + + + + + +""" + + String updateDBRequest_Active = + """ + + + + 88f65519-9a38-4c4b-8445-9eb4a5a5af56 + BPMN + Network MNS-25180-L-01-dmz_direct_net_1 already exists. Silent success. + + COMPLETED + 100 + <network-id>49c86598-f766-46f8-84f8-8d1c1b10f9b4</network-id><network-name>MNS-25180-L-01-dmz_direct_net_1</network-names> + 49c86598-f766-46f8-84f8-8d1c1b10f9b4 + + +""" + + String updateDBRequest = + """ + + + + 88f65519-9a38-4c4b-8445-9eb4a5a5af56 + BPMN + Network successfully updated. + + COMPLETED + 100 + <network-id></network-id><network-name></network-names> + + + +""" + + String updateDBRequestError = + """ + + + + 88f65519-9a38-4c4b-8445-9eb4a5a5af56 + BPMN + Received error from SDN-C: No availability zone available + + FAILED + <network-id></network-id><network-name></network-names> + + + """ + + String updateDBRequestError01 = + """ + + + + 88f65519-9a38-4c4b-8445-9eb4a5a5af56 + BPMN + Received error unexpectedly from SDN-C. + + FAILED + <network-id></network-id><network-name></network-names> + + + """ + + String updateDBRequest_Outputs = + """ + + + + 88f65519-9a38-4c4b-8445-9eb4a5a5af56 + BPMN + Network successfully updated. + + COMPLETED + 100 + <network-id>49c86598-f766-46f8-84f8-8d1c1b10f9b4</network-id><network-name>MNS-25180-L-01-dmz_direct_net_1</network-names> + 49c86598-f766-46f8-84f8-8d1c1b10f9b4 + + +""" + + String updateNetworkRequest = + """ + RDM2WAGPLCP + 7dd5365547234ee8937416c65507d266 + 49c86598-f766-46f8-84f8-8d1c1b10f9b4 + ST_2Bindings_6006/55288ef0-595c-47d3-819e-cf93aaac6326 + MNS-25180-L-01-dmz_direct_net_1 + CONTRAIL_EXTERNAL + + + CONTRAIL + + networkName + 414,415 + + + true + false + 13979:105757 + 13979:105757 + GN_EVPN_Test + refFQDN1 + refFQDN2 + + true + true + false + + true + a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb + true + true + 10.10.125.1 + + + 88f65519-9a38-4c4b-8445-9eb4a5a5af56 + f70e927b-6087-4974-9ef8-c5e4d5847ca4 + + messageId_generated + +""" + + + String updateNetworkRequest_noPhysicalName = + """ + RDM2WAGPLCP + 7dd5365547234ee8937416c65507d266 + 49c86598-f766-46f8-84f8-8d1c1b10f9b4 + ST_2Bindings_6006/55288ef0-595c-47d3-819e-cf93aaac6326 + MNS-25180-L-01-dmz_direct_net_1 + CONTRAIL_EXTERNAL + + + CONTRAIL + + networkName + 414,415 + + + true + false + 13979:105757 + 13979:105757 + GN_EVPN_Test + + true + true + false + + true + a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb + true + true + 10.10.125.1 + + + 88f65519-9a38-4c4b-8445-9eb4a5a5af56 + null + + messageId_generated + +""" + + String updateNetworkResponseREST = + """ + MNS-25180-L-01-dmz_direct_net_1/2c88a3a9-69b9-43a7-ada6-1aca577c3641 + c4f4e878-cde0-4b15-ae9a-bda857759cea + default-domain:MSOTest:GN_EVPN_direct_net_0_ST1 + + + + 57e9a1ff-d14f-4071-a828-b19ae98eb2fc + bd8e87c6-f4e2-41b8-b0bc-9596aa00cd73 + + + 57e9a1ff-d14f-4071-a828-b19ae98eb2fc + bd8e87c6-f4e2-41b8-b0bc-9596aa00cd73 + + + + MNS-25180-L-01-dmz_direct_net_1/2c88a3a9-69b9-43a7-ada6-1aca577c3641 + c4f4e878-cde0-4b15-ae9a-bda857759cea + + CONTRAIL_EXTERNAL + true + 7dd5365547234ee8937416c65507d266 + RDM2WAGPLCP + + 1ef47428-cade-45bd-a103-0751e8b2deb0 + + + + messageId_generated +""" + + String updateRollbackNetworkRequest = + """ + + MNS-25180-L-01-dmz_direct_net_1/2c88a3a9-69b9-43a7-ada6-1aca577c3641 + c4f4e878-cde0-4b15-ae9a-bda857759cea + + CONTRAIL_EXTERNAL + true + 7dd5365547234ee8937416c65507d266 + RDM2WAGPLCP + + 1ef47428-cade-45bd-a103-0751e8b2deb0 + + + +""" + + String updateNetworkResponse = + """ + MNS-25180-L-01-dmz_direct_net_1/2c88a3a9-69b9-43a7-ada6-1aca577c3641 + c4f4e878-cde0-4b15-ae9a-bda857759cea + MNS-25180-L-01-dmz_direct_net_1/2c88a3a9-69b9-43a7-ada6-1aca577c3641 + default-domain:MSOTest:GN_EVPN_direct_net_0_ST1 + + + 57e9a1ff-d14f-4071-a828-b19ae98eb2fc + bd8e87c6-f4e2-41b8-b0bc-9596aa00cd73 + + + + RDM2WAGPLCP + + 1ef47428-cade-45bd-a103-0751e8b2deb0 + + + true + MNS-25180-L-01-dmz_direct_net_1/2c88a3a9-69b9-43a7-ada6-1aca577c3641 + CONTRAIL_EXTERNAL + false + c4f4e878-cde0-4b15-ae9a-bda857759cea + 7dd5365547234ee8937416c65507d266 + +""" + + String updateContrailAAIPayloadRequest = + """ + 49c86598-f766-46f8-84f8-8d1c1b10f9b4 + MNS-25180-L-01-dmz_direct_net_1 + CONTRAIL_EXTERNAL + dmz_direct + contrail + c4f4e878-cde0-4b15-ae9a-bda857759cea + a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb + 0 + l3-version + active + ST_2Bindings_6006/55288ef0-595c-47d3-819e-cf93aaac6326 + default-domain:MSOTest:GN_EVPN_direct_net_0_ST1 + networkName + false + true + false + + + 57e9a1ff-d14f-4071-a828-b19ae98eb2fc + bd8e87c6-f4e2-41b8-b0bc-9596aa00cd73 + 107.239.52.1 + 107.239.52.0 + 24 + 4 + active + true + subnetName + + + 57e9a1ff-d14f-4071-a828-b19ae98eb2fc + bd8e87c6-f4e2-41b8-b0bc-9596aa00cd73 + 107.239.52.1 + 107.239.52.0 + 24 + 4 + active + true + subnetName + + + + 414 + + + 415 + + + + inner + ctag-version + + + tenant + https://aai-ext1.test.com:8443/aai/v8/cloud-infrastructure/tenants/tenant/897deadc2b954a6bac6d3c197fb3525e/ + + tenant.tenant-id + 897deadc2b954a6bac6d3c197fb3525e + + + tenant.tenant-name + MSOTest1 + + + + vpn-binding + https://aai-ext1.test.com:8443/aai/v8/network/vpn-bindings/vpn-binding/a290b841-f672-44dd-b9cd-6f8c20d7d8c8/ + + vpn-binding.vpn-id + a290b841-f672-44dd-b9cd-6f8c20d7d8c8 + + + vpn-binding.vpn-name + oam_protected_net_6_MTN5_msotest2 + + + + vpn-binding + https://aai-ext1.test.com:8443/aai/v8/network/vpn-bindings/vpn-binding/24a4b507-853a-4a38-99aa-05fcc54be24d/ + + vpn-binding.vpn-id + 24a4b507-853a-4a38-99aa-05fcc54be24d + + + vpn-binding.vpn-name + oam_protected_net_6_MTN5_msotest1 + + + + + + + + vpn-binding + https://aai-app-e2e.test.com:8443/aai/v8/network/vpn-bindings/vpn-binding/85f015d0-2e32-4c30-96d2-87a1a27f8017/ + + vpn-binding.vpn-id + 85f015d0-2e32-4c30-96d2-87a1a27f8017 + + + + vpn-binding + https://aai-app-e2e.test.com:8443/aai/v8/network/vpn-bindings/vpn-binding/c980a6ef-3b88-49f0-9751-dbad8608d0a6/ + + vpn-binding.vpn-id + c980a6ef-3b88-49f0-9751-dbad8608d0a6 + + + + tenant + https://aai-app-e2e.test.com:8443/aai/v8/cloud-infrastructure/tenants/tenant/7dd5365547234ee8937416c65507d266/ + + tenant.tenant-id + 7dd5365547234ee8937416c65507d266 + + + + network-policy + https://aai-app-e2e.test.com:8443/aai/v8/network/network-policies/network-policy/cee6d136-e378-4678-a024-2cd15f0ee0cg + + network-policy.network-policy-id + cee6d136-e378-4678-a024-2cd15f0ee0cg + + + + route-table-reference + https://aai-app-e2e.test.com:8443/aai/v8/network/route-table-references/route-table-reference/refFQDN1 + + route-table-reference.route-table-reference-id + cee6d136-e378-4678-a024-2cd15f0ee0hi + + + + route-table-reference + https://aai-app-e2e.test.com:8443/aai/v8/network/route-table-references/route-table-reference/refFQDN2 + + route-table-reference.route-table-reference-id + cee6d136-e378-4678-a024-2cd15f0ee0hi + + + +""" + + String updateContrailAAIResponse = + """ + + + + + + + + +""" + + String updateNetworkErrorResponse = + """ + 680bd458-5ec1-4a16-b77c-509022e53450INTERNAL + 400 Bad Request: The server could not comply with the request since it is either malformed or otherwise incorrect., error.type=StackValidationFailed, error.message=Property error: : resources.network.properties: : Unknown Property network_ipam_refs_data + true + """ + + + String networkException500 = + """soap:VersionMismatch"http://org.openecomp.mso/network", the namespace on the "updateNetworkContrail" element, is not a valid SOAP version.""" + + String aaiResponse = + """ + + + + + + + + + + + + bdc5efe8-404a-409b-85f6-0dcc9eebae30 + HSL_direct_net_2 + CONTRAIL_BASIC + HSL_direct + contrail + 8bbd3edf-b835-4610-96a2-a5cafa029042 + a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb + active + HSL_direct_net_2/57594a56-1c92-4a38-9caa-641c1fa3d4b6 + + + ea5f2a2c-604f-47ff-a9c5-253ee4f0ef0a + 5a77fdc2-7789-4649-a1b9-6eaf1db1813a + 172.16.34.1 + 172.16.34.0 + 28 + 4 + active + true + + + + + + tenant + https://aai-app-e2e.test.com:8443/aai/v3/cloud-infrastructure/tenants/tenant/e81d842d3e8b45c5a59f57cd76af3aaf/ + + tenant.tenant-id + e81d842d3e8b45c5a59f57cd76af3aaf + + + + + + """ + + String changeAssignSDNCRequest = + """ + + 88f65519-9a38-4c4b-8445-9eb4a5a5af56 + f70e927b-6087-4974-9ef8-c5e4d5847ca4 + changeassign + network-topology-operation + sdncCallback + + + + 88f65519-9a38-4c4b-8445-9eb4a5a5af56 + NetworkActivateRequest + VID + + + + + + a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb + MSO-dev-service-type + f70e927b-6087-4974-9ef8-c5e4d5847ca4 + MSO_1610_dev + + + 49c86598-f766-46f8-84f8-8d1c1b10f9b4 + CONTRAIL_EXTERNAL + MNS-25180-L-01-dmz_direct_net_1 + 7dd5365547234ee8937416c65507d266 + RDM2WAGPLCP + + +""" + +String assignResponse = +""" 006927ca-f5a3-47fd-880c-dfcbcd81a093 200 OK 200006927ca-f5a3-47fd-880c-dfcbcd81a093Ynotsurewecarea9a77d5a-123e-4ca2-9eb9-0b015d2ee0fbGN_EVPN_direct_net_0_ST_noGW8abc633a-810b-4ca5-8b3a-09511d13a2ce """ + + String sdncRollbackRequest = + """ + + 88f65519-9a38-4c4b-8445-9eb4a5a5af56 + f70e927b-6087-4974-9ef8-c5e4d5847ca4 + rollback + network-topology-operation + sdncCallback + + + + 88f65519-9a38-4c4b-8445-9eb4a5a5af56 + NetworkActivateRequest + VID + + + + + + a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb + MSO-dev-service-type + f70e927b-6087-4974-9ef8-c5e4d5847ca4 + MSO_1610_dev + + + 8abc633a-810b-4ca5-8b3a-09511d13a2ce + CONTRAIL_EXTERNAL + MNS-25180-L-01-dmz_direct_net_1 + 7dd5365547234ee8937416c65507d266 + RDM2WAGPLCP + + +""" + + String sdncAdapterWorkflowResponse = + """ + + + 745b1b50-e39e-4685-9cc8-c71f0bde8bf0 + 200 + OK + + <output xmlns="org:openecomp:sdnctl:vnf"><svc-request-id>00703dc8-71ff-442d-a4a8-3adc5beef6a9</svc-request-id><response-code>200</response-code><ack-final-indicator>Y</ack-final-indicator><network-information><network-id>49c86598-f766-46f8-84f8-8d1c1b10f9b4</network-id></network-information><service-information><service-type>a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb</service-type><service-instance-id>MNS-25180-L-01-dmz_direct_net_1</service-instance-id><subscriber-name>notsurewecare</subscriber-name></service-information></output> + +""" + + + String sdncAdapterWorkflowResponse_Error = + """ + + + + 400 + Error writing to l3-netework + Y + c79240d8-34b5-4853-af69-2021928dba00 + + + +""" + + String expected_sdncAdapterWorkflowResponse_Error = + """ + + + + 400 + Error writing to l3-netework + Y + c79240d8-34b5-4853-af69-2021928dba00 + + + +""" + + String sdncAdapterWorkflowFormattedResponse = + """ + + + 00703dc8-71ff-442d-a4a8-3adc5beef6a9 + 200 + Y + + 49c86598-f766-46f8-84f8-8d1c1b10f9b4 + + + a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb + f70e927b-6087-4974-9ef8-c5e4d5847ca4 + notsurewecare + + + +""" + + String falloutHandlerRequest = + """ + + b69c9054-da09-4a2c-adf5-51042b62bfac + UPDATE + PORTAL + + + Received error from SDN-C: No availability zone available. + 5300 + + """ + + String falloutHandlerRequestObject = + """ + + b69c9054-da09-4a2c-adf5-51042b62bfac + UPDATE + VID + + + Received error from SDN-C: No availability zone available + 7000 + + """ + + + String falloutHandlerRequest_Scenario01 = + """ + + b69c9054-da09-4a2c-adf5-51042b62bfac + UPDATE + VID + + + Unexpected Response from AAI - 400 + 7020 + + """ + + String completeMsoProcessRequest = + """ + + 88f65519-9a38-4c4b-8445-9eb4a5a5af56 + UPDATE + PORTAL + + BPMN Network action: UPDATE +""" + +// - - - - - - - - + + + @Before + public void init() + { + MockitoAnnotations.initMocks(this) + + } + + public void initializeVariables (Execution mockExecution) { + + verify(mockExecution).setVariable("UPDNETI_messageId", "") + verify(mockExecution).setVariable("BasicAuthHeaderValuePO", "") + verify(mockExecution).setVariable("BasicAuthHeaderValueSDNC", "") + verify(mockExecution).setVariable("UPDNETI_UpdateNetworkInstanceInfraJsonRequest", "") + verify(mockExecution).setVariable("UPDNETI_networkRequest", "") + verify(mockExecution).setVariable("UPDNETI_networkInputs", "") + verify(mockExecution).setVariable("UPDNETI_networkOutputs", "") + verify(mockExecution).setVariable("UPDNETI_requestId", "") + verify(mockExecution).setVariable("UPDNETI_source", "") + verify(mockExecution).setVariable("UPDNETI_networkId", "") + + verify(mockExecution).setVariable("UPDNETI_CompleteMsoProcessRequest", "") + verify(mockExecution).setVariable("UPDNETI_FalloutHandlerRequest", "") + verify(mockExecution).setVariable("UPDNETI_isSilentSuccess", false) + verify(mockExecution).setVariable("UPDNETI_isPONR", false) + + // AAI query Cloud Region + verify(mockExecution).setVariable("UPDNETI_queryCloudRegionRequest","") + verify(mockExecution).setVariable("UPDNETI_queryCloudRegionReturnCode","") + verify(mockExecution).setVariable("UPDNETI_queryCloudRegionResponse","") + verify(mockExecution).setVariable("UPDNETI_cloudRegionPo","") + verify(mockExecution).setVariable("UPDNETI_cloudRegionSdnc","") + verify(mockExecution).setVariable("UPDNETI_isCloudRegionGood", false) + + // AAI query Id + verify(mockExecution).setVariable("UPDNETI_queryIdAAIRequest","") + verify(mockExecution).setVariable("UPDNETI_queryIdAAIResponse", "") + verify(mockExecution).setVariable("UPDNETI_aaiIdReturnCode", "") + + // AAI query vpn binding + verify(mockExecution).setVariable("UPDNETI_queryVpnBindingAAIRequest","") + verify(mockExecution).setVariable("UPDNETI_queryVpnBindingAAIResponse", "") + verify(mockExecution).setVariable("UPDNETI_aaiQqueryVpnBindingReturnCode", "") + verify(mockExecution).setVariable("UPDNETI_vpnBindings", null) + verify(mockExecution).setVariable("UPDNETI_vpnCount", 0) + verify(mockExecution).setVariable("UPDNETI_routeCollection", "") + + // AAI query network policy + verify(mockExecution).setVariable("UPDNETI_queryNetworkPolicyAAIRequest","") + verify(mockExecution).setVariable("UPDNETI_queryNetworkPolicyAAIResponse", "") + verify(mockExecution).setVariable("UPDNETI_aaiQqueryNetworkPolicyReturnCode", "") + verify(mockExecution).setVariable("UPDNETI_networkPolicyUriList", null) + verify(mockExecution).setVariable("UPDNETI_networkPolicyCount", 0) + verify(mockExecution).setVariable("UPDNETI_networkCollection", "") + + // AAI query route table reference + verify(mockExecution).setVariable("UPDNETI_queryNetworkTableRefAAIRequest","") + verify(mockExecution).setVariable("UPDNETI_queryNetworkTableRefAAIResponse", "") + verify(mockExecution).setVariable("UPDNETI_aaiQqueryNetworkTableRefReturnCode", "") + verify(mockExecution).setVariable("UPDNETI_networkTableRefUriList", null) + verify(mockExecution).setVariable("UPDNETI_networkTableRefCount", 0) + verify(mockExecution).setVariable("UPDNETI_tableRefCollection", "") + + + // AAI requery Id + verify(mockExecution).setVariable("UPDNETI_requeryIdAAIRequest","") + verify(mockExecution).setVariable("UPDNETI_requeryIdAAIResponse", "") + verify(mockExecution).setVariable("UPDNETI_aaiRequeryIdReturnCode", "") + + // AAI update contrail + verify(mockExecution).setVariable("UPDNETI_updateContrailAAIUrlRequest","") + verify(mockExecution).setVariable("UPDNETI_updateContrailAAIPayloadRequest","") + verify(mockExecution).setVariable("UPDNETI_updateContrailAAIResponse", "") + verify(mockExecution).setVariable("UPDNETI_aaiUpdateContrailReturnCode", "") + + verify(mockExecution).setVariable("UPDNETI_updateNetworkRequest", "") + verify(mockExecution).setVariable("UPDNETI_updateNetworkResponse", "") + verify(mockExecution).setVariable("UPDNETI_rollbackNetworkRequest", "") + verify(mockExecution).setVariable("UPDNETI_rollbackNetworkResponse", "") + verify(mockExecution).setVariable("UPDNETI_networkReturnCode", "") + verify(mockExecution).setVariable("UPDNETI_rollbackNetworkReturnCode", "") + verify(mockExecution).setVariable("UPDNETI_isNetworkRollbackNeeded", false) + + verify(mockExecution).setVariable("UPDNETI_changeAssignSDNCRequest", "") + verify(mockExecution).setVariable("UPDNETI_changeAssignSDNCResponse", "") + verify(mockExecution).setVariable("UPDNETI_rollbackSDNCRequest", "") + verify(mockExecution).setVariable("UPDNETI_rollbackSDNCResponse", "") + verify(mockExecution).setVariable("UPDNETI_sdncReturnCode", "") + verify(mockExecution).setVariable("UPDNETI_rollbackSDNCReturnCode", "") + verify(mockExecution).setVariable("UPDNETI_isSdncRollbackNeeded", false) + verify(mockExecution).setVariable("UPDNETI_sdncResponseSuccess", false) + + verify(mockExecution).setVariable("UPDNETI_updateDBRequest", "") + verify(mockExecution).setVariable("UPDNETI_updateDBResponse", "") + verify(mockExecution).setVariable("UPDNETI_dbReturnCode", "") + + verify(mockExecution).setVariable("UPDNETI_isVnfBindingPresent", false) + verify(mockExecution).setVariable("UPDNETI_Success", false) + verify(mockExecution).setVariable("UPDNETI_serviceInstanceId", "") + verify(mockExecution).setVariable("GENGS_type", "service-instance") // Setting for Generic Sub Flow use + + + } + + @Test + //@Ignore + public void preProcessRequest_NetworkRequest() { + + println "************ preProcessRequest_Payload ************* " + ExecutionEntity mockExecution = setupMock() + // Initialize prerequisite variables + when(mockExecution.getVariable("mso-request-id")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56") + when(mockExecution.getVariable("requestId")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56") + when(mockExecution.getVariable("isBaseVfModule")).thenReturn(true) + when(mockExecution.getVariable("recipeTimeout")).thenReturn(0) + when(mockExecution.getVariable("requestAction")).thenReturn("UPDATE") + when(mockExecution.getVariable("serviceInstanceId")).thenReturn("f70e927b-6087-4974-9ef8-c5e4d5847ca4") + when(mockExecution.getVariable("vnfId")).thenReturn("") + when(mockExecution.getVariable("volumeGroupId")).thenReturn("") + when(mockExecution.getVariable("networkId")).thenReturn("49c86598-f766-46f8-84f8-8d1c1b10f9b4") + when(mockExecution.getVariable("serviceType")).thenReturn("MOG") + when(mockExecution.getVariable("networkType")).thenReturn("modelName") + when(mockExecution.getVariable("bpmnRequest")).thenReturn(jsonIncomingRequest) + + when(mockExecution.getVariable("UPDNETI_messageId")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56") + when(mockExecution.getVariable("URN_mso_adapters_po_auth")).thenReturn("3141634BF7E070AA289CF2892C986C0B") + when(mockExecution.getVariable("URN_mso_adapters_db_auth")).thenReturn("757A94191D685FD2092AC1490730A4FC") + when(mockExecution.getVariable("URN_mso_msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7") + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("URN_mso_rollback")).thenReturn("true") + + // preProcessRequest(Execution execution) + UpdateNetworkInstanceInfra UpdateNetworkInstanceInfra = new UpdateNetworkInstanceInfra() + UpdateNetworkInstanceInfra.preProcessRequest(mockExecution) + + // check the sequence of variable invocation + //MockitoDebuggerImpl preDebugger = new MockitoDebuggerImpl() + //preDebugger.printInvocations(mockExecution) + + verify(mockExecution).getVariable("isDebugLogEnabled") + verify(mockExecution).setVariable("prefix", "UPDNETI_") + + //verify variable initialization + initializeVariables(mockExecution) + + // Authentications + verify(mockExecution).setVariable("BasicAuthHeaderValuePO", "Basic cGFzc3dvcmQ=") + verify(mockExecution).setVariable("BasicAuthHeaderValueSDNC", "Basic cGFzc3dvcmQ=") + + verify(mockExecution).setVariable("UPDNETI_UpdateNetworkInstanceInfraJsonRequest", jsonIncomingRequest) + //verify(mockExecution).setVariable("UPDNETI_networkRequest", expectedNetworkRequest) + //verify(mockExecution).setVariable("UPDNETI_networkInputs", expectedNetworkInputs) + //verify(mockExecution, atLeast(3)).setVariable("UPDNETI_networkOutputs", "") + + //verify(mockExecution).setVariable("UPDNETI_requestId", "88f65519-9a38-4c4b-8445-9eb4a5a5af56") + //verify(mockExecution).setVariable("UPDNETI_source", "VID") + //verify(mockExecution).setVariable("UPDNETI_messageId", "88f65519-9a38-4c4b-8445-9eb4a5a5af56") + //verify(mockExecution, atLeast(1)).setVariable("GENGS_type", "service-instance") + + } + + + @Test + //@Ignore + public void preProcessRequest_MissingNetworkId() { + + println "************ preProcessRequest_MissingName() ************* " + + WorkflowException missingNameWorkflowException = new WorkflowException("UpdateNetworkInstanceInfra", 2500, "Variable 'network-id' value/element is missing.") + + ExecutionEntity mockExecution = setupMock() + // Initialize prerequisite variables + when(mockExecution.getVariable("mso-request-id")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56") + when(mockExecution.getVariable("requestId")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56") + when(mockExecution.getVariable("isBaseVfModule")).thenReturn(true) + when(mockExecution.getVariable("recipeTimeout")).thenReturn(0) + when(mockExecution.getVariable("requestAction")).thenReturn("UPDATE") + when(mockExecution.getVariable("serviceInstanceId")).thenReturn("f70e927b-6087-4974-9ef8-c5e4d5847ca4") + when(mockExecution.getVariable("vnfId")).thenReturn("") + when(mockExecution.getVariable("volumeGroupId")).thenReturn("") + //when(mockExecution.getVariable("networkId")).thenReturn("49c86598-f766-46f8-84f8-8d1c1b10f9b4") + when(mockExecution.getVariable("serviceType")).thenReturn("MOG") + when(mockExecution.getVariable("networkType")).thenReturn("modelName") + when(mockExecution.getVariable("bpmnRequest")).thenReturn(jsonIncomingRequest) + + when(mockExecution.getVariable("UPDNETI_messageId")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56") + when(mockExecution.getVariable("URN_mso_adapters_po_auth")).thenReturn("3141634BF7E070AA289CF2892C986C0B") + when(mockExecution.getVariable("URN_mso_adapters_db_auth")).thenReturn("757A94191D685FD2092AC1490730A4FC") + when(mockExecution.getVariable("URN_mso_msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7") + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("URN_mso_rollback")).thenReturn("true") + + // preProcessRequest(Execution execution) + UpdateNetworkInstanceInfra UpdateNetworkInstanceInfra = new UpdateNetworkInstanceInfra() + try { + UpdateNetworkInstanceInfra.preProcessRequest(mockExecution) + } catch (Exception ex) { + println " Test End - Handle catch-throw BpmnError()! " + } + + // check the sequence of variable invocation + //MockitoDebuggerImpl preDebugger = new MockitoDebuggerImpl() + //preDebugger.printInvocations(mockExecution) + + verify(mockExecution, atLeast(1)).getVariable("isDebugLogEnabled") + verify(mockExecution, atLeast(1)).setVariable("prefix", "UPDNETI_") + + //verify variable initialization + initializeVariables(mockExecution) + + // Authentications + verify(mockExecution).setVariable("BasicAuthHeaderValuePO", "Basic cGFzc3dvcmQ=") + verify(mockExecution).setVariable("BasicAuthHeaderValueSDNC", "Basic cGFzc3dvcmQ=") + + verify(mockExecution).setVariable("UPDNETI_UpdateNetworkInstanceInfraJsonRequest", jsonIncomingRequest) + //verify(mockExecution, atLeast(1)).setVariable("UPDNETI_networkOutputs", networkOutputs) + //verify(mockExecution).setVariable("UPDNETI_networkRequest", expectedNetworkRequestMissingNetworkId) + //verify(mockExecution).setVariable("UPDNETI_networkInputs", expectedNetworkInputs) + + //verify(mockExecution).setVariable("UPDNETI_requestId", "88f65519-9a38-4c4b-8445-9eb4a5a5af56") + //verify(mockExecution).setVariable("UPDNETI_source", "VID") + //verify(mockExecution).setVariable("UPDNETI_messageId", "88f65519-9a38-4c4b-8445-9eb4a5a5af56") + + verify(mockExecution).setVariable(eq("WorkflowException"), refEq(missingNameWorkflowException)) + + } + + @Test + //@Ignore + public void preProcessRequest_MissingCloudRegion() { + + println "************ preProcessRequest_MissingCloudRegion() ************* " + + WorkflowException missingCloudRegionWorkflowException = new WorkflowException("UpdateNetworkInstanceInfra", 2500, "requestDetails has missing 'aic-cloud-region' value/element.") + + ExecutionEntity mockExecution = setupMock() + // Initialize prerequisite variables + when(mockExecution.getVariable("mso-request-id")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56") + when(mockExecution.getVariable("requestId")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56") + when(mockExecution.getVariable("isBaseVfModule")).thenReturn(true) + when(mockExecution.getVariable("recipeTimeout")).thenReturn(0) + when(mockExecution.getVariable("requestAction")).thenReturn("UPDATE") + when(mockExecution.getVariable("serviceInstanceId")).thenReturn("f70e927b-6087-4974-9ef8-c5e4d5847ca4") + when(mockExecution.getVariable("vnfId")).thenReturn("") + when(mockExecution.getVariable("volumeGroupId")).thenReturn("") + when(mockExecution.getVariable("networkId")).thenReturn("networkId") + when(mockExecution.getVariable("serviceType")).thenReturn("MOG") + when(mockExecution.getVariable("networkType")).thenReturn("modelName") + + when(mockExecution.getVariable("bpmnRequest")).thenReturn(jsonIncomingRequest_MissingCloudRegion) + when(mockExecution.getVariable("UPDNETI_messageId")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56") + when(mockExecution.getVariable("URN_mso_adapters_po_auth")).thenReturn("3141634BF7E070AA289CF2892C986C0B") + when(mockExecution.getVariable("URN_mso_adapters_db_auth")).thenReturn("757A94191D685FD2092AC1490730A4FC") + when(mockExecution.getVariable("URN_mso_msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7") + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("URN_mso_rollback")).thenReturn("true") + + + // preProcessRequest(Execution execution) + UpdateNetworkInstanceInfra UpdateNetworkInstanceInfra = new UpdateNetworkInstanceInfra() + try { + UpdateNetworkInstanceInfra.preProcessRequest(mockExecution) + } catch (Exception ex) { + println " Test End - Handle catch-throw BpmnError()! " + } + // check the sequence of variable invocation + //MockitoDebuggerImpl preDebugger = new MockitoDebuggerImpl() + //preDebugger.printInvocations(mockExecution) + + verify(mockExecution, atLeast(1)).getVariable("isDebugLogEnabled") + verify(mockExecution, atLeast(1)).setVariable("prefix", "UPDNETI_") + + //verify variable initialization + initializeVariables(mockExecution) + + verify(mockExecution).setVariable("UPDNETI_messageId", "88f65519-9a38-4c4b-8445-9eb4a5a5af56") + // Authentications + verify(mockExecution).setVariable("BasicAuthHeaderValuePO", "Basic cGFzc3dvcmQ=") + verify(mockExecution).setVariable("BasicAuthHeaderValueSDNC", "Basic cGFzc3dvcmQ=") + + verify(mockExecution).setVariable("UPDNETI_UpdateNetworkInstanceInfraJsonRequest", jsonIncomingRequest_MissingCloudRegion) + //verify(mockExecution).setVariable("UPDNETI_networkRequest", "") + //verify(mockExecution).setVariable("UPDNETI_networkInputs", "") + //verify(mockExecution, atLeast(1)).setVariable("UPDNETI_networkOutputs", "") + + //verify(mockExecution).setVariable("UPDNETI_requestId", "88f65519-9a38-4c4b-8445-9eb4a5a5af56") + //verify(mockExecution).setVariable("UPDNETI_source", "VID") + + verify(mockExecution).setVariable(eq("WorkflowException"), refEq(missingCloudRegionWorkflowException)) + + } + + @Test + //@Ignore + public void sendSyncResponse() { + + println "************ sendSyncResponse ************* " + + ExecutionEntity mockExecution = setupMock() + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("isAsyncProcess")).thenReturn(true) + when(mockExecution.getVariable("mso-request-id")).thenReturn("e8ebf6a0-f8ea-4dc0-8b99-fe98a87722d6") + //when(mockExecution.getVariable("serviceInstanceId")).thenReturn("f70e927b-6087-4974-9ef8-c5e4d5847ca4") + + // preProcessRequest(Execution execution) + UpdateNetworkInstanceInfra UpdateNetworkInstanceInfra = new UpdateNetworkInstanceInfra() + UpdateNetworkInstanceInfra.sendSyncResponse(mockExecution) + + verify(mockExecution).setVariable("prefix", "UPDNETI_") + verify(mockExecution).setVariable("UpdateNetworkInstanceInfraResponseCode", "202") + + + } + + @Test + //@Ignore + public void sendSyncError() { + + println "************ sendSyncError ************* " + + ExecutionEntity mockExecution = setupMock() + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("isAsyncProcess")).thenReturn(true) + when(mockExecution.getVariable("mso-request-id")).thenReturn("e8ebf6a0-f8ea-4dc0-8b99-fe98a87722d6") + //when(mockExecution.getVariable("serviceInstanceId")).thenReturn("f70e927b-6087-4974-9ef8-c5e4d5847ca4") + + + // preProcessRequest(Execution execution) + UpdateNetworkInstanceInfra UpdateNetworkInstanceInfra = new UpdateNetworkInstanceInfra() + UpdateNetworkInstanceInfra.sendSyncError(mockExecution) + + verify(mockExecution).setVariable("prefix", "UPDNETI_") + verify(mockExecution).setVariable("UpdateNetworkInstanceInfraResponseCode", "500") + + } + + + @Test + //@Ignore + public void prepareDBRequest() { + + println "************ prepareDBRequest ************* " + ExecutionEntity mockExecution = mock(ExecutionEntity.class) + // Initialize prerequisite variables + when(mockExecution.getVariable("UPDNETI_networkOutputs")).thenReturn("") + when(mockExecution.getVariable("UPDNETI_requestId")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56") + when(mockExecution.getVariable("UPDNETI_orchestrationStatus")).thenReturn("") + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("URN_mso_adapters_db_auth")).thenReturn("757A94191D685FD2092AC1490730A4FC") + when(mockExecution.getVariable("URN_mso_msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7") + + // preProcessRequest(Execution execution) + UpdateNetworkInstanceInfra UpdateNetworkInstanceInfra = new UpdateNetworkInstanceInfra() + UpdateNetworkInstanceInfra.prepareDBRequest(mockExecution) + + verify(mockExecution).setVariable("prefix", "UPDNETI_") + verify(mockExecution).setVariable("UPDNETI_updateDBRequest", updateDBRequest) + + } + + @Test + //@Ignore + public void prepareDBRequestErro_ExceptionObject() { + + println "************ prepareDBRequest ************* " + + WorkflowException sndcWorkflowException = new WorkflowException("UpdateNetworkInstanceInfra", 500, "Received error from SDN-C: No availability zone available") + + ExecutionEntity mockExecution = mock(ExecutionEntity.class) + // Initialize prerequisite variables + when(mockExecution.getVariable("UPDNETI_networkOutputs")).thenReturn("") + when(mockExecution.getVariable("UPDNETI_requestId")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56") + when(mockExecution.getVariable("UPDNETI_networkOutputs")).thenReturn("") + when(mockExecution.getVariable("UPDNETI_orchestrationStatus")).thenReturn("") + when(mockExecution.getVariable("WorkflowException")).thenReturn(sndcWorkflowException) + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("URN_mso_adapters_db_auth")).thenReturn("757A94191D685FD2092AC1490730A4FC") + when(mockExecution.getVariable("URN_mso_msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7") + + // preProcessRequest(Execution execution) + UpdateNetworkInstanceInfra UpdateNetworkInstanceInfra = new UpdateNetworkInstanceInfra() + UpdateNetworkInstanceInfra.prepareDBRequestError(mockExecution) + + verify(mockExecution).setVariable("prefix", "UPDNETI_") + verify(mockExecution).setVariable("UPDNETI_updateDBRequest", updateDBRequestError) + + } + + @Test + //@Ignore + public void prepareDBRequest_Outputs() { + + println "************ prepareDBRequest ************* " + ExecutionEntity mockExecution = mock(ExecutionEntity.class) + // Initialize prerequisite variables + when(mockExecution.getVariable("UPDNETI_networkOutputs")).thenReturn(networkOutputs) + when(mockExecution.getVariable("UPDNETI_requestId")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56") + when(mockExecution.getVariable("UPDNETI_orchestrationStatus")).thenReturn("") + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("URN_mso_adapters_db_auth")).thenReturn("757A94191D685FD2092AC1490730A4FC") + when(mockExecution.getVariable("URN_mso_msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7") + + // preProcessRequest(Execution execution) + UpdateNetworkInstanceInfra UpdateNetworkInstanceInfra = new UpdateNetworkInstanceInfra() + UpdateNetworkInstanceInfra.prepareDBRequest(mockExecution) + + verify(mockExecution).setVariable("prefix", "UPDNETI_") + verify(mockExecution).setVariable("UPDNETI_updateDBRequest", updateDBRequest_Outputs) + + } + + @Test + //@Ignore + public void prepareUpdateNetworkRequest() { + + println "************ prepareNetworkRequest ************* " + ExecutionEntity mockExecution = setupMock() + // Initialize prerequisite variables + when(mockExecution.getVariable("UPDNETI_networkRequest")).thenReturn(expectedNetworkRequest) + when(mockExecution.getVariable("UPDNETI_requeryIdAAIResponse")).thenReturn(queryIdAIIResponse) + when(mockExecution.getVariable("UPDNETI_cloudRegionPo")).thenReturn("RDM2WAGPLCP") + when(mockExecution.getVariable("UPDNETI_messageId")).thenReturn("messageId_generated") + when(mockExecution.getVariable("UPDNETI_source")).thenReturn("VID") + //when(mockExecution.getVariable("UPDNETI_queryVpnBindingAAIResponse")).thenReturn(queryVpnBindingAAIResponse) + when(mockExecution.getVariable("UPDNETI_routeCollection")).thenReturn("13979:10575713979:105757") + when(mockExecution.getVariable("UPDNETI_networkCollection")).thenReturn("GN_EVPN_Test") + when(mockExecution.getVariable("UPDNETI_tableRefCollection")).thenReturn("refFQDN1refFQDN2") + when(mockExecution.getVariable("UPDNETI_requestId")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56") + //when(mockExecution.getVariable("URN_?????")).thenReturn("") // notificationUrl, //TODO - is this coming from URN? What variable/value to use? + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("UPDNETI_rollbackEnabled")).thenReturn("true") + + // preProcessRequest(Execution execution) + UpdateNetworkInstanceInfra UpdateNetworkInstanceInfra = new UpdateNetworkInstanceInfra() + UpdateNetworkInstanceInfra.prepareUpdateNetworkRequest(mockExecution) + + // check the sequence of variable invocation + //MockitoDebuggerImpl preDebugger = new MockitoDebuggerImpl() + //preDebugger.printInvocations(mockExecution) + + // verify set prefix = "UPDNETI_" + verify(mockExecution).setVariable("prefix", "UPDNETI_") + + verify(mockExecution).setVariable("UPDNETI_updateNetworkRequest", updateNetworkRequest) + + } + + + @Test + //@Ignore + public void prepareUpdateNetworkRequest_NoPhysicalname() { + + println "************ prepareNetworkRequest ************* " + ExecutionEntity mockExecution = mock(ExecutionEntity.class) + // Initialize prerequisite variables + when(mockExecution.getVariable("UPDNETI_networkRequest")).thenReturn(NetworkRequest_noPhysicalName) + when(mockExecution.getVariable("UPDNETI_requeryIdAAIResponse")).thenReturn(queryIdAIIResponse) + when(mockExecution.getVariable("UPDNETI_cloudRegionPo")).thenReturn("RDM2WAGPLCP") + when(mockExecution.getVariable("UPDNETI_messageId")).thenReturn("messageId_generated") + when(mockExecution.getVariable("UPDNETI_source")).thenReturn("VID") + //when(mockExecution.getVariable("UPDNETI_queryVpnBindingAAIResponse")).thenReturn(queryVpnBindingAAIResponse) + when(mockExecution.getVariable("UPDNETI_routeCollection")).thenReturn("13979:10575713979:105757") + when(mockExecution.getVariable("UPDNETI_networkCollection")).thenReturn("GN_EVPN_Test") + when(mockExecution.getVariable("UPDNETI_tableRefCollection")).thenReturn("") + when(mockExecution.getVariable("UPDNETI_requestId")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56") + //when(mockExecution.getVariable("URN_?????")).thenReturn("") // notificationUrl, //TODO - is this coming from URN? What variable/value to use? + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("UPDNETI_rollbackEnabled")).thenReturn("true") + + // preProcessRequest(Execution execution) + UpdateNetworkInstanceInfra UpdateNetworkInstanceInfra = new UpdateNetworkInstanceInfra() + UpdateNetworkInstanceInfra.prepareUpdateNetworkRequest(mockExecution) + + // check the sequence of variable invocation + //MockitoDebuggerImpl preDebugger = new MockitoDebuggerImpl() + //preDebugger.printInvocations(mockExecution) + + // verify set prefix = "UPDNETI_" + verify(mockExecution).setVariable("prefix", "UPDNETI_") + + verify(mockExecution).setVariable("UPDNETI_updateNetworkRequest", updateNetworkRequest_noPhysicalName) + + } + + @Test + //@Ignore + public void prepareSDNCRequest() { + + println "************ prepareSDNCRequest ************* " + + ExecutionEntity mockExecution = mock(ExecutionEntity.class) + // Initialize prerequisite variables + when(mockExecution.getVariable("UPDNETI_networkRequest")).thenReturn(expectedNetworkRequest) + when(mockExecution.getVariable("UPDNETI_cloudRegionSdnc")).thenReturn("RDM2WAGPLCP") + when(mockExecution.getVariable("UPDNETI_serviceInstanceId")).thenReturn("f70e927b-6087-4974-9ef8-c5e4d5847ca4") + when(mockExecution.getVariable("mso-request-id")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56") + when(mockExecution.getVariable("URN_mso_workflow_sdncadapter_callback")).thenReturn("http://localhost:28090/SDNCAdapterCallback") + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("GENGSI_siResourceLink")).thenReturn("https://aai-int1.test.com:8443/aai/v8/business/customers/customer/MSO_1610_dev/service-subscriptions/service-subscription/MSO-dev-service-type/service-instances/service-instance/6d4eb22a-82f1-4257-9f80-4176262cfe69/") + + + // preProcessRequest(Execution execution) + UpdateNetworkInstanceInfra UpdateNetworkInstanceInfra = new UpdateNetworkInstanceInfra() + UpdateNetworkInstanceInfra.prepareSDNCRequest(mockExecution) + + // verify set prefix = "UPDNETI_" + verify(mockExecution).setVariable("prefix", "UPDNETI_") + verify(mockExecution).setVariable("UPDNETI_changeAssignSDNCRequest", changeAssignSDNCRequest) + + } + + @Test + //@Ignore + public void prepareSDNCRollbackRequest() { + + println "************ prepareSDNCRollbackRequest ************* " + + + + ExecutionEntity mockExecution = mock(ExecutionEntity.class) + // Initialize prerequisite variables + when(mockExecution.getVariable("UPDNETI_networkRequest")).thenReturn(expectedNetworkRequest) + when(mockExecution.getVariable("UPDNETI_cloudRegionSdnc")).thenReturn("RDM2WAGPLCP") + when(mockExecution.getVariable("UPDNETI_serviceInstanceId")).thenReturn("f70e927b-6087-4974-9ef8-c5e4d5847ca4") + when(mockExecution.getVariable("UPDNETI_changeAssignSDNCResponse")).thenReturn(assignResponse) + when(mockExecution.getVariable("mso-request-id")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56") + when(mockExecution.getVariable("URN_mso_workflow_sdncadapter_callback")).thenReturn("http://localhost:28090/SDNCAdapterCallback") + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("GENGSI_siResourceLink")).thenReturn("https://aai-int1.test.com:8443/aai/v8/business/customers/customer/MSO_1610_dev/service-subscriptions/service-subscription/MSO-dev-service-type/service-instances/service-instance/6d4eb22a-82f1-4257-9f80-4176262cfe69/") + + // preProcessRequest(Execution execution) + UpdateNetworkInstanceInfra UpdateNetworkInstanceInfra = new UpdateNetworkInstanceInfra() + UpdateNetworkInstanceInfra.prepareSDNCRollbackRequest(mockExecution) + + // verify set prefix = "UPDNETI_" + verify(mockExecution).setVariable("prefix", "UPDNETI_") + verify(mockExecution).setVariable("UPDNETI_rollbackSDNCRequest", sdncRollbackRequest) + + } + + @Test + //@Ignore + public void callRESTQueryAAINetworkId_200() { + + println "************ callRESTQueryAAINetworkId ************* " + + WireMock.reset(); + + MockGetNetwork("49c86598-f766-46f8-84f8-8d1c1b10f9b4", "UpdateNetworkV2/updateNetwork_queryNetworkId_AAIResponse_Success.xml", 200); + + ExecutionEntity mockExecution = setupMock() + when(mockExecution.getVariable("UPDNETI_networkRequest")).thenReturn(expectedNetworkRequest) + when(mockExecution.getVariable("UPDNETI_messageId")).thenReturn("e8ebf6a0-f8ea-4dc0-8b99-fe98a87722d6") + when(mockExecution.getVariable("URN_aai_endpoint")).thenReturn("http://localhost:28090") + when(mockExecution.getVariable("URN_mso_workflow_global_default_aai_version")).thenReturn("8") + when(mockExecution.getVariable("URN_mso_workflow_default_aai_v8_l3_network_uri")).thenReturn("/aai/v8/network/l3-networks/l3-network") + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("URN_aai_auth")).thenReturn("757A94191D685FD2092AC1490730A4FC") + when(mockExecution.getVariable("URN_mso_msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7") + + // preProcessRequest(Execution execution) + UpdateNetworkInstanceInfra UpdateNetworkInstanceInfra = new UpdateNetworkInstanceInfra() + UpdateNetworkInstanceInfra.callRESTQueryAAINetworkId(mockExecution) + + // check the sequence of variable invocation + //MockitoDebuggerImpl preDebugger = new MockitoDebuggerImpl() + //preDebugger.printInvocations(mockExecution) + + verify(mockExecution).setVariable("prefix", "UPDNETI_") + verify(mockExecution).setVariable("UPDNETI_queryIdAAIRequest", "http://localhost:28090/aai/v8/network/l3-networks/l3-network/49c86598-f766-46f8-84f8-8d1c1b10f9b4") + verify(mockExecution).setVariable("UPDNETI_aaiIdReturnCode", "200") + + } + + @Test + //@Ignore + public void callRESTQueryAAICloudRegion30_200() { + + println "************ callRESTQueryAAICloudRegion30_200 ************* " + + WireMock.reset(); + MockGetCloudRegion("RDM2WAGPLCP", 200, "CreateNetworkV2/cloudRegion30_AAIResponse_Success.xml") + + ExecutionEntity mockExecution = setupMock() + when(mockExecution.getVariable("prefix")).thenReturn("UPDNETI_") + when(mockExecution.getVariable("UPDNETI_networkInputs")).thenReturn(expectedNetworkRequest) + when(mockExecution.getVariable("URN_aai_endpoint")).thenReturn("http://localhost:28090") + when(mockExecution.getVariable("URN_mso_workflow_global_default_aai_version")).thenReturn("8") + when(mockExecution.getVariable("URN_mso_workflow_default_aai_v8_cloud_region_uri")).thenReturn("/aai/v8/cloud-infrastructure/cloud-regions/cloud-region/att-aic") + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("URN_aai_auth")).thenReturn("757A94191D685FD2092AC1490730A4FC") + when(mockExecution.getVariable("URN_mso_msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7") + + // preProcessRequest(Execution execution) + UpdateNetworkInstanceInfra UpdateNetworkInstanceInfra = new UpdateNetworkInstanceInfra() + UpdateNetworkInstanceInfra.callRESTQueryAAICloudRegion(mockExecution) + + // check the sequence of variable invocation + //MockitoDebuggerImpl preDebugger = new MockitoDebuggerImpl() + //preDebugger.printInvocations(mockExecution) + + verify(mockExecution, atLeast(1)).setVariable("prefix", "UPDNETI_") + verify(mockExecution).setVariable("UPDNETI_queryCloudRegionRequest", "http://localhost:28090/aai/v8/cloud-infrastructure/cloud-regions/cloud-region/att-aic/RDM2WAGPLCP") + verify(mockExecution, atLeast(2)).setVariable("UPDNETI_queryCloudRegionReturnCode", "200") + verify(mockExecution).setVariable("UPDNETI_isCloudRegionGood", true) + + } + + @Test + //@Ignore + public void callRESTQueryAAICloudRegion25_200() { + + println "************ callRESTQueryAAICloudRegion25_200 ************* " + + WireMock.reset(); + MockGetCloudRegion("RDM2WAGPLCP", 200, "CreateNetworkV2/cloudRegion25_AAIResponse_Success.xml") + + ExecutionEntity mockExecution = setupMock() + when(mockExecution.getVariable("prefix")).thenReturn("UPDNETI_") + when(mockExecution.getVariable("UPDNETI_networkInputs")).thenReturn(expectedNetworkRequest) + when(mockExecution.getVariable("URN_aai_endpoint")).thenReturn("http://localhost:28090") + when(mockExecution.getVariable("URN_mso_workflow_global_default_aai_version")).thenReturn("8") + when(mockExecution.getVariable("URN_mso_workflow_default_aai_v8_cloud_region_uri")).thenReturn("/aai/v8/cloud-infrastructure/cloud-regions/cloud-region/att-aic") + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("URN_aai_auth")).thenReturn("757A94191D685FD2092AC1490730A4FC") + when(mockExecution.getVariable("URN_mso_msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7") + + // preProcessRequest(Execution execution) + UpdateNetworkInstanceInfra UpdateNetworkInstanceInfra = new UpdateNetworkInstanceInfra() + UpdateNetworkInstanceInfra.callRESTQueryAAICloudRegion(mockExecution) + + // check the sequence of variable invocation + //MockitoDebuggerImpl preDebugger = new MockitoDebuggerImpl() + //preDebugger.printInvocations(mockExecution) + + verify(mockExecution, atLeast(1)).setVariable("prefix", "UPDNETI_") + verify(mockExecution).setVariable("UPDNETI_queryCloudRegionRequest", "http://localhost:28090/aai/v8/cloud-infrastructure/cloud-regions/cloud-region/att-aic/RDM2WAGPLCP") + verify(mockExecution, atLeast(2)).setVariable("UPDNETI_queryCloudRegionReturnCode", "200") + verify(mockExecution).setVariable("UPDNETI_isCloudRegionGood", true) + + } + + @Test + //@Ignore + public void callRESTQueryAAICloudRegion_NotFound() { + + println "************ callRESTQueryAAICloudRegionFake ************* " + + WireMock.reset(); + MockGetCloudRegion("MDTWNJ21", 404, "") + + ExecutionEntity mockExecution = setupMock() + when(mockExecution.getVariable("prefix")).thenReturn("UPDNETI_") + when(mockExecution.getVariable("UPDNETI_networkInputs")).thenReturn(vnfRequestFakeRegion) + when(mockExecution.getVariable("URN_aai_endpoint")).thenReturn("http://localhost:28090") + when(mockExecution.getVariable("URN_mso_workflow_global_default_aai_version")).thenReturn("8") + when(mockExecution.getVariable("URN_mso_workflow_default_aai_v8_cloud_region_uri")).thenReturn("/aai/v8/cloud-infrastructure/cloud-regions/cloud-region/att-aic") + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("URN_aai_auth")).thenReturn("757A94191D685FD2092AC1490730A4FC") + when(mockExecution.getVariable("URN_mso_msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7") + + // preProcessRequest(Execution execution) + UpdateNetworkInstanceInfra UpdateNetworkInstanceInfra = new UpdateNetworkInstanceInfra() + UpdateNetworkInstanceInfra.callRESTQueryAAICloudRegion(mockExecution) + + // check the sequence of variable invocation + //MockitoDebuggerImpl preDebugger = new MockitoDebuggerImpl() + //preDebugger.printInvocations(mockExecution) + + verify(mockExecution, atLeast(1)).setVariable("prefix", "UPDNETI_") + verify(mockExecution).setVariable("UPDNETI_queryCloudRegionRequest", "http://localhost:28090/aai/v8/cloud-infrastructure/cloud-regions/cloud-region/att-aic/MDTWNJ21") + verify(mockExecution, atLeast(1)).setVariable("UPDNETI_queryCloudRegionReturnCode", "404") + verify(mockExecution).setVariable("UPDNETI_cloudRegionPo", "MDTWNJ21") + verify(mockExecution).setVariable("UPDNETI_cloudRegionSdnc", "AAIAIC25") + verify(mockExecution).setVariable("UPDNETI_isCloudRegionGood", true) + + } + + @Test + //@Ignore + public void callRESTQueryAAINetworkVpnBinding_200() { + + println "************ callRESTQueryAAINetworkVpnBinding_200 ************* " + + WireMock.reset(); + MockGetNetworkVpnBinding("85f015d0-2e32-4c30-96d2-87a1a27f8017", "UpdateNetworkV2/updateNetwork_queryVpnBinding_AAIResponse_Success.xml", 200) + MockGetNetworkVpnBinding("c980a6ef-3b88-49f0-9751-dbad8608d0a6", "UpdateNetworkV2/updateNetwork_queryVpnBinding_AAIResponse_Success.xml", 200); + + ExecutionEntity mockExecution = setupMock() + when(mockExecution.getVariable("UPDNETI_requeryIdAAIResponse")).thenReturn(queryIdAIIResponse) // v6 + when(mockExecution.getVariable("UPDNETI_messageId")).thenReturn("e8ebf6a0-f8ea-4dc0-8b99-fe98a87722d6") + when(mockExecution.getVariable("URN_aai_endpoint")).thenReturn("http://localhost:28090") + when(mockExecution.getVariable("URN_mso_workflow_global_default_aai_version")).thenReturn("8") + when(mockExecution.getVariable("URN_mso_workflow_default_aai_v8_vpn_binding_uri")).thenReturn("/aai/v8/network/vpn-bindings/vpn-binding") +// when(mockExecution.getVariable("URN_mso_workflow_UpdateNetworkInstanceInfra_aai_network_vpn-binding_uri")).thenReturn("") + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("URN_aai_auth")).thenReturn("757A94191D685FD2092AC1490730A4FC") + when(mockExecution.getVariable("URN_mso_msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7") + + // preProcessRequest(Execution execution) + UpdateNetworkInstanceInfra UpdateNetworkInstanceInfra = new UpdateNetworkInstanceInfra() + UpdateNetworkInstanceInfra.callRESTQueryAAINetworkVpnBinding(mockExecution) + + // check the sequence of variable invocation + //MockitoDebuggerImpl preDebugger = new MockitoDebuggerImpl() + //preDebugger.printInvocations(mockExecution) + + verify(mockExecution).setVariable("prefix", "UPDNETI_") + verify(mockExecution).setVariable("UPDNETI_vpnCount", 2) + verify(mockExecution).setVariable("UPDNETI_vpnBindings", ['/aai/v8/network/vpn-bindings/vpn-binding/85f015d0-2e32-4c30-96d2-87a1a27f8017/', '/aai/v8/network/vpn-bindings/vpn-binding/c980a6ef-3b88-49f0-9751-dbad8608d0a6/']) + // the last vpnBinding value is saved. + verify(mockExecution).setVariable("UPDNETI_queryVpnBindingAAIRequest", "http://localhost:28090/aai/v8/network/vpn-bindings/vpn-binding/85f015d0-2e32-4c30-96d2-87a1a27f8017") + verify(mockExecution, atLeast(2)).setVariable("UPDNETI_aaiQqueryVpnBindingReturnCode", "200") + + } + + @Test + //@Ignore + public void callRESTQueryAAINetworkVpnBinding_TestScenario01_200() { + + println "************ callRESTQueryAAINetworkVpnBinding_200 ************* " + + WireMock.reset(); + MockGetNetworkVpnBinding("85f015d0-2e32-4c30-96d2-87a1a27f8017", "UpdateNetworkV2/updateNetwork_queryVpnBinding_AAIResponse_Success.xml", 200) + + ExecutionEntity mockExecution = setupMock() + when(mockExecution.getVariable("UPDNETI_requeryIdAAIResponse")).thenReturn(queryIdAIIResponseTestScenario01) + when(mockExecution.getVariable("UPDNETI_messageId")).thenReturn("e8ebf6a0-f8ea-4dc0-8b99-fe98a87722d6") + when(mockExecution.getVariable("URN_aai_endpoint")).thenReturn("http://localhost:28090") + when(mockExecution.getVariable("URN_mso_workflow_global_default_aai_version")).thenReturn("8") + when(mockExecution.getVariable("URN_mso_workflow_default_aai_v8_vpn_binding_uri")).thenReturn("/aai/v8/network/vpn-bindings/vpn-binding") +// when(mockExecution.getVariable("URN_mso_workflow_UpdateNetworkInstanceInfra_aai_network_vpn-binding_uri")).thenReturn("") + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("URN_aai_auth")).thenReturn("757A94191D685FD2092AC1490730A4FC") + when(mockExecution.getVariable("URN_mso_msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7") + + // preProcessRequest(Execution execution) + UpdateNetworkInstanceInfra UpdateNetworkInstanceInfra = new UpdateNetworkInstanceInfra() + UpdateNetworkInstanceInfra.callRESTQueryAAINetworkVpnBinding(mockExecution) + + // check the sequence of variable invocation + //MockitoDebuggerImpl preDebugger = new MockitoDebuggerImpl() + //preDebugger.printInvocations(mockExecution) + + verify(mockExecution).setVariable("prefix", "UPDNETI_") + verify(mockExecution).setVariable("UPDNETI_vpnCount", 1) + verify(mockExecution).setVariable("UPDNETI_vpnBindings", ['/aai/v8/network/vpn-bindings/vpn-binding/85f015d0-2e32-4c30-96d2-87a1a27f8017/']) + // the last vpnBinding value is saved. + verify(mockExecution).setVariable("UPDNETI_queryVpnBindingAAIRequest", "http://localhost:28090/aai/v8/network/vpn-bindings/vpn-binding/85f015d0-2e32-4c30-96d2-87a1a27f8017") + verify(mockExecution).setVariable("UPDNETI_aaiQqueryVpnBindingReturnCode", "200") + + } + + @Test + //@Ignore + public void callRESTQueryAAINetworkVpnBinding_200_URN_Uri() { + + println "************ callRESTQueryAAINetworkVpnBinding_200 ************* " + + WireMock.reset(); + MockGetNetworkVpnBinding("85f015d0-2e32-4c30-96d2-87a1a27f8017", "UpdateNetworkV2/updateNetwork_queryVpnBinding_AAIResponse_Success.xml", 200) + MockGetNetworkVpnBinding("c980a6ef-3b88-49f0-9751-dbad8608d0a6", "UpdateNetworkV2/updateNetwork_queryVpnBinding_AAIResponse_Success.xml", 200); + + ExecutionEntity mockExecution = setupMock() + when(mockExecution.getVariable("UPDNETI_requeryIdAAIResponse")).thenReturn(queryIdAIIResponse) + when(mockExecution.getVariable("UPDNETI_messageId")).thenReturn("e8ebf6a0-f8ea-4dc0-8b99-fe98a87722d6") + when(mockExecution.getVariable("URN_aai_endpoint")).thenReturn("http://localhost:28090") + when(mockExecution.getVariable("URN_mso_workflow_global_default_aai_version")).thenReturn("8") + when(mockExecution.getVariable("URN_mso_workflow_default_aai_v8_vpn_binding_uri")).thenReturn("/aai/v8/network/vpn-bindings/vpn-binding") + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("URN_aai_auth")).thenReturn("757A94191D685FD2092AC1490730A4FC") + when(mockExecution.getVariable("URN_mso_msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7") + + // preProcessRequest(Execution execution) + UpdateNetworkInstanceInfra UpdateNetworkInstanceInfra = new UpdateNetworkInstanceInfra() + UpdateNetworkInstanceInfra.callRESTQueryAAINetworkVpnBinding(mockExecution) + + // check the sequence of variable invocation + //MockitoDebuggerImpl preDebugger = new MockitoDebuggerImpl() + //preDebugger.printInvocations(mockExecution) + + verify(mockExecution).setVariable("prefix", "UPDNETI_") + verify(mockExecution).setVariable("UPDNETI_vpnCount", 2) + verify(mockExecution).setVariable("UPDNETI_vpnBindings", ['/aai/v8/network/vpn-bindings/vpn-binding/85f015d0-2e32-4c30-96d2-87a1a27f8017/', '/aai/v8/network/vpn-bindings/vpn-binding/c980a6ef-3b88-49f0-9751-dbad8608d0a6/']) + // the last vpnBinding value is saved. + verify(mockExecution).setVariable("UPDNETI_queryVpnBindingAAIRequest", "http://localhost:28090/aai/v8/network/vpn-bindings/vpn-binding/85f015d0-2e32-4c30-96d2-87a1a27f8017") + verify(mockExecution, atLeast(2)).setVariable("UPDNETI_aaiQqueryVpnBindingReturnCode", "200") + + } + + @Test + //@Ignore + public void callRESTQueryAAINetworkVpnBinding_NotPresent() { + + println "************ callRESTQueryAAINetworkVpnBinding_NotPresent ************* " + + WireMock.reset(); + MockGetNetworkVpnBinding("85f015d0-2e32-4c30-96d2-87a1a27f8017", "UpdateNetworkV2/updateNetwork_queryVpnBinding_AAIResponse_Success.xml", 200) + + ExecutionEntity mockExecution = setupMock() + // Initialize prerequisite variables + + when(mockExecution.getVariable("UPDNETI_requeryIdAAIResponse")).thenReturn(queryIdAIIResponseVpnNotPresent) + when(mockExecution.getVariable("UPDNETI_messageId")).thenReturn("e8ebf6a0-f8ea-4dc0-8b99-fe98a87722d6") + when(mockExecution.getVariable("URN_aai_endpoint")).thenReturn("http://localhost:28090") + when(mockExecution.getVariable("URN_mso_workflow_global_default_aai_version")).thenReturn("8") + when(mockExecution.getVariable("URN_mso_workflow_default_aai_v8_l3_network_uri")).thenReturn("/aai/v8/network/l3-networks/l3-network") + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + + // preProcessRequest(Execution execution) + UpdateNetworkInstanceInfra UpdateNetworkInstanceInfra = new UpdateNetworkInstanceInfra() + UpdateNetworkInstanceInfra.callRESTQueryAAINetworkVpnBinding(mockExecution) + + // check the sequence of variable invocation + //MockitoDebuggerImpl preDebugger = new MockitoDebuggerImpl() + //preDebugger.printInvocations(mockExecution) + + verify(mockExecution).setVariable("prefix", "UPDNETI_") + verify(mockExecution).setVariable("UPDNETI_aaiQqueryVpnBindingReturnCode", "200") + verify(mockExecution).setVariable("UPDNETI_vpnCount", 0) + verify(mockExecution).setVariable("UPDNETI_queryVpnBindingAAIResponse", aaiVpnResponseStub) + + } + + @Test + //@Ignore + public void callRESTQueryAAINetworkTableRef_200() { + + println "************ callRESTQueryAAINetworkTableRef_200 ************* " + + WireMock.reset(); + MockGetNetworkRouteTable("refFQDN1", "CreateNetworkV2/createNetwork_queryNetworkTableRef1_AAIResponse_Success.xml", 200) + MockGetNetworkRouteTable("refFQDN2", "CreateNetworkV2/createNetwork_queryNetworkTableRef2_AAIResponse_Success.xml", 200) + + ExecutionEntity mockExecution = setupMock() + when(mockExecution.getVariable("UPDNETI_requeryIdAAIResponse")).thenReturn(queryIdAIIResponse) + when(mockExecution.getVariable("UPDNETI_messageId")).thenReturn("e8ebf6a0-f8ea-4dc0-8b99-fe98a87722d6") + when(mockExecution.getVariable("URN_aai_endpoint")).thenReturn("http://localhost:28090") + when(mockExecution.getVariable("URN_mso_workflow_global_default_aai_version")).thenReturn("8") + when(mockExecution.getVariable("URN_mso_workflow_default_aai_v8_route_table_reference_uri")).thenReturn("/aai/v8/network/route-table-references/route-table-reference") +// when(mockExecution.getVariable("URN_mso_workflow_CreateNetworkInstanceInfra_aai_network_table_reference_uri")).thenReturn("") + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("URN_aai_auth")).thenReturn("757A94191D685FD2092AC1490730A4FC") + when(mockExecution.getVariable("URN_mso_msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7") + + // preProcessRequest(Execution execution) + UpdateNetworkInstanceInfra UpdateNetworkInstanceInfra = new UpdateNetworkInstanceInfra() + UpdateNetworkInstanceInfra.callRESTQueryAAINetworkTableRef(mockExecution) + + // check the sequence of variable invocation + //MockitoDebuggerImpl preDebugger = new MockitoDebuggerImpl() + //preDebugger.printInvocations(mockExecution) + + verify(mockExecution).setVariable("prefix", "UPDNETI_") + verify(mockExecution).setVariable("UPDNETI_networkTableRefCount", 2) + verify(mockExecution).setVariable("UPDNETI_networkTableRefUriList", ['/aai/v8/network/route-table-references/route-table-reference/refFQDN1','/aai/v8/network/route-table-references/route-table-reference/refFQDN2']) + // the last vpnBinding value is saved. + verify(mockExecution).setVariable("UPDNETI_queryNetworkTableRefAAIRequest", "http://localhost:28090/aai/v8/network/route-table-references/route-table-reference/refFQDN1") + verify(mockExecution, atLeast(2)).setVariable("UPDNETI_aaiQqueryNetworkTableRefReturnCode", "200") + + } + + @Test + //@Ignore + public void callRESTQueryAAINetworkPolicy_200() { + + println "************ callRESTQueryAAINetworkPolicy_200 ************* " + + WireMock.reset(); + MockGetNetworkPolicy("cee6d136-e378-4678-a024-2cd15f0ee0cg", "UpdateNetworkV2/updateNetwork_queryNetworkPolicy_AAIResponse_Success.xml", 200) + + ExecutionEntity mockExecution = setupMock() + when(mockExecution.getVariable("UPDNETI_requeryIdAAIResponse")).thenReturn(queryIdAIIResponse) + when(mockExecution.getVariable("UPDNETI_messageId")).thenReturn("e8ebf6a0-f8ea-4dc0-8b99-fe98a87722d6") + when(mockExecution.getVariable("URN_aai_endpoint")).thenReturn("http://localhost:28090") + when(mockExecution.getVariable("URN_mso_workflow_global_default_aai_version")).thenReturn("8") + when(mockExecution.getVariable("URN_mso_workflow_default_aai_v8_network_policy_uri")).thenReturn("/aai/v8/network/network-policies/network-policy") +// when(mockExecution.getVariable("URN_mso_workflow_UpdateNetworkInstanceInfra_aai_network_policy_uri")).thenReturn("") + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("URN_aai_auth")).thenReturn("757A94191D685FD2092AC1490730A4FC") + when(mockExecution.getVariable("URN_mso_msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7") + + // preProcessRequest(Execution execution) + UpdateNetworkInstanceInfra UpdateNetworkInstanceInfra = new UpdateNetworkInstanceInfra() + UpdateNetworkInstanceInfra.callRESTQueryAAINetworkPolicy(mockExecution) + + // check the sequence of variable invocation + //MockitoDebuggerImpl preDebugger = new MockitoDebuggerImpl() + //preDebugger.printInvocations(mockExecution) + + verify(mockExecution).setVariable("prefix", "UPDNETI_") + verify(mockExecution).setVariable("UPDNETI_networkPolicyCount", 1) + verify(mockExecution).setVariable("UPDNETI_networkPolicyUriList", ['/aai/v8/network/network-policies/network-policy/cee6d136-e378-4678-a024-2cd15f0ee0cg']) + // the last vpnBinding value is saved. + verify(mockExecution).setVariable("UPDNETI_queryNetworkPolicyAAIRequest", "http://localhost:28090/aai/v8/network/network-policies/network-policy/cee6d136-e378-4678-a024-2cd15f0ee0cg") + verify(mockExecution).setVariable("UPDNETI_aaiQqueryNetworkPolicyReturnCode", "200") + + } + + + @Test + //@Ignore + public void callRESTReQueryAAINetworkId_200() { + + println "************ callRESTReQueryAAINetworkId ************* " + + WireMock.reset(); + MockGetNetwork("49c86598-f766-46f8-84f8-8d1c1b10f9b4", "UpdateNetworkV2/updateNetwork_queryNetworkId_AAIResponse_Success.xml", 200) + + ExecutionEntity mockExecution = setupMock() + when(mockExecution.getVariable("UPDNETI_changeAssignSDNCResponse")).thenReturn(sdncAdapterWorkflowFormattedResponse) + when(mockExecution.getVariable("UPDNETI_messageId")).thenReturn("e8ebf6a0-f8ea-4dc0-8b99-fe98a87722d6") + when(mockExecution.getVariable("URN_aai_endpoint")).thenReturn("http://localhost:28090") + when(mockExecution.getVariable("URN_mso_workflow_global_default_aai_version")).thenReturn("8") + when(mockExecution.getVariable("URN_mso_workflow_default_aai_v8_l3_network_uri")).thenReturn("/aai/v8/network/l3-networks/l3-network") + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("URN_aai_auth")).thenReturn("757A94191D685FD2092AC1490730A4FC") + when(mockExecution.getVariable("URN_mso_msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7") + + // preProcessRequest(Execution execution) + UpdateNetworkInstanceInfra UpdateNetworkInstanceInfra = new UpdateNetworkInstanceInfra() + UpdateNetworkInstanceInfra.callRESTReQueryAAINetworkId(mockExecution) + + // check the sequence of variable invocation + //MockitoDebuggerImpl preDebugger = new MockitoDebuggerImpl() + //preDebugger.printInvocations(mockExecution) + + verify(mockExecution).setVariable("prefix", "UPDNETI_") + verify(mockExecution).setVariable("UPDNETI_requeryIdAAIRequest", "http://localhost:28090/aai/v8/network/l3-networks/l3-network/49c86598-f766-46f8-84f8-8d1c1b10f9b4") + verify(mockExecution).setVariable("UPDNETI_aaiRequeryIdReturnCode", "200") + + } + + + @Test + @Ignore + public void callRESTUpdateContrailAAINetworkREST_200() { + + println "************ callRESTUpdateContrailAAINetwork ************* " + + WireMock.reset(); + MockPutNetwork("49c86598-f766-46f8-84f8-8d1c1b10f9b4", 200, "UpdateNetworkV2/updateNetwork_updateContrail_AAIResponse_Success.xml") + + ExecutionEntity mockExecution = setupMock() + when(mockExecution.getVariable("UPDNETI_changeAssignSDNCResponse")).thenReturn(sdncAdapterWorkflowFormattedResponse) + when(mockExecution.getVariable("UPDNETI_requeryIdAAIResponse")).thenReturn(queryIdAIIResponse) + when(mockExecution.getVariable("UPDNETI_updateNetworkResponse")).thenReturn(updateNetworkResponseREST) + when(mockExecution.getVariable("UPDNETI_messageId")).thenReturn("e8ebf6a0-f8ea-4dc0-8b99-fe98a87722d6") + when(mockExecution.getVariable("URN_aai_endpoint")).thenReturn("http://localhost:28090") + when(mockExecution.getVariable("URN_mso_workflow_global_default_aai_version")).thenReturn("8") + when(mockExecution.getVariable("URN_mso_workflow_default_aai_v8_l3_network_uri")).thenReturn("/aai/v8/network/l3-networks/l3-network") + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("URN_aai_auth")).thenReturn("757A94191D685FD2092AC1490730A4FC") + when(mockExecution.getVariable("URN_mso_msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7") + + // preProcessRequest(Execution execution) + UpdateNetworkInstanceInfra UpdateNetworkInstanceInfra = new UpdateNetworkInstanceInfra() + UpdateNetworkInstanceInfra.callRESTUpdateContrailAAINetwork(mockExecution) + + // Capture the arguments to setVariable + ArgumentCaptor captor1 = ArgumentCaptor.forClass(String.class); + ArgumentCaptor captor2 = ArgumentCaptor.forClass(String.class); + + verify(mockExecution, times(6)).setVariable(captor1.capture(), captor2.capture()) + List arg2List = captor2.getAllValues() + String payloadResponseActual = arg2List.get(4) + + assertEquals(updateContrailAAIResponse.replaceAll("\\s+", ""), payloadResponseActual.replaceAll("\\s+", "")) + + verify(mockExecution).setVariable("prefix", "UPDNETI_") + verify(mockExecution).setVariable("UPDNETI_updateContrailAAIUrlRequest", "http://localhost:28090/aai/v8/network/l3-networks/l3-network/49c86598-f766-46f8-84f8-8d1c1b10f9b4") + verify(mockExecution).setVariable("UPDNETI_updateContrailAAIPayloadRequest", updateContrailAAIPayloadRequest) + verify(mockExecution).setVariable("UPDNETI_aaiUpdateContrailReturnCode", "200") + verify(mockExecution).setVariable("UPDNETI_isPONR", true) + + } + + + + @Test + //@Ignore + public void validateUpdateNetworkResponseREST() { + + println "************ validateNetworkResponse ************* " + + ExecutionEntity mockExecution = mock(ExecutionEntity.class) + // Initialize prerequisite variables + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("UPDNETI_updateNetworkResponse")).thenReturn(updateNetworkResponseREST) + when(mockExecution.getVariable("UPDNETI_networkReturnCode")).thenReturn('200') + + UpdateNetworkInstanceInfra UpdateNetworkInstanceInfra = new UpdateNetworkInstanceInfra() + UpdateNetworkInstanceInfra.validateUpdateNetworkResponse(mockExecution) + + //MockitoDebuggerImpl debugger = new MockitoDebuggerImpl() + //debugger.printInvocations(mockExecution) + + verify(mockExecution).setVariable("prefix", "UPDNETI_") + verify(mockExecution).setVariable("UPDNETI_updateNetworkResponse", updateNetworkResponseREST) + verify(mockExecution).setVariable("UPDNETI_isNetworkRollbackNeeded", true) + verify(mockExecution).setVariable("UPDNETI_rollbackNetworkRequest", updateRollbackNetworkRequest) + + } + + @Test + //@Ignore + public void validateUpdateNetworkResponseREST_Error() { + + println "************ validateNetworkResponse ************* " + + WorkflowException workflowException = new WorkflowException("UpdateNetworkInstanceInfra", 2500, "Received error from Network Adapter: JBWEB000065: HTTP Status 500.") + + ExecutionEntity mockExecution = setupMock() + // Initialize prerequisite variables + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("UPDNETI_updateNetworkResponse")).thenReturn(networkException500) + when(mockExecution.getVariable("UPDNETI_networkReturnCode")).thenReturn('500') + + UpdateNetworkInstanceInfra UpdateNetworkInstanceInfra = new UpdateNetworkInstanceInfra() + try { + UpdateNetworkInstanceInfra.validateUpdateNetworkResponse(mockExecution) + } catch (Exception ex) { + println " Test End - Handle catch-throw BpmnError()! " + } + + verify(mockExecution).setVariable("prefix", "UPDNETI_") + verify(mockExecution, atLeast(1)).setVariable("WorkflowException", refEq(workflowException, any(WorkflowException.class))) + + } + + @Test + //@Ignore + public void validateSDNCResponse() { + + println "************ validateSDNCResponse ************* " + + ExecutionEntity mockExecution = setupMock() + // Initialize prerequisite variables + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("UPDNETI_changeAssignSDNCResponse")).thenReturn(sdncAdapterWorkflowResponse) + when(mockExecution.getVariable("prefix")).thenReturn("UPDNETI_") + when(mockExecution.getVariable("SDNCA_SuccessIndicator")).thenReturn(true) + when(mockExecution.getVariable("UPDNETI_sdncReturnCode")).thenReturn("200") + when(mockExecution.getVariable("UPDNETI_isResponseGood")).thenReturn(true) + + UpdateNetworkInstanceInfra UpdateNetworkInstanceInfra = new UpdateNetworkInstanceInfra() + try { + UpdateNetworkInstanceInfra.validateSDNCResponse(mockExecution) + verify(mockExecution).setVariable("UPDNETI_isSdncRollbackNeeded", true) + verify(mockExecution).setVariable("UPDNETI_rollbackSDNCRequest", "") + + } catch (Exception ex) { + println " Graceful Exit - " + ex.getMessage() + } + //MockitoDebuggerImpl debugger = new MockitoDebuggerImpl() + //debugger.printInvocations(mockExecution) + + //verify(mockExecution).setVariable("UPDNETI_isSdncRollbackNeeded", true) + + } + + @Test + //@Ignore + public void validateSDNCResponse_Error() { + + println "************ validateSDNCResponse ************* " + //ExecutionEntity mockExecution = mock(ExecutionEntity.class) + ExecutionEntity mockExecution = setupMock() + // Initialize prerequisite variables + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("UPDNETI_changeAssignSDNCResponse")).thenReturn(sdncAdapterWorkflowResponse_Error) + when(mockExecution.getVariable("prefix")).thenReturn("UPDNETI_") + when(mockExecution.getVariable("SDNCA_SuccessIndicator")).thenReturn(false) + when(mockExecution.getVariable("UPDNETI_sdncReturnCode")).thenReturn("200") + when(mockExecution.getVariable("UPDNETI_isResponseGood")).thenReturn(true) + + UpdateNetworkInstanceInfra UpdateNetworkInstanceInfra = new UpdateNetworkInstanceInfra() + try { + UpdateNetworkInstanceInfra.validateSDNCResponse(mockExecution) + } catch (Exception ex) { + println " Graceful Exit! - " + ex.getMessage() + } + //MockitoDebuggerImpl debugger = new MockitoDebuggerImpl() + //debugger.printInvocations(mockExecution) + + // verify set prefix = "UPDNETI_" + //verify(mockExecution).setVariable("UPDNETI_sdncResponseSuccess", false) + + } + + + + @Test + //@Ignore + public void postProcessResponse() { + + println "************ postProcessResponse ************* " + ExecutionEntity mockExecution = mock(ExecutionEntity.class) + // Initialize prerequisite variables + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("UPDNETI_source")).thenReturn("PORTAL") + when(mockExecution.getVariable("UPDNETI_requestId")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56") + when(mockExecution.getVariable("UPDNETI_dbReturnCode")).thenReturn("200") + + // postProcessResponse(Execution execution) + UpdateNetworkInstanceInfra UpdateNetworkInstanceInfra = new UpdateNetworkInstanceInfra() + UpdateNetworkInstanceInfra.postProcessResponse(mockExecution) + + // check the sequence of variable invocation + //MockitoDebuggerImpl preDebugger = new MockitoDebuggerImpl() + //preDebugger.printInvocations(mockExecution) + + verify(mockExecution).setVariable("prefix", "UPDNETI_") + verify(mockExecution).setVariable("UPDNETI_Success", true) + verify(mockExecution).setVariable("UPDNETI_CompleteMsoProcessRequest", completeMsoProcessRequest) + + } + + @Test + //@Ignore + public void validateRollbackResponses_Good() { + + WorkflowException workflowException = new WorkflowException("UpdateNetworkInstanceInfra", 2500, "AAI Update Contrail Failed. Error 404.") + WorkflowException expectedWorkflowException = new WorkflowException("UpdateNetworkInstanceInfra", 2500, "AAI Update Contrail Failed. Error 404. + PO Network rollback is not supported for Update. Submit another Update to restore/rollback. + SNDC rollback completed.") + + println "************ validateRollbackResponses_Good() ************* " + ExecutionEntity mockExecution = setupMock() + // Initialize prerequisite variables + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("prefix")).thenReturn("UPDNETI_") + + when(mockExecution.getVariable("UPDNETI_isNetworkRollbackNeeded")).thenReturn(true) + when(mockExecution.getVariable("UPDNETI_rollbackNetworkReturnCode")).thenReturn("200") + when(mockExecution.getVariable("UPDNETI_rollbackNetworkResponse")).thenReturn("GoodResponse") + when(mockExecution.getVariable("UPDNETI_isSdncRollbackNeeded")).thenReturn(true) + when(mockExecution.getVariable("UPDNETI_rollbackSDNCReturnCode")).thenReturn("200") + when(mockExecution.getVariable("UPDNETI_rollbackSDNCResponse")).thenReturn("GoodResponse") + when(mockExecution.getVariable("WorkflowException")).thenReturn(workflowException) + + UpdateNetworkInstanceInfra UpdateNetworkInstanceInfra = new UpdateNetworkInstanceInfra() + UpdateNetworkInstanceInfra.validateRollbackResponses(mockExecution) + + // verify set prefix = "UPDNETI_" + verify(mockExecution, atLeast(1)).setVariable("prefix", "UPDNETI_") + verify(mockExecution).setVariable("WorkflowException", refEq(expectedWorkflowException, any(WorkflowException.class))) + + } + + @Test + //@Ignore + public void validateRollbackResponses_Failed() { + + WorkflowException workflowException = new WorkflowException("UpdateNetworkInstanceInfra", 7020, "AAI Update Contrail Failed. Error 404.") + WorkflowException expectedWorkflowException = new WorkflowException("UpdateNetworkInstanceInfra", 7020, "AAI Update Contrail Failed. Error 404. + PO Network rollback is not supported for Update. Submit another Update to restore/rollback. + SDNC rollback failed. ") + + println "************ validateRollbackResponses_Failed() ************* " + ExecutionEntity mockExecution = setupMock() + // Initialize prerequisite variables + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("prefix")).thenReturn("UPDNETI_") + + when(mockExecution.getVariable("UPDNETI_isNetworkRollbackNeeded")).thenReturn(true) + when(mockExecution.getVariable("UPDNETI_rollbackNetworkReturnCode")).thenReturn("404") + when(mockExecution.getVariable("UPDNETI_rollbackNetworkResponse")).thenReturn("BadResponse") + when(mockExecution.getVariable("UPDNETI_isSdncRollbackNeeded")).thenReturn(true) + when(mockExecution.getVariable("UPDNETI_rollbackSDNCReturnCode")).thenReturn("500") + when(mockExecution.getVariable("UPDNETI_rollbackSDNCResponse")).thenReturn("BadResponse") + when(mockExecution.getVariable("WorkflowException")).thenReturn(workflowException) + + UpdateNetworkInstanceInfra UpdateNetworkInstanceInfra = new UpdateNetworkInstanceInfra() + UpdateNetworkInstanceInfra.validateRollbackResponses(mockExecution) + + // verify set prefix = "UPDNETI_" + verify(mockExecution, atLeast(1)).setVariable("prefix", "UPDNETI_") + verify(mockExecution, atLeast(1)).setVariable("WorkflowException", refEq(expectedWorkflowException, any(WorkflowException.class))) + + } + + @Test + //@Ignore + public void validateRollbackResponses_NetworkFailed() { + + WorkflowException workflowException = new WorkflowException("UpdateNetworkInstanceInfra", 7020, "AAI Update Contrail Failed. Error 404.") + WorkflowException expectedWorkflowExceptionFailed = new WorkflowException("UpdateNetworkInstanceInfra", 7020, "AAI Update Contrail Failed. Error 404. + PO Network rollback is not supported for Update. Submit another Update to restore/rollback. + SNDC rollback completed.") + + println "************ validateRollbackResponses_NetworkFailed() ************* " + ExecutionEntity mockExecution = setupMock() + // Initialize prerequisite variables + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("prefix")).thenReturn("UPDNETI_") + + when(mockExecution.getVariable("UPDNETI_isNetworkRollbackNeeded")).thenReturn(true) + when(mockExecution.getVariable("UPDNETI_rollbackNetworkReturnCode")).thenReturn("404") + when(mockExecution.getVariable("UPDNETI_rollbackNetworkResponse")).thenReturn("BadResponse") + when(mockExecution.getVariable("UPDNETI_isSdncRollbackNeeded")).thenReturn(true) + when(mockExecution.getVariable("UPDNETI_rollbackSDNCReturnCode")).thenReturn("200") + when(mockExecution.getVariable("UPDNETI_rollbackSDNCResponse")).thenReturn("GoodResponse") + when(mockExecution.getVariable("WorkflowException")).thenReturn(workflowException) + + UpdateNetworkInstanceInfra UpdateNetworkInstanceInfra = new UpdateNetworkInstanceInfra() + UpdateNetworkInstanceInfra.validateRollbackResponses(mockExecution) + + // verify set prefix = "UPDNETI_" + verify(mockExecution, atLeast(1)).setVariable("prefix", "UPDNETI_") + verify(mockExecution, atLeast(1)).setVariable("WorkflowException", refEq(expectedWorkflowExceptionFailed , any(WorkflowException.class))) + + } + + @Test + //@Ignore + public void validateRollbackResponses_SdncFailed() { + + WorkflowException workflowException = new WorkflowException("UpdateNetworkInstanceInfra", 7020, "AAI Update Contrail Failed. Error 404.") + WorkflowException expectedWorkflowException = new WorkflowException("UpdateNetworkInstanceInfra", 7020, "AAI Update Contrail Failed. Error 404. + PO Network rollback is not supported for Update. Submit another Update to restore/rollback. + SDNC rollback failed. ") + + println "************ validateRollbackResponses_SdncFailed() ************* " + ExecutionEntity mockExecution = setupMock() + // Initialize prerequisite variables + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("prefix")).thenReturn("UPDNETI_") + + when(mockExecution.getVariable("UPDNETI_isNetworkRollbackNeeded")).thenReturn(true) + when(mockExecution.getVariable("UPDNETI_rollbackNetworkReturnCode")).thenReturn("200") + when(mockExecution.getVariable("UPDNETI_rollbackNetworkResponse")).thenReturn("GoodResponse") + when(mockExecution.getVariable("UPDNETI_isSdncRollbackNeeded")).thenReturn(true) + when(mockExecution.getVariable("UPDNETI_rollbackSDNCReturnCode")).thenReturn("200") + when(mockExecution.getVariable("UPDNETI_rollbackSDNCResponse")).thenReturn("400") + when(mockExecution.getVariable("WorkflowException")).thenReturn(workflowException) + + UpdateNetworkInstanceInfra UpdateNetworkInstanceInfra = new UpdateNetworkInstanceInfra() + UpdateNetworkInstanceInfra.validateRollbackResponses(mockExecution) + + // verify set prefix = "UPDNETI_" + verify(mockExecution, atLeast(1)).setVariable("prefix", "UPDNETI_") + verify(mockExecution).setVariable("WorkflowException", refEq(expectedWorkflowException , any(WorkflowException.class))) + + } + + @Test + //@Ignore + public void validateRollbackResponses_NoRollbacks() { + + WorkflowException workflowException = new WorkflowException("UpdateNetworkInstanceInfra", 2500, " AAI Update Contrail Failed. Error 404") + WorkflowException expectedWorkflowException = new WorkflowException("UpdateNetworkInstanceInfra", 2500, " AAI Update Contrail Failed. Error 404") + + println "************ validateRollbackResponses_NoRollbacks() ************* " + ExecutionEntity mockExecution = setupMock() + // Initialize prerequisite variables + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("prefix")).thenReturn("UPDNETI_") + + when(mockExecution.getVariable("UPDNETI_isNetworkRollbackNeeded")).thenReturn(false) + when(mockExecution.getVariable("UPDNETI_rollbackNetworkReturnCode")).thenReturn("200") + when(mockExecution.getVariable("UPDNETI_rollbackNetworkResponse")).thenReturn("GoodResponse") + when(mockExecution.getVariable("UPDNETI_isSdncRollbackNeeded")).thenReturn(false) + when(mockExecution.getVariable("UPDNETI_rollbackSDNCReturnCode")).thenReturn("200") + when(mockExecution.getVariable("UPDNETI_rollbackSDNCResponse")).thenReturn("GoodResponse") + when(mockExecution.getVariable("WorkflowException")).thenReturn(workflowException) + + UpdateNetworkInstanceInfra UpdateNetworkInstanceInfra = new UpdateNetworkInstanceInfra() + UpdateNetworkInstanceInfra.validateRollbackResponses(mockExecution) + + // verify set prefix = "UPDNETI_" + verify(mockExecution, atLeast(1)).setVariable("prefix", "UPDNETI_") + //verify(mockExecution, atLeast(1)).setVariable("WorkflowException", any(expectedWorkflowException)) + verify(mockExecution, atLeast(1)).setVariable("WorkflowException", refEq(expectedWorkflowException, any(WorkflowException.class))) + + } + + + @Test + //@Ignore + public void buildErrorResponse() { + + println "************ buildErrorResponse ************* " + + + WorkflowException sndcWorkflowException = new WorkflowException("UpdateNetworkInstanceInfra", 5300, "Received error from SDN-C: No availability zone available.") + + ExecutionEntity mockExecution = setupMock() + // Initialize prerequisite variables + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("UPDNETI_requestId")).thenReturn("b69c9054-da09-4a2c-adf5-51042b62bfac") + when(mockExecution.getVariable("UPDNETI_source")).thenReturn("PORTAL") + when(mockExecution.getVariable("WorkflowException")).thenReturn(sndcWorkflowException) + + // buildErrorResponse(Execution execution) + UpdateNetworkInstanceInfra UpdateNetworkInstanceInfra = new UpdateNetworkInstanceInfra() + UpdateNetworkInstanceInfra.buildErrorResponse(mockExecution) + + // verify set prefix = "UPDNETI_" + verify(mockExecution, atLeast(1)).setVariable("prefix", "UPDNETI_") + verify(mockExecution).setVariable("UPDNETI_Success", false) + verify(mockExecution).setVariable("UPDNETI_FalloutHandlerRequest", falloutHandlerRequest) + + //MockitoDebuggerImpl debugger = new MockitoDebuggerImpl() + //debugger.printInvocations(mockExecution) + + } + + @Test + //@Ignore + public void buildErrorResponse_WorkflowExceptionObject() { + + println "************ buildErrorResponse ************* " + + WorkflowException sndcWorkflowException = new WorkflowException("UpdateNetworkInstanceInfra", 7000, "Received error from SDN-C: No availability zone available") + + ExecutionEntity mockExecution = setupMock() + // Initialize prerequisite variables + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("UPDNETI_requestId")).thenReturn("b69c9054-da09-4a2c-adf5-51042b62bfac") + when(mockExecution.getVariable("UPDNETI_source")).thenReturn("VID") + when(mockExecution.getVariable("WorkflowException")).thenReturn(sndcWorkflowException) + + // buildErrorResponse(Execution execution) + UpdateNetworkInstanceInfra UpdateNetworkInstanceInfra = new UpdateNetworkInstanceInfra() + UpdateNetworkInstanceInfra.buildErrorResponse(mockExecution) + + // verify set prefix = "UPDNETI_" + verify(mockExecution).setVariable("prefix", "UPDNETI_") + verify(mockExecution).setVariable("UPDNETI_Success", false) + verify(mockExecution).setVariable("UPDNETI_FalloutHandlerRequest", falloutHandlerRequestObject) + + //MockitoDebuggerImpl debugger = new MockitoDebuggerImpl() + //debugger.printInvocations(mockExecution) + + } + + @Test + //@Ignore + public void buildErrorResponse_Scenario01() { + + WorkflowException aaiWorkflowException_Secnario01 = new WorkflowException("UpdateNetworkInstanceInfra", 7020, "Unexpected Response from AAI - 400") + + println "************ buildErrorResponse ************* " + ExecutionEntity mockExecution = setupMock() + // Initialize prerequisite variables + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("UPDNETI_requestId")).thenReturn("b69c9054-da09-4a2c-adf5-51042b62bfac") + when(mockExecution.getVariable("UPDNETI_source")).thenReturn("VID") + when(mockExecution.getVariable("WorkflowException")).thenReturn(aaiWorkflowException_Secnario01) + when(mockExecution.getVariable("UPDNETI_dbReturnCode")).thenReturn("200") + when(mockExecution.getVariable("UPDNETI_updateDBResponse")).thenReturn("") + + when(mockExecution.getVariable("UPDNETI_aaiRequeryIdReturnCode")).thenReturn("400") + + // buildErrorResponse(Execution execution) + UpdateNetworkInstanceInfra UpdateNetworkInstanceInfra = new UpdateNetworkInstanceInfra() + UpdateNetworkInstanceInfra.buildErrorResponse(mockExecution) + + // verify set prefix = "UPDNETI_" + verify(mockExecution, atLeast(1)).setVariable("prefix", "UPDNETI_") + verify(mockExecution).setVariable("UPDNETI_Success", false) + verify(mockExecution).setVariable("UPDNETI_FalloutHandlerRequest", falloutHandlerRequest_Scenario01) + + //MockitoDebuggerImpl debugger = new MockitoDebuggerImpl() + //debugger.printInvocations(mockExecution) + + } + + + private ExecutionEntity setupMock() { + + ProcessDefinition mockProcessDefinition = mock(ProcessDefinition.class) + when(mockProcessDefinition.getKey()).thenReturn("UpdateNetworkInstanceInfra") + RepositoryService mockRepositoryService = mock(RepositoryService.class) + when(mockRepositoryService.getProcessDefinition()).thenReturn(mockProcessDefinition) + when(mockRepositoryService.getProcessDefinition().getKey()).thenReturn("UpdateNetworkInstanceInfra") + when(mockRepositoryService.getProcessDefinition().getId()).thenReturn("100") + ProcessEngineServices mockProcessEngineServices = mock(ProcessEngineServices.class) + when(mockProcessEngineServices.getRepositoryService()).thenReturn(mockRepositoryService) + + ExecutionEntity mockExecution = mock(ExecutionEntity.class) + // Initialize prerequisite variables + + when(mockExecution.getId()).thenReturn("100") + when(mockExecution.getProcessDefinitionId()).thenReturn("UpdateNetworkInstanceInfra") + when(mockExecution.getProcessInstanceId()).thenReturn("UpdateNetworkInstanceInfra") + when(mockExecution.getProcessEngineServices()).thenReturn(mockProcessEngineServices) + when(mockExecution.getProcessEngineServices().getRepositoryService().getProcessDefinition(mockExecution.getProcessDefinitionId())).thenReturn(mockProcessDefinition) + + return mockExecution + } + + +} diff --git a/bpmn/MSOInfrastructureBPMN/src/test/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/UpdateVfModuleVolumeInfraV1Test.groovy b/bpmn/MSOInfrastructureBPMN/src/test/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/UpdateVfModuleVolumeInfraV1Test.groovy index 2e9efad215..4ca68f3b2b 100644 --- a/bpmn/MSOInfrastructureBPMN/src/test/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/UpdateVfModuleVolumeInfraV1Test.groovy +++ b/bpmn/MSOInfrastructureBPMN/src/test/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/UpdateVfModuleVolumeInfraV1Test.groovy @@ -1,93 +1,93 @@ -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - MSO - * ================================================================================ - * 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.openecomp.mso.bpmn.infrastructure.scripts; - -import static org.junit.Assert.* -import static org.mockito.Mockito.* - -import org.junit.Before -import org.junit.Ignore -import org.junit.Rule -import org.junit.runner.RunWith -import org.mockito.MockitoAnnotations -import org.mockito.runners.MockitoJUnitRunner - -import com.github.tomakehurst.wiremock.junit.WireMockRule - -@RunWith(MockitoJUnitRunner.class) -@Ignore // No Junits exists in this class to run -class UpdateVfModuleVolumeInfraV1Test { - - String xml = """ - - - tenant - https://aai-ext1.test.com:8443/aai/v7/cloud-infrastructure/cloud-regions/cloud-region/att-aic/mdt1/tenants/tenant/fba1bd1e195a404cacb9ce17a9b2b421/ - - tenant.tenant-id - fba1bd1e195a404cacb9ce17a9b2b421 - - - cloud-region.cloud-owner - att-aic - - - cloud-region.cloud-region-id - mdt1 - - - tenant.tenant-name - ECOMP_MDT1 - - - - vf-module - https://aai-ext1.test.com:8443/aai/v7/cloud-infrastructure/cloud-regions/cloud-region/att-aic/mdt1/tenants/tenant/fba1bd1e195a404cacb9ce17a9b2b421/ - - vf-module.vf-module-ids - fba1bd1e195a404cacb9ce17a9b2b421 - - - cloud-region.cloud-owner - att-aic - - - cloud-region.cloud-region-id - mdt1 - - - vf-module.vf-module-name - ECOMP_MDT1 - - - -""" - - @Rule - public WireMockRule wireMockRule = new WireMockRule(28090); - - @Before - public void init() - { - MockitoAnnotations.initMocks(this) - - } -} +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.bpmn.infrastructure.scripts; + +import static org.junit.Assert.* +import static org.mockito.Mockito.* + +import org.junit.Before +import org.junit.Ignore +import org.junit.Rule +import org.junit.runner.RunWith +import org.mockito.MockitoAnnotations +import org.mockito.runners.MockitoJUnitRunner + +import com.github.tomakehurst.wiremock.junit.WireMockRule + +@RunWith(MockitoJUnitRunner.class) +@Ignore // No Junits exists in this class to run +class UpdateVfModuleVolumeInfraV1Test { + + String xml = """ + + + tenant + https://aai-ext1.test.com:8443/aai/v7/cloud-infrastructure/cloud-regions/cloud-region/att-aic/mdt1/tenants/tenant/fba1bd1e195a404cacb9ce17a9b2b421/ + + tenant.tenant-id + fba1bd1e195a404cacb9ce17a9b2b421 + + + cloud-region.cloud-owner + att-aic + + + cloud-region.cloud-region-id + mdt1 + + + tenant.tenant-name + ECOMP_MDT1 + + + + vf-module + https://aai-ext1.test.com:8443/aai/v7/cloud-infrastructure/cloud-regions/cloud-region/att-aic/mdt1/tenants/tenant/fba1bd1e195a404cacb9ce17a9b2b421/ + + vf-module.vf-module-ids + fba1bd1e195a404cacb9ce17a9b2b421 + + + cloud-region.cloud-owner + att-aic + + + cloud-region.cloud-region-id + mdt1 + + + vf-module.vf-module-name + ECOMP_MDT1 + + + +""" + + @Rule + public WireMockRule wireMockRule = new WireMockRule(28090); + + @Before + public void init() + { + MockitoAnnotations.initMocks(this) + + } +} diff --git a/bpmn/MSOInfrastructureBPMN/src/test/java/org/openecomp/mso/bpmn/infrastructure/CreateVfModuleInfraTest.java b/bpmn/MSOInfrastructureBPMN/src/test/java/org/openecomp/mso/bpmn/infrastructure/CreateVfModuleInfraTest.java index 7a9864caa5..4f987f0d48 100644 --- a/bpmn/MSOInfrastructureBPMN/src/test/java/org/openecomp/mso/bpmn/infrastructure/CreateVfModuleInfraTest.java +++ b/bpmn/MSOInfrastructureBPMN/src/test/java/org/openecomp/mso/bpmn/infrastructure/CreateVfModuleInfraTest.java @@ -1,243 +1,249 @@ -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - MSO - * ================================================================================ - * 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.openecomp.mso.bpmn.infrastructure; - -import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockGetCloudRegion; -import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockGetGenericVnfById; -import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockGetGenericVnfByIdWithDepth; -import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockGetGenericVnfByIdWithPriority; -import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockGetNetworkPolicyfqdn; -import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockGetVolumeGroupById; -import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockPutGenericVnf; -import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockPutNetwork; -import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockPutVfModuleIdNoResponse; -import static org.openecomp.mso.bpmn.mock.StubResponseDatabase.mockUpdateRequestDB; -import static org.openecomp.mso.bpmn.mock.StubResponseSDNCAdapter.mockSDNCAdapter; -import static org.openecomp.mso.bpmn.mock.StubResponseVNFAdapter.mockVNFPost; - -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; - -import org.camunda.bpm.engine.test.Deployment; -import org.junit.Test; -import org.openecomp.mso.bpmn.common.WorkflowTest; -import org.openecomp.mso.bpmn.common.workflow.service.WorkflowResponse; -import org.openecomp.mso.bpmn.mock.FileUtil; - -/** - * Unit test cases for CreateVfModuleInfra.bpmn - */ -public class CreateVfModuleInfraTest extends WorkflowTest { - - private final CallbackSet callbacks = new CallbackSet(); - - public CreateVfModuleInfraTest() throws IOException { - callbacks.put("assign", FileUtil.readResourceFile( - "__files/VfModularity/SDNCTopologyAssignCallback.xml")); - callbacks.put("query", FileUtil.readResourceFile( - "__files/VfModularity/SDNCTopologyQueryCallbackVfModule.xml")); - callbacks.put("activate", FileUtil.readResourceFile( - "__files/VfModularity/SDNCTopologyActivateCallback.xml")); - callbacks.put("vnfCreate", FileUtil.readResourceFile( - "__files/VfModularity/VNFAdapterRestCreateCallback.xml")); - } - - - /** - * Sunny day VID scenario. - * - * @throws Exception - */ - @Test - @Deployment(resources = { - "process/CreateVfModuleInfra.bpmn", - "subprocess/DoCreateVfModule.bpmn", - "subprocess/SDNCAdapterV1.bpmn", - "subprocess/VnfAdapterRestV1.bpmn", - "subprocess/ConfirmVolumeGroupTenant.bpmn", - "subprocess/ConfirmVolumeGroupName.bpmn", - "subprocess/CreateAAIVfModule.bpmn", - "subprocess/UpdateAAIVfModule.bpmn", - "subprocess/UpdateAAIGenericVnf.bpmn", - "subprocess/CompleteMsoProcess.bpmn", - "subprocess/FalloutHandler.bpmn" - }) - public void sunnyDayVID() throws Exception { - - logStart(); - - MockGetGenericVnfByIdWithDepth("skask", 1, "VfModularity/GenericVnf.xml"); - MockGetGenericVnfByIdWithPriority("skask", ".*", 200, "VfModularity/VfModule-new.xml", 5); - MockGetGenericVnfById("skask", "VfModularity/GenericVnf.xml", 200); - MockPutVfModuleIdNoResponse("skask", "PCRF", ".*"); - MockPutNetwork(".*", "VfModularity/AddNetworkPolicy_AAIResponse_Success.xml", 200); - MockPutGenericVnf("skask"); - mockVNFPost("", 202, "skask"); - mockSDNCAdapter("/SDNCAdapter", "vnf-type>STMTN", 200, "VfModularity/StandardSDNCSynchResponse.xml"); - mockSDNCAdapter("/SDNCAdapter", "SvcAction>query", 200, "VfModularity/StandardSDNCSynchResponse.xml"); - mockUpdateRequestDB(200, "Database/DBUpdateResponse.xml"); - - String businessKey = UUID.randomUUID().toString(); - String createVfModuleRequest = - FileUtil.readResourceFile("__files/CreateVfModule_VID_request.json"); - - Map variables = setupVariablesSunnyDayVID(); - - TestAsyncResponse asyncResponse = invokeAsyncProcess("CreateVfModuleInfra", - "v1", businessKey, createVfModuleRequest, variables); - - WorkflowResponse response = receiveResponse(businessKey, asyncResponse, 10000); - - String responseBody = response.getResponse(); - System.out.println("Workflow (Synch) Response:\n" + responseBody); - - injectSDNCCallbacks(callbacks, "assign, query"); - injectVNFRestCallbacks(callbacks, "vnfCreate"); - injectSDNCCallbacks(callbacks, "activate"); - - // TODO add appropriate assertions - - waitForProcessEnd(businessKey, 10000); - checkVariable(businessKey, "CreateVfModuleSuccessIndicator", true); - - logEnd(); - } - - // Active Scenario - private Map setupVariablesSunnyDayVID() { - Map variables = new HashMap(); - //try { - // variables.put("bpmnRequest", FileUtil.readResourceFile("__files/CreateVfModule_VID_request.json")); - //} - //catch (Exception e) { - - //} - //variables.put("mso-request-id", "testRequestId"); - variables.put("requestId", "testRequestId"); - variables.put("isBaseVfModule", false); - variables.put("isDebugLogEnabled", "true"); - variables.put("recipeTimeout", "0"); - variables.put("requestAction", "CREATE_VF_MODULE"); - variables.put("serviceInstanceId", "f70e927b-6087-4974-9ef8-c5e4d5847ca4"); - variables.put("vnfId", "skask"); - variables.put("vnfType", "vSAMP12"); - variables.put("vfModuleId", ""); - variables.put("volumeGroupId", ""); - variables.put("serviceType", "MOG"); - variables.put("vfModuleType", ""); - return variables; - - } - - /** - * Sunny day VID with volume attach scenario. - * - * @throws Exception - */ - @Test - @Deployment(resources = { - "process/CreateVfModuleInfra.bpmn", - "subprocess/DoCreateVfModule.bpmn", - "subprocess/SDNCAdapterV1.bpmn", - "subprocess/VnfAdapterRestV1.bpmn", - "subprocess/ConfirmVolumeGroupTenant.bpmn", - "subprocess/ConfirmVolumeGroupName.bpmn", - "subprocess/CreateAAIVfModule.bpmn", - "subprocess/CreateAAIVfModuleVolumeGroup.bpmn", - "subprocess/UpdateAAIVfModule.bpmn", - "subprocess/UpdateAAIGenericVnf.bpmn", - "subprocess/CompleteMsoProcess.bpmn", - "subprocess/FalloutHandler.bpmn" - }) - public void sunnyDayVIDWithVolumeGroupAttach() throws Exception { - - logStart(); - - MockGetVolumeGroupById("AAIAIC25", "78987", "VfModularity/VolumeGroup.xml"); - MockGetGenericVnfByIdWithDepth("skask", 1, "VfModularity/GenericVnf.xml"); - MockGetCloudRegion("MDTWNJ21", 200, "CreateNetworkV2/cloudRegion30_AAIResponse_Success.xml"); - MockGetVolumeGroupById("RDM2WAGPLCP", "78987", "DeleteVfModuleVolumeInfraV1/queryVolumeId_AAIResponse_Success.xml"); - MockPutVfModuleIdNoResponse("skask", "PCRF", ".*"); - mockVNFPost("", 202, "skask"); - MockGetNetworkPolicyfqdn(".*", "VfModularity/QueryNetworkPolicy_AAIResponse_Success.xml", 200); - MockPutGenericVnf("skask"); - MockGetGenericVnfByIdWithPriority("skask", ".*", 200, "VfModularity/VfModule-new.xml", 5); - mockSDNCAdapter("/SDNCAdapter", "vnf-type>STMTN", 200, "VfModularity/StandardSDNCSynchResponse.xml"); - mockSDNCAdapter("/SDNCAdapter", "SvcAction>query", 200, "VfModularity/StandardSDNCSynchResponse.xml"); - mockVNFPost("", 202, "skask"); - mockUpdateRequestDB(200, "Database/DBUpdateResponse.xml"); - - String businessKey = UUID.randomUUID().toString(); - String createVfModuleRequest = - FileUtil.readResourceFile("__files/CreateVfModuleVolumeGroup_VID_request.json"); - - Map variables = setupVariablesSunnyDayVIDWVolumeAttach(); - - TestAsyncResponse asyncResponse = invokeAsyncProcess("CreateVfModuleInfra", - "v1", businessKey, createVfModuleRequest, variables); - - WorkflowResponse response = receiveResponse(businessKey, asyncResponse, 10000); - - String responseBody = response.getResponse(); - System.out.println("Workflow (Synch) Response:\n" + responseBody); - - injectSDNCCallbacks(callbacks, "assign, query"); - injectVNFRestCallbacks(callbacks, "vnfCreate"); - injectSDNCCallbacks(callbacks, "activate"); - - // TODO add appropriate assertions - - waitForProcessEnd(businessKey, 10000); - checkVariable(businessKey, "CreateVfModuleSuccessIndicator", true); - - logEnd(); - } - - // Active Scenario - private Map setupVariablesSunnyDayVIDWVolumeAttach() { - Map variables = new HashMap(); - //try { - // variables.put("bpmnRequest", FileUtil.readResourceFile("__files/CreateVfModule_VID_request.json")); - //} - //catch (Exception e) { - - //} - //variables.put("mso-request-id", "testRequestId"); - variables.put("requestId", "testRequestId"); - variables.put("isBaseVfModule", false); - variables.put("isDebugLogEnabled", "true"); - variables.put("recipeTimeout", "0"); - variables.put("requestAction", "CREATE_VF_MODULE"); - variables.put("serviceInstanceId", "f70e927b-6087-4974-9ef8-c5e4d5847ca4"); - variables.put("vnfId", "skask"); - variables.put("vnfType", "vSAMP12"); - variables.put("vfModuleId", ""); - variables.put("volumeGroupId", "78987"); - variables.put("serviceType", "MOG"); - variables.put("vfModuleType", ""); - return variables; - - } - - -} +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.bpmn.infrastructure; + +import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockGetCloudRegion; +import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockGetGenericVnfById; +import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockGetGenericVnfByIdWithDepth; +import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockGetGenericVnfByIdWithPriority; +import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockGetNetworkPolicyfqdn; +import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockGetVolumeGroupById; +import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockPatchGenericVnf; +import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockPatchVfModuleId; +import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockPutGenericVnf; +import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockPutNetwork; +import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockPutVfModuleIdNoResponse; +import static org.openecomp.mso.bpmn.mock.StubResponseDatabase.mockUpdateRequestDB; +import static org.openecomp.mso.bpmn.mock.StubResponseSDNCAdapter.mockSDNCAdapter; +import static org.openecomp.mso.bpmn.mock.StubResponseVNFAdapter.mockVNFPost; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +import org.camunda.bpm.engine.test.Deployment; +import org.junit.Test; +import org.openecomp.mso.bpmn.common.WorkflowTest; +import org.openecomp.mso.bpmn.common.workflow.service.WorkflowResponse; +import org.openecomp.mso.bpmn.mock.FileUtil; + +/** + * Unit test cases for CreateVfModuleInfra.bpmn + */ +public class CreateVfModuleInfraTest extends WorkflowTest { + + private final CallbackSet callbacks = new CallbackSet(); + + public CreateVfModuleInfraTest() throws IOException { + callbacks.put("assign", FileUtil.readResourceFile( + "__files/VfModularity/SDNCTopologyAssignCallback.xml")); + callbacks.put("query", FileUtil.readResourceFile( + "__files/VfModularity/SDNCTopologyQueryCallbackVfModule.xml")); + callbacks.put("activate", FileUtil.readResourceFile( + "__files/VfModularity/SDNCTopologyActivateCallback.xml")); + callbacks.put("vnfCreate", FileUtil.readResourceFile( + "__files/VfModularity/VNFAdapterRestCreateCallback.xml")); + } + + + /** + * Sunny day VID scenario. + * + * @throws Exception + */ + @Test + @Deployment(resources = { + "process/CreateVfModuleInfra.bpmn", + "subprocess/DoCreateVfModule.bpmn", + "subprocess/SDNCAdapterV1.bpmn", + "subprocess/VnfAdapterRestV1.bpmn", + "subprocess/ConfirmVolumeGroupTenant.bpmn", + "subprocess/ConfirmVolumeGroupName.bpmn", + "subprocess/CreateAAIVfModule.bpmn", + "subprocess/UpdateAAIVfModule.bpmn", + "subprocess/UpdateAAIGenericVnf.bpmn", + "subprocess/CompleteMsoProcess.bpmn", + "subprocess/FalloutHandler.bpmn" + }) + public void sunnyDayVID() throws Exception { + + logStart(); + + MockGetGenericVnfByIdWithDepth("skask", 1, "VfModularity/GenericVnf.xml"); + MockGetGenericVnfByIdWithPriority("skask", ".*", 200, "VfModularity/VfModule-new.xml", 5); + MockGetGenericVnfById("skask", "VfModularity/GenericVnf.xml", 200); + MockPutVfModuleIdNoResponse("skask", "PCRF", ".*"); + MockPutNetwork(".*", "VfModularity/AddNetworkPolicy_AAIResponse_Success.xml", 200); + MockPutGenericVnf("skask"); + mockVNFPost("", 202, "skask"); + mockSDNCAdapter("/SDNCAdapter", "vnf-type>STMTN", 200, "VfModularity/StandardSDNCSynchResponse.xml"); + mockSDNCAdapter("/SDNCAdapter", "SvcAction>query", 200, "VfModularity/StandardSDNCSynchResponse.xml"); + mockUpdateRequestDB(200, "Database/DBUpdateResponse.xml"); + MockPatchGenericVnf("skask"); + MockPatchVfModuleId("skask", ".*"); + + String businessKey = UUID.randomUUID().toString(); + String createVfModuleRequest = + FileUtil.readResourceFile("__files/CreateVfModule_VID_request.json"); + + Map variables = setupVariablesSunnyDayVID(); + + TestAsyncResponse asyncResponse = invokeAsyncProcess("CreateVfModuleInfra", + "v1", businessKey, createVfModuleRequest, variables); + + WorkflowResponse response = receiveResponse(businessKey, asyncResponse, 10000); + + String responseBody = response.getResponse(); + System.out.println("Workflow (Synch) Response:\n" + responseBody); + + injectSDNCCallbacks(callbacks, "assign, query"); + injectVNFRestCallbacks(callbacks, "vnfCreate"); + injectSDNCCallbacks(callbacks, "activate"); + + // TODO add appropriate assertions + + waitForProcessEnd(businessKey, 10000); + checkVariable(businessKey, "CreateVfModuleSuccessIndicator", true); + + logEnd(); + } + + // Active Scenario + private Map setupVariablesSunnyDayVID() { + Map variables = new HashMap(); + //try { + // variables.put("bpmnRequest", FileUtil.readResourceFile("__files/CreateVfModule_VID_request.json")); + //} + //catch (Exception e) { + + //} + //variables.put("mso-request-id", "testRequestId"); + variables.put("requestId", "testRequestId"); + variables.put("isBaseVfModule", false); + variables.put("isDebugLogEnabled", "true"); + variables.put("recipeTimeout", "0"); + variables.put("requestAction", "CREATE_VF_MODULE"); + variables.put("serviceInstanceId", "f70e927b-6087-4974-9ef8-c5e4d5847ca4"); + variables.put("vnfId", "skask"); + variables.put("vnfType", "vSAMP12"); + variables.put("vfModuleId", ""); + variables.put("volumeGroupId", ""); + variables.put("serviceType", "MOG"); + variables.put("vfModuleType", ""); + return variables; + + } + + /** + * Sunny day VID with volume attach scenario. + * + * @throws Exception + */ + @Test + @Deployment(resources = { + "process/CreateVfModuleInfra.bpmn", + "subprocess/DoCreateVfModule.bpmn", + "subprocess/SDNCAdapterV1.bpmn", + "subprocess/VnfAdapterRestV1.bpmn", + "subprocess/ConfirmVolumeGroupTenant.bpmn", + "subprocess/ConfirmVolumeGroupName.bpmn", + "subprocess/CreateAAIVfModule.bpmn", + "subprocess/CreateAAIVfModuleVolumeGroup.bpmn", + "subprocess/UpdateAAIVfModule.bpmn", + "subprocess/UpdateAAIGenericVnf.bpmn", + "subprocess/CompleteMsoProcess.bpmn", + "subprocess/FalloutHandler.bpmn" + }) + public void sunnyDayVIDWithVolumeGroupAttach() throws Exception { + + logStart(); + + MockGetVolumeGroupById("AAIAIC25", "78987", "VfModularity/VolumeGroup.xml"); + MockGetGenericVnfByIdWithDepth("skask", 1, "VfModularity/GenericVnf.xml"); + MockGetCloudRegion("MDTWNJ21", 200, "CreateNetworkV2/cloudRegion30_AAIResponse_Success.xml"); + MockGetVolumeGroupById("RDM2WAGPLCP", "78987", "DeleteVfModuleVolumeInfraV1/queryVolumeId_AAIResponse_Success.xml"); + MockPutVfModuleIdNoResponse("skask", "PCRF", ".*"); + mockVNFPost("", 202, "skask"); + MockGetNetworkPolicyfqdn(".*", "VfModularity/QueryNetworkPolicy_AAIResponse_Success.xml", 200); + MockPutGenericVnf("skask"); + MockGetGenericVnfByIdWithPriority("skask", ".*", 200, "VfModularity/VfModule-new.xml", 5); + mockSDNCAdapter("/SDNCAdapter", "vnf-type>STMTN", 200, "VfModularity/StandardSDNCSynchResponse.xml"); + mockSDNCAdapter("/SDNCAdapter", "SvcAction>query", 200, "VfModularity/StandardSDNCSynchResponse.xml"); + mockVNFPost("", 202, "skask"); + mockUpdateRequestDB(200, "Database/DBUpdateResponse.xml"); + MockPatchGenericVnf("skask"); + MockPatchVfModuleId("skask", ".*"); + + String businessKey = UUID.randomUUID().toString(); + String createVfModuleRequest = + FileUtil.readResourceFile("__files/CreateVfModuleVolumeGroup_VID_request.json"); + + Map variables = setupVariablesSunnyDayVIDWVolumeAttach(); + + TestAsyncResponse asyncResponse = invokeAsyncProcess("CreateVfModuleInfra", + "v1", businessKey, createVfModuleRequest, variables); + + WorkflowResponse response = receiveResponse(businessKey, asyncResponse, 10000); + + String responseBody = response.getResponse(); + System.out.println("Workflow (Synch) Response:\n" + responseBody); + + injectSDNCCallbacks(callbacks, "assign, query"); + injectVNFRestCallbacks(callbacks, "vnfCreate"); + injectSDNCCallbacks(callbacks, "activate"); + + // TODO add appropriate assertions + + waitForProcessEnd(businessKey, 10000); + checkVariable(businessKey, "CreateVfModuleSuccessIndicator", true); + + logEnd(); + } + + // Active Scenario + private Map setupVariablesSunnyDayVIDWVolumeAttach() { + Map variables = new HashMap(); + //try { + // variables.put("bpmnRequest", FileUtil.readResourceFile("__files/CreateVfModule_VID_request.json")); + //} + //catch (Exception e) { + + //} + //variables.put("mso-request-id", "testRequestId"); + variables.put("requestId", "testRequestId"); + variables.put("isBaseVfModule", false); + variables.put("isDebugLogEnabled", "true"); + variables.put("recipeTimeout", "0"); + variables.put("requestAction", "CREATE_VF_MODULE"); + variables.put("serviceInstanceId", "f70e927b-6087-4974-9ef8-c5e4d5847ca4"); + variables.put("vnfId", "skask"); + variables.put("vnfType", "vSAMP12"); + variables.put("vfModuleId", ""); + variables.put("volumeGroupId", "78987"); + variables.put("serviceType", "MOG"); + variables.put("vfModuleType", ""); + return variables; + + } + + +} diff --git a/bpmn/MSOInfrastructureBPMN/src/test/java/org/openecomp/mso/bpmn/infrastructure/DeleteVfModuleInfraTest.java b/bpmn/MSOInfrastructureBPMN/src/test/java/org/openecomp/mso/bpmn/infrastructure/DeleteVfModuleInfraTest.java index a6ae368fd3..9a3ffe988d 100644 --- a/bpmn/MSOInfrastructureBPMN/src/test/java/org/openecomp/mso/bpmn/infrastructure/DeleteVfModuleInfraTest.java +++ b/bpmn/MSOInfrastructureBPMN/src/test/java/org/openecomp/mso/bpmn/infrastructure/DeleteVfModuleInfraTest.java @@ -1,579 +1,579 @@ -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - MSO - * ================================================================================ - * 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.openecomp.mso.bpmn.infrastructure; - -import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; -import static com.github.tomakehurst.wiremock.client.WireMock.containing; -import static com.github.tomakehurst.wiremock.client.WireMock.delete; -import static com.github.tomakehurst.wiremock.client.WireMock.get; -import static com.github.tomakehurst.wiremock.client.WireMock.post; -import static com.github.tomakehurst.wiremock.client.WireMock.put; -import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; -import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; -import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching; -import static org.openecomp.mso.bpmn.mock.StubResponseDatabase.mockUpdateRequestDB; -import static org.openecomp.mso.bpmn.mock.StubResponseVNFAdapter.mockVNFDelete; - -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; - -import org.camunda.bpm.engine.test.Deployment; -import org.junit.Ignore; -import org.junit.Test; -import org.openecomp.mso.bpmn.common.WorkflowTest; -import org.openecomp.mso.bpmn.common.workflow.service.WorkflowResponse; -import org.openecomp.mso.bpmn.core.WorkflowException; -import org.openecomp.mso.bpmn.mock.FileUtil; - -import com.github.tomakehurst.wiremock.client.WireMock; -/** - * Unit test for DoDeleteVfModule.bpmn. - */ -public class DeleteVfModuleInfraTest extends WorkflowTest { - private final CallbackSet callbacks = new CallbackSet(); - - private static final String EOL = "\n"; - - private final String vnfAdapterDeleteCallback = - "" + EOL + - " a27ce5a9-29c4-4c22-a017-6615ac73c721" + EOL + - " 973ed047-d251-4fb9-bf1a-65b8949e0a73" + EOL + - " true" + EOL + - " {{MESSAGE-ID}}" + EOL + - " " + EOL + - " " + EOL + - " policyKey1_contrail_network_policy_fqdn" + EOL + - " MSOTest:DefaultPolicyFQDN1" + EOL + - "" + EOL + - "" + EOL + - "policyKey2_contrail_network_policy_fqdn" + EOL + - "MSOTest:DefaultPolicyFQDN2" + EOL + - "" + EOL + - " " + EOL + - " oam_management_v4_address" + EOL + - " 1234" + EOL + - "" + EOL + - " " + EOL + - " oam_management_v6_address" + EOL + - " 1234" + EOL + - "" + EOL + - "" + EOL + - "" + EOL; - - private final String vnfAdapterDeleteCallbackFail = - "" + EOL + - " Error processing request to VNF-Async. Not Found." + EOL + - " INTERNAL" + EOL + - " false" + EOL + - " {{MESSAGE-ID}}" + EOL + - "" + EOL; - - private final String sdncAdapterDeleteCallback = - "" + EOL + - " {{REQUEST-ID}}" + EOL + - " Y" + EOL + - "" + EOL; - - public DeleteVfModuleInfraTest() throws IOException { - callbacks.put("sdncChangeDelete", sdncAdapterDeleteCallback); - callbacks.put("sdncDelete", sdncAdapterDeleteCallback); - callbacks.put("vnfDelete", vnfAdapterDeleteCallback); - callbacks.put("vnfDeleteFail", vnfAdapterDeleteCallbackFail); - } - - @Test - @Deployment(resources = { - "process/Infrastructure/DeleteVfModuleInfra.bpmn", - "subprocess/DoDeleteVfModule.bpmn", - "subprocess/PrepareUpdateAAIVfModule.bpmn", - "subprocess/UpdateAAIVfModule.bpmn", - "subprocess/UpdateAAIGenericVnf.bpmn", - "subprocess/DeleteAAIVfModule.bpmn", - "subprocess/SDNCAdapterV1.bpmn", - "subprocess/VnfAdapterRestV1.bpmn", - "subprocess/CompleteMsoProcess.bpmn", - "subprocess/FalloutHandler.bpmn" - }) - @Ignore - public void TestDeleteVfModuleSuccess() throws Exception { - // delete the Base Module - // vnf-id=a27ce5a9-29c4-4c22-a017-6615ac73c721, vf-module-id=973ed047-d251-4fb9-bf1a-65b8949e0a73 - String request = - "" + EOL + - " " + EOL + - " a27ce5a9-29c4-4c22-a017-6615ac73c721" + EOL + - " DELETE_VF_MODULE" + EOL + - " PORTAL" + EOL + - " " + EOL + - " " + EOL + - " a27ce5a9-29c4-4c22-a017-6615ac73c721" + EOL + - " STMTN5MMSC21" + EOL + - " asc_heat-int" + EOL + - " 973ed047-d251-4fb9-bf1a-65b8949e0a73" + EOL + - " STMTN5MMSC21-MMSC::module-0-0" + EOL + - " 00000000-0000-0000-0000-000000000000" + EOL + - " SDN-ETHERNET-INTERNET" + EOL + - " fba1bd1e195a404cacb9ce17a9b2b421" + EOL + - " pending-delete" + EOL + - " RDM2WAGPLCP" + EOL + - " " + EOL + - " " + EOL + - "" + EOL; - logStart(); - WireMock.reset(); - - stubFor(post(urlEqualTo("/SDNCAdapter")) - .withRequestBody(containing("SvcAction>changedelete")) - .willReturn(aResponse() - .withStatus(200) - .withHeader("Content-Type", "text/xml") - .withBodyFile("DeleteGenericVNFV1/sdncAdapterResponse.xml"))); - stubFor(post(urlEqualTo("/SDNCAdapter")) - .withRequestBody(containing("SvcAction>delete")) - .willReturn(aResponse() - .withStatus(200) - .withHeader("Content-Type", "text/xml") - .withBodyFile("DeleteGenericVNFV1/sdncAdapterResponse.xml"))); - - mockVNFDelete(".*", "/.*", 202); -// MockAAIGenericVnfSearch(); -// MockAAIVfModulePUT(false); -// MockAAIDeleteGenericVnf(); -// MockAAIDeleteVfModule(); - mockUpdateRequestDB(200, "VfModularity/DBUpdateResponse.xml"); - - stubFor(delete(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c721/vf-modules/vf-module/973ed047-d251-4fb9-bf1a-65b8949e0a73/[?]resource-version=0000073")) - .willReturn(aResponse() - .withStatus(200))); - stubFor(delete(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c720/vf-modules/vf-module/973ed047-d251-4fb9-bf1a-65b8949e0a75/[?]resource-version=0000075")) - .willReturn(aResponse() - .withStatus(200))); - stubFor(delete(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c718/vf-modules/vf-module/973ed047-d251-4fb9-bf1a-65b8949e0a78/[?]resource-version=0000078")) - .willReturn(aResponse() - .withStatus(200))); - stubFor(delete(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c719/vf-modules/vf-module/973ed047-d251-4fb9-bf1a-65b8949e0a77/[?]resource-version=0000077")) - .willReturn(aResponse() - .withStatus(500) - .withHeader("Content-Type", "text/xml") - .withBodyFile("aaiFault.xml"))); - stubFor(get(urlMatching("/aai/v[0-9]+/network/network-policies/network-policy\\?network-policy-fqdn=.*")) - .willReturn(aResponse() - .withStatus(200) - .withHeader("Content-Type", "text/xml") - .withBodyFile("VfModularity/QueryNetworkPolicy_AAIResponse_Success.xml"))); - - stubFor(delete(urlMatching("/aai/v[0-9]+/network/network-policies/network-policy/.*")) - .willReturn(aResponse() - .withStatus(200))); - - - stubFor(delete(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c721/[?]resource-version=0000021")) - .willReturn(aResponse() - .withStatus(200))); - stubFor(delete(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c718/[?]resource-version=0000018")) - .willReturn(aResponse() - .withStatus(500) - .withHeader("Content-Type", "text/xml") - .withBodyFile("aaiFault.xml"))); - - stubFor(put(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/.*/vf-modules/vf-module/.*")) - .withRequestBody(containing("MMSC")) - .willReturn(aResponse() - .withStatus(200))); - stubFor(put(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/.*/vf-modules/vf-module/.*")) - .withRequestBody(containing("PCRF")) - .willReturn(aResponse() - .withStatus(500) - .withHeader("Content-Type", "text/xml") - .withBodyFile("aaiFault.xml"))); - stubFor(put(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c721")) - .willReturn(aResponse() - .withStatus(200))); - - String body; - - // The following stubs are for CreateAAIVfModule and UpdateAAIVfModule - - stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/[?]vnf-name=STMTN5MMSC23&depth=1")) - .willReturn(aResponse() - .withStatus(500) - .withHeader("Content-Type", "text/xml") - .withBodyFile("aaiFault.xml"))); - - stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/[?]vnf-name=STMTN5MMSC22&depth=1")) - .willReturn(aResponse() - .withStatus(404) - .withHeader("Content-Type", "text/xml") - .withBody("Generic VNF Not Found"))); - stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/768073c7-f41f-4822-9323-b75962763d74[?]depth=1")) - .willReturn(aResponse() - .withStatus(404) - .withHeader("Content-Type", "text/xml") - .withBody("Generic VNF Not Found"))); - - body = - "" + EOL + - " a27ce5a9-29c4-4c22-a017-6615ac73c721" + EOL + - " STMTN5MMSC21" + EOL + - " mmsc-capacity" + EOL + - " SDN-MOBILITY" + EOL + - " vMMSC" + EOL + - " pending-create" + EOL + - " false" + EOL + - " false" + EOL + - " 1508691" + EOL + - " " + EOL + - " " + EOL + - " 973ed047-d251-4fb9-bf1a-65b8949e0a73" + EOL + - " STMTN5MMSC21-MMSC::module-0-0" + EOL + - " 973ed047-d251-4fb9-bf1a-65b8949e0a73" + EOL + - " 1.0" + EOL + - " true" + EOL + - " FILLED-IN-BY-MSO" + EOL + - " pending-create" + EOL + - " 1508692" + EOL + - " " + EOL + - " " + EOL + - " " + EOL + - " " + EOL + - " " + EOL + - "" + EOL; - stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/[?]vnf-name=STMTN5MMSC21&depth=1")) - .willReturn(aResponse() - .withStatus(200) - .withHeader("Content-Type", "text/xml") - .withBody(body))); - stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c721[?]depth=1")) - .willReturn(aResponse() - .withStatus(200) - .withHeader("Content-Type", "text/xml") - .withBody(body))); - - body = - "" + EOL + - " 2f6aee38-1e2a-11e6-82d1-ffc7d9ee8aa4" + EOL + - " STMTN5MMSC20" + EOL + - " mmsc-capacity" + EOL + - " SDN-MOBILITY" + EOL + - " vMMSC" + EOL + - " pending-create" + EOL + - " false" + EOL + - " false" + EOL + - " 1508691" + EOL + - " " + EOL + - " " + EOL + - " 973ed047-d251-4fb9-bf1a-65b8949e0a73" + EOL + - " STMTN5MMSC20-MMSC::module-0-0" + EOL + - " 973ed047-d251-4fb9-bf1a-65b8949e0a73" + EOL + - " 1.0" + EOL + - " true" + EOL + - " FILLED-IN-BY-MSO" + EOL + - " pending-create" + EOL + - " 1508692" + EOL + - " " + EOL + - " " + EOL + - " 973ed047-d251-4fb9-bf1a-65b8949e0a74" + EOL + - " STMTN5MMSC20-MMSC::module-1-0" + EOL + - " 973ed047-d251-4fb9-bf1a-65b8949e0a74" + EOL + - " 1.0" + EOL + - " false" + EOL + - " FILLED-IN-BY-MSO" + EOL + - " pending-create" + EOL + - " 1508692" + EOL + - " " + EOL + - " " + EOL + - " " + EOL + - " " + EOL + - " " + EOL + - "" + EOL; - stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/[?]vnf-name=STMTN5MMSC20&depth=1")) - .willReturn(aResponse() - .withStatus(200) - .withHeader("Content-Type", "text/xml") - .withBody(body))); - stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/2f6aee38-1e2a-11e6-82d1-ffc7d9ee8aa4[?]depth=1")) - .willReturn(aResponse() - .withStatus(200) - .withHeader("Content-Type", "text/xml") - .withBody(body))); - - // The following stubs are for DeleteAAIVfModule - - stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c723[?]depth=1")) - .willReturn(aResponse() - .withStatus(500) - .withHeader("Content-Type", "text/xml") - .withBodyFile("aaiFault.xml"))); - - stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c722[?]depth=1")) - .willReturn(aResponse() - .withStatus(404) - .withHeader("Content-Type", "text/xml") - .withBody("Generic VNF Not Found"))); - - body = - "" + EOL + - " a27ce5a9-29c4-4c22-a017-6615ac73c721" + EOL + - " STMTN5MMSC21" + EOL + - " mmsc-capacity" + EOL + - " SDN-MOBILITY" + EOL + - " vMMSC" + EOL + - " pending-create" + EOL + - " false" + EOL + - " false" + EOL + - " 0000021" + EOL + - " " + EOL + - " " + EOL + - " 973ed047-d251-4fb9-bf1a-65b8949e0a73" + EOL + - " STMTN5MMSC21-MMSC::module-0-0" + EOL + - " 973ed047-d251-4fb9-bf1a-65b8949e0a73" + EOL + - " 1.0" + EOL + - " true" + EOL + - " FILLED-IN-BY-MSO" + EOL + - " pending-create" + EOL + - " 0000073" + EOL + - " " + EOL + - " " + EOL + - " " + EOL + - " " + EOL + - " " + EOL + - "" + EOL; - stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c721[?]depth=1")) - .willReturn(aResponse() - .withStatus(200) - .withHeader("Content-Type", "text/xml") - .withBody(body))); - - body = - "" + EOL + - " a27ce5a9-29c4-4c22-a017-6615ac73c720" + EOL + - " STMTN5MMSC20" + EOL + - " mmsc-capacity" + EOL + - " SDN-MOBILITY" + EOL + - " vMMSC" + EOL + - " pending-create" + EOL + - " false" + EOL + - " false" + EOL + - " 0000020" + EOL + - " " + EOL + - " " + EOL + - " 973ed047-d251-4fb9-bf1a-65b8949e0a74" + EOL + - " STMTN5MMSC20-MMSC::module-0-0" + EOL + - " 973ed047-d251-4fb9-bf1a-65b8949e0a74" + EOL + - " 1.0" + EOL + - " true" + EOL + - " FILLED-IN-BY-MSO" + EOL + - " pending-create" + EOL + - " 0000074" + EOL + - " " + EOL + - " " + EOL + - " 973ed047-d251-4fb9-bf1a-65b8949e0a75" + EOL + - " STMTN5MMSC20-MMSC::module-1-0" + EOL + - " 973ed047-d251-4fb9-bf1a-65b8949e0a75" + EOL + - " 1.0" + EOL + - " false" + EOL + - " FILLED-IN-BY-MSO" + EOL + - " pending-create" + EOL + - " 0000075" + EOL + - " " + EOL + - " " + EOL + - " " + EOL + - " " + EOL + - " " + EOL + - "" + EOL; - stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c720[?]depth=1")) - .willReturn(aResponse() - .withStatus(200) - .withHeader("Content-Type", "text/xml") - .withBody(body))); - - body = - "" + EOL + - " a27ce5a9-29c4-4c22-a017-6615ac73c719" + EOL + - " STMTN5MMSC19" + EOL + - " mmsc-capacity" + EOL + - " SDN-MOBILITY" + EOL + - " vMMSC" + EOL + - " pending-create" + EOL + - " false" + EOL + - " false" + EOL + - " 0000019" + EOL + - " " + EOL + - " " + EOL + - " 973ed047-d251-4fb9-bf1a-65b8949e0a76" + EOL + - " STMTN5MMSC19-MMSC::module-0-0" + EOL + - " 973ed047-d251-4fb9-bf1a-65b8949e0a76" + EOL + - " 1.0" + EOL + - " true" + EOL + - " FILLED-IN-BY-MSO" + EOL + - " pending-create" + EOL + - " 0000076" + EOL + - " " + EOL + - " " + EOL + - " 973ed047-d251-4fb9-bf1a-65b8949e0a77" + EOL + - " STMTN5MMSC19-MMSC::module-1-0" + EOL + - " 973ed047-d251-4fb9-bf1a-65b8949e0a77" + EOL + - " 1.0" + EOL + - " false" + EOL + - " FILLED-IN-BY-MSO" + EOL + - " pending-create" + EOL + - " 0000077" + EOL + - " " + EOL + - " " + EOL + - " " + EOL + - " " + EOL + - " " + EOL + - "" + EOL; - stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c719[?]depth=1")) - .willReturn(aResponse() - .withStatus(200) - .withHeader("Content-Type", "text/xml") - .withBody(body))); - - body = - "" + EOL + - " a27ce5a9-29c4-4c22-a017-6615ac73c718" + EOL + - " STMTN5MMSC18" + EOL + - " mmsc-capacity" + EOL + - " SDN-MOBILITY" + EOL + - " vMMSC" + EOL + - " pending-create" + EOL + - " false" + EOL + - " false" + EOL + - " 0000018" + EOL + - " " + EOL + - " " + EOL + - " 973ed047-d251-4fb9-bf1a-65b8949e0a78" + EOL + - " STMTN5MMSC18-MMSC::module-0-0" + EOL + - " 973ed047-d251-4fb9-bf1a-65b8949e0a78" + EOL + - " 1.0" + EOL + - " true" + EOL + - " FILLED-IN-BY-MSO" + EOL + - " pending-create" + EOL + - " 0000078" + EOL + - " " + EOL + - " " + EOL + - " " + EOL + - " " + EOL + - " " + EOL + - "" + EOL; - stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c718[?]depth=1")) - .willReturn(aResponse() - .withStatus(200) - .withHeader("Content-Type", "text/xml") - .withBody(body))); - - body = - "" + EOL + - " a27ce5a9-29c4-4c22-a017-6615ac73c721" + EOL + - " STMTN5MMSC21" + EOL + - " mmsc-capacity" + EOL + - " SDN-MOBILITY" + EOL + - " vMMSC" + EOL + - " pending-create" + EOL + - " false" + EOL + - " false" + EOL + - " 0000021" + EOL + - " " + EOL + - " " + EOL + - " 973ed047-d251-4fb9-bf1a-65b8949e0a73" + EOL + - " STMTN5MMSC21-MMSC::module-0-0" + EOL + - " 973ed047-d251-4fb9-bf1a-65b8949e0a73" + EOL + - " 1.0" + EOL + - " true" + EOL + - " FILLED-IN-BY-MSO" + EOL + - " pending-create" + EOL + - " 0000073" + EOL + - " " + EOL + - " " + EOL + - " " + EOL + - " " + EOL + - " " + EOL + - "" + EOL; - stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c721/vf-modules/vf-module/973ed047-d251-4fb9-bf1a-65b8949e0a73")) - .willReturn(aResponse() - .withStatus(200) - .withHeader("Content-Type", "text/xml") - .withBody(body))); - - String businessKey = UUID.randomUUID().toString(); - String deleteVfModuleRequest = - FileUtil.readResourceFile("__files/DeleteVfModule_VID_request.json"); - //Map variables = new HashMap(); - - //variables.put("isDebugLogEnabled","true"); -// variables.put("mso-request-id", "a27ce5a9-29c4-4c22-a017-6615ac73c721"); -// variables.put("mso-service-instance-id", "a27ce5a9-29c4-4c22-a017-6615ac73c721"); - - Map variables = setupVariablesSunnyDayVID(); - - TestAsyncResponse asyncResponse = invokeAsyncProcess("DeleteVfModuleInfra", - "v1", businessKey, deleteVfModuleRequest, variables); - WorkflowResponse response = receiveResponse(businessKey, asyncResponse, 10000); - String responseBody = response.getResponse(); - System.out.println("Workflow (Synch) Response:\n" + responseBody); - - // "changedelete" operation not required for deleting a Vf Module -// injectSDNCCallbacks(callbacks, "sdncChangeDelete"); - injectVNFRestCallbacks(callbacks, "vnfDelete"); - waitForRunningProcessCount("vnfAdapterDeleteV1", 0, 120000); - injectSDNCCallbacks(callbacks, "sdncDelete"); - - waitForProcessEnd(businessKey, 10000); - WorkflowException wfe = (WorkflowException) getVariableFromHistory(businessKey, "WorkflowException"); - checkVariable(businessKey, "DeleteVfModuleInfraSuccessIndicator", true); - checkVariable(businessKey, "WorkflowException", null); - if (wfe != null) { - System.out.println("TestDeleteVfModuleInfraSuccess: ErrorCode=" + wfe.getErrorCode() + - ", ErrorMessage=" + wfe.getErrorMessage()); - } - logEnd(); - } - - // Active Scenario - private Map setupVariablesSunnyDayVID() { - Map variables = new HashMap(); - //try { - // variables.put("bpmnRequest", FileUtil.readResourceFile("__files/CreateVfModule_VID_request.json")); - //} - //catch (Exception e) { - - //} - //variables.put("mso-request-id", "testRequestId"); - variables.put("requestId", "testRequestId"); - variables.put("isBaseVfModule", "true"); - variables.put("isDebugLogEnabled", "true"); - variables.put("recipeTimeout", "0"); - variables.put("requestAction", "DELETE_VF_MODULE"); - variables.put("serviceInstanceId", "f70e927b-6087-4974-9ef8-c5e4d5847ca4"); - variables.put("vnfId", "a27ce5a9-29c4-4c22-a017-6615ac73c721"); - variables.put("vfModuleId", "973ed047-d251-4fb9-bf1a-65b8949e0a73"); - variables.put("volumeGroupId", ""); - variables.put("serviceType", "MOG"); - variables.put("vfModuleType", ""); - return variables; - - } - - +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.bpmn.infrastructure; + +import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; +import static com.github.tomakehurst.wiremock.client.WireMock.containing; +import static com.github.tomakehurst.wiremock.client.WireMock.delete; +import static com.github.tomakehurst.wiremock.client.WireMock.get; +import static com.github.tomakehurst.wiremock.client.WireMock.post; +import static com.github.tomakehurst.wiremock.client.WireMock.put; +import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; +import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; +import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching; +import static org.openecomp.mso.bpmn.mock.StubResponseDatabase.mockUpdateRequestDB; +import static org.openecomp.mso.bpmn.mock.StubResponseVNFAdapter.mockVNFDelete; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +import org.camunda.bpm.engine.test.Deployment; +import org.junit.Ignore; +import org.junit.Test; +import org.openecomp.mso.bpmn.common.WorkflowTest; +import org.openecomp.mso.bpmn.common.workflow.service.WorkflowResponse; +import org.openecomp.mso.bpmn.core.WorkflowException; +import org.openecomp.mso.bpmn.mock.FileUtil; + +import com.github.tomakehurst.wiremock.client.WireMock; +/** + * Unit test for DoDeleteVfModule.bpmn. + */ +public class DeleteVfModuleInfraTest extends WorkflowTest { + private final CallbackSet callbacks = new CallbackSet(); + + private static final String EOL = "\n"; + + private final String vnfAdapterDeleteCallback = + "" + EOL + + " a27ce5a9-29c4-4c22-a017-6615ac73c721" + EOL + + " 973ed047-d251-4fb9-bf1a-65b8949e0a73" + EOL + + " true" + EOL + + " {{MESSAGE-ID}}" + EOL + + " " + EOL + + " " + EOL + + " policyKey1_contrail_network_policy_fqdn" + EOL + + " MSOTest:DefaultPolicyFQDN1" + EOL + + "" + EOL + + "" + EOL + + "policyKey2_contrail_network_policy_fqdn" + EOL + + "MSOTest:DefaultPolicyFQDN2" + EOL + + "" + EOL + + " " + EOL + + " oam_management_v4_address" + EOL + + " 1234" + EOL + + "" + EOL + + " " + EOL + + " oam_management_v6_address" + EOL + + " 1234" + EOL + + "" + EOL + + "" + EOL + + "" + EOL; + + private final String vnfAdapterDeleteCallbackFail = + "" + EOL + + " Error processing request to VNF-Async. Not Found." + EOL + + " INTERNAL" + EOL + + " false" + EOL + + " {{MESSAGE-ID}}" + EOL + + "" + EOL; + + private final String sdncAdapterDeleteCallback = + "" + EOL + + " {{REQUEST-ID}}" + EOL + + " Y" + EOL + + "" + EOL; + + public DeleteVfModuleInfraTest() throws IOException { + callbacks.put("sdncChangeDelete", sdncAdapterDeleteCallback); + callbacks.put("sdncDelete", sdncAdapterDeleteCallback); + callbacks.put("vnfDelete", vnfAdapterDeleteCallback); + callbacks.put("vnfDeleteFail", vnfAdapterDeleteCallbackFail); + } + + @Test + @Deployment(resources = { + "process/Infrastructure/DeleteVfModuleInfra.bpmn", + "subprocess/DoDeleteVfModule.bpmn", + "subprocess/PrepareUpdateAAIVfModule.bpmn", + "subprocess/UpdateAAIVfModule.bpmn", + "subprocess/UpdateAAIGenericVnf.bpmn", + "subprocess/DeleteAAIVfModule.bpmn", + "subprocess/SDNCAdapterV1.bpmn", + "subprocess/VnfAdapterRestV1.bpmn", + "subprocess/CompleteMsoProcess.bpmn", + "subprocess/FalloutHandler.bpmn" + }) + @Ignore + public void TestDeleteVfModuleSuccess() throws Exception { + // delete the Base Module + // vnf-id=a27ce5a9-29c4-4c22-a017-6615ac73c721, vf-module-id=973ed047-d251-4fb9-bf1a-65b8949e0a73 + String request = + "" + EOL + + " " + EOL + + " a27ce5a9-29c4-4c22-a017-6615ac73c721" + EOL + + " DELETE_VF_MODULE" + EOL + + " PORTAL" + EOL + + " " + EOL + + " " + EOL + + " a27ce5a9-29c4-4c22-a017-6615ac73c721" + EOL + + " STMTN5MMSC21" + EOL + + " asc_heat-int" + EOL + + " 973ed047-d251-4fb9-bf1a-65b8949e0a73" + EOL + + " STMTN5MMSC21-MMSC::module-0-0" + EOL + + " 00000000-0000-0000-0000-000000000000" + EOL + + " SDN-ETHERNET-INTERNET" + EOL + + " fba1bd1e195a404cacb9ce17a9b2b421" + EOL + + " pending-delete" + EOL + + " RDM2WAGPLCP" + EOL + + " " + EOL + + " " + EOL + + "" + EOL; + logStart(); + WireMock.reset(); + + stubFor(post(urlEqualTo("/SDNCAdapter")) + .withRequestBody(containing("SvcAction>changedelete")) + .willReturn(aResponse() + .withStatus(200) + .withHeader("Content-Type", "text/xml") + .withBodyFile("DeleteGenericVNFV1/sdncAdapterResponse.xml"))); + stubFor(post(urlEqualTo("/SDNCAdapter")) + .withRequestBody(containing("SvcAction>delete")) + .willReturn(aResponse() + .withStatus(200) + .withHeader("Content-Type", "text/xml") + .withBodyFile("DeleteGenericVNFV1/sdncAdapterResponse.xml"))); + + mockVNFDelete(".*", "/.*", 202); +// MockAAIGenericVnfSearch(); +// MockAAIVfModulePUT(false); +// MockAAIDeleteGenericVnf(); +// MockAAIDeleteVfModule(); + mockUpdateRequestDB(200, "VfModularity/DBUpdateResponse.xml"); + + stubFor(delete(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c721/vf-modules/vf-module/973ed047-d251-4fb9-bf1a-65b8949e0a73/[?]resource-version=0000073")) + .willReturn(aResponse() + .withStatus(200))); + stubFor(delete(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c720/vf-modules/vf-module/973ed047-d251-4fb9-bf1a-65b8949e0a75/[?]resource-version=0000075")) + .willReturn(aResponse() + .withStatus(200))); + stubFor(delete(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c718/vf-modules/vf-module/973ed047-d251-4fb9-bf1a-65b8949e0a78/[?]resource-version=0000078")) + .willReturn(aResponse() + .withStatus(200))); + stubFor(delete(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c719/vf-modules/vf-module/973ed047-d251-4fb9-bf1a-65b8949e0a77/[?]resource-version=0000077")) + .willReturn(aResponse() + .withStatus(500) + .withHeader("Content-Type", "text/xml") + .withBodyFile("aaiFault.xml"))); + stubFor(get(urlMatching("/aai/v[0-9]+/network/network-policies/network-policy\\?network-policy-fqdn=.*")) + .willReturn(aResponse() + .withStatus(200) + .withHeader("Content-Type", "text/xml") + .withBodyFile("VfModularity/QueryNetworkPolicy_AAIResponse_Success.xml"))); + + stubFor(delete(urlMatching("/aai/v[0-9]+/network/network-policies/network-policy/.*")) + .willReturn(aResponse() + .withStatus(200))); + + + stubFor(delete(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c721/[?]resource-version=0000021")) + .willReturn(aResponse() + .withStatus(200))); + stubFor(delete(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c718/[?]resource-version=0000018")) + .willReturn(aResponse() + .withStatus(500) + .withHeader("Content-Type", "text/xml") + .withBodyFile("aaiFault.xml"))); + + stubFor(put(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/.*/vf-modules/vf-module/.*")) + .withRequestBody(containing("MMSC")) + .willReturn(aResponse() + .withStatus(200))); + stubFor(put(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/.*/vf-modules/vf-module/.*")) + .withRequestBody(containing("PCRF")) + .willReturn(aResponse() + .withStatus(500) + .withHeader("Content-Type", "text/xml") + .withBodyFile("aaiFault.xml"))); + stubFor(put(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c721")) + .willReturn(aResponse() + .withStatus(200))); + + String body; + + // The following stubs are for CreateAAIVfModule and UpdateAAIVfModule + + stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/[?]vnf-name=STMTN5MMSC23&depth=1")) + .willReturn(aResponse() + .withStatus(500) + .withHeader("Content-Type", "text/xml") + .withBodyFile("aaiFault.xml"))); + + stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/[?]vnf-name=STMTN5MMSC22&depth=1")) + .willReturn(aResponse() + .withStatus(404) + .withHeader("Content-Type", "text/xml") + .withBody("Generic VNF Not Found"))); + stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/768073c7-f41f-4822-9323-b75962763d74[?]depth=1")) + .willReturn(aResponse() + .withStatus(404) + .withHeader("Content-Type", "text/xml") + .withBody("Generic VNF Not Found"))); + + body = + "" + EOL + + " a27ce5a9-29c4-4c22-a017-6615ac73c721" + EOL + + " STMTN5MMSC21" + EOL + + " mmsc-capacity" + EOL + + " SDN-MOBILITY" + EOL + + " vMMSC" + EOL + + " pending-create" + EOL + + " false" + EOL + + " false" + EOL + + " 1508691" + EOL + + " " + EOL + + " " + EOL + + " 973ed047-d251-4fb9-bf1a-65b8949e0a73" + EOL + + " STMTN5MMSC21-MMSC::module-0-0" + EOL + + " 973ed047-d251-4fb9-bf1a-65b8949e0a73" + EOL + + " 1.0" + EOL + + " true" + EOL + + " FILLED-IN-BY-MSO" + EOL + + " pending-create" + EOL + + " 1508692" + EOL + + " " + EOL + + " " + EOL + + " " + EOL + + " " + EOL + + " " + EOL + + "" + EOL; + stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/[?]vnf-name=STMTN5MMSC21&depth=1")) + .willReturn(aResponse() + .withStatus(200) + .withHeader("Content-Type", "text/xml") + .withBody(body))); + stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c721[?]depth=1")) + .willReturn(aResponse() + .withStatus(200) + .withHeader("Content-Type", "text/xml") + .withBody(body))); + + body = + "" + EOL + + " 2f6aee38-1e2a-11e6-82d1-ffc7d9ee8aa4" + EOL + + " STMTN5MMSC20" + EOL + + " mmsc-capacity" + EOL + + " SDN-MOBILITY" + EOL + + " vMMSC" + EOL + + " pending-create" + EOL + + " false" + EOL + + " false" + EOL + + " 1508691" + EOL + + " " + EOL + + " " + EOL + + " 973ed047-d251-4fb9-bf1a-65b8949e0a73" + EOL + + " STMTN5MMSC20-MMSC::module-0-0" + EOL + + " 973ed047-d251-4fb9-bf1a-65b8949e0a73" + EOL + + " 1.0" + EOL + + " true" + EOL + + " FILLED-IN-BY-MSO" + EOL + + " pending-create" + EOL + + " 1508692" + EOL + + " " + EOL + + " " + EOL + + " 973ed047-d251-4fb9-bf1a-65b8949e0a74" + EOL + + " STMTN5MMSC20-MMSC::module-1-0" + EOL + + " 973ed047-d251-4fb9-bf1a-65b8949e0a74" + EOL + + " 1.0" + EOL + + " false" + EOL + + " FILLED-IN-BY-MSO" + EOL + + " pending-create" + EOL + + " 1508692" + EOL + + " " + EOL + + " " + EOL + + " " + EOL + + " " + EOL + + " " + EOL + + "" + EOL; + stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/[?]vnf-name=STMTN5MMSC20&depth=1")) + .willReturn(aResponse() + .withStatus(200) + .withHeader("Content-Type", "text/xml") + .withBody(body))); + stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/2f6aee38-1e2a-11e6-82d1-ffc7d9ee8aa4[?]depth=1")) + .willReturn(aResponse() + .withStatus(200) + .withHeader("Content-Type", "text/xml") + .withBody(body))); + + // The following stubs are for DeleteAAIVfModule + + stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c723[?]depth=1")) + .willReturn(aResponse() + .withStatus(500) + .withHeader("Content-Type", "text/xml") + .withBodyFile("aaiFault.xml"))); + + stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c722[?]depth=1")) + .willReturn(aResponse() + .withStatus(404) + .withHeader("Content-Type", "text/xml") + .withBody("Generic VNF Not Found"))); + + body = + "" + EOL + + " a27ce5a9-29c4-4c22-a017-6615ac73c721" + EOL + + " STMTN5MMSC21" + EOL + + " mmsc-capacity" + EOL + + " SDN-MOBILITY" + EOL + + " vMMSC" + EOL + + " pending-create" + EOL + + " false" + EOL + + " false" + EOL + + " 0000021" + EOL + + " " + EOL + + " " + EOL + + " 973ed047-d251-4fb9-bf1a-65b8949e0a73" + EOL + + " STMTN5MMSC21-MMSC::module-0-0" + EOL + + " 973ed047-d251-4fb9-bf1a-65b8949e0a73" + EOL + + " 1.0" + EOL + + " true" + EOL + + " FILLED-IN-BY-MSO" + EOL + + " pending-create" + EOL + + " 0000073" + EOL + + " " + EOL + + " " + EOL + + " " + EOL + + " " + EOL + + " " + EOL + + "" + EOL; + stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c721[?]depth=1")) + .willReturn(aResponse() + .withStatus(200) + .withHeader("Content-Type", "text/xml") + .withBody(body))); + + body = + "" + EOL + + " a27ce5a9-29c4-4c22-a017-6615ac73c720" + EOL + + " STMTN5MMSC20" + EOL + + " mmsc-capacity" + EOL + + " SDN-MOBILITY" + EOL + + " vMMSC" + EOL + + " pending-create" + EOL + + " false" + EOL + + " false" + EOL + + " 0000020" + EOL + + " " + EOL + + " " + EOL + + " 973ed047-d251-4fb9-bf1a-65b8949e0a74" + EOL + + " STMTN5MMSC20-MMSC::module-0-0" + EOL + + " 973ed047-d251-4fb9-bf1a-65b8949e0a74" + EOL + + " 1.0" + EOL + + " true" + EOL + + " FILLED-IN-BY-MSO" + EOL + + " pending-create" + EOL + + " 0000074" + EOL + + " " + EOL + + " " + EOL + + " 973ed047-d251-4fb9-bf1a-65b8949e0a75" + EOL + + " STMTN5MMSC20-MMSC::module-1-0" + EOL + + " 973ed047-d251-4fb9-bf1a-65b8949e0a75" + EOL + + " 1.0" + EOL + + " false" + EOL + + " FILLED-IN-BY-MSO" + EOL + + " pending-create" + EOL + + " 0000075" + EOL + + " " + EOL + + " " + EOL + + " " + EOL + + " " + EOL + + " " + EOL + + "" + EOL; + stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c720[?]depth=1")) + .willReturn(aResponse() + .withStatus(200) + .withHeader("Content-Type", "text/xml") + .withBody(body))); + + body = + "" + EOL + + " a27ce5a9-29c4-4c22-a017-6615ac73c719" + EOL + + " STMTN5MMSC19" + EOL + + " mmsc-capacity" + EOL + + " SDN-MOBILITY" + EOL + + " vMMSC" + EOL + + " pending-create" + EOL + + " false" + EOL + + " false" + EOL + + " 0000019" + EOL + + " " + EOL + + " " + EOL + + " 973ed047-d251-4fb9-bf1a-65b8949e0a76" + EOL + + " STMTN5MMSC19-MMSC::module-0-0" + EOL + + " 973ed047-d251-4fb9-bf1a-65b8949e0a76" + EOL + + " 1.0" + EOL + + " true" + EOL + + " FILLED-IN-BY-MSO" + EOL + + " pending-create" + EOL + + " 0000076" + EOL + + " " + EOL + + " " + EOL + + " 973ed047-d251-4fb9-bf1a-65b8949e0a77" + EOL + + " STMTN5MMSC19-MMSC::module-1-0" + EOL + + " 973ed047-d251-4fb9-bf1a-65b8949e0a77" + EOL + + " 1.0" + EOL + + " false" + EOL + + " FILLED-IN-BY-MSO" + EOL + + " pending-create" + EOL + + " 0000077" + EOL + + " " + EOL + + " " + EOL + + " " + EOL + + " " + EOL + + " " + EOL + + "" + EOL; + stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c719[?]depth=1")) + .willReturn(aResponse() + .withStatus(200) + .withHeader("Content-Type", "text/xml") + .withBody(body))); + + body = + "" + EOL + + " a27ce5a9-29c4-4c22-a017-6615ac73c718" + EOL + + " STMTN5MMSC18" + EOL + + " mmsc-capacity" + EOL + + " SDN-MOBILITY" + EOL + + " vMMSC" + EOL + + " pending-create" + EOL + + " false" + EOL + + " false" + EOL + + " 0000018" + EOL + + " " + EOL + + " " + EOL + + " 973ed047-d251-4fb9-bf1a-65b8949e0a78" + EOL + + " STMTN5MMSC18-MMSC::module-0-0" + EOL + + " 973ed047-d251-4fb9-bf1a-65b8949e0a78" + EOL + + " 1.0" + EOL + + " true" + EOL + + " FILLED-IN-BY-MSO" + EOL + + " pending-create" + EOL + + " 0000078" + EOL + + " " + EOL + + " " + EOL + + " " + EOL + + " " + EOL + + " " + EOL + + "" + EOL; + stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c718[?]depth=1")) + .willReturn(aResponse() + .withStatus(200) + .withHeader("Content-Type", "text/xml") + .withBody(body))); + + body = + "" + EOL + + " a27ce5a9-29c4-4c22-a017-6615ac73c721" + EOL + + " STMTN5MMSC21" + EOL + + " mmsc-capacity" + EOL + + " SDN-MOBILITY" + EOL + + " vMMSC" + EOL + + " pending-create" + EOL + + " false" + EOL + + " false" + EOL + + " 0000021" + EOL + + " " + EOL + + " " + EOL + + " 973ed047-d251-4fb9-bf1a-65b8949e0a73" + EOL + + " STMTN5MMSC21-MMSC::module-0-0" + EOL + + " 973ed047-d251-4fb9-bf1a-65b8949e0a73" + EOL + + " 1.0" + EOL + + " true" + EOL + + " FILLED-IN-BY-MSO" + EOL + + " pending-create" + EOL + + " 0000073" + EOL + + " " + EOL + + " " + EOL + + " " + EOL + + " " + EOL + + " " + EOL + + "" + EOL; + stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c721/vf-modules/vf-module/973ed047-d251-4fb9-bf1a-65b8949e0a73")) + .willReturn(aResponse() + .withStatus(200) + .withHeader("Content-Type", "text/xml") + .withBody(body))); + + String businessKey = UUID.randomUUID().toString(); + String deleteVfModuleRequest = + FileUtil.readResourceFile("__files/DeleteVfModule_VID_request.json"); + //Map variables = new HashMap(); + + //variables.put("isDebugLogEnabled","true"); +// variables.put("mso-request-id", "a27ce5a9-29c4-4c22-a017-6615ac73c721"); +// variables.put("mso-service-instance-id", "a27ce5a9-29c4-4c22-a017-6615ac73c721"); + + Map variables = setupVariablesSunnyDayVID(); + + TestAsyncResponse asyncResponse = invokeAsyncProcess("DeleteVfModuleInfra", + "v1", businessKey, deleteVfModuleRequest, variables); + WorkflowResponse response = receiveResponse(businessKey, asyncResponse, 10000); + String responseBody = response.getResponse(); + System.out.println("Workflow (Synch) Response:\n" + responseBody); + + // "changedelete" operation not required for deleting a Vf Module +// injectSDNCCallbacks(callbacks, "sdncChangeDelete"); + injectVNFRestCallbacks(callbacks, "vnfDelete"); + waitForRunningProcessCount("vnfAdapterDeleteV1", 0, 120000); + injectSDNCCallbacks(callbacks, "sdncDelete"); + + waitForProcessEnd(businessKey, 10000); + WorkflowException wfe = (WorkflowException) getVariableFromHistory(businessKey, "WorkflowException"); + checkVariable(businessKey, "DeleteVfModuleInfraSuccessIndicator", true); + checkVariable(businessKey, "WorkflowException", null); + if (wfe != null) { + System.out.println("TestDeleteVfModuleInfraSuccess: ErrorCode=" + wfe.getErrorCode() + + ", ErrorMessage=" + wfe.getErrorMessage()); + } + logEnd(); + } + + // Active Scenario + private Map setupVariablesSunnyDayVID() { + Map variables = new HashMap(); + //try { + // variables.put("bpmnRequest", FileUtil.readResourceFile("__files/CreateVfModule_VID_request.json")); + //} + //catch (Exception e) { + + //} + //variables.put("mso-request-id", "testRequestId"); + variables.put("requestId", "testRequestId"); + variables.put("isBaseVfModule", "true"); + variables.put("isDebugLogEnabled", "true"); + variables.put("recipeTimeout", "0"); + variables.put("requestAction", "DELETE_VF_MODULE"); + variables.put("serviceInstanceId", "f70e927b-6087-4974-9ef8-c5e4d5847ca4"); + variables.put("vnfId", "a27ce5a9-29c4-4c22-a017-6615ac73c721"); + variables.put("vfModuleId", "973ed047-d251-4fb9-bf1a-65b8949e0a73"); + variables.put("volumeGroupId", ""); + variables.put("serviceType", "MOG"); + variables.put("vfModuleType", ""); + return variables; + + } + + } \ No newline at end of file diff --git a/bpmn/MSOInfrastructureBPMN/src/test/java/org/openecomp/mso/bpmn/infrastructure/DoCreateVfModuleRollbackTest.java b/bpmn/MSOInfrastructureBPMN/src/test/java/org/openecomp/mso/bpmn/infrastructure/DoCreateVfModuleRollbackTest.java index 7a9345f83a..5b0d4c73bd 100644 --- a/bpmn/MSOInfrastructureBPMN/src/test/java/org/openecomp/mso/bpmn/infrastructure/DoCreateVfModuleRollbackTest.java +++ b/bpmn/MSOInfrastructureBPMN/src/test/java/org/openecomp/mso/bpmn/infrastructure/DoCreateVfModuleRollbackTest.java @@ -1,157 +1,160 @@ -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - MSO - * ================================================================================ - * 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.openecomp.mso.bpmn.infrastructure; - -import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockDeleteGenericVnf; -import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockDeleteVfModuleId; -import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockGetGenericVnfByIdWithDepth; -import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockGetVfModuleId; -import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockPutGenericVnf; -import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockPutVfModuleIdNoResponse; -import static org.openecomp.mso.bpmn.mock.StubResponseSDNCAdapter.mockSDNCAdapter; -import static org.openecomp.mso.bpmn.mock.StubResponseVNFAdapter.mockVNFDelete; - -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; - -import org.camunda.bpm.engine.test.Deployment; -import org.junit.Test; -import org.openecomp.mso.bpmn.common.WorkflowTest; -import org.openecomp.mso.bpmn.common.WorkflowTest.CallbackSet; -import org.openecomp.mso.bpmn.core.RollbackData; -import org.openecomp.mso.bpmn.core.WorkflowException; - -/** - * Unit test for DoDeleteVfModule.bpmn. - */ -public class DoCreateVfModuleRollbackTest extends WorkflowTest { - private final CallbackSet callbacks = new CallbackSet(); - - private static final String EOL = "\n"; - - private final String vnfAdapterDeleteCallback = - "" + EOL + - " a27ce5a9-29c4-4c22-a017-6615ac73c721" + EOL + - " 973ed047-d251-4fb9-bf1a-65b8949e0a73" + EOL + - " true" + EOL + - " {{MESSAGE-ID}}" + EOL + - "" + EOL; - - private final String vnfAdapterDeleteCallbackFail = - "" + EOL + - " Error processing request to VNF-Async. Not Found." + EOL + - " INTERNAL" + EOL + - " false" + EOL + - " {{MESSAGE-ID}}" + EOL + - "" + EOL; - - private final String sdncAdapterDeleteCallback = - "" + EOL + - " {{REQUEST-ID}}" + EOL + - " Y" + EOL + - "" + EOL; - - public DoCreateVfModuleRollbackTest() throws IOException { - callbacks.put("sdncChangeDelete", sdncAdapterDeleteCallback); - callbacks.put("sdncDelete", sdncAdapterDeleteCallback); - callbacks.put("vnfDelete", vnfAdapterDeleteCallback); - callbacks.put("vnfDeleteFail", vnfAdapterDeleteCallbackFail); - } - - @Test - - @Deployment(resources = { - "subprocess/DoCreateVfModuleRollback.bpmn", - "subprocess/PrepareUpdateAAIVfModule.bpmn", - "subprocess/UpdateAAIVfModule.bpmn", - "subprocess/UpdateAAIGenericVnf.bpmn", - "subprocess/DeleteAAIVfModule.bpmn", - "subprocess/SDNCAdapterV1.bpmn", - "subprocess/VnfAdapterRestV1.bpmn" - }) - public void TestCreateVfModuleRollbackSuccess() { - logStart(); - - mockSDNCAdapter("/SDNCAdapter", "SvcAction>delete", 200, "DeleteGenericVNFV1/sdncAdapterResponse.xml"); - mockVNFDelete("a27ce5a9-29c4-4c22-a017-6615ac73c721", "/973ed047-d251-4fb9-bf1a-65b8949e0a73", 202); - MockDeleteGenericVnf("a27ce5a9-29c4-4c22-a017-6615ac73c721", "0000021", 200); - MockDeleteVfModuleId("a27ce5a9-29c4-4c22-a017-6615ac73c721", "973ed047-d251-4fb9-bf1a-65b8949e0a73", "0000073", 200); - MockPutVfModuleIdNoResponse("a27ce5a9-29c4-4c22-a017-6615ac73c721", "MMSC", "973ed047-d251-4fb9-bf1a-65b8949e0a73"); - MockPutGenericVnf("a27ce5a9-29c4-4c22-a017-6615ac73c721"); - MockGetGenericVnfByIdWithDepth("a27ce5a9-29c4-4c22-a017-6615ac73c721", 1, "DoCreateVfModuleRollback/GenericVnf.xml"); - MockGetVfModuleId("a27ce5a9-29c4-4c22-a017-6615ac73c721", "973ed047-d251-4fb9-bf1a-65b8949e0a73", "DoCreateVfModuleRollback/GenericVnfVfModule.xml", 200); - - String businessKey = UUID.randomUUID().toString(); - Map variables = new HashMap(); - RollbackData rollbackData = new RollbackData(); - rollbackData.put("VFMODULE", "source", "PORTAL"); - rollbackData.put("VFMODULE", "vnfid", "a27ce5a9-29c4-4c22-a017-6615ac73c721"); - rollbackData.put("VFMODULE", "vnfname", "STMTN5MMSC21"); - rollbackData.put("VFMODULE", "vnftype", "asc_heat-int"); - rollbackData.put("VFMODULE", "vfmoduleid", "973ed047-d251-4fb9-bf1a-65b8949e0a73"); - rollbackData.put("VFMODULE", "vfmodulename", "STMTN5MMSC21-MMSC::module-0-0"); - rollbackData.put("VFMODULE", "tenantid", "fba1bd1e195a404cacb9ce17a9b2b421"); - rollbackData.put("VFMODULE", "aiccloudregion", "RDM2WAGPLCP"); - rollbackData.put("VFMODULE", "heatstackid", "thisisaheatstack"); - rollbackData.put("VFMODULE", "contrailNetworkPolicyFqdn0", "MSOTest:DefaultPolicyFQDN1"); - rollbackData.put("VFMODULE", "contrailNetworkPolicyFqdn1", "MSOTest:DefaultPolicyFQDN2"); - rollbackData.put("VFMODULE", "oamManagementV6Address", "2000:abc:bce:1111"); - rollbackData.put("VFMODULE", "oamManagementV4Address", "127.0.0.1"); - - rollbackData.put("VFMODULE", "rollbackPrepareUpdateVfModule", "true"); - rollbackData.put("VFMODULE", "rollbackVnfAdapterCreate", "true"); - rollbackData.put("VFMODULE", "rollbackUpdateAAIVfModule", "true"); - rollbackData.put("VFMODULE", "rollbackSDNCRequestActivate", "true"); - rollbackData.put("VFMODULE", "rollbackCreateAAIVfModule", "true"); - rollbackData.put("VFMODULE", "rollbackCreateNetworkPoliciesAAI", "true"); - rollbackData.put("VFMODULE", "rollbackUpdateVnfAAI", "true"); - - - - variables.put("isDebugLogEnabled","true"); - variables.put("mso-request-id", "a27ce5a9-29c4-4c22-a017-6615ac73c721"); - variables.put("mso-service-instance-id", "a27ce5a9-29c4-4c22-a017-6615ac73c721"); - rollbackData.put("VFMODULE", "msorequestid", "a27ce5a9-29c4-4c22-a017-6615ac73c721"); - rollbackData.put("VFMODULE", "serviceinstanceid", "a27ce5a9-29c4-4c22-a017-6615ac73c721"); - variables.put("RollbackData", rollbackData); - invokeSubProcess("DoCreateVfModuleRollback", businessKey, variables); - - // "changedelete" operation not required for deleting a Vf Module -// injectSDNCCallbacks(callbacks, "sdncChangeDelete"); - injectVNFRestCallbacks(callbacks, "vnfDelete"); - waitForRunningProcessCount("vnfAdapterDeleteV1", 0, 120000); - injectSDNCCallbacks(callbacks, "sdncDelete"); - - waitForProcessEnd(businessKey, 10000); - WorkflowException wfe = (WorkflowException) getVariableFromHistory(businessKey, "WorkflowException"); - checkVariable(businessKey, "WorkflowException", null); - if (wfe != null) { - System.out.println("TestCreateVfModuleSuccess: ErrorCode=" + wfe.getErrorCode() + - ", ErrorMessage=" + wfe.getErrorMessage()); - } - logEnd(); - } - - -} - +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.bpmn.infrastructure; + +import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockDeleteGenericVnf; +import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockDeleteVfModuleId; +import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockGetGenericVnfByIdWithDepth; +import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockGetVfModuleId; +import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockPatchGenericVnf; +import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockPatchVfModuleId; +import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockPutGenericVnf; +import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockPutVfModuleIdNoResponse; +import static org.openecomp.mso.bpmn.mock.StubResponseSDNCAdapter.mockSDNCAdapter; +import static org.openecomp.mso.bpmn.mock.StubResponseVNFAdapter.mockVNFDelete; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +import org.camunda.bpm.engine.test.Deployment; +import org.junit.Test; +import org.openecomp.mso.bpmn.common.WorkflowTest; +import org.openecomp.mso.bpmn.core.RollbackData; +import org.openecomp.mso.bpmn.core.WorkflowException; + +/** + * Unit test for DoDeleteVfModule.bpmn. + */ +public class DoCreateVfModuleRollbackTest extends WorkflowTest { + private final CallbackSet callbacks = new CallbackSet(); + + private static final String EOL = "\n"; + + private final String vnfAdapterDeleteCallback = + "" + EOL + + " a27ce5a9-29c4-4c22-a017-6615ac73c721" + EOL + + " 973ed047-d251-4fb9-bf1a-65b8949e0a73" + EOL + + " true" + EOL + + " {{MESSAGE-ID}}" + EOL + + "" + EOL; + + private final String vnfAdapterDeleteCallbackFail = + "" + EOL + + " Error processing request to VNF-Async. Not Found." + EOL + + " INTERNAL" + EOL + + " false" + EOL + + " {{MESSAGE-ID}}" + EOL + + "" + EOL; + + private final String sdncAdapterDeleteCallback = + "" + EOL + + " {{REQUEST-ID}}" + EOL + + " Y" + EOL + + "" + EOL; + + public DoCreateVfModuleRollbackTest() throws IOException { + callbacks.put("sdncChangeDelete", sdncAdapterDeleteCallback); + callbacks.put("sdncDelete", sdncAdapterDeleteCallback); + callbacks.put("vnfDelete", vnfAdapterDeleteCallback); + callbacks.put("vnfDeleteFail", vnfAdapterDeleteCallbackFail); + } + + @Test + + @Deployment(resources = { + "subprocess/DoCreateVfModuleRollback.bpmn", + "subprocess/PrepareUpdateAAIVfModule.bpmn", + "subprocess/UpdateAAIVfModule.bpmn", + "subprocess/UpdateAAIGenericVnf.bpmn", + "subprocess/DeleteAAIVfModule.bpmn", + "subprocess/SDNCAdapterV1.bpmn", + "subprocess/VnfAdapterRestV1.bpmn" + }) + public void TestCreateVfModuleRollbackSuccess() { + logStart(); + + mockSDNCAdapter("/SDNCAdapter", "SvcAction>delete", 200, "DeleteGenericVNFV1/sdncAdapterResponse.xml"); + mockVNFDelete("a27ce5a9-29c4-4c22-a017-6615ac73c721", "/973ed047-d251-4fb9-bf1a-65b8949e0a73", 202); + MockDeleteGenericVnf("a27ce5a9-29c4-4c22-a017-6615ac73c721", "0000021", 200); + MockDeleteVfModuleId("a27ce5a9-29c4-4c22-a017-6615ac73c721", "973ed047-d251-4fb9-bf1a-65b8949e0a73", "0000073", 200); + MockPutVfModuleIdNoResponse("a27ce5a9-29c4-4c22-a017-6615ac73c721", "MMSC", "973ed047-d251-4fb9-bf1a-65b8949e0a73"); + MockPutGenericVnf("a27ce5a9-29c4-4c22-a017-6615ac73c721"); + MockGetGenericVnfByIdWithDepth("a27ce5a9-29c4-4c22-a017-6615ac73c721", 1, "DoCreateVfModuleRollback/GenericVnf.xml"); + MockGetVfModuleId("a27ce5a9-29c4-4c22-a017-6615ac73c721", "973ed047-d251-4fb9-bf1a-65b8949e0a73", "DoCreateVfModuleRollback/GenericVnfVfModule.xml", 200); + MockPatchGenericVnf("a27ce5a9-29c4-4c22-a017-6615ac73c721"); + MockPatchVfModuleId("a27ce5a9-29c4-4c22-a017-6615ac73c721", "973ed047-d251-4fb9-bf1a-65b8949e0a73"); + + String businessKey = UUID.randomUUID().toString(); + Map variables = new HashMap(); + RollbackData rollbackData = new RollbackData(); + rollbackData.put("VFMODULE", "source", "PORTAL"); + rollbackData.put("VFMODULE", "vnfid", "a27ce5a9-29c4-4c22-a017-6615ac73c721"); + rollbackData.put("VFMODULE", "vnfname", "STMTN5MMSC21"); + rollbackData.put("VFMODULE", "vnftype", "asc_heat-int"); + rollbackData.put("VFMODULE", "vfmoduleid", "973ed047-d251-4fb9-bf1a-65b8949e0a73"); + rollbackData.put("VFMODULE", "vfmodulename", "STMTN5MMSC21-MMSC::module-0-0"); + rollbackData.put("VFMODULE", "tenantid", "fba1bd1e195a404cacb9ce17a9b2b421"); + rollbackData.put("VFMODULE", "aiccloudregion", "RDM2WAGPLCP"); + rollbackData.put("VFMODULE", "heatstackid", "thisisaheatstack"); + rollbackData.put("VFMODULE", "contrailNetworkPolicyFqdn0", "MSOTest:DefaultPolicyFQDN1"); + rollbackData.put("VFMODULE", "contrailNetworkPolicyFqdn1", "MSOTest:DefaultPolicyFQDN2"); + rollbackData.put("VFMODULE", "oamManagementV6Address", "2000:abc:bce:1111"); + rollbackData.put("VFMODULE", "oamManagementV4Address", "127.0.0.1"); + + rollbackData.put("VFMODULE", "rollbackPrepareUpdateVfModule", "true"); + rollbackData.put("VFMODULE", "rollbackVnfAdapterCreate", "true"); + rollbackData.put("VFMODULE", "rollbackUpdateAAIVfModule", "true"); + rollbackData.put("VFMODULE", "rollbackSDNCRequestActivate", "true"); + rollbackData.put("VFMODULE", "rollbackCreateAAIVfModule", "true"); + rollbackData.put("VFMODULE", "rollbackCreateNetworkPoliciesAAI", "true"); + rollbackData.put("VFMODULE", "rollbackUpdateVnfAAI", "true"); + + + + variables.put("isDebugLogEnabled","true"); + variables.put("mso-request-id", "a27ce5a9-29c4-4c22-a017-6615ac73c721"); + variables.put("mso-service-instance-id", "a27ce5a9-29c4-4c22-a017-6615ac73c721"); + rollbackData.put("VFMODULE", "msorequestid", "a27ce5a9-29c4-4c22-a017-6615ac73c721"); + rollbackData.put("VFMODULE", "serviceinstanceid", "a27ce5a9-29c4-4c22-a017-6615ac73c721"); + variables.put("RollbackData", rollbackData); + invokeSubProcess("DoCreateVfModuleRollback", businessKey, variables); + + // "changedelete" operation not required for deleting a Vf Module +// injectSDNCCallbacks(callbacks, "sdncChangeDelete"); + injectVNFRestCallbacks(callbacks, "vnfDelete"); + waitForRunningProcessCount("vnfAdapterDeleteV1", 0, 120000); + injectSDNCCallbacks(callbacks, "sdncDelete"); + + waitForProcessEnd(businessKey, 10000); + WorkflowException wfe = (WorkflowException) getVariableFromHistory(businessKey, "WorkflowException"); + checkVariable(businessKey, "WorkflowException", null); + if (wfe != null) { + System.out.println("TestCreateVfModuleSuccess: ErrorCode=" + wfe.getErrorCode() + + ", ErrorMessage=" + wfe.getErrorMessage()); + } + logEnd(); + } + + +} + diff --git a/bpmn/MSOInfrastructureBPMN/src/test/java/org/openecomp/mso/bpmn/infrastructure/DoCreateVfModuleTest.java b/bpmn/MSOInfrastructureBPMN/src/test/java/org/openecomp/mso/bpmn/infrastructure/DoCreateVfModuleTest.java index 235deb85af..fc4816cef3 100644 --- a/bpmn/MSOInfrastructureBPMN/src/test/java/org/openecomp/mso/bpmn/infrastructure/DoCreateVfModuleTest.java +++ b/bpmn/MSOInfrastructureBPMN/src/test/java/org/openecomp/mso/bpmn/infrastructure/DoCreateVfModuleTest.java @@ -1,149 +1,150 @@ -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - MSO - * ================================================================================ - * 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.openecomp.mso.bpmn.infrastructure; - - -import static org.openecomp.mso.bpmn.common.BPMNUtil.getRawVariable; -import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockGetGenericVnfByIdWithDepth; -import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockGetGenericVnfByIdWithPriority; -import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockPutGenericVnf; -import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockPutNetwork; -import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockPutVfModuleIdNoResponse; -import static org.openecomp.mso.bpmn.mock.StubResponseDatabase.mockUpdateRequestDB; -import static org.openecomp.mso.bpmn.mock.StubResponseSDNCAdapter.mockSDNCAdapter; -import static org.openecomp.mso.bpmn.mock.StubResponseVNFAdapter.mockVNFPost; - -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; - -import org.camunda.bpm.engine.test.Deployment; -import org.junit.Assert; -import org.junit.Test; -import org.openecomp.mso.bpmn.common.WorkflowTest; -import org.openecomp.mso.bpmn.common.WorkflowTest.CallbackSet; -import org.openecomp.mso.bpmn.mock.FileUtil; - -/** - * Unit tests for DoCreateVfModuleTest.bpmn. - */ -public class DoCreateVfModuleTest extends WorkflowTest { - - private final CallbackSet callbacks = new CallbackSet(); - - public DoCreateVfModuleTest() throws IOException { - callbacks.put("assign", FileUtil.readResourceFile( - "__files/VfModularity/SDNCTopologyAssignCallback.xml")); - callbacks.put("query", FileUtil.readResourceFile( - "__files/VfModularity/SDNCTopologyQueryCallback.xml")); - callbacks.put("activate", FileUtil.readResourceFile( - "__files/VfModularity/SDNCTopologyActivateCallback.xml")); - callbacks.put("vnfCreate", FileUtil.readResourceFile( - "__files/VfModularity/VNFAdapterRestCreateCallback.xml")); - } - - /** - * Test the sunny day scenario. - */ - @Test - - @Deployment(resources = { - "subprocess/DoCreateVfModule.bpmn", - "subprocess/SDNCAdapterV1.bpmn", - "subprocess/VnfAdapterRestV1.bpmn", - "subprocess/ConfirmVolumeGroupTenant.bpmn", - "subprocess/ConfirmVolumeGroupName.bpmn", - "subprocess/CreateAAIVfModule.bpmn", - "subprocess/UpdateAAIVfModule.bpmn", - "subprocess/CreateAAIVfModuleVolumeGroup.bpmn", - "subprocess/UpdateAAIGenericVnf.bpmn" - }) - public void sunnyDay() throws IOException { - - logStart(); - - MockGetGenericVnfByIdWithPriority("skask", ".*", 200, "VfModularity/VfModule-new.xml", 5); - MockGetGenericVnfByIdWithDepth("skask", 1, "VfModularity/GenericVnf.xml"); - MockPutVfModuleIdNoResponse("skask", "PCRF", ".*"); - MockPutNetwork(".*", "VfModularity/AddNetworkPolicy_AAIResponse_Success.xml", 200); - MockPutGenericVnf("skask"); - mockSDNCAdapter("/SDNCAdapter", "vnf-type>STMTN", 200, "VfModularity/StandardSDNCSynchResponse.xml"); - mockSDNCAdapter("/SDNCAdapter", "SvcAction>query", 200, "VfModularity/StandardSDNCSynchResponse.xml"); - mockVNFPost("", 202, "skask"); - mockUpdateRequestDB(200, "Database/DBUpdateResponse.xml"); - - String businessKey = UUID.randomUUID().toString(); - //RuntimeService runtimeService = processEngineRule.getRuntimeService(); - - Map variables = setupVariablesSunnyDayBuildingBlocks(); - //runtimeService.startProcessInstanceByKey("DoCreateVfModule", variables); - invokeSubProcess("DoCreateVfModule", businessKey, variables); - - injectSDNCCallbacks(callbacks, "assign, query"); - injectVNFRestCallbacks(callbacks, "vnfCreate"); - injectSDNCCallbacks(callbacks, "activate"); - - waitForProcessEnd(businessKey, 10000); - - Assert.assertTrue(isProcessEnded(businessKey)); - Assert.assertTrue((boolean) getRawVariable(processEngineRule, "DoCreateVfModule", "DCVFM_SuccessIndicator")); - - logEnd(); - } - - private Map setupVariablesSunnyDayBuildingBlocks() { - Map variables = new HashMap(); - - variables.put("mso-request-id", "testRequestId"); - variables.put("requestId", "testRequestId"); - variables.put("isBaseVfModule", false); - variables.put("isDebugLogEnabled", "true"); - variables.put("disableRollback", "true"); - //variables.put("recipeTimeout", "0"); - //variables.put("requestAction", "CREATE_VF_MODULE"); - variables.put("serviceInstanceId", "f70e927b-6087-4974-9ef8-c5e4d5847ca4"); - variables.put("vnfId", "skask"); - variables.put("vfModuleName", "PCRF::module-0-2"); - variables.put("vnfType", "vSAMP12"); - variables.put("vfModuleId", ""); - variables.put("volumeGroupId", ""); - variables.put("serviceType", "MOG"); - variables.put("vfModuleType", ""); - variables.put("isVidRequest", "true"); - variables.put("asdcServiceModelVersion", "1.0"); - - String vfModuleModelInfo = "{" + "\"modelInfo\": { "+ "\"modelType\": \"vfModule\"," + - "\"modelInvariantId\": \"ff5256d2-5a33-55df-13ab-12abad84e7ff\"," + - "\"modelNameVersionId\": \"fe6478e5-ea33-3346-ac12-ab121484a3fe\"," + - "\"modelName\": \"STMTN5MMSC21-MMSC::model-1-0\"," + - "\"modelVersion\": \"1\"," + - "\"modelCustomizationId\": \"MODEL-123\"" + "}}"; - variables.put("vfModuleModelInfo", vfModuleModelInfo); - - String cloudConfiguration = "{" + "\"cloudConfiguration\": { " + - "\"lcpCloudRegionId\": \"MDTWNJ21\"," + - "\"tenantId\": \"fba1bd1e195a404cacb9ce17a9b2b421\"" + "}}"; - variables.put("cloudConfiguration", cloudConfiguration); - return variables; - - } -} +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.bpmn.infrastructure; + + +import static org.openecomp.mso.bpmn.common.BPMNUtil.getRawVariable; +import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockGetGenericVnfByIdWithDepth; +import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockGetGenericVnfByIdWithPriority; +import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockPutGenericVnf; +import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockPutNetwork; +import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockPutVfModuleIdNoResponse; +import static org.openecomp.mso.bpmn.mock.StubResponseDatabase.mockUpdateRequestDB; +import static org.openecomp.mso.bpmn.mock.StubResponseSDNCAdapter.mockSDNCAdapter; +import static org.openecomp.mso.bpmn.mock.StubResponseVNFAdapter.mockVNFPost; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +import org.camunda.bpm.engine.test.Deployment; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; +import org.openecomp.mso.bpmn.common.WorkflowTest; +import org.openecomp.mso.bpmn.common.WorkflowTest.CallbackSet; +import org.openecomp.mso.bpmn.mock.FileUtil; + +/** + * Unit tests for DoCreateVfModuleTest.bpmn. + */ +public class DoCreateVfModuleTest extends WorkflowTest { + + private final CallbackSet callbacks = new CallbackSet(); + + public DoCreateVfModuleTest() throws IOException { + callbacks.put("assign", FileUtil.readResourceFile( + "__files/VfModularity/SDNCTopologyAssignCallback.xml")); + callbacks.put("query", FileUtil.readResourceFile( + "__files/VfModularity/SDNCTopologyQueryCallback.xml")); + callbacks.put("activate", FileUtil.readResourceFile( + "__files/VfModularity/SDNCTopologyActivateCallback.xml")); + callbacks.put("vnfCreate", FileUtil.readResourceFile( + "__files/VfModularity/VNFAdapterRestCreateCallback.xml")); + } + + /** + * Test the sunny day scenario. + */ + @Test + @Ignore + @Deployment(resources = { + "subprocess/DoCreateVfModule.bpmn", + "subprocess/SDNCAdapterV1.bpmn", + "subprocess/VnfAdapterRestV1.bpmn", + "subprocess/ConfirmVolumeGroupTenant.bpmn", + "subprocess/ConfirmVolumeGroupName.bpmn", + "subprocess/CreateAAIVfModule.bpmn", + "subprocess/UpdateAAIVfModule.bpmn", + "subprocess/CreateAAIVfModuleVolumeGroup.bpmn", + "subprocess/UpdateAAIGenericVnf.bpmn" + }) + public void sunnyDay() throws IOException { + + logStart(); + + MockGetGenericVnfByIdWithPriority("skask", ".*", 200, "VfModularity/VfModule-new.xml", 5); + MockGetGenericVnfByIdWithDepth("skask", 1, "VfModularity/GenericVnf.xml"); + MockPutVfModuleIdNoResponse("skask", "PCRF", ".*"); + MockPutNetwork(".*", "VfModularity/AddNetworkPolicy_AAIResponse_Success.xml", 200); + MockPutGenericVnf("skask"); + mockSDNCAdapter("/SDNCAdapter", "vnf-type>STMTN", 200, "VfModularity/StandardSDNCSynchResponse.xml"); + mockSDNCAdapter("/SDNCAdapter", "SvcAction>query", 200, "VfModularity/StandardSDNCSynchResponse.xml"); + mockVNFPost("", 202, "skask"); + mockUpdateRequestDB(200, "Database/DBUpdateResponse.xml"); + + String businessKey = UUID.randomUUID().toString(); + //RuntimeService runtimeService = processEngineRule.getRuntimeService(); + + Map variables = setupVariablesSunnyDayBuildingBlocks(); + //runtimeService.startProcessInstanceByKey("DoCreateVfModule", variables); + invokeSubProcess("DoCreateVfModule", businessKey, variables); + + injectSDNCCallbacks(callbacks, "assign, query"); + injectVNFRestCallbacks(callbacks, "vnfCreate"); + injectSDNCCallbacks(callbacks, "activate"); + + waitForProcessEnd(businessKey, 10000); + + Assert.assertTrue(isProcessEnded(businessKey)); + Assert.assertTrue((boolean) getRawVariable(processEngineRule, "DoCreateVfModule", "DCVFM_SuccessIndicator")); + + logEnd(); + } + + private Map setupVariablesSunnyDayBuildingBlocks() { + Map variables = new HashMap(); + + variables.put("mso-request-id", "testRequestId"); + variables.put("requestId", "testRequestId"); + variables.put("isBaseVfModule", false); + variables.put("isDebugLogEnabled", "true"); + variables.put("disableRollback", "true"); + //variables.put("recipeTimeout", "0"); + //variables.put("requestAction", "CREATE_VF_MODULE"); + variables.put("serviceInstanceId", "f70e927b-6087-4974-9ef8-c5e4d5847ca4"); + variables.put("vnfId", "skask"); + variables.put("vfModuleName", "PCRF::module-0-2"); + variables.put("vnfType", "vSAMP12"); + variables.put("vfModuleId", ""); + variables.put("volumeGroupId", ""); + variables.put("serviceType", "MOG"); + variables.put("vfModuleType", ""); + variables.put("isVidRequest", "true"); + variables.put("asdcServiceModelVersion", "1.0"); + + String vfModuleModelInfo = "{" + "\"modelInfo\": { "+ "\"modelType\": \"vfModule\"," + + "\"modelInvariantId\": \"ff5256d2-5a33-55df-13ab-12abad84e7ff\"," + + "\"modelNameVersionId\": \"fe6478e5-ea33-3346-ac12-ab121484a3fe\"," + + "\"modelName\": \"STMTN5MMSC21-MMSC::model-1-0\"," + + "\"modelVersion\": \"1\"," + + "\"modelCustomizationId\": \"MODEL-123\"" + "}}"; + variables.put("vfModuleModelInfo", vfModuleModelInfo); + + String cloudConfiguration = "{" + "\"cloudConfiguration\": { " + + "\"lcpCloudRegionId\": \"MDTWNJ21\"," + + "\"tenantId\": \"fba1bd1e195a404cacb9ce17a9b2b421\"" + "}}"; + variables.put("cloudConfiguration", cloudConfiguration); + return variables; + + } +} diff --git a/bpmn/MSOInfrastructureBPMN/src/test/java/org/openecomp/mso/bpmn/infrastructure/DoDeleteVfModuleTest.java b/bpmn/MSOInfrastructureBPMN/src/test/java/org/openecomp/mso/bpmn/infrastructure/DoDeleteVfModuleTest.java index a04ed1759d..a3165f7ff3 100644 --- a/bpmn/MSOInfrastructureBPMN/src/test/java/org/openecomp/mso/bpmn/infrastructure/DoDeleteVfModuleTest.java +++ b/bpmn/MSOInfrastructureBPMN/src/test/java/org/openecomp/mso/bpmn/infrastructure/DoDeleteVfModuleTest.java @@ -1,549 +1,561 @@ -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - MSO - * ================================================================================ - * 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.openecomp.mso.bpmn.infrastructure; - -import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; -import static com.github.tomakehurst.wiremock.client.WireMock.containing; -import static com.github.tomakehurst.wiremock.client.WireMock.delete; -import static com.github.tomakehurst.wiremock.client.WireMock.post; -import static com.github.tomakehurst.wiremock.client.WireMock.put; -import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; -import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; -import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching; -import static org.openecomp.mso.bpmn.common.DeleteAAIVfModuleTest.MockAAIDeleteGenericVnf; -import static org.openecomp.mso.bpmn.common.DeleteAAIVfModuleTest.MockAAIDeleteVfModule; -import static org.openecomp.mso.bpmn.common.DeleteAAIVfModuleTest.MockAAIGenericVnfSearch; - -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; - -import org.camunda.bpm.engine.test.Deployment; -import org.junit.Assert; -import org.junit.Test; -import org.openecomp.mso.bpmn.common.WorkflowTest; -import org.openecomp.mso.bpmn.common.WorkflowTest.CallbackSet; -import org.openecomp.mso.bpmn.core.WorkflowException; - -/** - * Unit test for DoDeleteVfModule.bpmn. - */ -public class DoDeleteVfModuleTest extends WorkflowTest { - private final CallbackSet callbacks = new CallbackSet(); - - private static final String EOL = "\n"; - - private final String vnfAdapterDeleteCallback = - "" + EOL + - " a27ce5a9-29c4-4c22-a017-6615ac73c721" + EOL + - " 973ed047-d251-4fb9-bf1a-65b8949e0a73" + EOL + - " true" + EOL + - " {{MESSAGE-ID}}" + EOL + - "" + EOL; - - private final String vnfAdapterDeleteCallbackFail = - "" + EOL + - " Error processing request to VNF-Async. Not Found." + EOL + - " INTERNAL" + EOL + - " false" + EOL + - " {{MESSAGE-ID}}" + EOL + - "" + EOL; - - private final String sdncAdapterDeleteCallback = - "" + EOL + - " {{REQUEST-ID}}" + EOL + - " Y" + EOL + - "" + EOL; - - public DoDeleteVfModuleTest() throws IOException { - callbacks.put("sdncChangeDelete", sdncAdapterDeleteCallback); - callbacks.put("sdncDelete", sdncAdapterDeleteCallback); - callbacks.put("vnfDelete", vnfAdapterDeleteCallback); - callbacks.put("vnfDeleteFail", vnfAdapterDeleteCallbackFail); - } - - private final String wfeString = "WorkflowException"; - - @Test - @Deployment(resources = { - "subprocess/DoDeleteVfModule.bpmn", - "subprocess/PrepareUpdateAAIVfModule.bpmn", - "subprocess/UpdateAAIVfModule.bpmn", - "subprocess/UpdateAAIGenericVnf.bpmn", - "subprocess/DeleteAAIVfModule.bpmn", - "subprocess/SDNCAdapterV1.bpmn", - "subprocess/VnfAdapterRestV1.bpmn" - }) - public void TestDoDeleteVfModuleSuccess() { - // delete the Base Module and Generic Vnf - // vnf-id=a27ce5a9-29c4-4c22-a017-6615ac73c721, vf-module-id=973ed047-d251-4fb9-bf1a-65b8949e0a73 - String request = - "" + EOL + - " " + EOL + - " DELETE_VF_MODULE" + EOL + - " PORTAL" + EOL + - " " + EOL + - " " + EOL + - " a27ce5a9-29c4-4c22-a017-6615ac73c721" + EOL + - " STMTN5MMSC21" + EOL + - " asc_heat-int" + EOL + - " 973ed047-d251-4fb9-bf1a-65b8949e0a73" + EOL + - " STMTN5MMSC21-MMSC::module-0-0" + EOL + - " 00000000-0000-0000-0000-000000000000" + EOL + - " SDN-ETHERNET-INTERNET" + EOL + - " fba1bd1e195a404cacb9ce17a9b2b421" + EOL + - " pending-delete" + EOL + - " RDM2WAGPLCP" + EOL + - " " + EOL + - " " + EOL + - "" + EOL; - logStart(); - MockDoDeleteVfModule_SDNCSuccess(); - MockDoDeleteVfModule_DeleteVNFSuccess(); - MockAAIGenericVnfSearch(); - MockAAIVfModulePUT(false); - MockAAIDeleteGenericVnf(); - MockAAIDeleteVfModule(); - String businessKey = UUID.randomUUID().toString(); - Map variables = new HashMap(); - variables.put("isDebugLogEnabled","true"); - variables.put("mso-request-id", "a27ce5a9-29c4-4c22-a017-6615ac73c721"); - variables.put("mso-service-instance-id", "a27ce5a9-29c4-4c22-a017-6615ac73c721"); - variables.put("DoDeleteVfModuleRequest",request); - variables.put("isVidRequest", "true"); - invokeSubProcess("DoDeleteVfModule", businessKey, variables); - - // "changedelete" operation not required for deleting a Vf Module -// injectSDNCCallbacks(callbacks, "sdncChangeDelete"); - injectVNFRestCallbacks(callbacks, "vnfDelete"); - waitForRunningProcessCount("vnfAdapterDeleteV1", 0, 120000); - injectSDNCCallbacks(callbacks, "sdncDelete"); - - waitForProcessEnd(businessKey, 10000); - WorkflowException wfe = (WorkflowException) getVariableFromHistory(businessKey, wfeString); - checkVariable(businessKey, wfeString, null); - if (wfe != null) { - System.out.println("TestDoDeleteVfModuleSuccess: ErrorCode=" + wfe.getErrorCode() + - ", ErrorMessage=" + wfe.getErrorMessage()); - } - logEnd(); - } - - @Test - @Deployment(resources = { - "subprocess/DoDeleteVfModule.bpmn", - "subprocess/PrepareUpdateAAIVfModule.bpmn", - "subprocess/UpdateAAIVfModule.bpmn", - "subprocess/UpdateAAIGenericVnf.bpmn", - "subprocess/DeleteAAIVfModule.bpmn", - "subprocess/SDNCAdapterV1.bpmn", - "subprocess/VnfAdapterRestV1.bpmn" - }) - public void TestDoDeleteVfModule_Building_Block_Success() { - logStart(); - MockDoDeleteVfModule_SDNCSuccess(); - MockDoDeleteVfModule_DeleteVNFSuccess(); - MockAAIGenericVnfSearch(); - MockAAIVfModulePUT(false); - MockAAIDeleteGenericVnf(); - MockAAIDeleteVfModule(); - String businessKey = UUID.randomUUID().toString(); - Map variables = new HashMap(); - - variables.put("mso-request-id", "a27ce5a9-29c4-4c22-a017-6615ac73c721"); - variables.put("requestId", "a27ce5a9-29c4-4c22-a017-6615ac73c721"); - variables.put("isDebugLogEnabled","true"); - variables.put("vnfId", "a27ce5a9-29c4-4c22-a017-6615ac73c721"); - variables.put("vfModuleId", "973ed047-d251-4fb9-bf1a-65b8949e0a73"); - variables.put("serviceInstanceId", "a27ce5a9-29c4-4c22-a017-6615ac73c721"); - variables.put("vfModuleName", "STMTN5MMSC21-MMSC::module-0-0"); - variables.put("sdncVersion", "1610"); - variables.put("isVidRequest", "true"); - String vfModuleModelInfo = "{" + "\"modelType\": \"vnf\"," + - "\"modelInvariantId\": \"ff5256d2-5a33-55df-13ab-12abad84e7ff\"," + - "\"modelNameVersionId\": \"fe6478e5-ea33-3346-ac12-ab121484a3fe\"," + - "\"modelName\": \"vSAMP12\"," + - "\"modelVersion\": \"1.0\"," + - "\"modelCustomizationId\": \"MODEL-ID-1234\"," + - "}"; - variables.put("vfModuleModelInfo", vfModuleModelInfo); - - String cloudConfiguration = "{" + - "\"lcpCloudRegionId\": \"RDM2WAGPLCP\"," + - "\"tenantId\": \"fba1bd1e195a404cacb9ce17a9b2b421\"" + "}"; - variables.put("cloudConfiguration", cloudConfiguration); - - - invokeSubProcess("DoDeleteVfModule", businessKey, variables); - - // "changedelete" operation not required for deleting a Vf Module -// injectSDNCCallbacks(callbacks, "sdncChangeDelete"); - injectVNFRestCallbacks(callbacks, "vnfDelete"); - waitForRunningProcessCount("vnfAdapterDeleteV1", 0, 120000); - injectSDNCCallbacks(callbacks, "sdncDelete"); - - waitForProcessEnd(businessKey, 10000); - WorkflowException wfe = (WorkflowException) getVariableFromHistory(businessKey, wfeString); - checkVariable(businessKey, wfeString, null); - if (wfe != null) { - System.out.println("TestDoDeleteVfModule_Building_Block_Success: ErrorCode=" + wfe.getErrorCode() + - ", ErrorMessage=" + wfe.getErrorMessage()); - } - logEnd(); - } - - - @Test - @Deployment(resources = { - "subprocess/DoDeleteVfModule.bpmn", - "subprocess/PrepareUpdateAAIVfModule.bpmn", - "subprocess/UpdateAAIVfModule.bpmn", - "subprocess/UpdateAAIGenericVnf.bpmn", - "subprocess/DeleteAAIVfModule.bpmn", - "subprocess/SDNCAdapterV1.bpmn", - "subprocess/VnfAdapterRestV1.bpmn" - }) - public void TestDoDeleteVfModuleSDNCFailure() { - // delete the Base Module and Generic Vnf - SDNCAdapter failure - // vnf-id=a27ce5a9-29c4-4c22-a017-6615ac73c721, vf-module-id=973ed047-d251-4fb9-bf1a-65b8949e0a73 - String request = - "" + EOL + - " " + EOL + - " DELETE_VF_MODULE" + EOL + - " PORTAL" + EOL + - " " + EOL + - " " + EOL + - " a27ce5a9-29c4-4c22-a017-6615ac73c721" + EOL + - " STMTN5MMSC21" + EOL + - " asc_heat-int" + EOL + - " 973ed047-d251-4fb9-bf1a-65b8949e0a73" + EOL + - " STMTN5MMSC21-MMSC::module-0-0" + EOL + - " 00000000-0000-0000-0000-000000000000" + EOL + - " SDN-ETHERNET-INTERNET" + EOL + - " fba1bd1e195a404cacb9ce17a9b2b421" + EOL + - " pending-delete" + EOL + - " RDM2WAGPLCP" + EOL + - " " + EOL + - " " + EOL + - "" + EOL; - - logStart(); - MockDoDeleteVfModule_SDNCFailure(); - MockDoDeleteVfModule_DeleteVNFSuccess(); - MockAAIGenericVnfSearch(); - MockAAIVfModulePUT(false); - MockAAIDeleteGenericVnf(); - MockAAIDeleteVfModule(); - String businessKey = UUID.randomUUID().toString(); - Map variables = new HashMap(); - variables.put("isDebugLogEnabled","true"); - variables.put("mso-request-id", "a27ce5a9-29c4-4c22-a017-6615ac73c721"); - variables.put("mso-service-instance-id", "a27ce5a9-29c4-4c22-a017-6615ac73c721"); - variables.put("DoDeleteVfModuleRequest", request); - variables.put("isVidRequest", "true"); - invokeSubProcess("DoDeleteVfModule", businessKey, variables); - - // "changedelete" operation not required for deleting a Vf Module -// injectSDNCCallbacks(callbacks, "sdncChangeDelete"); - injectVNFRestCallbacks(callbacks, "vnfDelete"); - waitForRunningProcessCount("vnfAdapterDeleteV1", 0, 120000); - // cause a failure by not injecting a callback -// injectSDNCCallbacks(callbacks, "sdncDelete"); - - waitForProcessEnd(businessKey, 10000); - WorkflowException wfe = (WorkflowException) getVariableFromHistory(businessKey, wfeString); - Assert.assertNotNull(wfe); - if (wfe != null) { - System.out.println("TestDoDeleteVfModuleSDNCFailure: ErrorCode=" + wfe.getErrorCode() + - ", ErrorMessage=" + wfe.getErrorMessage()); - Assert.assertTrue(wfe.getErrorCode() == 7000); - Assert.assertTrue(wfe.getErrorMessage().startsWith("Could not communicate")); - } - logEnd(); - } - - @Test - @Deployment(resources = { - "subprocess/DoDeleteVfModule.bpmn", - "subprocess/PrepareUpdateAAIVfModule.bpmn", - "subprocess/UpdateAAIVfModule.bpmn", - "subprocess/UpdateAAIGenericVnf.bpmn", - "subprocess/DeleteAAIVfModule.bpmn", - "subprocess/SDNCAdapterV1.bpmn", - "subprocess/VnfAdapterRestV1.bpmn" - }) - public void TestDoDeleteVfModuleSDNCCallbackFailure() { - // delete the Base Module and Generic Vnf - SDNCAdapter Callback failure - // vnf-id=a27ce5a9-29c4-4c22-a017-6615ac73c721, vf-module-id=973ed047-d251-4fb9-bf1a-65b8949e0a73 - String request = - "" + EOL + - " " + EOL + - " DELETE_VF_MODULE" + EOL + - " PORTAL" + EOL + - " " + EOL + - " " + EOL + - " a27ce5a9-29c4-4c22-a017-6615ac73c721" + EOL + - " STMTN5MMSC21" + EOL + - " asc_heat-int" + EOL + - " 973ed047-d251-4fb9-bf1a-65b8949e0a73" + EOL + - " STMTN5MMSC21-MMSC::module-0-0" + EOL + - " 00000000-0000-0000-0000-000000000000" + EOL + - " SDN-ETHERNET-INTERNET" + EOL + - " fba1bd1e195a404cacb9ce17a9b2b421" + EOL + - " pending-delete" + EOL + - " RDM2WAGPLCP" + EOL + - " " + EOL + - " " + EOL + - "" + EOL; - - logStart(); - MockDoDeleteVfModule_SDNCSuccess(); - MockDoDeleteVfModule_DeleteVNFSuccess(); - MockAAIGenericVnfSearch(); - MockAAIVfModulePUT(false); - MockAAIDeleteGenericVnf(); - MockAAIDeleteVfModule(); - String businessKey = UUID.randomUUID().toString(); - Map variables = new HashMap(); - variables.put("isDebugLogEnabled","true"); - variables.put("mso-request-id", "a27ce5a9-29c4-4c22-a017-6615ac73c721"); - variables.put("mso-service-instance-id", "a27ce5a9-29c4-4c22-a017-6615ac73c721"); - variables.put("DoDeleteVfModuleRequest",request); - variables.put("isVidRequest", "true"); - invokeSubProcess("DoDeleteVfModule", businessKey, variables); - - // "changedelete" operation not required for deleting a Vf Module -// injectSDNCCallbacks(callbacks, "sdncChangeDelete:ERR"); - injectVNFRestCallbacks(callbacks, "vnfDelete"); - waitForRunningProcessCount("vnfAdapterDeleteV1", 0, 120000); - // return a failure in the callback - injectSDNCCallbacks(callbacks, "sdncDelete:ERR"); - - waitForProcessEnd(businessKey, 10000); - WorkflowException wfe = (WorkflowException) getVariableFromHistory(businessKey, wfeString); - Assert.assertNotNull(wfe); - if (wfe != null) { - System.out.println("TestDoDeleteVfModuleSDNCCallbackFailure: ErrorCode=" + wfe.getErrorCode() + - ", ErrorMessage=" + wfe.getErrorMessage()); - Assert.assertTrue(wfe.getErrorCode() == 5310); - Assert.assertTrue(wfe.getErrorMessage().startsWith("Received error from SDN-C")); - } - logEnd(); - } - - @Test - @Deployment(resources = { - "subprocess/DoDeleteVfModule.bpmn", - "subprocess/PrepareUpdateAAIVfModule.bpmn", - "subprocess/UpdateAAIVfModule.bpmn", - "subprocess/UpdateAAIGenericVnf.bpmn", - "subprocess/DeleteAAIVfModule.bpmn", - "subprocess/SDNCAdapterV1.bpmn", - "subprocess/VnfAdapterRestV1.bpmn" - }) - public void TestDoDeleteVfModuleVNFFailure() { - // delete the Base Module and Generic Vnf - VNFAdapter failure - // vnf-id=a27ce5a9-29c4-4c22-a017-6615ac73c721, vf-module-id=973ed047-d251-4fb9-bf1a-65b8949e0a73 - String request = - "" + EOL + - " " + EOL + - " DELETE_VF_MODULE" + EOL + - " PORTAL" + EOL + - " " + EOL + - " " + EOL + - " a27ce5a9-29c4-4c22-a017-6615ac73c721" + EOL + - " STMTN5MMSC21" + EOL + - " asc_heat-int" + EOL + - " 973ed047-d251-4fb9-bf1a-65b8949e0a73" + EOL + - " STMTN5MMSC21-MMSC::module-0-0" + EOL + - " 00000000-0000-0000-0000-000000000000" + EOL + - " SDN-ETHERNET-INTERNET" + EOL + - " fba1bd1e195a404cacb9ce17a9b2b421" + EOL + - " pending-delete" + EOL + - " RDM2WAGPLCP" + EOL + - " " + EOL + - " " + EOL + - "" + EOL; - - logStart(); - MockDoDeleteVfModule_SDNCSuccess(); - MockDoDeleteVfModule_DeleteVNFFailure(); - MockAAIGenericVnfSearch(); - MockAAIVfModulePUT(false); - MockAAIDeleteGenericVnf(); - MockAAIDeleteVfModule(); - String businessKey = UUID.randomUUID().toString(); - Map variables = new HashMap(); - variables.put("isDebugLogEnabled","true"); - variables.put("mso-request-id", "a27ce5a9-29c4-4c22-a017-6615ac73c721"); - variables.put("mso-service-instance-id", "a27ce5a9-29c4-4c22-a017-6615ac73c721"); - variables.put("DoDeleteVfModuleRequest",request); - invokeSubProcess("DoDeleteVfModule", businessKey, variables); - - // "changedelete" operation not required for deleting a Vf Module -// injectSDNCCallbacks(callbacks, "sdncChangeDelete"); - // cause a failure by not injecting a callback -// injectVNFRestCallbacks(callbacks, "vnfDelete"); -// waitForRunningProcessCount("vnfAdapterDeleteV1", 0, 120000); -// injectSDNCCallbacks(callbacks, "sdncDelete"); - - waitForProcessEnd(businessKey, 10000); - WorkflowException wfe = (WorkflowException) getVariableFromHistory(businessKey, wfeString); - Assert.assertNotNull(wfe); - if (wfe != null) { - System.out.println("TestDoDeleteVfModuleVNFFailure: ErrorCode=" + wfe.getErrorCode() + - ", ErrorMessage=" + wfe.getErrorMessage()); - Assert.assertTrue(wfe.getErrorCode() == 7020); - Assert.assertTrue(wfe.getErrorMessage().startsWith("Received error from VnfAdapter")); - } - logEnd(); - } - - @Test - @Deployment(resources = { - "subprocess/DoDeleteVfModule.bpmn", - "subprocess/PrepareUpdateAAIVfModule.bpmn", - "subprocess/UpdateAAIVfModule.bpmn", - "subprocess/UpdateAAIGenericVnf.bpmn", - "subprocess/DeleteAAIVfModule.bpmn", - "subprocess/SDNCAdapterV1.bpmn", - "subprocess/VnfAdapterRestV1.bpmn" - }) - public void TestDoDeleteVfModuleVNFCallbackFailure() { - // delete the Base Module and Generic Vnf - VNFAdapter Callback failure - // vnf-id=a27ce5a9-29c4-4c22-a017-6615ac73c721, vf-module-id=973ed047-d251-4fb9-bf1a-65b8949e0a73 - String request = - "" + EOL + - " " + EOL + - " DELETE_VF_MODULE" + EOL + - " PORTAL" + EOL + - " " + EOL + - " " + EOL + - " a27ce5a9-29c4-4c22-a017-6615ac73c721" + EOL + - " STMTN5MMSC21" + EOL + - " asc_heat-int" + EOL + - " 973ed047-d251-4fb9-bf1a-65b8949e0a73" + EOL + - " STMTN5MMSC21-MMSC::module-0-0" + EOL + - " 00000000-0000-0000-0000-000000000000" + EOL + - " SDN-ETHERNET-INTERNET" + EOL + - " fba1bd1e195a404cacb9ce17a9b2b421" + EOL + - " pending-delete" + EOL + - " RDM2WAGPLCP" + EOL + - " " + EOL + - " " + EOL + - "" + EOL; - - logStart(); - MockDoDeleteVfModule_SDNCSuccess(); - MockDoDeleteVfModule_DeleteVNFSuccess(); - MockAAIGenericVnfSearch(); - MockAAIVfModulePUT(false); - MockAAIDeleteGenericVnf(); - MockAAIDeleteVfModule(); - String businessKey = UUID.randomUUID().toString(); - Map variables = new HashMap(); - variables.put("isDebugLogEnabled","true"); - variables.put("mso-request-id", "a27ce5a9-29c4-4c22-a017-6615ac73c721"); - variables.put("mso-service-instance-id", "a27ce5a9-29c4-4c22-a017-6615ac73c721"); - variables.put("DoDeleteVfModuleRequest",request); - invokeSubProcess("DoDeleteVfModule", businessKey, variables); - - // "changedelete" operation not required for deleting a Vf Module -// injectSDNCCallbacks(callbacks, "sdncChangeDelete"); - injectVNFRestCallbacks(callbacks, "vnfDeleteFail"); - waitForRunningProcessCount("vnfAdapterDeleteV1", 0, 120000); -// injectSDNCCallbacks(callbacks, "sdncDelete"); - - waitForProcessEnd(businessKey, 10000); - WorkflowException wfe = (WorkflowException) getVariableFromHistory(businessKey, wfeString); - Assert.assertNotNull(wfe); - if (wfe != null) { - System.out.println("TestDoDeleteVfModuleVNFCallbackFailure: ErrorCode=" + wfe.getErrorCode() + - ", ErrorMessage=" + wfe.getErrorMessage()); - Assert.assertTrue(wfe.getErrorCode() == 7020); - Assert.assertTrue(wfe.getErrorMessage().startsWith("Received vfModuleException from VnfAdapter")); - } - logEnd(); - } - - // start of mocks used locally and by other VF Module unit tests - public static void MockAAIVfModulePUT(boolean isCreate){ - stubFor(put(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/.*/vf-modules/vf-module/.*")) - .withRequestBody(containing("MMSC")) - .willReturn(aResponse() - .withStatus(isCreate ? 201 : 200))); - stubFor(put(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/.*/vf-modules/vf-module/.*")) - .withRequestBody(containing("PCRF")) - .willReturn(aResponse() - .withStatus(500) - .withHeader("Content-Type", "text/xml") - .withBodyFile("aaiFault.xml"))); - stubFor(put(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c721")) - .willReturn(aResponse() - .withStatus(200))); - } - - public static void MockDoDeleteVfModule_SDNCSuccess() { - stubFor(post(urlEqualTo("/SDNCAdapter")) - .withRequestBody(containing("SvcAction>changedelete")) - .willReturn(aResponse() - .withStatus(200) - .withHeader("Content-Type", "text/xml") - .withBodyFile("DeleteGenericVNFV1/sdncAdapterResponse.xml"))); - stubFor(post(urlEqualTo("/SDNCAdapter")) - .withRequestBody(containing("SvcAction>delete")) - .willReturn(aResponse() - .withStatus(200) - .withHeader("Content-Type", "text/xml") - .withBodyFile("DeleteGenericVNFV1/sdncAdapterResponse.xml"))); - } - - public static void MockDoDeleteVfModule_SDNCFailure() { - stubFor(post(urlEqualTo("/SDNCAdapter")) - .withRequestBody(containing("SvcAction>changedelete")) - .willReturn(aResponse() - .withStatus(500))); - stubFor(post(urlEqualTo("/SDNCAdapter")) - .withRequestBody(containing("SvcAction>delete")) - .willReturn(aResponse() - .withStatus(500))); - } - - public static void MockDoDeleteVfModule_DeleteVNFSuccess() { - stubFor(delete(urlMatching("/vnfs/v1/vnfs/.*/vf-modules/.*")) - .willReturn(aResponse() - .withStatus(202) - .withHeader("Content-Type", "application/xml"))); - stubFor(delete(urlMatching("/vnfs/v1/volume-groups/78987")) - .willReturn(aResponse() - .withStatus(202) - .withHeader("Content-Type", "application/xml"))); - } - - public static void MockDoDeleteVfModule_DeleteVNFFailure() { - stubFor(delete(urlMatching("/vnfs/v1/vnfs/.*/vf-modules/.*")) - .willReturn(aResponse() - .withStatus(500) - .withHeader("Content-Type", "application/xml"))); - } -} - +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.bpmn.infrastructure; + +import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; +import static com.github.tomakehurst.wiremock.client.WireMock.containing; +import static com.github.tomakehurst.wiremock.client.WireMock.delete; +import static com.github.tomakehurst.wiremock.client.WireMock.post; +import static com.github.tomakehurst.wiremock.client.WireMock.put; +import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; +import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; +import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching; +import static org.openecomp.mso.bpmn.common.DeleteAAIVfModuleTest.MockAAIDeleteGenericVnf; +import static org.openecomp.mso.bpmn.common.DeleteAAIVfModuleTest.MockAAIDeleteVfModule; +import static org.openecomp.mso.bpmn.common.DeleteAAIVfModuleTest.MockAAIGenericVnfSearch; +import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockPatchVfModuleId; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +import org.camunda.bpm.engine.test.Deployment; +import org.junit.Assert; +import org.junit.Test; +import org.openecomp.mso.bpmn.common.WorkflowTest; +import org.openecomp.mso.bpmn.core.WorkflowException; + +/** + * Unit test for DoDeleteVfModule.bpmn. + */ +public class DoDeleteVfModuleTest extends WorkflowTest { + private final CallbackSet callbacks = new CallbackSet(); + + private static final String EOL = "\n"; + + private final String vnfAdapterDeleteCallback = + "" + EOL + + " a27ce5a9-29c4-4c22-a017-6615ac73c721" + EOL + + " 973ed047-d251-4fb9-bf1a-65b8949e0a73" + EOL + + " true" + EOL + + " {{MESSAGE-ID}}" + EOL + + "" + EOL; + + private final String vnfAdapterDeleteCallbackFail = + "" + EOL + + " Error processing request to VNF-Async. Not Found." + EOL + + " INTERNAL" + EOL + + " false" + EOL + + " {{MESSAGE-ID}}" + EOL + + "" + EOL; + + private final String sdncAdapterDeleteCallback = + "" + EOL + + " {{REQUEST-ID}}" + EOL + + " Y" + EOL + + "" + EOL; + + public DoDeleteVfModuleTest() throws IOException { + callbacks.put("sdncChangeDelete", sdncAdapterDeleteCallback); + callbacks.put("sdncDelete", sdncAdapterDeleteCallback); + callbacks.put("vnfDelete", vnfAdapterDeleteCallback); + callbacks.put("vnfDeleteFail", vnfAdapterDeleteCallbackFail); + } + + private final String wfeString = "WorkflowException"; + + @Test + @Deployment(resources = { + "subprocess/DoDeleteVfModule.bpmn", + "subprocess/PrepareUpdateAAIVfModule.bpmn", + "subprocess/UpdateAAIVfModule.bpmn", + "subprocess/UpdateAAIGenericVnf.bpmn", + "subprocess/DeleteAAIVfModule.bpmn", + "subprocess/SDNCAdapterV1.bpmn", + "subprocess/VnfAdapterRestV1.bpmn" + }) + public void TestDoDeleteVfModuleSuccess() { + // delete the Base Module and Generic Vnf + // vnf-id=a27ce5a9-29c4-4c22-a017-6615ac73c721, vf-module-id=973ed047-d251-4fb9-bf1a-65b8949e0a73 + String request = + "" + EOL + + " " + EOL + + " DELETE_VF_MODULE" + EOL + + " PORTAL" + EOL + + " " + EOL + + " " + EOL + + " a27ce5a9-29c4-4c22-a017-6615ac73c721" + EOL + + " STMTN5MMSC21" + EOL + + " asc_heat-int" + EOL + + " 973ed047-d251-4fb9-bf1a-65b8949e0a73" + EOL + + " STMTN5MMSC21-MMSC::module-0-0" + EOL + + " 00000000-0000-0000-0000-000000000000" + EOL + + " SDN-ETHERNET-INTERNET" + EOL + + " fba1bd1e195a404cacb9ce17a9b2b421" + EOL + + " pending-delete" + EOL + + " RDM2WAGPLCP" + EOL + + " " + EOL + + " " + EOL + + "" + EOL; + logStart(); + MockDoDeleteVfModule_SDNCSuccess(); + MockDoDeleteVfModule_DeleteVNFSuccess(); + MockAAIGenericVnfSearch(); + MockAAIVfModulePUT(false); + MockAAIDeleteGenericVnf(); + MockAAIDeleteVfModule(); + MockPatchVfModuleId("a27ce5a9-29c4-4c22-a017-6615ac73c721", "973ed047-d251-4fb9-bf1a-65b8949e0a73"); + + String businessKey = UUID.randomUUID().toString(); + Map variables = new HashMap(); + variables.put("isDebugLogEnabled","true"); + variables.put("mso-request-id", "a27ce5a9-29c4-4c22-a017-6615ac73c721"); + variables.put("mso-service-instance-id", "a27ce5a9-29c4-4c22-a017-6615ac73c721"); + variables.put("DoDeleteVfModuleRequest",request); + variables.put("isVidRequest", "true"); + invokeSubProcess("DoDeleteVfModule", businessKey, variables); + + // "changedelete" operation not required for deleting a Vf Module +// injectSDNCCallbacks(callbacks, "sdncChangeDelete"); + injectVNFRestCallbacks(callbacks, "vnfDelete"); + waitForRunningProcessCount("vnfAdapterDeleteV1", 0, 120000); + injectSDNCCallbacks(callbacks, "sdncDelete"); + + waitForProcessEnd(businessKey, 10000); + WorkflowException wfe = (WorkflowException) getVariableFromHistory(businessKey, wfeString); + checkVariable(businessKey, wfeString, null); + if (wfe != null) { + System.out.println("TestDoDeleteVfModuleSuccess: ErrorCode=" + wfe.getErrorCode() + + ", ErrorMessage=" + wfe.getErrorMessage()); + } + logEnd(); + } + + @Test + @Deployment(resources = { + "subprocess/DoDeleteVfModule.bpmn", + "subprocess/PrepareUpdateAAIVfModule.bpmn", + "subprocess/UpdateAAIVfModule.bpmn", + "subprocess/UpdateAAIGenericVnf.bpmn", + "subprocess/DeleteAAIVfModule.bpmn", + "subprocess/SDNCAdapterV1.bpmn", + "subprocess/VnfAdapterRestV1.bpmn" + }) + public void TestDoDeleteVfModule_Building_Block_Success() { + logStart(); + MockDoDeleteVfModule_SDNCSuccess(); + MockDoDeleteVfModule_DeleteVNFSuccess(); + MockAAIGenericVnfSearch(); + MockAAIVfModulePUT(false); + MockAAIDeleteGenericVnf(); + MockAAIDeleteVfModule(); + MockPatchVfModuleId("a27ce5a9-29c4-4c22-a017-6615ac73c721", "973ed047-d251-4fb9-bf1a-65b8949e0a73"); + + String businessKey = UUID.randomUUID().toString(); + Map variables = new HashMap(); + + variables.put("mso-request-id", "a27ce5a9-29c4-4c22-a017-6615ac73c721"); + variables.put("requestId", "a27ce5a9-29c4-4c22-a017-6615ac73c721"); + variables.put("isDebugLogEnabled","true"); + variables.put("vnfId", "a27ce5a9-29c4-4c22-a017-6615ac73c721"); + variables.put("vfModuleId", "973ed047-d251-4fb9-bf1a-65b8949e0a73"); + variables.put("serviceInstanceId", "a27ce5a9-29c4-4c22-a017-6615ac73c721"); + variables.put("vfModuleName", "STMTN5MMSC21-MMSC::module-0-0"); + variables.put("sdncVersion", "1610"); + variables.put("isVidRequest", "true"); + String vfModuleModelInfo = "{" + "\"modelType\": \"vnf\"," + + "\"modelInvariantId\": \"ff5256d2-5a33-55df-13ab-12abad84e7ff\"," + + "\"modelNameVersionId\": \"fe6478e5-ea33-3346-ac12-ab121484a3fe\"," + + "\"modelName\": \"vSAMP12\"," + + "\"modelVersion\": \"1.0\"," + + "\"modelCustomizationId\": \"MODEL-ID-1234\"," + + "}"; + variables.put("vfModuleModelInfo", vfModuleModelInfo); + + String cloudConfiguration = "{" + + "\"lcpCloudRegionId\": \"RDM2WAGPLCP\"," + + "\"tenantId\": \"fba1bd1e195a404cacb9ce17a9b2b421\"" + "}"; + variables.put("cloudConfiguration", cloudConfiguration); + + + invokeSubProcess("DoDeleteVfModule", businessKey, variables); + + // "changedelete" operation not required for deleting a Vf Module +// injectSDNCCallbacks(callbacks, "sdncChangeDelete"); + injectVNFRestCallbacks(callbacks, "vnfDelete"); + waitForRunningProcessCount("vnfAdapterDeleteV1", 0, 120000); + injectSDNCCallbacks(callbacks, "sdncDelete"); + + waitForProcessEnd(businessKey, 10000); + WorkflowException wfe = (WorkflowException) getVariableFromHistory(businessKey, wfeString); + checkVariable(businessKey, wfeString, null); + if (wfe != null) { + System.out.println("TestDoDeleteVfModule_Building_Block_Success: ErrorCode=" + wfe.getErrorCode() + + ", ErrorMessage=" + wfe.getErrorMessage()); + } + logEnd(); + } + + + @Test + @Deployment(resources = { + "subprocess/DoDeleteVfModule.bpmn", + "subprocess/PrepareUpdateAAIVfModule.bpmn", + "subprocess/UpdateAAIVfModule.bpmn", + "subprocess/UpdateAAIGenericVnf.bpmn", + "subprocess/DeleteAAIVfModule.bpmn", + "subprocess/SDNCAdapterV1.bpmn", + "subprocess/VnfAdapterRestV1.bpmn" + }) + public void TestDoDeleteVfModuleSDNCFailure() { + // delete the Base Module and Generic Vnf - SDNCAdapter failure + // vnf-id=a27ce5a9-29c4-4c22-a017-6615ac73c721, vf-module-id=973ed047-d251-4fb9-bf1a-65b8949e0a73 + String request = + "" + EOL + + " " + EOL + + " DELETE_VF_MODULE" + EOL + + " PORTAL" + EOL + + " " + EOL + + " " + EOL + + " a27ce5a9-29c4-4c22-a017-6615ac73c721" + EOL + + " STMTN5MMSC21" + EOL + + " asc_heat-int" + EOL + + " 973ed047-d251-4fb9-bf1a-65b8949e0a73" + EOL + + " STMTN5MMSC21-MMSC::module-0-0" + EOL + + " 00000000-0000-0000-0000-000000000000" + EOL + + " SDN-ETHERNET-INTERNET" + EOL + + " fba1bd1e195a404cacb9ce17a9b2b421" + EOL + + " pending-delete" + EOL + + " RDM2WAGPLCP" + EOL + + " " + EOL + + " " + EOL + + "" + EOL; + + logStart(); + MockDoDeleteVfModule_SDNCFailure(); + MockDoDeleteVfModule_DeleteVNFSuccess(); + MockAAIGenericVnfSearch(); + MockAAIVfModulePUT(false); + MockAAIDeleteGenericVnf(); + MockAAIDeleteVfModule(); + MockPatchVfModuleId("a27ce5a9-29c4-4c22-a017-6615ac73c721", "973ed047-d251-4fb9-bf1a-65b8949e0a73"); + + String businessKey = UUID.randomUUID().toString(); + Map variables = new HashMap(); + variables.put("isDebugLogEnabled","true"); + variables.put("mso-request-id", "a27ce5a9-29c4-4c22-a017-6615ac73c721"); + variables.put("mso-service-instance-id", "a27ce5a9-29c4-4c22-a017-6615ac73c721"); + variables.put("DoDeleteVfModuleRequest", request); + variables.put("isVidRequest", "true"); + invokeSubProcess("DoDeleteVfModule", businessKey, variables); + + // "changedelete" operation not required for deleting a Vf Module +// injectSDNCCallbacks(callbacks, "sdncChangeDelete"); + injectVNFRestCallbacks(callbacks, "vnfDelete"); + waitForRunningProcessCount("vnfAdapterDeleteV1", 0, 120000); + // cause a failure by not injecting a callback +// injectSDNCCallbacks(callbacks, "sdncDelete"); + + waitForProcessEnd(businessKey, 10000); + WorkflowException wfe = (WorkflowException) getVariableFromHistory(businessKey, wfeString); + Assert.assertNotNull(wfe); + if (wfe != null) { + System.out.println("TestDoDeleteVfModuleSDNCFailure: ErrorCode=" + wfe.getErrorCode() + + ", ErrorMessage=" + wfe.getErrorMessage()); + Assert.assertTrue(wfe.getErrorCode() == 7000); + Assert.assertTrue(wfe.getErrorMessage().startsWith("Could not communicate")); + } + logEnd(); + } + + @Test + @Deployment(resources = { + "subprocess/DoDeleteVfModule.bpmn", + "subprocess/PrepareUpdateAAIVfModule.bpmn", + "subprocess/UpdateAAIVfModule.bpmn", + "subprocess/UpdateAAIGenericVnf.bpmn", + "subprocess/DeleteAAIVfModule.bpmn", + "subprocess/SDNCAdapterV1.bpmn", + "subprocess/VnfAdapterRestV1.bpmn" + }) + public void TestDoDeleteVfModuleSDNCCallbackFailure() { + // delete the Base Module and Generic Vnf - SDNCAdapter Callback failure + // vnf-id=a27ce5a9-29c4-4c22-a017-6615ac73c721, vf-module-id=973ed047-d251-4fb9-bf1a-65b8949e0a73 + String request = + "" + EOL + + " " + EOL + + " DELETE_VF_MODULE" + EOL + + " PORTAL" + EOL + + " " + EOL + + " " + EOL + + " a27ce5a9-29c4-4c22-a017-6615ac73c721" + EOL + + " STMTN5MMSC21" + EOL + + " asc_heat-int" + EOL + + " 973ed047-d251-4fb9-bf1a-65b8949e0a73" + EOL + + " STMTN5MMSC21-MMSC::module-0-0" + EOL + + " 00000000-0000-0000-0000-000000000000" + EOL + + " SDN-ETHERNET-INTERNET" + EOL + + " fba1bd1e195a404cacb9ce17a9b2b421" + EOL + + " pending-delete" + EOL + + " RDM2WAGPLCP" + EOL + + " " + EOL + + " " + EOL + + "" + EOL; + + logStart(); + MockDoDeleteVfModule_SDNCSuccess(); + MockDoDeleteVfModule_DeleteVNFSuccess(); + MockAAIGenericVnfSearch(); + MockAAIVfModulePUT(false); + MockAAIDeleteGenericVnf(); + MockAAIDeleteVfModule(); + MockPatchVfModuleId("a27ce5a9-29c4-4c22-a017-6615ac73c721", "973ed047-d251-4fb9-bf1a-65b8949e0a73"); + + String businessKey = UUID.randomUUID().toString(); + Map variables = new HashMap(); + variables.put("isDebugLogEnabled","true"); + variables.put("mso-request-id", "a27ce5a9-29c4-4c22-a017-6615ac73c721"); + variables.put("mso-service-instance-id", "a27ce5a9-29c4-4c22-a017-6615ac73c721"); + variables.put("DoDeleteVfModuleRequest",request); + variables.put("isVidRequest", "true"); + invokeSubProcess("DoDeleteVfModule", businessKey, variables); + + // "changedelete" operation not required for deleting a Vf Module +// injectSDNCCallbacks(callbacks, "sdncChangeDelete:ERR"); + injectVNFRestCallbacks(callbacks, "vnfDelete"); + waitForRunningProcessCount("vnfAdapterDeleteV1", 0, 120000); + // return a failure in the callback + injectSDNCCallbacks(callbacks, "sdncDelete:ERR"); + + waitForProcessEnd(businessKey, 10000); + WorkflowException wfe = (WorkflowException) getVariableFromHistory(businessKey, wfeString); + Assert.assertNotNull(wfe); + if (wfe != null) { + System.out.println("TestDoDeleteVfModuleSDNCCallbackFailure: ErrorCode=" + wfe.getErrorCode() + + ", ErrorMessage=" + wfe.getErrorMessage()); + Assert.assertTrue(wfe.getErrorCode() == 5310); + Assert.assertTrue(wfe.getErrorMessage().startsWith("Received error from SDN-C")); + } + logEnd(); + } + + @Test + @Deployment(resources = { + "subprocess/DoDeleteVfModule.bpmn", + "subprocess/PrepareUpdateAAIVfModule.bpmn", + "subprocess/UpdateAAIVfModule.bpmn", + "subprocess/UpdateAAIGenericVnf.bpmn", + "subprocess/DeleteAAIVfModule.bpmn", + "subprocess/SDNCAdapterV1.bpmn", + "subprocess/VnfAdapterRestV1.bpmn" + }) + public void TestDoDeleteVfModuleVNFFailure() { + // delete the Base Module and Generic Vnf - VNFAdapter failure + // vnf-id=a27ce5a9-29c4-4c22-a017-6615ac73c721, vf-module-id=973ed047-d251-4fb9-bf1a-65b8949e0a73 + String request = + "" + EOL + + " " + EOL + + " DELETE_VF_MODULE" + EOL + + " PORTAL" + EOL + + " " + EOL + + " " + EOL + + " a27ce5a9-29c4-4c22-a017-6615ac73c721" + EOL + + " STMTN5MMSC21" + EOL + + " asc_heat-int" + EOL + + " 973ed047-d251-4fb9-bf1a-65b8949e0a73" + EOL + + " STMTN5MMSC21-MMSC::module-0-0" + EOL + + " 00000000-0000-0000-0000-000000000000" + EOL + + " SDN-ETHERNET-INTERNET" + EOL + + " fba1bd1e195a404cacb9ce17a9b2b421" + EOL + + " pending-delete" + EOL + + " RDM2WAGPLCP" + EOL + + " " + EOL + + " " + EOL + + "" + EOL; + + logStart(); + MockDoDeleteVfModule_SDNCSuccess(); + MockDoDeleteVfModule_DeleteVNFFailure(); + MockAAIGenericVnfSearch(); + MockAAIVfModulePUT(false); + MockAAIDeleteGenericVnf(); + MockAAIDeleteVfModule(); + MockPatchVfModuleId("a27ce5a9-29c4-4c22-a017-6615ac73c721", "973ed047-d251-4fb9-bf1a-65b8949e0a73"); + + String businessKey = UUID.randomUUID().toString(); + Map variables = new HashMap(); + variables.put("isDebugLogEnabled","true"); + variables.put("mso-request-id", "a27ce5a9-29c4-4c22-a017-6615ac73c721"); + variables.put("mso-service-instance-id", "a27ce5a9-29c4-4c22-a017-6615ac73c721"); + variables.put("DoDeleteVfModuleRequest",request); + invokeSubProcess("DoDeleteVfModule", businessKey, variables); + + // "changedelete" operation not required for deleting a Vf Module +// injectSDNCCallbacks(callbacks, "sdncChangeDelete"); + // cause a failure by not injecting a callback +// injectVNFRestCallbacks(callbacks, "vnfDelete"); +// waitForRunningProcessCount("vnfAdapterDeleteV1", 0, 120000); +// injectSDNCCallbacks(callbacks, "sdncDelete"); + + waitForProcessEnd(businessKey, 10000); + WorkflowException wfe = (WorkflowException) getVariableFromHistory(businessKey, wfeString); + Assert.assertNotNull(wfe); + if (wfe != null) { + System.out.println("TestDoDeleteVfModuleVNFFailure: ErrorCode=" + wfe.getErrorCode() + + ", ErrorMessage=" + wfe.getErrorMessage()); + Assert.assertTrue(wfe.getErrorCode() == 7020); + Assert.assertTrue(wfe.getErrorMessage().startsWith("Received error from VnfAdapter")); + } + logEnd(); + } + + @Test + @Deployment(resources = { + "subprocess/DoDeleteVfModule.bpmn", + "subprocess/PrepareUpdateAAIVfModule.bpmn", + "subprocess/UpdateAAIVfModule.bpmn", + "subprocess/UpdateAAIGenericVnf.bpmn", + "subprocess/DeleteAAIVfModule.bpmn", + "subprocess/SDNCAdapterV1.bpmn", + "subprocess/VnfAdapterRestV1.bpmn" + }) + public void TestDoDeleteVfModuleVNFCallbackFailure() { + // delete the Base Module and Generic Vnf - VNFAdapter Callback failure + // vnf-id=a27ce5a9-29c4-4c22-a017-6615ac73c721, vf-module-id=973ed047-d251-4fb9-bf1a-65b8949e0a73 + String request = + "" + EOL + + " " + EOL + + " DELETE_VF_MODULE" + EOL + + " PORTAL" + EOL + + " " + EOL + + " " + EOL + + " a27ce5a9-29c4-4c22-a017-6615ac73c721" + EOL + + " STMTN5MMSC21" + EOL + + " asc_heat-int" + EOL + + " 973ed047-d251-4fb9-bf1a-65b8949e0a73" + EOL + + " STMTN5MMSC21-MMSC::module-0-0" + EOL + + " 00000000-0000-0000-0000-000000000000" + EOL + + " SDN-ETHERNET-INTERNET" + EOL + + " fba1bd1e195a404cacb9ce17a9b2b421" + EOL + + " pending-delete" + EOL + + " RDM2WAGPLCP" + EOL + + " " + EOL + + " " + EOL + + "" + EOL; + + logStart(); + MockDoDeleteVfModule_SDNCSuccess(); + MockDoDeleteVfModule_DeleteVNFSuccess(); + MockAAIGenericVnfSearch(); + MockAAIVfModulePUT(false); + MockAAIDeleteGenericVnf(); + MockAAIDeleteVfModule(); + MockPatchVfModuleId("a27ce5a9-29c4-4c22-a017-6615ac73c721", "973ed047-d251-4fb9-bf1a-65b8949e0a73"); + + String businessKey = UUID.randomUUID().toString(); + Map variables = new HashMap(); + variables.put("isDebugLogEnabled","true"); + variables.put("mso-request-id", "a27ce5a9-29c4-4c22-a017-6615ac73c721"); + variables.put("mso-service-instance-id", "a27ce5a9-29c4-4c22-a017-6615ac73c721"); + variables.put("DoDeleteVfModuleRequest",request); + invokeSubProcess("DoDeleteVfModule", businessKey, variables); + + // "changedelete" operation not required for deleting a Vf Module +// injectSDNCCallbacks(callbacks, "sdncChangeDelete"); + injectVNFRestCallbacks(callbacks, "vnfDeleteFail"); + waitForRunningProcessCount("vnfAdapterDeleteV1", 0, 120000); +// injectSDNCCallbacks(callbacks, "sdncDelete"); + + waitForProcessEnd(businessKey, 10000); + WorkflowException wfe = (WorkflowException) getVariableFromHistory(businessKey, wfeString); + Assert.assertNotNull(wfe); + if (wfe != null) { + System.out.println("TestDoDeleteVfModuleVNFCallbackFailure: ErrorCode=" + wfe.getErrorCode() + + ", ErrorMessage=" + wfe.getErrorMessage()); + Assert.assertTrue(wfe.getErrorCode() == 7020); + Assert.assertTrue(wfe.getErrorMessage().startsWith("Received vfModuleException from VnfAdapter")); + } + logEnd(); + } + + // start of mocks used locally and by other VF Module unit tests + public static void MockAAIVfModulePUT(boolean isCreate){ + stubFor(put(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/.*/vf-modules/vf-module/.*")) + .withRequestBody(containing("MMSC")) + .willReturn(aResponse() + .withStatus(isCreate ? 201 : 200))); + stubFor(put(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/.*/vf-modules/vf-module/.*")) + .withRequestBody(containing("PCRF")) + .willReturn(aResponse() + .withStatus(500) + .withHeader("Content-Type", "text/xml") + .withBodyFile("aaiFault.xml"))); + stubFor(put(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c721")) + .willReturn(aResponse() + .withStatus(200))); + } + + public static void MockDoDeleteVfModule_SDNCSuccess() { + stubFor(post(urlEqualTo("/SDNCAdapter")) + .withRequestBody(containing("SvcAction>changedelete")) + .willReturn(aResponse() + .withStatus(200) + .withHeader("Content-Type", "text/xml") + .withBodyFile("DeleteGenericVNFV1/sdncAdapterResponse.xml"))); + stubFor(post(urlEqualTo("/SDNCAdapter")) + .withRequestBody(containing("SvcAction>delete")) + .willReturn(aResponse() + .withStatus(200) + .withHeader("Content-Type", "text/xml") + .withBodyFile("DeleteGenericVNFV1/sdncAdapterResponse.xml"))); + } + + public static void MockDoDeleteVfModule_SDNCFailure() { + stubFor(post(urlEqualTo("/SDNCAdapter")) + .withRequestBody(containing("SvcAction>changedelete")) + .willReturn(aResponse() + .withStatus(500))); + stubFor(post(urlEqualTo("/SDNCAdapter")) + .withRequestBody(containing("SvcAction>delete")) + .willReturn(aResponse() + .withStatus(500))); + } + + public static void MockDoDeleteVfModule_DeleteVNFSuccess() { + stubFor(delete(urlMatching("/vnfs/v1/vnfs/.*/vf-modules/.*")) + .willReturn(aResponse() + .withStatus(202) + .withHeader("Content-Type", "application/xml"))); + stubFor(delete(urlMatching("/vnfs/v1/volume-groups/78987")) + .willReturn(aResponse() + .withStatus(202) + .withHeader("Content-Type", "application/xml"))); + } + + public static void MockDoDeleteVfModule_DeleteVNFFailure() { + stubFor(delete(urlMatching("/vnfs/v1/vnfs/.*/vf-modules/.*")) + .willReturn(aResponse() + .withStatus(500) + .withHeader("Content-Type", "application/xml"))); + } +} + diff --git a/bpmn/MSOInfrastructureBPMN/src/test/java/org/openecomp/mso/bpmn/infrastructure/DoUpdateVfModuleTest.java b/bpmn/MSOInfrastructureBPMN/src/test/java/org/openecomp/mso/bpmn/infrastructure/DoUpdateVfModuleTest.java index e202b0349b..bba6f62adc 100644 --- a/bpmn/MSOInfrastructureBPMN/src/test/java/org/openecomp/mso/bpmn/infrastructure/DoUpdateVfModuleTest.java +++ b/bpmn/MSOInfrastructureBPMN/src/test/java/org/openecomp/mso/bpmn/infrastructure/DoUpdateVfModuleTest.java @@ -1,115 +1,116 @@ -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - MSO - * ================================================================================ - * 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.openecomp.mso.bpmn.infrastructure; - - - -import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockGetGenericVnfByIdWithDepth; -import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockGetGenericVnfByIdWithPriority; -import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockGetVfModuleIdNoResponse; -import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockGetVolumeGroupById; -import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockPutGenericVnf; -import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockPutVfModuleIdNoResponse; -import static org.openecomp.mso.bpmn.mock.StubResponseSDNCAdapter.mockSDNCAdapter; -import static org.openecomp.mso.bpmn.mock.StubResponseVNFAdapter.mockVNFPut; - -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; - -import org.camunda.bpm.engine.test.Deployment; -import org.junit.Assert; -import org.junit.Test; -import org.openecomp.mso.bpmn.common.WorkflowTest; -import org.openecomp.mso.bpmn.common.WorkflowTest.CallbackSet; -import org.openecomp.mso.bpmn.mock.FileUtil; - -/** - * Unit tests for DoUpdateVfModule.bpmn. - */ -public class DoUpdateVfModuleTest extends WorkflowTest { - - private final CallbackSet callbacks = new CallbackSet(); - - public DoUpdateVfModuleTest() throws IOException { - callbacks.put("changeassign", FileUtil.readResourceFile( - "__files/VfModularity/SDNCTopologyChangeAssignCallback.xml")); - callbacks.put("query", FileUtil.readResourceFile( - "__files/VfModularity/SDNCTopologyQueryCallback.xml")); - callbacks.put("activate", FileUtil.readResourceFile( - "__files/VfModularity/SDNCTopologyActivateCallback.xml")); - callbacks.put("vnfUpdate", FileUtil.readResourceFile( - "__files/VfModularity/VNFAdapterRestUpdateCallback.xml")); - } - - /** - * Test the happy path through the flow. - */ - @Test - - @Deployment(resources = { - "subprocess/DoUpdateVfModule.bpmn", - "subprocess/PrepareUpdateAAIVfModule.bpmn", - "subprocess/ConfirmVolumeGroupTenant.bpmn", - "subprocess/SDNCAdapterV1.bpmn", - "subprocess/VnfAdapterRestV1.bpmn", - "subprocess/UpdateAAIGenericVnf.bpmn", - "subprocess/UpdateAAIVfModule.bpmn" - }) - public void happyPath() throws IOException { - - logStart(); - - String doUpdateVfModuleRequest = FileUtil.readResourceFile("__files/VfModularity/DoUpdateVfModuleRequest.xml"); - MockGetGenericVnfByIdWithDepth("skask", 1, "VfModularity/GenericVnf.xml"); - MockGetVfModuleIdNoResponse("skask", "PCRF", "supercool"); - MockPutVfModuleIdNoResponse("skask", "PCRF", "supercool"); - MockGetVolumeGroupById("MDTWNJ21", "78987", "VfModularity/VolumeGroup.xml"); - mockSDNCAdapter("/SDNCAdapter", "SvcAction>query", 200, "VfModularity/StandardSDNCSynchResponse.xml"); - mockSDNCAdapter("/SDNCAdapter", "SvcInstanceId><", 200, "VfModularity/StandardSDNCSynchResponse.xml"); - mockVNFPut("skask", "/supercool", 202); - MockPutGenericVnf("skask"); - MockGetGenericVnfByIdWithPriority("skask", "supercool", 200, "VfModularity/VfModule-supercool.xml", 1); - - String businessKey = UUID.randomUUID().toString(); - Map variables = new HashMap(); - variables.put("mso-request-id", "DEV-VF-0011"); - variables.put("isDebugLogEnabled","true"); - variables.put("DoUpdateVfModuleRequest", doUpdateVfModuleRequest); - invokeSubProcess("DoUpdateVfModule", businessKey, variables); - - injectSDNCCallbacks(callbacks, "changeassign, query"); - injectVNFRestCallbacks(callbacks, "vnfUpdate"); - injectSDNCCallbacks(callbacks, "activate"); - - waitForProcessEnd(businessKey, 10000); - - Assert.assertTrue(isProcessEnded(businessKey)); - checkVariable(businessKey, "DoUpdateVfModuleSuccessIndicator", true); - - String heatStackId = (String) getVariableFromHistory(businessKey, "DOUPVfMod_heatStackId"); - System.out.println("Heat stack Id from AAI: " + heatStackId); - - logEnd(); - } -} - +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.bpmn.infrastructure; + + + +import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockGetGenericVnfByIdWithDepth; +import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockGetGenericVnfByIdWithPriority; +import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockGetVfModuleIdNoResponse; +import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockGetVolumeGroupById; +import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockPutGenericVnf; +import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockPutVfModuleIdNoResponse; +import static org.openecomp.mso.bpmn.mock.StubResponseSDNCAdapter.mockSDNCAdapter; +import static org.openecomp.mso.bpmn.mock.StubResponseVNFAdapter.mockVNFPut; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +import org.camunda.bpm.engine.test.Deployment; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; +import org.openecomp.mso.bpmn.common.WorkflowTest; +import org.openecomp.mso.bpmn.common.WorkflowTest.CallbackSet; +import org.openecomp.mso.bpmn.mock.FileUtil; + +/** + * Unit tests for DoUpdateVfModule.bpmn. + */ +public class DoUpdateVfModuleTest extends WorkflowTest { + + private final CallbackSet callbacks = new CallbackSet(); + + public DoUpdateVfModuleTest() throws IOException { + callbacks.put("changeassign", FileUtil.readResourceFile( + "__files/VfModularity/SDNCTopologyChangeAssignCallback.xml")); + callbacks.put("query", FileUtil.readResourceFile( + "__files/VfModularity/SDNCTopologyQueryCallback.xml")); + callbacks.put("activate", FileUtil.readResourceFile( + "__files/VfModularity/SDNCTopologyActivateCallback.xml")); + callbacks.put("vnfUpdate", FileUtil.readResourceFile( + "__files/VfModularity/VNFAdapterRestUpdateCallback.xml")); + } + + /** + * Test the happy path through the flow. + */ + @Test + @Ignore + @Deployment(resources = { + "subprocess/DoUpdateVfModule.bpmn", + "subprocess/PrepareUpdateAAIVfModule.bpmn", + "subprocess/ConfirmVolumeGroupTenant.bpmn", + "subprocess/SDNCAdapterV1.bpmn", + "subprocess/VnfAdapterRestV1.bpmn", + "subprocess/UpdateAAIGenericVnf.bpmn", + "subprocess/UpdateAAIVfModule.bpmn" + }) + public void happyPath() throws IOException { + + logStart(); + + String doUpdateVfModuleRequest = FileUtil.readResourceFile("__files/VfModularity/DoUpdateVfModuleRequest.xml"); + MockGetGenericVnfByIdWithDepth("skask", 1, "VfModularity/GenericVnf.xml"); + MockGetVfModuleIdNoResponse("skask", "PCRF", "supercool"); + MockPutVfModuleIdNoResponse("skask", "PCRF", "supercool"); + MockGetVolumeGroupById("MDTWNJ21", "78987", "VfModularity/VolumeGroup.xml"); + mockSDNCAdapter("/SDNCAdapter", "SvcAction>query", 200, "VfModularity/StandardSDNCSynchResponse.xml"); + mockSDNCAdapter("/SDNCAdapter", "SvcInstanceId><", 200, "VfModularity/StandardSDNCSynchResponse.xml"); + mockVNFPut("skask", "/supercool", 202); + MockPutGenericVnf("skask"); + MockGetGenericVnfByIdWithPriority("skask", "supercool", 200, "VfModularity/VfModule-supercool.xml", 1); + + String businessKey = UUID.randomUUID().toString(); + Map variables = new HashMap(); + variables.put("mso-request-id", "DEV-VF-0011"); + variables.put("isDebugLogEnabled","true"); + variables.put("DoUpdateVfModuleRequest", doUpdateVfModuleRequest); + invokeSubProcess("DoUpdateVfModule", businessKey, variables); + + injectSDNCCallbacks(callbacks, "changeassign, query"); + injectVNFRestCallbacks(callbacks, "vnfUpdate"); + injectSDNCCallbacks(callbacks, "activate"); + + waitForProcessEnd(businessKey, 10000); + + Assert.assertTrue(isProcessEnded(businessKey)); + checkVariable(businessKey, "DoUpdateVfModuleSuccessIndicator", true); + + String heatStackId = (String) getVariableFromHistory(businessKey, "DOUPVfMod_heatStackId"); + System.out.println("Heat stack Id from AAI: " + heatStackId); + + logEnd(); + } +} + diff --git a/bpmn/MSOInfrastructureBPMN/src/test/java/org/openecomp/mso/bpmn/infrastructure/UpdateVfModuleInfraTest.java b/bpmn/MSOInfrastructureBPMN/src/test/java/org/openecomp/mso/bpmn/infrastructure/UpdateVfModuleInfraTest.java index cadca4c3a3..cbf91bfdb3 100644 --- a/bpmn/MSOInfrastructureBPMN/src/test/java/org/openecomp/mso/bpmn/infrastructure/UpdateVfModuleInfraTest.java +++ b/bpmn/MSOInfrastructureBPMN/src/test/java/org/openecomp/mso/bpmn/infrastructure/UpdateVfModuleInfraTest.java @@ -1,144 +1,145 @@ -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - MSO - * ================================================================================ - * 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.openecomp.mso.bpmn.infrastructure; - -import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockGetGenericVnfByIdWithDepth; -import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockGetGenericVnfByIdWithPriority; -import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockPutVfModuleIdNoResponse; -import static org.openecomp.mso.bpmn.mock.StubResponseDatabase.mockUpdateRequestDB; -import static org.openecomp.mso.bpmn.mock.StubResponseSDNCAdapter.mockSDNCAdapter; -import static org.openecomp.mso.bpmn.mock.StubResponseVNFAdapter.mockVNFPut; - -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; - -import org.camunda.bpm.engine.test.Deployment; -import org.junit.Test; -import org.openecomp.mso.bpmn.common.WorkflowTest; -import org.openecomp.mso.bpmn.common.workflow.service.WorkflowResponse; -import org.openecomp.mso.bpmn.mock.FileUtil; - -/** - * Unit test cases for UpdateVfModule.bpmn - */ -public class UpdateVfModuleInfraTest extends WorkflowTest { - - private final CallbackSet callbacks = new CallbackSet(); - - public UpdateVfModuleInfraTest() throws IOException { - callbacks.put("changeassign", FileUtil.readResourceFile( - "__files/VfModularity/SDNCTopologyChangeAssignCallback.xml")); - callbacks.put("query", FileUtil.readResourceFile( - "__files/VfModularity/SDNCTopologyQueryCallback.xml")); - callbacks.put("activate", FileUtil.readResourceFile( - "__files/VfModularity/SDNCTopologyActivateCallback.xml")); - callbacks.put("vnfUpdate", FileUtil.readResourceFile( - "__files/VfModularity/VNFAdapterRestUpdateCallback.xml")); - } - - /** - * Sunny day scenario. - * - * @throws Exception - */ - @Test - - @Deployment(resources = { - "process/UpdateVfModuleInfra.bpmn", - "subprocess/DoUpdateVfModule.bpmn", - "subprocess/PrepareUpdateAAIVfModule.bpmn", - "subprocess/ConfirmVolumeGroupTenant.bpmn", - "subprocess/SDNCAdapterV1.bpmn", - "subprocess/VnfAdapterRestV1.bpmn", - "subprocess/UpdateAAIGenericVnf.bpmn", - "subprocess/UpdateAAIVfModule.bpmn", - "subprocess/CompleteMsoProcess.bpmn", - "subprocess/FalloutHandler.bpmn" - }) - public void sunnyDay() throws Exception { - - logStart(); - - MockGetGenericVnfByIdWithDepth("skask", 1, "VfModularity/GenericVnf.xml"); - MockPutVfModuleIdNoResponse("skask", "PCRF", "supercool"); - MockGetGenericVnfByIdWithPriority("skask", "supercool", 200, "VfModularity/VfModule-supercool.xml", 1); - mockSDNCAdapter("/SDNCAdapter", "SvcInstanceId><", 200, "VfModularity/StandardSDNCSynchResponse.xml"); - mockSDNCAdapter("/SDNCAdapter", "vnf-type>STMTN", 200, "VfModularity/StandardSDNCSynchResponse.xml"); - mockSDNCAdapter("/SDNCAdapter", "SvcAction>query", 200, "VfModularity/StandardSDNCSynchResponse.xml"); - mockVNFPut("skask", "/supercool", 202); - mockUpdateRequestDB(200, "Database/DBUpdateResponse.xml"); - - String businessKey = UUID.randomUUID().toString(); - String updaetVfModuleRequest = - FileUtil.readResourceFile("__files/InfrastructureFlows/UpdateVfModule_VID_request.json"); - - Map variables = setupVariablesSunnyDayVID(); - - - TestAsyncResponse asyncResponse = invokeAsyncProcess("UpdateVfModuleInfra", - "v1", businessKey, updaetVfModuleRequest, variables); - - WorkflowResponse response = receiveResponse(businessKey, asyncResponse, 10000); - - String responseBody = response.getResponse(); - System.out.println("Workflow (Synch) Response:\n" + responseBody); - - injectSDNCCallbacks(callbacks, "changeassign, query"); - injectVNFRestCallbacks(callbacks, "vnfUpdate"); - injectSDNCCallbacks(callbacks, "activate"); - - // TODO add appropriate assertions - - waitForProcessEnd(businessKey, 10000); - checkVariable(businessKey, "UpdateVfModuleInfraSuccessIndicator", true); - - logEnd(); - } - - // Active Scenario - private Map setupVariablesSunnyDayVID() { - Map variables = new HashMap(); - //try { - // variables.put("bpmnRequest", FileUtil.readResourceFile("__files/CreateVfModule_VID_request.json")); - //} - //catch (Exception e) { - - //} - //variables.put("mso-request-id", "testRequestId"); - variables.put("requestId", "testRequestId"); - variables.put("isBaseVfModule", false); - variables.put("isDebugLogEnabled", "true"); - variables.put("recipeTimeout", "0"); - variables.put("requestAction", "UPDATE_VF_MODULE"); - variables.put("serviceInstanceId", "f70e927b-6087-4974-9ef8-c5e4d5847ca4"); - variables.put("vnfId", "skask"); - variables.put("vnfType", "vSAMP12"); - variables.put("vfModuleId", "supercool"); - variables.put("volumeGroupId", ""); - variables.put("serviceType", "MOG"); - variables.put("vfModuleType", ""); - return variables; - - } - -} +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.bpmn.infrastructure; + +import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockGetGenericVnfByIdWithDepth; +import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockGetGenericVnfByIdWithPriority; +import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockPutVfModuleIdNoResponse; +import static org.openecomp.mso.bpmn.mock.StubResponseDatabase.mockUpdateRequestDB; +import static org.openecomp.mso.bpmn.mock.StubResponseSDNCAdapter.mockSDNCAdapter; +import static org.openecomp.mso.bpmn.mock.StubResponseVNFAdapter.mockVNFPut; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +import org.camunda.bpm.engine.test.Deployment; +import org.junit.Ignore; +import org.junit.Test; +import org.openecomp.mso.bpmn.common.WorkflowTest; +import org.openecomp.mso.bpmn.common.workflow.service.WorkflowResponse; +import org.openecomp.mso.bpmn.mock.FileUtil; + +/** + * Unit test cases for UpdateVfModule.bpmn + */ +public class UpdateVfModuleInfraTest extends WorkflowTest { + + private final CallbackSet callbacks = new CallbackSet(); + + public UpdateVfModuleInfraTest() throws IOException { + callbacks.put("changeassign", FileUtil.readResourceFile( + "__files/VfModularity/SDNCTopologyChangeAssignCallback.xml")); + callbacks.put("query", FileUtil.readResourceFile( + "__files/VfModularity/SDNCTopologyQueryCallback.xml")); + callbacks.put("activate", FileUtil.readResourceFile( + "__files/VfModularity/SDNCTopologyActivateCallback.xml")); + callbacks.put("vnfUpdate", FileUtil.readResourceFile( + "__files/VfModularity/VNFAdapterRestUpdateCallback.xml")); + } + + /** + * Sunny day scenario. + * + * @throws Exception + */ + @Test + @Ignore + @Deployment(resources = { + "process/UpdateVfModuleInfra.bpmn", + "subprocess/DoUpdateVfModule.bpmn", + "subprocess/PrepareUpdateAAIVfModule.bpmn", + "subprocess/ConfirmVolumeGroupTenant.bpmn", + "subprocess/SDNCAdapterV1.bpmn", + "subprocess/VnfAdapterRestV1.bpmn", + "subprocess/UpdateAAIGenericVnf.bpmn", + "subprocess/UpdateAAIVfModule.bpmn", + "subprocess/CompleteMsoProcess.bpmn", + "subprocess/FalloutHandler.bpmn" + }) + public void sunnyDay() throws Exception { + + logStart(); + + MockGetGenericVnfByIdWithDepth("skask", 1, "VfModularity/GenericVnf.xml"); + MockPutVfModuleIdNoResponse("skask", "PCRF", "supercool"); + MockGetGenericVnfByIdWithPriority("skask", "supercool", 200, "VfModularity/VfModule-supercool.xml", 1); + mockSDNCAdapter("/SDNCAdapter", "SvcInstanceId><", 200, "VfModularity/StandardSDNCSynchResponse.xml"); + mockSDNCAdapter("/SDNCAdapter", "vnf-type>STMTN", 200, "VfModularity/StandardSDNCSynchResponse.xml"); + mockSDNCAdapter("/SDNCAdapter", "SvcAction>query", 200, "VfModularity/StandardSDNCSynchResponse.xml"); + mockVNFPut("skask", "/supercool", 202); + mockUpdateRequestDB(200, "Database/DBUpdateResponse.xml"); + + String businessKey = UUID.randomUUID().toString(); + String updaetVfModuleRequest = + FileUtil.readResourceFile("__files/InfrastructureFlows/UpdateVfModule_VID_request.json"); + + Map variables = setupVariablesSunnyDayVID(); + + + TestAsyncResponse asyncResponse = invokeAsyncProcess("UpdateVfModuleInfra", + "v1", businessKey, updaetVfModuleRequest, variables); + + WorkflowResponse response = receiveResponse(businessKey, asyncResponse, 10000); + + String responseBody = response.getResponse(); + System.out.println("Workflow (Synch) Response:\n" + responseBody); + + injectSDNCCallbacks(callbacks, "changeassign, query"); + injectVNFRestCallbacks(callbacks, "vnfUpdate"); + injectSDNCCallbacks(callbacks, "activate"); + + // TODO add appropriate assertions + + waitForProcessEnd(businessKey, 10000); + checkVariable(businessKey, "UpdateVfModuleInfraSuccessIndicator", true); + + logEnd(); + } + + // Active Scenario + private Map setupVariablesSunnyDayVID() { + Map variables = new HashMap(); + //try { + // variables.put("bpmnRequest", FileUtil.readResourceFile("__files/CreateVfModule_VID_request.json")); + //} + //catch (Exception e) { + + //} + //variables.put("mso-request-id", "testRequestId"); + variables.put("requestId", "testRequestId"); + variables.put("isBaseVfModule", false); + variables.put("isDebugLogEnabled", "true"); + variables.put("recipeTimeout", "0"); + variables.put("requestAction", "UPDATE_VF_MODULE"); + variables.put("serviceInstanceId", "f70e927b-6087-4974-9ef8-c5e4d5847ca4"); + variables.put("vnfId", "skask"); + variables.put("vnfType", "vSAMP12"); + variables.put("vfModuleId", "supercool"); + variables.put("volumeGroupId", ""); + variables.put("serviceType", "MOG"); + variables.put("vfModuleType", ""); + return variables; + + } + +} diff --git a/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/CreateNetworkV2/cloudRegion25_AAIResponse_Success.xml b/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/CreateNetworkV2/cloudRegion25_AAIResponse_Success.xml index 90c668c576..40eca5a038 100644 --- a/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/CreateNetworkV2/cloudRegion25_AAIResponse_Success.xml +++ b/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/CreateNetworkV2/cloudRegion25_AAIResponse_Success.xml @@ -1,20 +1,20 @@ - - - - - - - - - - - - - att-aic - RDM2WAGPLCP - 2.5 - RDM2WAGPLCP - - - + + + + + + + + + + + + + att-aic + RDM2WAGPLCP + 2.5 + RDM2WAGPLCP + + + diff --git a/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/CreateNetworkV2/cloudRegion30_AAIResponse_Success.xml b/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/CreateNetworkV2/cloudRegion30_AAIResponse_Success.xml index 9b651f25e3..1bf6df0d1f 100644 --- a/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/CreateNetworkV2/cloudRegion30_AAIResponse_Success.xml +++ b/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/CreateNetworkV2/cloudRegion30_AAIResponse_Success.xml @@ -1,20 +1,20 @@ - - - - - - - - - - - - - att-aic - RDM2WAGPLCP - 3.0 - RDM2WAGPLCP - - - + + + + + + + + + + + + + att-aic + RDM2WAGPLCP + 3.0 + RDM2WAGPLCP + + + diff --git a/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/CreateNetworkV2/createNetwork_queryInstance_Success.xml b/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/CreateNetworkV2/createNetwork_queryInstance_Success.xml index ca5145c226..09f01fb7ca 100644 --- a/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/CreateNetworkV2/createNetwork_queryInstance_Success.xml +++ b/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/CreateNetworkV2/createNetwork_queryInstance_Success.xml @@ -1,4 +1,4 @@ - - service-instance - https://aai-conexus-e2e.test.com:8443/aai/v8/business/customers/customer/8310000058863/service-subscriptions/service-subscription/vMOG/service-instances/service-instance/f70e927b-6087-4974-9ef8-c5e4d5847ca4 + + service-instance + https://aai-conexus-e2e.test.com:8443/aai/v8/business/customers/customer/8310000058863/service-subscriptions/service-subscription/vMOG/service-instances/service-instance/f70e927b-6087-4974-9ef8-c5e4d5847ca4 \ No newline at end of file diff --git a/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/CreateNetworkV2/createNetwork_queryName2_AAIResponse_Success.xml b/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/CreateNetworkV2/createNetwork_queryName2_AAIResponse_Success.xml index d6f7737a2a..b2d9ce2c5d 100644 --- a/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/CreateNetworkV2/createNetwork_queryName2_AAIResponse_Success.xml +++ b/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/CreateNetworkV2/createNetwork_queryName2_AAIResponse_Success.xml @@ -1,62 +1,62 @@ - - - - - - - - - - - - - 49c86598-f766-46f8-84f8-8d1c1b10f9b4_3 - MNS-25180-L-01-dmz_direct_net_1 - CONTRAIL_EXTERNAL - dmz_direct - contrail - a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb - 0 - pending-create - - - 57e9a1ff-d14f-4071-a828-b19ae98eb2fc - 107.239.52.1 - 107.239.52.0 - 24 - 4 - pending-create - true - - - - - - vpn-binding - https://aai-app-e2e.test.com:8443/aai/v8/network/vpn-bindings/vpn-binding/85f015d0-2e32-4c30-96d2-87a1a27f8017/ - - vpn-binding.vpn-id - 85f015d0-2e32-4c30-96d2-87a1a27f8017 - - - - vpn-binding - https://aai-app-e2e.test.com:8443/aai/v8/network/vpn-bindings/vpn-binding/c980a6ef-3b88-49f0-9751-dbad8608d0a6/ - - vpn-binding.vpn-id - c980a6ef-3b88-49f0-9751-dbad8608d0a6 - - - - tenant - https://aai-app-e2e.test.com:8443/aai/v8/cloud-infrastructure/tenants/tenant/7dd5365547234ee8937416c65507d266/ - - tenant.tenant-id - 7dd5365547234ee8937416c65507d266 - - - - - - + + + + + + + + + + + + + 49c86598-f766-46f8-84f8-8d1c1b10f9b4_3 + MNS-25180-L-01-dmz_direct_net_1 + CONTRAIL_EXTERNAL + dmz_direct + contrail + a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb + 0 + pending-create + + + 57e9a1ff-d14f-4071-a828-b19ae98eb2fc + 107.239.52.1 + 107.239.52.0 + 24 + 4 + pending-create + true + + + + + + vpn-binding + https://aai-app-e2e.test.com:8443/aai/v8/network/vpn-bindings/vpn-binding/85f015d0-2e32-4c30-96d2-87a1a27f8017/ + + vpn-binding.vpn-id + 85f015d0-2e32-4c30-96d2-87a1a27f8017 + + + + vpn-binding + https://aai-app-e2e.test.com:8443/aai/v8/network/vpn-bindings/vpn-binding/c980a6ef-3b88-49f0-9751-dbad8608d0a6/ + + vpn-binding.vpn-id + c980a6ef-3b88-49f0-9751-dbad8608d0a6 + + + + tenant + https://aai-app-e2e.test.com:8443/aai/v8/cloud-infrastructure/tenants/tenant/7dd5365547234ee8937416c65507d266/ + + tenant.tenant-id + 7dd5365547234ee8937416c65507d266 + + + + + + diff --git a/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/CreateNetworkV2/createNetwork_queryNameActive_AAIResponse_Success.xml b/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/CreateNetworkV2/createNetwork_queryNameActive_AAIResponse_Success.xml index 03b37814b1..4dfd8d3f12 100644 --- a/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/CreateNetworkV2/createNetwork_queryNameActive_AAIResponse_Success.xml +++ b/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/CreateNetworkV2/createNetwork_queryNameActive_AAIResponse_Success.xml @@ -1,74 +1,74 @@ - - - - - - - - - - - - - 49c86598-f766-46f8-84f8-8d1c1b10f9b4 - MNS-25180-L-01-dmz_direct_net_2 - CONTRAIL_EXTERNAL - dmz_direct - contrail - a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb - 0 - active - - - 57e9a1ff-d14f-4071-a828-b19ae98eb2fc - 107.239.52.1 - 107.239.52.0 - 24 - 4 - active - true - subnetName - - - - - 413 - 4132176 - - - - vpn-binding - https://aai-app-e2e.test.com:8443/aai/v8/network/vpn-bindings/vpn-binding/85f015d0-2e32-4c30-96d2-87a1a27f8017/ - - vpn-binding.vpn-id - 85f015d0-2e32-4c30-96d2-87a1a27f8017 - - - - vpn-binding - https://aai-app-e2e.test.com:8443/aai/v8/network/vpn-bindings/vpn-binding/c980a6ef-3b88-49f0-9751-dbad8608d0a6/ - - vpn-binding.vpn-id - c980a6ef-3b88-49f0-9751-dbad8608d0a6 - - - - tenant - https://aai-app-e2e.test.com:8443/aai/v8/cloud-infrastructure/tenants/tenant/7dd5365547234ee8937416c65507d266/ - - tenant.tenant-id - 7dd5365547234ee8937416c65507d266 - - - - route-table-reference - - route-table-reference.route-table-reference-id - cee6d136-e378-4678-a024-2cd15f0ee0hi - - - - - - + + + + + + + + + + + + + 49c86598-f766-46f8-84f8-8d1c1b10f9b4 + MNS-25180-L-01-dmz_direct_net_2 + CONTRAIL_EXTERNAL + dmz_direct + contrail + a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb + 0 + active + + + 57e9a1ff-d14f-4071-a828-b19ae98eb2fc + 107.239.52.1 + 107.239.52.0 + 24 + 4 + active + true + subnetName + + + + + 413 + 4132176 + + + + vpn-binding + https://aai-app-e2e.test.com:8443/aai/v8/network/vpn-bindings/vpn-binding/85f015d0-2e32-4c30-96d2-87a1a27f8017/ + + vpn-binding.vpn-id + 85f015d0-2e32-4c30-96d2-87a1a27f8017 + + + + vpn-binding + https://aai-app-e2e.test.com:8443/aai/v8/network/vpn-bindings/vpn-binding/c980a6ef-3b88-49f0-9751-dbad8608d0a6/ + + vpn-binding.vpn-id + c980a6ef-3b88-49f0-9751-dbad8608d0a6 + + + + tenant + https://aai-app-e2e.test.com:8443/aai/v8/cloud-infrastructure/tenants/tenant/7dd5365547234ee8937416c65507d266/ + + tenant.tenant-id + 7dd5365547234ee8937416c65507d266 + + + + route-table-reference + + route-table-reference.route-table-reference-id + cee6d136-e378-4678-a024-2cd15f0ee0hi + + + + + + diff --git a/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/CreateNetworkV2/createNetwork_queryName_AAIResponse_Success.xml b/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/CreateNetworkV2/createNetwork_queryName_AAIResponse_Success.xml index 4eadb1061e..77e3a649fb 100644 --- a/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/CreateNetworkV2/createNetwork_queryName_AAIResponse_Success.xml +++ b/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/CreateNetworkV2/createNetwork_queryName_AAIResponse_Success.xml @@ -1,62 +1,62 @@ - - - - - - - - - - - - - 49c86598-f766-46f8-84f8-8d1c1b10f9b4 - MNS-25180-L-01-dmz_direct_net_1 - CONTRAIL_EXTERNAL - dmz_direct - contrail - a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb - 0 - pending-create - - - 57e9a1ff-d14f-4071-a828-b19ae98eb2fc - 107.239.52.1 - 107.239.52.0 - 24 - 4 - pending-create - true - - - - - - vpn-binding - https://aai-app-e2e.test.com:8443/aai/v8/network/vpn-bindings/vpn-binding/85f015d0-2e32-4c30-96d2-87a1a27f8017/ - - vpn-binding.vpn-id - 85f015d0-2e32-4c30-96d2-87a1a27f8017 - - - - vpn-binding - https://aai-app-e2e.test.com:8443/aai/v8/network/vpn-bindings/vpn-binding/c980a6ef-3b88-49f0-9751-dbad8608d0a6/ - - vpn-binding.vpn-id - c980a6ef-3b88-49f0-9751-dbad8608d0a6 - - - - tenant - https://aai-app-e2e.test.com:8443/aai/v8/cloud-infrastructure/tenants/tenant/7dd5365547234ee8937416c65507d266/ - - tenant.tenant-id - 7dd5365547234ee8937416c65507d266 - - - - - - + + + + + + + + + + + + + 49c86598-f766-46f8-84f8-8d1c1b10f9b4 + MNS-25180-L-01-dmz_direct_net_1 + CONTRAIL_EXTERNAL + dmz_direct + contrail + a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb + 0 + pending-create + + + 57e9a1ff-d14f-4071-a828-b19ae98eb2fc + 107.239.52.1 + 107.239.52.0 + 24 + 4 + pending-create + true + + + + + + vpn-binding + https://aai-app-e2e.test.com:8443/aai/v8/network/vpn-bindings/vpn-binding/85f015d0-2e32-4c30-96d2-87a1a27f8017/ + + vpn-binding.vpn-id + 85f015d0-2e32-4c30-96d2-87a1a27f8017 + + + + vpn-binding + https://aai-app-e2e.test.com:8443/aai/v8/network/vpn-bindings/vpn-binding/c980a6ef-3b88-49f0-9751-dbad8608d0a6/ + + vpn-binding.vpn-id + c980a6ef-3b88-49f0-9751-dbad8608d0a6 + + + + tenant + https://aai-app-e2e.test.com:8443/aai/v8/cloud-infrastructure/tenants/tenant/7dd5365547234ee8937416c65507d266/ + + tenant.tenant-id + 7dd5365547234ee8937416c65507d266 + + + + + + diff --git a/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/CreateNetworkV2/createNetwork_queryNetworkId_AAIResponse_NoPayload_Success.xml b/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/CreateNetworkV2/createNetwork_queryNetworkId_AAIResponse_NoPayload_Success.xml index e06d27ea88..fb8c365844 100644 --- a/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/CreateNetworkV2/createNetwork_queryNetworkId_AAIResponse_NoPayload_Success.xml +++ b/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/CreateNetworkV2/createNetwork_queryNetworkId_AAIResponse_NoPayload_Success.xml @@ -1,73 +1,73 @@ - - - 49c86598-f766-46f8-84f8-8d1c1b10f9b4 - MNS-25180-L-01-dmz_direct_net_1 - CONTRAIL_EXTERNAL - dmz_direct - contrail - a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb - 0 - pending-create - networkName - false - true - false - - - 57e9a1ff-d14f-4071-a828-b19ae98eb2fc - 107.239.52.1 - 107.239.52.0 - 24 - 4 - pending-create - true - subnetName - - - - - 413 - 4132176 - - - - vpn-binding - https://aai-app-e2e.test.com:8443/aai/v8/network/vpn-bindings/vpn-binding/85f015d0-2e32-4c30-96d2-87a1a27f8017/ - - vpn-binding.vpn-id - 85f015d0-2e32-4c30-96d2-87a1a27f8017 - - - - vpn-binding - https://aai-app-e2e.test.com:8443/aai/v8/network/vpn-bindings/vpn-binding/c980a6ef-3b88-49f0-9751-dbad8608d0a6/ - - vpn-binding.vpn-id - c980a6ef-3b88-49f0-9751-dbad8608d0a6 - - - - tenant - https://aai-app-e2e.test.com:8443/aai/v8/cloud-infrastructure/tenants/tenant/7dd5365547234ee8937416c65507d266/ - - tenant.tenant-id - 7dd5365547234ee8937416c65507d266 - - - - network-policy - https://aai-app-e2e.test.com:8443/aai/v8/network/network-policies/network-policy/cee6d136-e378-4678-a024-2cd15f0ee0cg - - network-policy.network-policy-id - cee6d136-e378-4678-a024-2cd15f0ee0cg - - - - route-table-reference - - route-table-reference.route-table-reference-id - cee6d136-e378-4678-a024-2cd15f0ee0hi - - - - + + + 49c86598-f766-46f8-84f8-8d1c1b10f9b4 + MNS-25180-L-01-dmz_direct_net_1 + CONTRAIL_EXTERNAL + dmz_direct + contrail + a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb + 0 + pending-create + networkName + false + true + false + + + 57e9a1ff-d14f-4071-a828-b19ae98eb2fc + 107.239.52.1 + 107.239.52.0 + 24 + 4 + pending-create + true + subnetName + + + + + 413 + 4132176 + + + + vpn-binding + https://aai-app-e2e.test.com:8443/aai/v8/network/vpn-bindings/vpn-binding/85f015d0-2e32-4c30-96d2-87a1a27f8017/ + + vpn-binding.vpn-id + 85f015d0-2e32-4c30-96d2-87a1a27f8017 + + + + vpn-binding + https://aai-app-e2e.test.com:8443/aai/v8/network/vpn-bindings/vpn-binding/c980a6ef-3b88-49f0-9751-dbad8608d0a6/ + + vpn-binding.vpn-id + c980a6ef-3b88-49f0-9751-dbad8608d0a6 + + + + tenant + https://aai-app-e2e.test.com:8443/aai/v8/cloud-infrastructure/tenants/tenant/7dd5365547234ee8937416c65507d266/ + + tenant.tenant-id + 7dd5365547234ee8937416c65507d266 + + + + network-policy + https://aai-app-e2e.test.com:8443/aai/v8/network/network-policies/network-policy/cee6d136-e378-4678-a024-2cd15f0ee0cg + + network-policy.network-policy-id + cee6d136-e378-4678-a024-2cd15f0ee0cg + + + + route-table-reference + + route-table-reference.route-table-reference-id + cee6d136-e378-4678-a024-2cd15f0ee0hi + + + + diff --git a/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/CreateNetworkV2/createNetwork_queryNetworkId_AAIResponse_Success.xml b/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/CreateNetworkV2/createNetwork_queryNetworkId_AAIResponse_Success.xml index 599c34fa73..59deca9aee 100644 --- a/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/CreateNetworkV2/createNetwork_queryNetworkId_AAIResponse_Success.xml +++ b/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/CreateNetworkV2/createNetwork_queryNetworkId_AAIResponse_Success.xml @@ -1,95 +1,95 @@ - - - - - - - - - - - - - 49c86598-f766-46f8-84f8-8d1c1b10f9b4 - MNS-25180-L-01-dmz_direct_net_1 - CONTRAIL_EXTERNAL - dmz_direct - contrail - a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb - 0 - pending-create - networkName - false - true - false - - - 57e9a1ff-d14f-4071-a828-b19ae98eb2fc - 107.239.52.1 - 107.239.52.0 - 24 - 4 - pending-create - true - subnetName - - - - - 413 - 4132176 - - - - vpn-binding - https://aai-app-e2e.test.com:8443/aai/v8/network/vpn-bindings/vpn-binding/85f015d0-2e32-4c30-96d2-87a1a27f8017/ - - vpn-binding.vpn-id - 85f015d0-2e32-4c30-96d2-87a1a27f8017 - - - - vpn-binding - https://aai-app-e2e.test.com:8443/aai/v8/network/vpn-bindings/vpn-binding/c980a6ef-3b88-49f0-9751-dbad8608d0a6/ - - vpn-binding.vpn-id - c980a6ef-3b88-49f0-9751-dbad8608d0a6 - - - - tenant - https://aai-app-e2e.test.com:8443/aai/v8/cloud-infrastructure/tenants/tenant/7dd5365547234ee8937416c65507d266/ - - tenant.tenant-id - 7dd5365547234ee8937416c65507d266 - - - - network-policy - https://aai-app-e2e.test.com:8443/aai/v8/network/network-policies/network-policy/cee6d136-e378-4678-a024-2cd15f0ee0cg - - network-policy.network-policy-id - cee6d136-e378-4678-a024-2cd15f0ee0cg - - - - route-table-reference - https://aai-app-e2e.test.com:8443/aai/v8/network/route-table-references/route-table-reference/refFQDN1 - - route-table-reference.route-table-reference-id - cee6d136-e378-4678-a024-2cd15f0ee0hi - - - - route-table-reference - https://aai-app-e2e.test.com:8443/aai/v8/network/route-table-references/route-table-reference/refFQDN2 - - route-table-reference.route-table-reference-id - cee6d136-e378-4678-a024-2cd15f0ee0hi - - - - - + + + + + + + + + + + + + 49c86598-f766-46f8-84f8-8d1c1b10f9b4 + MNS-25180-L-01-dmz_direct_net_1 + CONTRAIL_EXTERNAL + dmz_direct + contrail + a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb + 0 + pending-create + networkName + false + true + false + + + 57e9a1ff-d14f-4071-a828-b19ae98eb2fc + 107.239.52.1 + 107.239.52.0 + 24 + 4 + pending-create + true + subnetName + + + + + 413 + 4132176 + + + + vpn-binding + https://aai-app-e2e.test.com:8443/aai/v8/network/vpn-bindings/vpn-binding/85f015d0-2e32-4c30-96d2-87a1a27f8017/ + + vpn-binding.vpn-id + 85f015d0-2e32-4c30-96d2-87a1a27f8017 + + + + vpn-binding + https://aai-app-e2e.test.com:8443/aai/v8/network/vpn-bindings/vpn-binding/c980a6ef-3b88-49f0-9751-dbad8608d0a6/ + + vpn-binding.vpn-id + c980a6ef-3b88-49f0-9751-dbad8608d0a6 + + + + tenant + https://aai-app-e2e.test.com:8443/aai/v8/cloud-infrastructure/tenants/tenant/7dd5365547234ee8937416c65507d266/ + + tenant.tenant-id + 7dd5365547234ee8937416c65507d266 + + + + network-policy + https://aai-app-e2e.test.com:8443/aai/v8/network/network-policies/network-policy/cee6d136-e378-4678-a024-2cd15f0ee0cg + + network-policy.network-policy-id + cee6d136-e378-4678-a024-2cd15f0ee0cg + + + + route-table-reference + https://aai-app-e2e.test.com:8443/aai/v8/network/route-table-references/route-table-reference/refFQDN1 + + route-table-reference.route-table-reference-id + cee6d136-e378-4678-a024-2cd15f0ee0hi + + + + route-table-reference + https://aai-app-e2e.test.com:8443/aai/v8/network/route-table-references/route-table-reference/refFQDN2 + + route-table-reference.route-table-reference-id + cee6d136-e378-4678-a024-2cd15f0ee0hi + + + + + \ No newline at end of file diff --git a/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/CreateNetworkV2/createNetwork_queryNetworkPolicy_AAIResponse_Success.xml b/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/CreateNetworkV2/createNetwork_queryNetworkPolicy_AAIResponse_Success.xml index 686ac1667f..02a280da58 100644 --- a/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/CreateNetworkV2/createNetwork_queryNetworkPolicy_AAIResponse_Success.xml +++ b/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/CreateNetworkV2/createNetwork_queryNetworkPolicy_AAIResponse_Success.xml @@ -1,21 +1,21 @@ - - - - - - - - - - - - - 9a7b327d9-287aa00-82c4b0-105757 - GN_EVPN_Test - 13979:105757 - 13979:105757 - - + + + + + + + + + + + + + 9a7b327d9-287aa00-82c4b0-105757 + GN_EVPN_Test + 13979:105757 + 13979:105757 + + \ No newline at end of file diff --git a/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/CreateNetworkV2/createNetwork_queryNetworkTableRef1_AAIResponse_Success.xml b/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/CreateNetworkV2/createNetwork_queryNetworkTableRef1_AAIResponse_Success.xml index b01e469cbf..52e9692b4d 100644 --- a/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/CreateNetworkV2/createNetwork_queryNetworkTableRef1_AAIResponse_Success.xml +++ b/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/CreateNetworkV2/createNetwork_queryNetworkTableRef1_AAIResponse_Success.xml @@ -1,20 +1,20 @@ - - - - - - - - - - - - - 5938baec-03ca-2bd5-a3f1-d54x123e253a - refFQDN1 - 12345 - - + + + + + + + + + + + + + 5938baec-03ca-2bd5-a3f1-d54x123e253a + refFQDN1 + 12345 + + \ No newline at end of file diff --git a/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/CreateNetworkV2/createNetwork_queryNetworkTableRef2_AAIResponse_Success.xml b/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/CreateNetworkV2/createNetwork_queryNetworkTableRef2_AAIResponse_Success.xml index a19f9412c8..ddae6b1182 100644 --- a/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/CreateNetworkV2/createNetwork_queryNetworkTableRef2_AAIResponse_Success.xml +++ b/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/CreateNetworkV2/createNetwork_queryNetworkTableRef2_AAIResponse_Success.xml @@ -1,20 +1,20 @@ - - - - - - - - - - - - - 5938baec-03ca-2bd5-a3f1-d54x123e253a - refFQDN2 - 12345 - - + + + + + + + + + + + + + 5938baec-03ca-2bd5-a3f1-d54x123e253a + refFQDN2 + 12345 + + \ No newline at end of file diff --git a/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/CreateNetworkV2/createNetwork_queryVpnBinding_AAIResponse_Success.xml b/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/CreateNetworkV2/createNetwork_queryVpnBinding_AAIResponse_Success.xml index c35faef27f..19aac50ee4 100644 --- a/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/CreateNetworkV2/createNetwork_queryVpnBinding_AAIResponse_Success.xml +++ b/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/CreateNetworkV2/createNetwork_queryVpnBinding_AAIResponse_Success.xml @@ -1,46 +1,46 @@ - - - - - - - - - - - - - 9a7b327d9-287aa00-82c4b0-105757 - GN_EVPN_Test - 13979:105757 - - - l3-network - https://aai-app-e2e.test.com:8443/aai/v8/network/l3-networks/l3-network/689ec39e-c5fc-4462-8db2-4f760763ad28/ - - l3-network.network-id - 689ec39e-c5fc-4462-8db2-4f760763ad28 - - - - l3-network - https://aai-app-e2e.test.com:8443/aai/v8/network/l3-networks/l3-network/1a49396b-19b3-40a4-8792-aa2fbd0f0704/ - - l3-network.network-id - 1a49396b-19b3-40a4-8792-aa2fbd0f0704 - - - - l3-network - https://aai-app-e2e.test.com:8443/aai/v8/network/l3-networks/l3-network/774f3329-3c83-4771-86c7-9e6207cd50fd/ - - l3-network.network-id - 774f3329-3c83-4771-86c7-9e6207cd50fd - - - - - + + + + + + + + + + + + + 9a7b327d9-287aa00-82c4b0-105757 + GN_EVPN_Test + 13979:105757 + + + l3-network + https://aai-app-e2e.test.com:8443/aai/v8/network/l3-networks/l3-network/689ec39e-c5fc-4462-8db2-4f760763ad28/ + + l3-network.network-id + 689ec39e-c5fc-4462-8db2-4f760763ad28 + + + + l3-network + https://aai-app-e2e.test.com:8443/aai/v8/network/l3-networks/l3-network/1a49396b-19b3-40a4-8792-aa2fbd0f0704/ + + l3-network.network-id + 1a49396b-19b3-40a4-8792-aa2fbd0f0704 + + + + l3-network + https://aai-app-e2e.test.com:8443/aai/v8/network/l3-networks/l3-network/774f3329-3c83-4771-86c7-9e6207cd50fd/ + + l3-network.network-id + 774f3329-3c83-4771-86c7-9e6207cd50fd + + + + + \ No newline at end of file diff --git a/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/CreateVfModuleVolumeInfraV1/GenericVnf.xml b/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/CreateVfModuleVolumeInfraV1/GenericVnf.xml index aea1a46017..4c18356bf9 100644 --- a/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/CreateVfModuleVolumeInfraV1/GenericVnf.xml +++ b/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/CreateVfModuleVolumeInfraV1/GenericVnf.xml @@ -1,38 +1,38 @@ - - TEST-VNF-ID-0123 - STMTN5MMSC20 - pcrf-capacity - SDN-MOBILITY - vPCRF - pending-create - false - false - introvert - 2.0 - 0000020 - - - lukewarm - PCRF::module-0-0 - introvert - 2.0 - true - fastburn - pending-create - 0000074 - - - supercool - PCRF::module-1-0 - extrovert - 2.0 - false - slowburn - pending-create - 0000075 - - - - - + + TEST-VNF-ID-0123 + STMTN5MMSC20 + pcrf-capacity + SDN-MOBILITY + vPCRF + pending-create + false + false + introvert + 2.0 + 0000020 + + + lukewarm + PCRF::module-0-0 + introvert + 2.0 + true + fastburn + pending-create + 0000074 + + + supercool + PCRF::module-1-0 + extrovert + 2.0 + false + slowburn + pending-create + 0000075 + + + + + \ No newline at end of file diff --git a/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/CreateVfModuleVolumeInfraV1/createVfModuleVolume_createVolumeName_AAIResponse_Success.xml b/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/CreateVfModuleVolumeInfraV1/createVfModuleVolume_createVolumeName_AAIResponse_Success.xml index 02b43ff186..bff26fa78a 100644 --- a/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/CreateVfModuleVolumeInfraV1/createVfModuleVolume_createVolumeName_AAIResponse_Success.xml +++ b/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/CreateVfModuleVolumeInfraV1/createVfModuleVolume_createVolumeName_AAIResponse_Success.xml @@ -1,49 +1,49 @@ - - - - - - - - - - - - - - - - - - - - - - - - simpleCinderVolume_201604071 - simpleCinderVolume_201604071 - simpleCinderVolume_201604071 - simple_cinder_master - Pending - 1460134360 - - - tenant - https://aai-ext1.test.com:8443/aai/v6/cloud-infrastructure/tenants/tenant/897deadc2b954a6bac6d3c197fb3525e/ - - tenant.tenant-id - 897deadc2b954a6bac6d3c197fb3525e - - - tenant.tenant-name - MSOTest1 - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + simpleCinderVolume_201604071 + simpleCinderVolume_201604071 + simpleCinderVolume_201604071 + simple_cinder_master + Pending + 1460134360 + + + tenant + https://aai-ext1.test.com:8443/aai/v6/cloud-infrastructure/tenants/tenant/897deadc2b954a6bac6d3c197fb3525e/ + + tenant.tenant-id + 897deadc2b954a6bac6d3c197fb3525e + + + tenant.tenant-name + MSOTest1 + + + + + + diff --git a/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/CreateVfModuleVolumeInfraV1/createVfModuleVolume_queryVolumeName_AAIResponse_404.xml b/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/CreateVfModuleVolumeInfraV1/createVfModuleVolume_queryVolumeName_AAIResponse_404.xml index 96e906f9bf..152bafc0eb 100644 --- a/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/CreateVfModuleVolumeInfraV1/createVfModuleVolume_queryVolumeName_AAIResponse_404.xml +++ b/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/CreateVfModuleVolumeInfraV1/createVfModuleVolume_queryVolumeName_AAIResponse_404.xml @@ -1,31 +1,31 @@ - - - 94f0f72f-4be1-49ed-8410-702396797163 - MSOTESTVOL103H-vSAMP12_base_vol_module-0 - - Test/vSAMP12 - Pending - 1469203133 - - - tenant - https://aai-ext1.test.com:8443/aai/v7/cloud-infrastructure/cloud-regions/cloud-region/att-aic/mtn6/tenants/tenant/e444c311b27a45dc9522f2370d70f90f/ - - tenant.tenant-id - e444c311b27a45dc9522f2370d70f90f - - - cloud-region.cloud-owner - att-aic - - - cloud-region.cloud-region-id - mtn6 - - - tenant.tenant-name - MSOCustomer1 - - - - + + + 94f0f72f-4be1-49ed-8410-702396797163 + MSOTESTVOL103H-vSAMP12_base_vol_module-0 + + Test/vSAMP12 + Pending + 1469203133 + + + tenant + https://aai-ext1.test.com:8443/aai/v7/cloud-infrastructure/cloud-regions/cloud-region/att-aic/mtn6/tenants/tenant/e444c311b27a45dc9522f2370d70f90f/ + + tenant.tenant-id + e444c311b27a45dc9522f2370d70f90f + + + cloud-region.cloud-owner + att-aic + + + cloud-region.cloud-region-id + mtn6 + + + tenant.tenant-name + MSOCustomer1 + + + + diff --git a/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/CreateVfModuleVolumeInfraV1/createVfModuleVolume_queryVolumeName_AAIResponse_Success.xml b/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/CreateVfModuleVolumeInfraV1/createVfModuleVolume_queryVolumeName_AAIResponse_Success.xml index 5e8913f335..cb20a41ca0 100644 --- a/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/CreateVfModuleVolumeInfraV1/createVfModuleVolume_queryVolumeName_AAIResponse_Success.xml +++ b/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/CreateVfModuleVolumeInfraV1/createVfModuleVolume_queryVolumeName_AAIResponse_Success.xml @@ -1,49 +1,49 @@ - - - - - - - - - - - - - - - - - - - - - - - - 8424bb3c-c3e7-4553-9662-469649ed9379 - MSOTESTVOL103W-vSAMP12_base_vol_module-0 - - simple_cinder_master - Pending - 1460134360 - - - tenant - https://aai-ext1.test.com:8443/aai/v6/cloud-infrastructure/tenants/tenant/897deadc2b954a6bac6d3c197fb3525e/ - - tenant.tenant-id - 897deadc2b954a6bac6d3c197fb3525e - - - tenant.tenant-name - MSOTest1 - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + 8424bb3c-c3e7-4553-9662-469649ed9379 + MSOTESTVOL103W-vSAMP12_base_vol_module-0 + + simple_cinder_master + Pending + 1460134360 + + + tenant + https://aai-ext1.test.com:8443/aai/v6/cloud-infrastructure/tenants/tenant/897deadc2b954a6bac6d3c197fb3525e/ + + tenant.tenant-id + 897deadc2b954a6bac6d3c197fb3525e + + + tenant.tenant-name + MSOTest1 + + + + + + diff --git a/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/CreateVfModuleVolumeInfraV1/getSIUrlById.xml b/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/CreateVfModuleVolumeInfraV1/getSIUrlById.xml index 416689e10c..55fdedb66c 100644 --- a/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/CreateVfModuleVolumeInfraV1/getSIUrlById.xml +++ b/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/CreateVfModuleVolumeInfraV1/getSIUrlById.xml @@ -1,6 +1,6 @@ - - - service-instance - https://aai-ext1.test.com:8443/aai/v7/business/customers/customer/SDN-ETHERNET-INTERNET/service-subscriptions/service-subscription/123456789/service-instances/service-instance/MIS%252F1604%252F0026%252FSW_INTERNET - + + + service-instance + https://aai-ext1.test.com:8443/aai/v7/business/customers/customer/SDN-ETHERNET-INTERNET/service-subscriptions/service-subscription/123456789/service-instances/service-instance/MIS%252F1604%252F0026%252FSW_INTERNET + \ No newline at end of file diff --git a/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/DeleteGenericVNFV1/sdncAdapterResponse.xml b/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/DeleteGenericVNFV1/sdncAdapterResponse.xml index 8056f05d5a..4b3ac855df 100644 --- a/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/DeleteGenericVNFV1/sdncAdapterResponse.xml +++ b/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/DeleteGenericVNFV1/sdncAdapterResponse.xml @@ -1,7 +1,7 @@ - - - - <output xmlns="org:openecomp:sdnctl:vnf"><svc-request-id>1660b8da-0a94-442d-8ed5-ea079e3c67c8</svc-request-id><response-code>200</response-code><ack-final-indicator>Y</ack-final-indicator><vnf-information><vnf-id>8925b50d-de67-44c1-b984-e7ce7b0f4dae</vnf-id></vnf-information><service-information><service-type>a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb</service-type><service-instance-id>8925b50d-de67-44c1-b984-e7ce7b0f4dae</service-instance-id><subscriber-name>notsurewecare</subscriber-name></service-information></output> - - + + + + <output xmlns="org:openecomp:sdnctl:vnf"><svc-request-id>1660b8da-0a94-442d-8ed5-ea079e3c67c8</svc-request-id><response-code>200</response-code><ack-final-indicator>Y</ack-final-indicator><vnf-information><vnf-id>8925b50d-de67-44c1-b984-e7ce7b0f4dae</vnf-id></vnf-information><service-information><service-type>a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb</service-type><service-instance-id>8925b50d-de67-44c1-b984-e7ce7b0f4dae</service-instance-id><subscriber-name>notsurewecare</subscriber-name></service-information></output> + + \ No newline at end of file diff --git a/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/DeleteVfModuleVolumeInfraV1/queryVolumeId_AAIResponse_Success.xml b/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/DeleteVfModuleVolumeInfraV1/queryVolumeId_AAIResponse_Success.xml index fd10548cef..c02c35f9c9 100644 --- a/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/DeleteVfModuleVolumeInfraV1/queryVolumeId_AAIResponse_Success.xml +++ b/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/DeleteVfModuleVolumeInfraV1/queryVolumeId_AAIResponse_Success.xml @@ -1,42 +1,42 @@ - - 78987 - MSOTESTVOL102a-vSAMP12_base_vol_module-0 - - Test/vSAMP12 - Pending - 0000020 - - - generic-vnf - https://aai-ext1.test.com:8443/aai/v8/network/generic-vnfs/generic-vnf/9e48f6ea-f786-46de-800a-d480e5ccc846/ - - generic-vnf.vnf-id - 9e48f6ea-f786-46de-800a-d480e5ccc846 - - - generic-vnf.vnf-name - MSOSTSAMP12-10601 - - - - tenant - https://aai-ext1.test.com:8443/aai/v7/cloud-infrastructure/cloud-regions/cloud-region/att-aic/mdt1/tenants/tenant/fba1bd1e195a404cacb9ce17a9b2b421/ - - tenant.tenant-id - fba1bd1e195a404cacb9ce17a9b2b421 - - - cloud-region.cloud-owner - att-aic - - - cloud-region.cloud-region-id - mdt1 - - - tenant.tenant-name - ECOMP_MDT1 - - - + + 78987 + MSOTESTVOL102a-vSAMP12_base_vol_module-0 + + Test/vSAMP12 + Pending + 0000020 + + + generic-vnf + https://aai-ext1.test.com:8443/aai/v8/network/generic-vnfs/generic-vnf/9e48f6ea-f786-46de-800a-d480e5ccc846/ + + generic-vnf.vnf-id + 9e48f6ea-f786-46de-800a-d480e5ccc846 + + + generic-vnf.vnf-name + MSOSTSAMP12-10601 + + + + tenant + https://aai-ext1.test.com:8443/aai/v7/cloud-infrastructure/cloud-regions/cloud-region/att-aic/mdt1/tenants/tenant/fba1bd1e195a404cacb9ce17a9b2b421/ + + tenant.tenant-id + fba1bd1e195a404cacb9ce17a9b2b421 + + + cloud-region.cloud-owner + att-aic + + + cloud-region.cloud-region-id + mdt1 + + + tenant.tenant-name + ECOMP_MDT1 + + + \ No newline at end of file diff --git a/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/DoCreateVfModuleRollback/GenericVnf.xml b/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/DoCreateVfModuleRollback/GenericVnf.xml index 50e4347e5f..5e8a62b25b 100644 --- a/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/DoCreateVfModuleRollback/GenericVnf.xml +++ b/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/DoCreateVfModuleRollback/GenericVnf.xml @@ -1,26 +1,26 @@ - - a27ce5a9-29c4-4c22-a017-6615ac73c721 - STMTN5MMSC21 - mmsc-capacity - SDN-MOBILITY - vMMSC - pending-create - false - false - 1508691 - - - 973ed047-d251-4fb9-bf1a-65b8949e0a73 - STMTN5MMSC21-MMSC::module-0-0 - 973ed047-d251-4fb9-bf1a-65b8949e0a73 - 1.0 - true - FILLED-IN-BY-MSO - pending-create - 1508692 - - - - - + + a27ce5a9-29c4-4c22-a017-6615ac73c721 + STMTN5MMSC21 + mmsc-capacity + SDN-MOBILITY + vMMSC + pending-create + false + false + 1508691 + + + 973ed047-d251-4fb9-bf1a-65b8949e0a73 + STMTN5MMSC21-MMSC::module-0-0 + 973ed047-d251-4fb9-bf1a-65b8949e0a73 + 1.0 + true + FILLED-IN-BY-MSO + pending-create + 1508692 + + + + + \ No newline at end of file diff --git a/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/DoCreateVfModuleRollback/GenericVnfVfModule.xml b/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/DoCreateVfModuleRollback/GenericVnfVfModule.xml index f60260d85b..586e0a620a 100644 --- a/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/DoCreateVfModuleRollback/GenericVnfVfModule.xml +++ b/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/DoCreateVfModuleRollback/GenericVnfVfModule.xml @@ -1,26 +1,26 @@ - - a27ce5a9-29c4-4c22-a017-6615ac73c721 - STMTN5MMSC21 - mmsc-capacity - SDN-MOBILITY - vMMSC - pending-create - false - false - 0000021 - - - 973ed047-d251-4fb9-bf1a-65b8949e0a73 - STMTN5MMSC21-MMSC::module-0-0 - 973ed047-d251-4fb9-bf1a-65b8949e0a73 - 1.0 - true - FILLED-IN-BY-MSO - pending-create - 0000073 - - - - - + + a27ce5a9-29c4-4c22-a017-6615ac73c721 + STMTN5MMSC21 + mmsc-capacity + SDN-MOBILITY + vMMSC + pending-create + false + false + 0000021 + + + 973ed047-d251-4fb9-bf1a-65b8949e0a73 + STMTN5MMSC21-MMSC::module-0-0 + 973ed047-d251-4fb9-bf1a-65b8949e0a73 + 1.0 + true + FILLED-IN-BY-MSO + pending-create + 0000073 + + + + + \ No newline at end of file diff --git a/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/DoCreateVfModuleVolumeV1/GenericVnf.xml b/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/DoCreateVfModuleVolumeV1/GenericVnf.xml index aea1a46017..4c18356bf9 100644 --- a/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/DoCreateVfModuleVolumeV1/GenericVnf.xml +++ b/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/DoCreateVfModuleVolumeV1/GenericVnf.xml @@ -1,38 +1,38 @@ - - TEST-VNF-ID-0123 - STMTN5MMSC20 - pcrf-capacity - SDN-MOBILITY - vPCRF - pending-create - false - false - introvert - 2.0 - 0000020 - - - lukewarm - PCRF::module-0-0 - introvert - 2.0 - true - fastburn - pending-create - 0000074 - - - supercool - PCRF::module-1-0 - extrovert - 2.0 - false - slowburn - pending-create - 0000075 - - - - - + + TEST-VNF-ID-0123 + STMTN5MMSC20 + pcrf-capacity + SDN-MOBILITY + vPCRF + pending-create + false + false + introvert + 2.0 + 0000020 + + + lukewarm + PCRF::module-0-0 + introvert + 2.0 + true + fastburn + pending-create + 0000074 + + + supercool + PCRF::module-1-0 + extrovert + 2.0 + false + slowburn + pending-create + 0000075 + + + + + \ No newline at end of file diff --git a/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/DoCreateVfModuleVolumeV1/createVfModuleVolume_createVolumeName_AAIResponse_Success.xml b/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/DoCreateVfModuleVolumeV1/createVfModuleVolume_createVolumeName_AAIResponse_Success.xml index 02b43ff186..bff26fa78a 100644 --- a/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/DoCreateVfModuleVolumeV1/createVfModuleVolume_createVolumeName_AAIResponse_Success.xml +++ b/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/DoCreateVfModuleVolumeV1/createVfModuleVolume_createVolumeName_AAIResponse_Success.xml @@ -1,49 +1,49 @@ - - - - - - - - - - - - - - - - - - - - - - - - simpleCinderVolume_201604071 - simpleCinderVolume_201604071 - simpleCinderVolume_201604071 - simple_cinder_master - Pending - 1460134360 - - - tenant - https://aai-ext1.test.com:8443/aai/v6/cloud-infrastructure/tenants/tenant/897deadc2b954a6bac6d3c197fb3525e/ - - tenant.tenant-id - 897deadc2b954a6bac6d3c197fb3525e - - - tenant.tenant-name - MSOTest1 - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + simpleCinderVolume_201604071 + simpleCinderVolume_201604071 + simpleCinderVolume_201604071 + simple_cinder_master + Pending + 1460134360 + + + tenant + https://aai-ext1.test.com:8443/aai/v6/cloud-infrastructure/tenants/tenant/897deadc2b954a6bac6d3c197fb3525e/ + + tenant.tenant-id + 897deadc2b954a6bac6d3c197fb3525e + + + tenant.tenant-name + MSOTest1 + + + + + + diff --git a/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/DoCreateVfModuleVolumeV1/createVfModuleVolume_queryVolumeName_AAIResponse_Success.xml b/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/DoCreateVfModuleVolumeV1/createVfModuleVolume_queryVolumeName_AAIResponse_Success.xml index 5e8913f335..cb20a41ca0 100644 --- a/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/DoCreateVfModuleVolumeV1/createVfModuleVolume_queryVolumeName_AAIResponse_Success.xml +++ b/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/DoCreateVfModuleVolumeV1/createVfModuleVolume_queryVolumeName_AAIResponse_Success.xml @@ -1,49 +1,49 @@ - - - - - - - - - - - - - - - - - - - - - - - - 8424bb3c-c3e7-4553-9662-469649ed9379 - MSOTESTVOL103W-vSAMP12_base_vol_module-0 - - simple_cinder_master - Pending - 1460134360 - - - tenant - https://aai-ext1.test.com:8443/aai/v6/cloud-infrastructure/tenants/tenant/897deadc2b954a6bac6d3c197fb3525e/ - - tenant.tenant-id - 897deadc2b954a6bac6d3c197fb3525e - - - tenant.tenant-name - MSOTest1 - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + 8424bb3c-c3e7-4553-9662-469649ed9379 + MSOTESTVOL103W-vSAMP12_base_vol_module-0 + + simple_cinder_master + Pending + 1460134360 + + + tenant + https://aai-ext1.test.com:8443/aai/v6/cloud-infrastructure/tenants/tenant/897deadc2b954a6bac6d3c197fb3525e/ + + tenant.tenant-id + 897deadc2b954a6bac6d3c197fb3525e + + + tenant.tenant-name + MSOTest1 + + + + + + diff --git a/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/UpdateVfModuleVolumeInfraV1/queryVolumeId_AAIResponse_Success.xml b/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/UpdateVfModuleVolumeInfraV1/queryVolumeId_AAIResponse_Success.xml index b03e95c013..244a51e160 100644 --- a/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/UpdateVfModuleVolumeInfraV1/queryVolumeId_AAIResponse_Success.xml +++ b/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/UpdateVfModuleVolumeInfraV1/queryVolumeId_AAIResponse_Success.xml @@ -1,44 +1,44 @@ - - - 78987 - MSOTESTVOL102a-vSAMP12_base_vol_module-0 - - Test/vSAMP12 - Pending - 0000020 - - - tenant - https://aai-ext1.test.com:8443/aai/v7/cloud-infrastructure/cloud-regions/cloud-region/att-aic/mdt1/tenants/tenant/fba1bd1e195a404cacb9ce17a9b2b421/ - - tenant.tenant-id - fba1bd1e195a404cacb9ce17a9b2b421 - - - cloud-region.cloud-owner - att-aic - - - cloud-region.cloud-region-id - mdt1 - - - tenant.tenant-name - ECOMP_MDT1 - - - - vf-module - http://localhost:28090/aai/v8/network/generic-vnfs/generic-vnf/9e48f6ea-f786-46de-800a-d480e5ccc846/vf-modules/vf-module/6a1dc898-b590-47b9-bbf0-34424a7a2ec3/ - - generic-vnf.vnf-id - 9e48f6ea-f786-46de-800a-d480e5ccc846 - - - vf-module.vf-module-id - 6a1dc898-b590-47b9-bbf0-34424a7a2ec3 - - - - + + + 78987 + MSOTESTVOL102a-vSAMP12_base_vol_module-0 + + Test/vSAMP12 + Pending + 0000020 + + + tenant + https://aai-ext1.test.com:8443/aai/v7/cloud-infrastructure/cloud-regions/cloud-region/att-aic/mdt1/tenants/tenant/fba1bd1e195a404cacb9ce17a9b2b421/ + + tenant.tenant-id + fba1bd1e195a404cacb9ce17a9b2b421 + + + cloud-region.cloud-owner + att-aic + + + cloud-region.cloud-region-id + mdt1 + + + tenant.tenant-name + ECOMP_MDT1 + + + + vf-module + http://localhost:28090/aai/v8/network/generic-vnfs/generic-vnf/9e48f6ea-f786-46de-800a-d480e5ccc846/vf-modules/vf-module/6a1dc898-b590-47b9-bbf0-34424a7a2ec3/ + + generic-vnf.vnf-id + 9e48f6ea-f786-46de-800a-d480e5ccc846 + + + vf-module.vf-module-id + 6a1dc898-b590-47b9-bbf0-34424a7a2ec3 + + + + \ No newline at end of file diff --git a/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/UpdateVfModuleVolumeInfraV1/vf_module_aai_response.xml b/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/UpdateVfModuleVolumeInfraV1/vf_module_aai_response.xml index aa2a85c579..58b8708809 100644 --- a/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/UpdateVfModuleVolumeInfraV1/vf_module_aai_response.xml +++ b/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/UpdateVfModuleVolumeInfraV1/vf_module_aai_response.xml @@ -1,29 +1,29 @@ - - 6a1dc898-b590-47b9-bbf0-34424a7a2ec3 - MSOST10606-vSAMP12_MTN6_base_module-0 - MSOST10606-vSAMP12_MTN6_base_module-0/81b01583-690c-4ec3-9c58-0eafa7a90be7 - active - true - 1475077639 - ff5256d2-5a33-55df-13ab-12abad84e7ff - 1.0 - - - volume-group - https://aai-ext1.test.com:8443/aai/v8/cloud-infrastructure/cloud-regions/cloud-region/att-aic/mtn6/volume-groups/volume-group/064bd1c6-e377-4009-a744-e958eec6e727/ - - cloud-region.cloud-owner - att-aic - - - cloud-region.cloud-region-id - mtn6 - - - volume-group.volume-group-id - 064bd1c6-e377-4009-a744-e958eec6e727 - - - - + + 6a1dc898-b590-47b9-bbf0-34424a7a2ec3 + MSOST10606-vSAMP12_MTN6_base_module-0 + MSOST10606-vSAMP12_MTN6_base_module-0/81b01583-690c-4ec3-9c58-0eafa7a90be7 + active + true + 1475077639 + ff5256d2-5a33-55df-13ab-12abad84e7ff + 1.0 + + + volume-group + https://aai-ext1.test.com:8443/aai/v8/cloud-infrastructure/cloud-regions/cloud-region/att-aic/mtn6/volume-groups/volume-group/064bd1c6-e377-4009-a744-e958eec6e727/ + + cloud-region.cloud-owner + att-aic + + + cloud-region.cloud-region-id + mtn6 + + + volume-group.volume-group-id + 064bd1c6-e377-4009-a744-e958eec6e727 + + + + \ No newline at end of file diff --git a/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/VfModularity/VolumeGroup.xml b/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/VfModularity/VolumeGroup.xml index df84706ec5..354ebb7160 100644 --- a/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/VfModularity/VolumeGroup.xml +++ b/bpmn/MSOInfrastructureBPMN/src/test/resources/__files/VfModularity/VolumeGroup.xml @@ -1,25 +1,25 @@ - - 78987 - Volume_2 - slowburn - pcrf-capacity - Active - 0000020 - - - tenant - - cloud-region.cloud-owner - att-aic - - - cloud-region.cloud-region-id - MDTWNJ21 - - - tenant.tenant-id - fba1bd1e195a404cacb9ce17a9b2b421 - - - + + 78987 + Volume_2 + slowburn + pcrf-capacity + Active + 0000020 + + + tenant + + cloud-region.cloud-owner + att-aic + + + cloud-region.cloud-region-id + MDTWNJ21 + + + tenant.tenant-id + fba1bd1e195a404cacb9ce17a9b2b421 + + + \ No newline at end of file diff --git a/bpmn/MSOInfrastructureBPMN/src/test/resources/camunda.cfg.xml b/bpmn/MSOInfrastructureBPMN/src/test/resources/camunda.cfg.xml index c94e32e686..68db73d5a5 100644 --- a/bpmn/MSOInfrastructureBPMN/src/test/resources/camunda.cfg.xml +++ b/bpmn/MSOInfrastructureBPMN/src/test/resources/camunda.cfg.xml @@ -1,61 +1,61 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/bpmn/MSOInfrastructureBPMN/src/test/resources/mso.bpmn.urn.properties b/bpmn/MSOInfrastructureBPMN/src/test/resources/mso.bpmn.urn.properties index 4ec6617431..ac340c79b6 100644 --- a/bpmn/MSOInfrastructureBPMN/src/test/resources/mso.bpmn.urn.properties +++ b/bpmn/MSOInfrastructureBPMN/src/test/resources/mso.bpmn.urn.properties @@ -1,85 +1,85 @@ -# Default URN Mappings for unit tests - -mso.rollback=true - -canopi.auth=757A94191D685FD2092AC1490730A4FC -csi.aots.addincidentmanagement.endpoint=http://localhost:28090/AddIncidentManagementTicketRequest -csi.networkstatus.endpoint=http://localhost:28090/SendManagedNetworkStatusNotification -mso.csi.pwd=4EA237303511EFBBC37F17A351562131 -mso.csi.usrname=mso -mso.msoKey=07a7159d3bf51a0e53be7a8f89699be7 - -mso.adapters.completemsoprocess.endpoint=http://localhost:28090/CompleteMsoProcess - -mso.adapters.db.endpoint=http://localhost:28090/dbadapters/RequestsDbAdapter -mso.adapters.db.auth=757A94191D685FD2092AC1490730A4FC - -mso.adapters.network.endpoint=http://localhost:28090/networks/NetworkAdapter -mso.adapters.network.rest.endpoint=http://localhost:28090/networks/NetworkAdapter - -mso.adapters.po.auth=757A94191D685FD2092AC1490730A4FC -mso.adapters.po.password=3141634BF7E070AA289CF2892C986C0B -mso.po.timeout=PT60S - -aai.auth=757A94191D685FD2092AC1490730A4FC - -mso.adapters.sdnc.endpoint=http://localhost:28090/SDNCAdapter -mso.adapters.sdnc.rest.endpoint=http://localhost:28090/SDNCAdapter/v1/sdnc -mso.adapters.sdnc.timeout=PT60S -mso.sdnc.firewall.yang.model=http://com/openecomp/svc/mis/firewall-lite-gui -mso.sdnc.firewall.yang.model.version=2015-05-15 -mso.sdnc.password=3141634BF7E070AA289CF2892C986C0B -mso.sdnc.timeout.firewall.minutes=20 -mso.sdnc.timeout=PT10S -mso.sdnc.timeout.ucpe.async.hours=120 -mso.sdnc.timeout.ucpe.async.minutes=5 -mso.workflow.message.endpoint=http://localhost:28080/mso/WorkflowMesssage -mso.workflow.sdncadapter.callback=http://localhost:28080/mso/SDNCAdapterCallbackService - -mso.catalog.db.endpoint=http://localhost:28090/ - -mso.adapters.tenant.endpoint=http://localhost:28090/tenantAdapterMock -mso.adapters.vnf-async.endpoint=http://localhost:28090/vnfs/VnfAdapterAsync -mso.adapters.vnf.endpoint=http://localhost:28090/vnfs/VnfAdapter -mso.adapters.vnf.rest.endpoint=http://localhost:28090/vnfs/v1/vnfs -mso.workflow.vnfadapter.create.callback=http://localhost:28080/mso/vnfAdapterNotify -mso.workflow.vnfadapter.delete.callback=http://localhost:28080/mso/vnfAdapterNotify -mso.workflow.vnfadapter.query.callback=http://localhost:28080/mso/services/VNFAdapterQuerCallbackV1 -mso.workflow.vnfadapter.rollback.callback=http://localhost:28080/mso/vnfAdapterNotify -mso.workflow.createvce.delay.seconds=1 -mso.infra.customer.id=testCustIdInfra - -aai.endpoint=http://localhost:28090 - -# AAI version mappings - -# Example to override default version for a resource: -#mso.workflow.default.aai.vce.version=6 -#mso.workflow.default.aai.v6.vce.uri=/aai/v6/network/vces/vce - -mso.workflow.global.default.aai.version=8 -mso.workflow.default.aai.cloud-region.version=9 -mso.workflow.default.aai.generic-vnf.version=9 - -mso.workflow.default.aai.v9.cloud-region.uri=/aai/v9/cloud-infrastructure/cloud-regions/cloud-region/att-aic -mso.workflow.default.aai.v8.customer.uri=/aai/v8/business/customers/customer -mso.workflow.default.aai.v8.generic-query.uri=/aai/v8/search/generic-query -mso.workflow.default.aai.v9.generic-vnf.uri=/aai/v9/network/generic-vnfs/generic-vnf -mso.workflow.default.aai.v8.l3-network.uri=/aai/v8/network/l3-networks/l3-network -mso.workflow.default.aai.v8.network-policy.uri=/aai/v8/network/network-policies/network-policy -mso.workflow.default.aai.v8.nodes-query.uri=/aai/v8/search/nodes-query -mso.workflow.default.aai.v8.route-table-reference.uri=/aai/v8/network/route-table-references/route-table-reference -mso.workflow.default.aai.v8.tenant.uri=/aai/v8/cloud-infrastructure/cloud-regions/cloud-region/att-aic/AAIAIC25/tenants/tenant -mso.workflow.default.aai.v8.vce.uri=/aai/v8/network/vces/vce -mso.workflow.default.aai.v8.vpn-binding.uri=/aai/v8/network/vpn-bindings/vpn-binding - - -log.debug.CompleteMsoProcess=true -log.debug.CreateNetworkInstanceInfra=true -log.debug.CreateServiceInstanceInfra=true -log.debug.DeleteNetworkInstanceInfra=true -log.debug.FalloutHandler=true -log.debug.GenericGetService=true -log.debug.sdncAdapter=true -log.debug.UpdateNetworkInstanceInfra=true +# Default URN Mappings for unit tests + +mso.rollback=true + +canopi.auth=757A94191D685FD2092AC1490730A4FC +csi.aots.addincidentmanagement.endpoint=http://localhost:28090/AddIncidentManagementTicketRequest +csi.networkstatus.endpoint=http://localhost:28090/SendManagedNetworkStatusNotification +mso.csi.pwd=4EA237303511EFBBC37F17A351562131 +mso.csi.usrname=mso +mso.msoKey=07a7159d3bf51a0e53be7a8f89699be7 + +mso.adapters.completemsoprocess.endpoint=http://localhost:28090/CompleteMsoProcess + +mso.adapters.db.endpoint=http://localhost:28090/dbadapters/RequestsDbAdapter +mso.adapters.db.auth=757A94191D685FD2092AC1490730A4FC + +mso.adapters.network.endpoint=http://localhost:28090/networks/NetworkAdapter +mso.adapters.network.rest.endpoint=http://localhost:28090/networks/NetworkAdapter + +mso.adapters.po.auth=757A94191D685FD2092AC1490730A4FC +mso.adapters.po.password=3141634BF7E070AA289CF2892C986C0B +mso.po.timeout=PT60S + +aai.auth=757A94191D685FD2092AC1490730A4FC + +mso.adapters.sdnc.endpoint=http://localhost:28090/SDNCAdapter +mso.adapters.sdnc.rest.endpoint=http://localhost:28090/SDNCAdapter/v1/sdnc +mso.adapters.sdnc.timeout=PT60S +mso.sdnc.firewall.yang.model=http://com/openecomp/svc/mis/firewall-lite-gui +mso.sdnc.firewall.yang.model.version=2015-05-15 +mso.sdnc.password=3141634BF7E070AA289CF2892C986C0B +mso.sdnc.timeout.firewall.minutes=20 +mso.sdnc.timeout=PT10S +mso.sdnc.timeout.ucpe.async.hours=120 +mso.sdnc.timeout.ucpe.async.minutes=5 +mso.workflow.message.endpoint=http://localhost:28080/mso/WorkflowMesssage +mso.workflow.sdncadapter.callback=http://localhost:28080/mso/SDNCAdapterCallbackService + +mso.catalog.db.endpoint=http://localhost:28090/ + +mso.adapters.tenant.endpoint=http://localhost:28090/tenantAdapterMock +mso.adapters.vnf-async.endpoint=http://localhost:28090/vnfs/VnfAdapterAsync +mso.adapters.vnf.endpoint=http://localhost:28090/vnfs/VnfAdapter +mso.adapters.vnf.rest.endpoint=http://localhost:28090/vnfs/v1/vnfs +mso.workflow.vnfadapter.create.callback=http://localhost:28080/mso/vnfAdapterNotify +mso.workflow.vnfadapter.delete.callback=http://localhost:28080/mso/vnfAdapterNotify +mso.workflow.vnfadapter.query.callback=http://localhost:28080/mso/services/VNFAdapterQuerCallbackV1 +mso.workflow.vnfadapter.rollback.callback=http://localhost:28080/mso/vnfAdapterNotify +mso.workflow.createvce.delay.seconds=1 +mso.infra.customer.id=testCustIdInfra + +aai.endpoint=http://localhost:28090 + +# AAI version mappings + +# Example to override default version for a resource: +#mso.workflow.default.aai.vce.version=6 +#mso.workflow.default.aai.v6.vce.uri=/aai/v6/network/vces/vce + +mso.workflow.global.default.aai.version=8 +mso.workflow.default.aai.cloud-region.version=9 +mso.workflow.default.aai.generic-vnf.version=9 + +mso.workflow.default.aai.v9.cloud-region.uri=/aai/v9/cloud-infrastructure/cloud-regions/cloud-region/att-aic +mso.workflow.default.aai.v8.customer.uri=/aai/v8/business/customers/customer +mso.workflow.default.aai.v8.generic-query.uri=/aai/v8/search/generic-query +mso.workflow.default.aai.v9.generic-vnf.uri=/aai/v9/network/generic-vnfs/generic-vnf +mso.workflow.default.aai.v8.l3-network.uri=/aai/v8/network/l3-networks/l3-network +mso.workflow.default.aai.v8.network-policy.uri=/aai/v8/network/network-policies/network-policy +mso.workflow.default.aai.v8.nodes-query.uri=/aai/v8/search/nodes-query +mso.workflow.default.aai.v8.route-table-reference.uri=/aai/v8/network/route-table-references/route-table-reference +mso.workflow.default.aai.v8.tenant.uri=/aai/v8/cloud-infrastructure/cloud-regions/cloud-region/att-aic/AAIAIC25/tenants/tenant +mso.workflow.default.aai.v8.vce.uri=/aai/v8/network/vces/vce +mso.workflow.default.aai.v8.vpn-binding.uri=/aai/v8/network/vpn-bindings/vpn-binding +mso.workflow.notification.name=GenericNotificationService + +log.debug.CompleteMsoProcess=true +log.debug.CreateNetworkInstanceInfra=true +log.debug.CreateServiceInstanceInfra=true +log.debug.DeleteNetworkInstanceInfra=true +log.debug.FalloutHandler=true +log.debug.GenericGetService=true +log.debug.sdncAdapter=true +log.debug.UpdateNetworkInstanceInfra=true log.debug.VnfAdapterRestV1=true \ No newline at end of file diff --git a/bpmn/MSOMockServer/src/main/java/org/openecomp/mso/bpmn/mock/StubResponseAAI.java b/bpmn/MSOMockServer/src/main/java/org/openecomp/mso/bpmn/mock/StubResponseAAI.java index 8effc08445..07bde0accb 100644 --- a/bpmn/MSOMockServer/src/main/java/org/openecomp/mso/bpmn/mock/StubResponseAAI.java +++ b/bpmn/MSOMockServer/src/main/java/org/openecomp/mso/bpmn/mock/StubResponseAAI.java @@ -1,776 +1,787 @@ -/* - * © 2014 AT&T Intellectual Property. All rights reserved. Used under license from AT&T Intellectual Property. - */ -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - MSO - * ================================================================================ - * 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.openecomp.mso.bpmn.mock; - -import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; -import static com.github.tomakehurst.wiremock.client.WireMock.containing; -import static com.github.tomakehurst.wiremock.client.WireMock.delete; -import static com.github.tomakehurst.wiremock.client.WireMock.get; -import static com.github.tomakehurst.wiremock.client.WireMock.put; -import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; -import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; -import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching; - -/** - * Reusable Mock StubResponses for AAI Endpoints - * - */ -public class StubResponseAAI { - - public static void setupAllMocks() { - - } - - - /** - * Tunnel-XConnect Mock Stub Response - */ - public static void MockPutTunnelXConnect(String globalCustId, String subscriptionType, String serviceInstanceId, String allottedResourceId, String tunnelId){ - stubFor(put(urlMatching("/aai/v[0-9]+/business/customers/customer/" + globalCustId + "/service-subscriptions/service-subscription/" + subscriptionType + "/service-instances/service-instance/" + serviceInstanceId + "/allotted-resources/allotted-resource/" + allottedResourceId + "/tunnel-xconnects/tunnel-xconnect/" + tunnelId)) - .willReturn(aResponse() - .withStatus(200))); - } - - - /** - * Allotted Resource Mock StubResponses below - */ - public static void MockPutAllottedResource(String globalCustId, String subscriptionType, String serviceInstanceId, String allottedResourceId) { - stubFor(put(urlMatching("/aai/v[0-9]+/business/customers/customer/" + globalCustId + "/service-subscriptions/service-subscription/" + subscriptionType + "/service-instances/service-instance/" + serviceInstanceId + "/allotted-resources/allotted-resource/" + allottedResourceId)) - .willReturn(aResponse() - .withStatus(200))); - } - - public static void MockPutAllottedResource_500(String globalCustId, String subscriptionType, String serviceInstanceId, String allottedResourceId) { - stubFor(put(urlMatching("/aai/v[0-9]+/business/customers/customer/" + globalCustId + "/service-subscriptions/service-subscription/" + subscriptionType + "/service-instances/service-instance/" + serviceInstanceId + "/allotted-resources/allotted-resource/" + allottedResourceId)) - .willReturn(aResponse() - .withStatus(500))); - } - - - /** - * Service Instance Mock StubResponses below - */ - public static void MockGetServiceInstance(String globalCustId, String subscriptionType, String serviceInstanceId, String responseFile) { - stubFor(get(urlMatching("/aai/v[0-9]+/business/customers/customer/" + globalCustId + "/service-subscriptions/service-subscription/" + subscriptionType + "/service-instances/service-instance/" + serviceInstanceId)) - .willReturn(aResponse() - .withStatus(200) - .withHeader("Content-Type", "text/xml") - .withBodyFile(responseFile))); - } - - public static void MockGetServiceInstance_404(String customer, String serviceSubscription, String serviceInstanceId){ - stubFor(get(urlMatching("/aai/v[0-9]+/business/customers/customer/" + customer + "/service-subscriptions/service-subscription/" + serviceSubscription + "/service-instances/service-instance/" + serviceInstanceId)) - .willReturn(aResponse() - .withStatus(404))); - } - - public static void MockGetServiceInstance_500(String customer, String serviceSubscription, String serviceInstanceId){ - stubFor(get(urlMatching("/aai/v[0-9]+/business/customers/customer/" + customer + "/service-subscriptions/service-subscription/" + serviceSubscription + "/service-instances/service-instance/" + serviceInstanceId)) - .willReturn(aResponse() - .withStatus(500))); - } - - public static void MockGetServiceInstance_500(String customer, String serviceSubscription, String serviceInstanceId, String responseFile){ - stubFor(get(urlMatching("/aai/v[0-9]+/business/customers/customer/" + customer + "/service-subscriptions/service-subscription/" + serviceSubscription + "/service-instances/service-instance/" + serviceInstanceId)) - .willReturn(aResponse() - .withStatus(500) - .withHeader("Content-Type", "text/xml") - .withBodyFile(responseFile))); - } - - public static void MockNodeQueryServiceInstanceByName(String serviceInstanceName, String responseFile){ - stubFor(get(urlMatching("/aai/v[0-9]+/search/nodes-query[?]search-node-type=service-instance[&]filter=service-instance-name:EQUALS:" + serviceInstanceName)) - .willReturn(aResponse() - .withStatus(200) - .withHeader("Content-Type", "text/xml") - .withBodyFile(responseFile))); - } - - public static void MockNodeQueryServiceInstanceByName_404(String serviceInstanceName){ - stubFor(get(urlMatching("/aai/v[0-9]+/search/nodes-query[?]search-node-type=service-instance&filter=service-instance-name:EQUALS:" + serviceInstanceName)) - .willReturn(aResponse() - .withStatus(404))); - } - - public static void MockNodeQueryServiceInstanceByName_500(String serviceInstanceName){ - stubFor(get(urlMatching("/aai/v[0-9]+/search/nodes-query[?]search-node-type=service-instance&filter=service-instance-name:EQUALS:" + serviceInstanceName)) - .willReturn(aResponse() - .withStatus(500))); - } - - public static void MockNodeQueryServiceInstanceById(String serviceInstanceId, String responseFile){ - stubFor(get(urlMatching("/aai/v[0-9]+/search/nodes-query[?]search-node-type=service-instance[&]filter=service-instance-id:EQUALS:" + serviceInstanceId)) - .willReturn(aResponse() - .withStatus(200) - .withHeader("Content-Type", "text/xml") - .withBodyFile(responseFile))); - } - - public static void MockNodeQueryServiceInstanceById_404(String serviceInstanceId){ - stubFor(get(urlMatching("/aai/v[0-9]+/search/nodes-query[?]search-node-type=service-instance&filter=service-instance-id:EQUALS:" + serviceInstanceId)) - .willReturn(aResponse() - .withStatus(404))); - } - - public static void MockNodeQueryServiceInstanceById_500(String serviceInstanceId){ - stubFor(get(urlMatching("/aai/v[0-9]+/search/nodes-query[?]search-node-type=service-instance&filter=service-instance-id:EQUALS:" + serviceInstanceId)) - .willReturn(aResponse() - .withStatus(500))); - } - - public static void MockDeleteServiceInstance(String customer, String serviceSubscription, String serviceInstanceId, String resourceVersion){ - stubFor(delete(urlMatching("/aai/v[0-9]+/business/customers/customer/" + customer + "/service-subscriptions/service-subscription/" + serviceSubscription + "/service-instances/service-instance/" + serviceInstanceId + "[?]resource-version=" + resourceVersion)) - .willReturn(aResponse() - .withStatus(204))); - } - - public static void MockGetServiceInstance(String customer, String serviceSubscription, String serviceInstanceId, String resourceVersion, int statusCode){ - stubFor(get(urlMatching("/aai/v[0-9]+/business/customers/customer/" + customer + "/service-subscriptions/service-subscription/" + serviceSubscription + "/service-instances/service-instance/" + serviceInstanceId + "[?]resource-version=" + resourceVersion)) - .willReturn(aResponse() - .withStatus(statusCode))); - } - - public static void MockGetServiceInstance(String customer, String serviceSubscription, String resourceVersion, int statusCode){ - stubFor(get(urlMatching("/aai/v[0-9]+/business/customers/customer/" + customer + "/service-subscriptions/service-subscription/" + serviceSubscription + "[?]resource-version=" + resourceVersion)) - .willReturn(aResponse() - .withStatus(200) - .withHeader("Content-Type", "text/xml"))); - } - - public static void MockDeleteServiceInstance(String customer, String serviceSubscription, String resourceVersion, int statusCode){ - stubFor(delete(urlMatching("/aai/v[0-9]+/business/customers/customer/" + customer + "/service-subscriptions/service-subscription/" + serviceSubscription + "[?]resource-version=" +1234)) - .willReturn(aResponse() - .withStatus(statusCode))); - } - - public static void MockDeleteServiceInstance_404(String customer, String serviceSubscription, String serviceInstanceId, String resourceVersion){ - stubFor(delete(urlMatching("/aai/v[0-9]+/business/customers/customer/" + customer + "/service-subscriptions/service-subscription/" + serviceSubscription + "/service-instances/service-instance/" + serviceInstanceId + "[?]resource-version=" + resourceVersion)) - .willReturn(aResponse() - .withStatus(404))); - } - - public static void MockDeleteServiceInstance_500(String customer, String serviceSubscription, String serviceInstanceId, String resourceVersion){ - stubFor(delete(urlMatching("/aai/v[0-9]+/business/customers/customer/" + customer + "/service-subscriptions/service-subscription/" + serviceSubscription + "/service-instances/service-instance/" + serviceInstanceId + "[?]resource-version=" + resourceVersion)) - .willReturn(aResponse() - .withStatus(500))); - } - - public static void MockPutServiceInstance(String globalCustId, String subscriptionType, String serviceInstanceId, String responseFile) { - stubFor(put(urlMatching("/aai/v[0-9]+/business/customers/customer/" + globalCustId + "/service-subscriptions/service-subscription/" + subscriptionType + "/service-instances/service-instance/" + serviceInstanceId)) - .willReturn(aResponse() - .withStatus(200) - .withHeader("Content-Type", "text/xml") - .withBodyFile(responseFile))); - } - - public static void MockPutServiceInstance_500(String globalCustId, String subscriptionType, String serviceInstanceId) { - stubFor(put(urlMatching("/aai/v[0-9]+/business/customers/customer/" + globalCustId + "/service-subscriptions/service-subscription/" + subscriptionType + "/service-instances/service-instance/" + serviceInstanceId)) - .willReturn(aResponse() - .withStatus(500))); - } - - - /** - * Service-Subscription Mock StubResponses below - */ - public static void MockGetServiceSubscription(String globalCustId, String subscriptionType, String responseFile) { - stubFor(get(urlMatching("/aai/v[0-9]+/business/customers/customer/" + globalCustId + "/service-subscriptions/service-subscription/" + subscriptionType)) - .willReturn(aResponse() - .withStatus(200) - .withHeader("Content-Type", "text/xml") - .withBodyFile(responseFile))); - } - - public static void MockDeleteServiceSubscription(String globalCustId, String subscriptionType, int statusCode) { - stubFor(delete(urlMatching("/aai/v[0-9]+/business/customers/customer/" + globalCustId + "/service-subscriptions/service-subscription/" + subscriptionType)) - .willReturn(aResponse() - .withStatus(statusCode))); - } - - public static void MockDeleteServiceInstanceId(String globalCustId, String subscriptionType, String serviceInstanceId) { - stubFor(delete(urlMatching("/aai/v[0-9]+/business/customers/customer/" + globalCustId + "/service-subscriptions/service-subscription/" + subscriptionType + "/service-instances/service-instance/" + serviceInstanceId)) - .willReturn(aResponse() - .withStatus(200))); - } - - public static void MockPutServiceSubscription(String globalCustId, String subscriptionType) { - stubFor(put(urlMatching("/aai/v[0-9]+/business/customers/customer/" + globalCustId + "/service-subscriptions/service-subscription/" + subscriptionType)) - .willReturn(aResponse() - .withStatus(200))); - } - - public static void MockGetServiceSubscription(String globalCustId, String subscriptionType, int statusCode) { - stubFor(get(urlMatching("/aai/v[0-9]+/business/customers/customer/" + globalCustId + "/service-subscriptions/service-subscription/" + subscriptionType)) - .willReturn(aResponse() - .withStatus(statusCode))); - } - - /** - * Customer Mock StubResponses below - */ - public static void MockGetCustomer(String globalCustId, String responseFile) { - stubFor(get(urlMatching("/aai/v[0-9]+/business/customers/customer/" + globalCustId)) - .willReturn(aResponse() - .withStatus(200) - .withHeader("Content-Type", "text/xml") - .withBodyFile(responseFile))); - } - - public static void MockDeleteCustomer(String globalCustId) { - stubFor(delete(urlMatching("/aai/v[0-9]+/business/customers/customer/" + globalCustId)) - .willReturn(aResponse() - .withStatus(200))); - } - - public static void MockPutCustomer(String globalCustId) { - stubFor(put(urlMatching("/aai/v[0-9]+/business/customers/customer/" + globalCustId)) - .willReturn(aResponse() - .withStatus(200))); - } - - public static void MockPutCustomer_500(String globalCustId) { - stubFor(put(urlMatching("/aai/v[0-9]+/business/customers/customer/" + globalCustId)) - .willReturn(aResponse() - .withStatus(500))); - } - - - /** - * Generic-Vnf Mock StubResponses below - */ - public static void MockGetGenericVnfById(String vnfId, String responseFile, int statusCode){ - stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf" + vnfId)) - .willReturn(aResponse() - .withStatus(statusCode) - .withHeader("Content-Type", "text/xml") - .withBodyFile(responseFile))); - } - - public static void MockGetGenericVnfByIdWithPriority(String vnfId, int statusCode, String responseFile) { - stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf" + vnfId)) - .atPriority(1) - .willReturn(aResponse() - .withStatus(statusCode) - .withHeader("Content-Type", "text/xml") - .withBodyFile(responseFile))); - } - - public static void MockGetGenericVnfByIdWithPriority(String vnfId, String vfModuleId, int statusCode, String responseFile, int priority) { - stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/" + vnfId + "/vf-modules/vf-module/" + vfModuleId)) - .atPriority(priority) - .willReturn(aResponse() - .withStatus(statusCode) - .withHeader("Content-Type", "text/xml") - .withBodyFile(responseFile))); - } - - public static void MockGetGenericVnfByIdWithDepth(String vnfId, int depth, String responseFile){ - stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/" + vnfId + "[?]depth=" + depth)) - .willReturn(aResponse() - .withStatus(200) - .withHeader("Content-Type", "text/xml") - .withBodyFile(responseFile))); - } - - public static void MockGetGenericVnfById_404(String vnfId){ - stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/" + vnfId)) - .willReturn(aResponse() - .withStatus(404))); - } - - public static void MockGetGenericVnfById_500(String vnfId){ - stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/" + vnfId)) - .willReturn(aResponse() - .withStatus(500))); - } - - public static void MockGetGenericVnfByName(String vnfName, String responseFile){ - stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf[?]vnf-name=" + vnfName)) - .willReturn(aResponse() - .withStatus(200) - .withHeader("Content-Type", "text/xml") - .withBodyFile(responseFile))); - } - - public static void MockGetGenericVnfByNameWithDepth(String vnfName, int depth, String responseFile){ - stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf[?]vnf-name=" + vnfName + "[&]depth=" + depth)) - .willReturn(aResponse() - .withStatus(200) - .withHeader("Content-Type", "text/xml") - .withBodyFile(responseFile))); - } - - public static void MockGetGenericVnfByName_404(String vnfName){ - stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf[?]vnf-name=" + vnfName)) - .willReturn(aResponse() - .withStatus(404))); - } - - public static void MockDeleteGenericVnf(String vnfId, String resourceVersion){ - stubFor(delete(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/" + vnfId + "[?]resource-version=" + resourceVersion)) - .willReturn(aResponse() - .withStatus(204))); - } - - public static void MockDeleteGenericVnf(String vnfId, String resourceVersion, int statusCode){ - stubFor(delete(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/" + vnfId + "[?]resource-version=" + resourceVersion)) - .willReturn(aResponse() - .withStatus(statusCode))); - } - - public static void MockDeleteGenericVnf_500(String vnfId, String resourceVersion){ - stubFor(delete(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/" + vnfId + "[?]resource-version=" + resourceVersion)) - .willReturn(aResponse() - .withStatus(500))); - } - - public static void MockPutGenericVnf(String vnfId){ - stubFor(put(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/" + vnfId)) - .willReturn(aResponse() - .withStatus(200))); - } - - public static void MockPutGenericVnf(String vnfId, String requestBodyContaining, int statusCode) { - stubFor(put(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf" + vnfId)) - .withRequestBody(containing(requestBodyContaining)) - .willReturn(aResponse() - .withStatus(statusCode))); - } - - public static void MockPutGenericVnf(String vnfId, int statusCode) { - stubFor(put(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf" + vnfId)) - .willReturn(aResponse() - .withStatus(statusCode))); - } - - public static void MockPutGenericVnf_Bad(String vnfId, int statusCode){ - stubFor(put(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/" + vnfId)) - .willReturn(aResponse() - .withStatus(statusCode))); - } - - - /** - * Vce Mock StubResponses below - */ - public static void MockGetVceById(String vnfId, String responseFile){ - stubFor(get(urlMatching("/aai/v[0-9]+/network/vces/vce/" + vnfId)) - .willReturn(aResponse() - .withStatus(200) - .withHeader("Content-Type", "text/xml") - .withBodyFile(responseFile))); - } - - public static void MockGetVceByName(String vnfName, String responseFile){ - stubFor(get(urlMatching("/aai/v[0-9]+/network/vces/vce[?]vnf-name=" + vnfName)) - .willReturn(aResponse() - .withStatus(200) - .withHeader("Content-Type", "text/xml") - .withBodyFile(responseFile))); - } - - public static void MockDeleteVce(String vnfId, String resourceVersion, int statusCode){ - stubFor(delete(urlMatching("/aai/v[0-9]+/network/vces/vce/" + vnfId + "[?]resource-version=" + resourceVersion)) - .willReturn(aResponse() - .withStatus(statusCode))); - } - - public static void MockPutVce(String vnfId){ - stubFor(put(urlMatching("/aai/v[0-9]+/network/vces/vce/" + vnfId)) - .willReturn(aResponse() - .withStatus(200))); - } - - public static void MockGetGenericVceByNameWithDepth(String vnfName, int depth, String responseFile){ - stubFor(get(urlMatching("/aai/v[0-9]+/network/vces/vce[?]vnf-name=" + vnfName + "[&]depth=" + depth)) - .willReturn(aResponse() - .withStatus(200) - .withHeader("Content-Type", "text/xml") - .withBodyFile(responseFile))); - } - - public static void MockGetVceGenericQuery(String serviceInstanceName, int depth, int statusCode, String responseFile){ - stubFor(get(urlMatching("/aai/v[0-9]+/search/generic-query[?]key=service-instance.service-instance-name:" + serviceInstanceName + "[&]start-node-type=service-instance[&]include=vce[&]depth=" + depth)) - .willReturn(aResponse() - .withStatus(statusCode) - .withHeader("Content-Type", "text/xml") - .withBodyFile(responseFile))); - } - - /** - * Tenant Mock StubResponses below - */ - public static void MockGetTenantGenericQuery(String customer, String serviceType, String responseFile) { - stubFor(get(urlMatching("/aai/v[0-9]+/search/generic-query[?]key=customer.global-customer-id:" + customer + "&key=service-subscription.service-type:" + serviceType + "&start-node-type=service-subscription&include=tenant&include=service-subscription&depth=1")) - .willReturn(aResponse() - .withStatus(200) - .withHeader("Content-Type", "text/xml") - .withBodyFile(responseFile))); - } - - public static void MockGetTenant(String tenantId, String responseFile) { - stubFor(get(urlEqualTo("/aai/v2/cloud-infrastructure/tenants/tenant/" + tenantId)) - .willReturn(aResponse() - .withStatus(200) - .withHeader("Content-Type", "text/xml") - .withBodyFile(responseFile))); - } - - /** - * Network Mock StubResponses below - */ - public static void MockGetNetwork(String networkId, String responseFile, int statusCode) { - stubFor(get(urlMatching("/aai/v[0-9]+/network/l3-networks/l3-network/" + networkId)) - .willReturn(aResponse() - .withStatus(statusCode) - .withHeader("Content-Type", "text/xml") - .withBodyFile(responseFile))); - } - - public static void MockPutNetwork(String networkId, int statusCode, String responseFile) { - stubFor(put(urlMatching("/aai/v[0-9]+/network/l3-networks/l3-network/" + networkId)) - .willReturn(aResponse() - .withStatus(statusCode) - .withHeader("Content-Type", "text/xml") - .withBodyFile(responseFile))); - } - - public static void MockPutNetwork(String networkPolicyId, String responseFile, int statusCode) { - stubFor(put(urlMatching("/aai/v[0-9]+/network/network-policies/network-policy/" + networkPolicyId)) - .willReturn(aResponse() - .withStatus(statusCode) - .withHeader("Content-Type", "text/xml") - .withBodyFile(responseFile))); - } - - public static void MockGetNetworkName(String networkPolicyName, String responseFile, int statusCode) { - stubFor(get(urlMatching("/aai/v[0-9]+/network/l3-networks/l3-network[?]network-name=" + networkPolicyName)) - .willReturn(aResponse() - .withStatus(statusCode) - .withHeader("Content-Type", "text/xml") - .withBodyFile(responseFile))); - } - - public static void MockGetNetworkVpnBinding(String networkBindingId, String responseFile, int statusCode) { - stubFor(get(urlMatching("/aai/v[0-9]+/network/vpn-bindings/vpn-binding/" + networkBindingId)) - .willReturn(aResponse() - .withStatus(statusCode) - .withHeader("Content-Type", "text/xml") - .withBodyFile(responseFile))); - } - - public static void MockGetNetworkPolicy(String networkPolicy, String responseFile, int statusCode) { - stubFor(get(urlMatching("/aai/v[0-9]+/network/network-policies/network-policy/" + networkPolicy)) - .willReturn(aResponse() - .withStatus(statusCode) - .withHeader("Content-Type", "text/xml") - .withBodyFile(responseFile))); - } - - public static void MockGetNetworkPolicyfqdn(String networkPolicy, String responseFile, int statusCode) { - stubFor(get(urlMatching("/aai/v[0-9]+/network/network-policies/network-policy[?]network-policy-fqdn=" + networkPolicy)) - .willReturn(aResponse() - .withStatus(statusCode) - .withHeader("Content-Type", "text/xml") - .withBodyFile(responseFile))); - } - - public static void MockGetNetworkRouteTable(String networkRouteId, String responseFile, int statusCode) { - stubFor(get(urlMatching("/aai/v[0-9]+/network/route-table-references/route-table-reference/" + networkRouteId)) - .willReturn(aResponse() - .withStatus(statusCode) - .withHeader("Content-Type", "text/xml") - .withBodyFile(responseFile))); - } - - - /** - * Cloud infrastructure below - */ - - public static void MockGetCloudRegion(String cloudRegionId, int statusCode, String responseFile) { - stubFor(get(urlMatching("/aai/v[0-9]+/cloud-infrastructure/cloud-regions/cloud-region/att-aic/" + cloudRegionId)) - .willReturn(aResponse() - .withStatus(statusCode) - .withHeader("Content-Type", "text/xml") - .withBodyFile(responseFile))); - } - - /** - * Volume Group StubResponse below - */ - public static void MockGetVolumeGroupById(String cloudRegionId, String volumeGroupId, String responseFile) { - stubFor(get(urlMatching("/aai/v[0-9]+/cloud-infrastructure/cloud-regions/cloud-region/att-aic/" + cloudRegionId + "/volume-groups/volume-group/" + volumeGroupId)) - .willReturn(aResponse() - .withStatus(200) - .withHeader("Content-Type", "text/xml") - .withBodyFile(responseFile))); - } - - public static void MockPutVolumeGroupById(String cloudRegionId, String volumeGroupId, String responseFile, int statusCode) { - stubFor(put(urlMatching("/aai/v[0-9]+/cloud-infrastructure/cloud-regions/cloud-region/att-aic/" + cloudRegionId + "/volume-groups/volume-group/" + volumeGroupId)) - .willReturn(aResponse() - .withStatus(statusCode) - .withHeader("Content-Type", "text/xml") - .withBodyFile(responseFile))); - } - - public static void MockGetVolumeGroupByName(String cloudRegionId, String volumeGroupName, String responseFile, int statusCode) { - stubFor(get(urlMatching("/aai/v[0-9]+/cloud-infrastructure/cloud-regions/cloud-region/att-aic/" + cloudRegionId + "/volume-groups[?]volume-group-name=" + volumeGroupName)) - .willReturn(aResponse() - .withStatus(statusCode) - .withHeader("Content-Type", "text/xml") - .withBodyFile(responseFile))); - } - - public static void MockDeleteVolumeGroupById(String cloudRegionId, String volumeGroupId, String resourceVersion, int statusCode) { - stubFor(delete(urlMatching("/aai/v[0-9]+/cloud-infrastructure/cloud-regions/cloud-region/att-aic/" + cloudRegionId + "/volume-groups/volume-group/" + volumeGroupId + "[?]resource-version=" + resourceVersion)) - .willReturn(aResponse() - .withStatus(statusCode))); - } - - /** - * VF-Module StubResponse below - * @param statusCode TODO - */ - public static void MockGetVfModuleId(String vnfId, String vfModuleId, String responseFile, int statusCode) { - stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/" + vnfId + "/vf-modules/vf-module/" + vfModuleId)) - .willReturn(aResponse() - .withStatus(statusCode) - .withHeader("Content-Type", "text/xml") - .withBodyFile(responseFile))); - } - - public static void MockGetVfModuleIdNoResponse(String vnfId, String requestContaining, String vfModuleId) { - stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/" + vnfId + "/vf-modules/vf-module/" + vfModuleId)) - .withRequestBody(containing(requestContaining)) - .willReturn(aResponse() - .withStatus(200) - .withHeader("Content-Type", "text/xml"))); - } - - public static void MockPutVfModuleIdNoResponse(String vnfId, String requestContaining, String vfModuleId) { - stubFor(put(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/" + vnfId +"/vf-modules/vf-module/" +vfModuleId)) - .withRequestBody(containing(requestContaining)) - .willReturn(aResponse() - .withStatus(200))); - } - - public static void MockPutVfModuleId(String vnfId, String vfModuleId) { - stubFor(put(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/" + vnfId + "/vf-modules/vf-module/" + vfModuleId)) - .willReturn(aResponse() - .withStatus(200))); - } - - public static void MockPutVfModuleId(String vnfId, String vfModuleId, int returnCode) { - stubFor(put(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/" + vnfId + "/vf-modules/vf-module/" + vfModuleId)) - .willReturn(aResponse() - .withStatus(returnCode))); - } - - public static void MockDeleteVfModuleId(String vnfId, String vfModuleId, String resourceVersion, int returnCode) { - stubFor(delete(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/" + vnfId + "/vf-modules/vf-module/" + vfModuleId + "/[?]resource-version=" + resourceVersion)) - .willReturn(aResponse() - .withStatus(returnCode))); - } - - //// Deprecated Stubs below - to be deleted once unit test that reference them are refactored to use common ones above //// - @Deprecated - public static void MockGetVceById(){ - stubFor(get(urlMatching("/aai/v[0-9]+/network/vces/vce/testVnfId123?depth=1")) - .willReturn(aResponse() - .withStatus(200) - .withHeader("Content-Type", "text/xml") - .withBodyFile("GenericFlows/getVceResponse.xml"))); - } - @Deprecated - public static void MockGetVceByName(){ - stubFor(get(urlMatching("/aai/v[0-9]+/network/vces/vce[?]vnf-name=testVnfName123")) - .willReturn(aResponse() - .withStatus(200) - .withHeader("Content-Type", "text/xml") - .withBodyFile("GenericFlows/getVceByNameResponse.xml"))); - } - @Deprecated - public static void MockPutVce(){ - stubFor(put(urlMatching("/aai/v[0-9]+/network/vces/vce/testVnfId123")) - .willReturn(aResponse() - .withStatus(200))); - } - @Deprecated - public static void MockDeleteVce(){ - stubFor(delete(urlMatching("/aai/v[0-9]+/network/vces/vce/testVnfId123[?]resource-version=testReVer123")) - .willReturn(aResponse() - .withStatus(204))); - } - @Deprecated - public static void MockDeleteVce_404(){ - stubFor(delete(urlMatching("/aai/v[0-9]+/network/vces/vce/testVnfId123[?]resource-version=testReVer123")) - .willReturn(aResponse() - .withStatus(404))); - } - - @Deprecated - public static void MockDeleteServiceSubscription(){ - stubFor(delete(urlMatching("/aai/v[0-9]+/business/customers/customer/1604-MVM-26/service-subscriptions/service-subscription/SDN-ETHERNET-INTERNET[?]resource-version=1234")) - .willReturn(aResponse() - .withStatus(204))); - } - @Deprecated - public static void MockGetServiceSubscription(){ - stubFor(get(urlMatching("/aai/v[0-9]+/business/customers/customer/1604-MVM-26/service-subscriptions/service-subscription/SDN-ETHERNET-INTERNET")) - .willReturn(aResponse() - .withStatus(200) - .withHeader("Content-Type", "text/xml") - .withBodyFile("GenericFlows/getServiceSubscription.xml"))); - } - @Deprecated - public static void MockGetServiceSubscription_200Empty(){ - stubFor(get(urlMatching("/aai/v[0-9]+/business/customers/customer/1604-MVM-26/service-subscriptions/service-subscription/SDN-ETHERNET-INTERNET[?]resource-version=1234")) - .willReturn(aResponse() - .withStatus(200) - .withHeader("Content-Type", "text/xml") - .withBody(" "))); - } - @Deprecated - public static void MockGetServiceSubscription_404() { - stubFor(get(urlMatching("/aai/v[0-9]+/business/customers/customer/1604-MVM-26/service-subscriptions/service-subscription/SDN-ETHERNET-INTERNET")) - .willReturn(aResponse() - .withStatus(404))); - } - @Deprecated - public static void MockGENPSIPutServiceInstance(){ - stubFor(put(urlMatching("/aai/v[0-9]+/business/customers/customer/1604-MVM-26/service-subscriptions/service-subscription/SDN-ETHERNET-INTERNET/service-instances/service-instance/MIS%252F1604%252F0026%252FSW_INTERNET")) - .willReturn(aResponse() - .withStatus(200) - .withHeader("Content-Type", "text/xml") - .withBodyFile("GenericPutServiceInstance/GenericPutServiceInstance_PutServiceInstance_AAIResponse_Success.xml"))); - } - - @Deprecated - public static void MockGENPSIPutServiceSubscription(){ - stubFor(put(urlMatching("/aai/v[0-9]+/business/customers/customer/1604-MVM-26/service-subscriptions/service-subscription/SDN-ETHERNET-INTERNET")) - .willReturn(aResponse() - .withStatus(200) - .withHeader("Content-Type", "text/xml") - .withBodyFile("GenericPutServiceInstance/GenericPutServiceInstance_PutServiceInstance_AAIResponse_Success.xml"))); - } - @Deprecated - public static void MockGENPSIPutServiceInstance_get500(){ - stubFor(put(urlMatching("/aai/v[0-9]+/business/customers/customer/1604-MVM-26/service-subscriptions/service-subscription/SDN-ETHERNET-INTERNET/service-instances/service-instance/MIS%252F1604%252F0026%252FSW_INTERNET")) - .willReturn(aResponse() - .withStatus(500) - .withHeader("Content-Type", "text/xml") - .withBodyFile("GenericPutServiceInstance/aaiFault.xml"))); - } - - @Deprecated - public static void MockGetGenericVnfById(){ - stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/testVnfId123")) - .willReturn(aResponse() - .withStatus(200) - .withHeader("Content-Type", "text/xml") - .withBodyFile("GenericFlows/getGenericVnfByNameResponse.xml"))); - } - @Deprecated - public static void MockGetGenericVnfById_404(){ - stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/testVnfId123")) - .willReturn(aResponse() - .withStatus(404))); - } - @Deprecated - public static void MockGetGenericVnfByName(){ - stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf[?]vnf-name=testVnfName123")) - .willReturn(aResponse() - .withStatus(200) - .withHeader("Content-Type", "text/xml") - .withBodyFile("GenericFlows/getGenericVnfResponse.xml"))); - } - @Deprecated - public static void MockGetGenericVnfByName_hasRelationships(){ - stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf[?]vnf-name=testVnfName123")) - .willReturn(aResponse() - .withStatus(200) - .withHeader("Content-Type", "text/xml") - .withBodyFile("GenericFlows/getGenericVnfResponse_hasRelationships.xml"))); - } - @Deprecated - public static void MockGetGenericVnfById_hasRelationships(){ - stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/testVnfId123")) - .willReturn(aResponse() - .withStatus(200) - .withHeader("Content-Type", "text/xml") - .withBodyFile("GenericFlows/getGenericVnfResponse_hasRelationships.xml"))); - } - @Deprecated - public static void MockGetGenericVnfById_500(){ - stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/testVnfId123")) - .willReturn(aResponse() - .withStatus(500))); - } - @Deprecated - public static void MockGetGenericVnfByName_404(){ - stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf[?]vnf-name=testVnfName123")) - .willReturn(aResponse() - .withStatus(404))); - } - @Deprecated - public static void MockPutGenericVnf(){ - stubFor(put(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/testVnfId123")) - .willReturn(aResponse() - .withStatus(200))); - } - @Deprecated - public static void MockPutGenericVnf_400(){ - stubFor(put(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/testVnfId123")) - .willReturn(aResponse() - .withStatus(400))); - } - @Deprecated - public static void MockDeleteGenericVnf(){ - stubFor(delete(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/testVnfId123[?]resource-version=testReVer123")) - .willReturn(aResponse() - .withStatus(204))); - } - @Deprecated - public static void MockDeleteGenericVnf_404(){ - stubFor(delete(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/testVnfId123[?]resource-version=testReVer123")) - .willReturn(aResponse() - .withStatus(404))); - } - @Deprecated - public static void MockDeleteGenericVnf_500(){ - stubFor(delete(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/testVnfId123[?]resource-version=testReVer123")) - .willReturn(aResponse() - .withStatus(500))); - } - @Deprecated - public static void MockDeleteGenericVnf_412(){ - stubFor(delete(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/testVnfId123[[?]]resource-version=testReVer123")) - .willReturn(aResponse() - .withStatus(412))); - } - -} +/* + * © 2014 AT&T Intellectual Property. All rights reserved. Used under license from AT&T Intellectual Property. + */ +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.mso.bpmn.mock; + +import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; +import static com.github.tomakehurst.wiremock.client.WireMock.containing; +import static com.github.tomakehurst.wiremock.client.WireMock.delete; +import static com.github.tomakehurst.wiremock.client.WireMock.get; +import static com.github.tomakehurst.wiremock.client.WireMock.patch; +import static com.github.tomakehurst.wiremock.client.WireMock.put; +import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; +import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; +import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching; + +/** + * Reusable Mock StubResponses for AAI Endpoints + * + */ +public class StubResponseAAI { + + public static void setupAllMocks() { + + } + + + /** + * Tunnel-XConnect Mock Stub Response + */ + public static void MockPutTunnelXConnect(String globalCustId, String subscriptionType, String serviceInstanceId, String allottedResourceId, String tunnelId){ + stubFor(put(urlMatching("/aai/v[0-9]+/business/customers/customer/" + globalCustId + "/service-subscriptions/service-subscription/" + subscriptionType + "/service-instances/service-instance/" + serviceInstanceId + "/allotted-resources/allotted-resource/" + allottedResourceId + "/tunnel-xconnects/tunnel-xconnect/" + tunnelId)) + .willReturn(aResponse() + .withStatus(200))); + } + + + /** + * Allotted Resource Mock StubResponses below + */ + public static void MockPutAllottedResource(String globalCustId, String subscriptionType, String serviceInstanceId, String allottedResourceId) { + stubFor(put(urlMatching("/aai/v[0-9]+/business/customers/customer/" + globalCustId + "/service-subscriptions/service-subscription/" + subscriptionType + "/service-instances/service-instance/" + serviceInstanceId + "/allotted-resources/allotted-resource/" + allottedResourceId)) + .willReturn(aResponse() + .withStatus(200))); + } + + public static void MockPutAllottedResource_500(String globalCustId, String subscriptionType, String serviceInstanceId, String allottedResourceId) { + stubFor(put(urlMatching("/aai/v[0-9]+/business/customers/customer/" + globalCustId + "/service-subscriptions/service-subscription/" + subscriptionType + "/service-instances/service-instance/" + serviceInstanceId + "/allotted-resources/allotted-resource/" + allottedResourceId)) + .willReturn(aResponse() + .withStatus(500))); + } + + + /** + * Service Instance Mock StubResponses below + */ + public static void MockGetServiceInstance(String globalCustId, String subscriptionType, String serviceInstanceId, String responseFile) { + stubFor(get(urlMatching("/aai/v[0-9]+/business/customers/customer/" + globalCustId + "/service-subscriptions/service-subscription/" + subscriptionType + "/service-instances/service-instance/" + serviceInstanceId)) + .willReturn(aResponse() + .withStatus(200) + .withHeader("Content-Type", "text/xml") + .withBodyFile(responseFile))); + } + + public static void MockGetServiceInstance_404(String customer, String serviceSubscription, String serviceInstanceId){ + stubFor(get(urlMatching("/aai/v[0-9]+/business/customers/customer/" + customer + "/service-subscriptions/service-subscription/" + serviceSubscription + "/service-instances/service-instance/" + serviceInstanceId)) + .willReturn(aResponse() + .withStatus(404))); + } + + public static void MockGetServiceInstance_500(String customer, String serviceSubscription, String serviceInstanceId){ + stubFor(get(urlMatching("/aai/v[0-9]+/business/customers/customer/" + customer + "/service-subscriptions/service-subscription/" + serviceSubscription + "/service-instances/service-instance/" + serviceInstanceId)) + .willReturn(aResponse() + .withStatus(500))); + } + + public static void MockGetServiceInstance_500(String customer, String serviceSubscription, String serviceInstanceId, String responseFile){ + stubFor(get(urlMatching("/aai/v[0-9]+/business/customers/customer/" + customer + "/service-subscriptions/service-subscription/" + serviceSubscription + "/service-instances/service-instance/" + serviceInstanceId)) + .willReturn(aResponse() + .withStatus(500) + .withHeader("Content-Type", "text/xml") + .withBodyFile(responseFile))); + } + + public static void MockNodeQueryServiceInstanceByName(String serviceInstanceName, String responseFile){ + stubFor(get(urlMatching("/aai/v[0-9]+/search/nodes-query[?]search-node-type=service-instance[&]filter=service-instance-name:EQUALS:" + serviceInstanceName)) + .willReturn(aResponse() + .withStatus(200) + .withHeader("Content-Type", "text/xml") + .withBodyFile(responseFile))); + } + + public static void MockNodeQueryServiceInstanceByName_404(String serviceInstanceName){ + stubFor(get(urlMatching("/aai/v[0-9]+/search/nodes-query[?]search-node-type=service-instance&filter=service-instance-name:EQUALS:" + serviceInstanceName)) + .willReturn(aResponse() + .withStatus(404))); + } + + public static void MockNodeQueryServiceInstanceByName_500(String serviceInstanceName){ + stubFor(get(urlMatching("/aai/v[0-9]+/search/nodes-query[?]search-node-type=service-instance&filter=service-instance-name:EQUALS:" + serviceInstanceName)) + .willReturn(aResponse() + .withStatus(500))); + } + + public static void MockNodeQueryServiceInstanceById(String serviceInstanceId, String responseFile){ + stubFor(get(urlMatching("/aai/v[0-9]+/search/nodes-query[?]search-node-type=service-instance[&]filter=service-instance-id:EQUALS:" + serviceInstanceId)) + .willReturn(aResponse() + .withStatus(200) + .withHeader("Content-Type", "text/xml") + .withBodyFile(responseFile))); + } + + public static void MockNodeQueryServiceInstanceById_404(String serviceInstanceId){ + stubFor(get(urlMatching("/aai/v[0-9]+/search/nodes-query[?]search-node-type=service-instance&filter=service-instance-id:EQUALS:" + serviceInstanceId)) + .willReturn(aResponse() + .withStatus(404))); + } + + public static void MockNodeQueryServiceInstanceById_500(String serviceInstanceId){ + stubFor(get(urlMatching("/aai/v[0-9]+/search/nodes-query[?]search-node-type=service-instance&filter=service-instance-id:EQUALS:" + serviceInstanceId)) + .willReturn(aResponse() + .withStatus(500))); + } + + public static void MockDeleteServiceInstance(String customer, String serviceSubscription, String serviceInstanceId, String resourceVersion){ + stubFor(delete(urlMatching("/aai/v[0-9]+/business/customers/customer/" + customer + "/service-subscriptions/service-subscription/" + serviceSubscription + "/service-instances/service-instance/" + serviceInstanceId + "[?]resource-version=" + resourceVersion)) + .willReturn(aResponse() + .withStatus(204))); + } + + public static void MockGetServiceInstance(String customer, String serviceSubscription, String serviceInstanceId, String resourceVersion, int statusCode){ + stubFor(get(urlMatching("/aai/v[0-9]+/business/customers/customer/" + customer + "/service-subscriptions/service-subscription/" + serviceSubscription + "/service-instances/service-instance/" + serviceInstanceId + "[?]resource-version=" + resourceVersion)) + .willReturn(aResponse() + .withStatus(statusCode))); + } + + public static void MockGetServiceInstance(String customer, String serviceSubscription, String resourceVersion, int statusCode){ + stubFor(get(urlMatching("/aai/v[0-9]+/business/customers/customer/" + customer + "/service-subscriptions/service-subscription/" + serviceSubscription + "[?]resource-version=" + resourceVersion)) + .willReturn(aResponse() + .withStatus(200) + .withHeader("Content-Type", "text/xml"))); + } + + public static void MockDeleteServiceInstance(String customer, String serviceSubscription, String resourceVersion, int statusCode){ + stubFor(delete(urlMatching("/aai/v[0-9]+/business/customers/customer/" + customer + "/service-subscriptions/service-subscription/" + serviceSubscription + "[?]resource-version=" +1234)) + .willReturn(aResponse() + .withStatus(statusCode))); + } + + public static void MockDeleteServiceInstance_404(String customer, String serviceSubscription, String serviceInstanceId, String resourceVersion){ + stubFor(delete(urlMatching("/aai/v[0-9]+/business/customers/customer/" + customer + "/service-subscriptions/service-subscription/" + serviceSubscription + "/service-instances/service-instance/" + serviceInstanceId + "[?]resource-version=" + resourceVersion)) + .willReturn(aResponse() + .withStatus(404))); + } + + public static void MockDeleteServiceInstance_500(String customer, String serviceSubscription, String serviceInstanceId, String resourceVersion){ + stubFor(delete(urlMatching("/aai/v[0-9]+/business/customers/customer/" + customer + "/service-subscriptions/service-subscription/" + serviceSubscription + "/service-instances/service-instance/" + serviceInstanceId + "[?]resource-version=" + resourceVersion)) + .willReturn(aResponse() + .withStatus(500))); + } + + public static void MockPutServiceInstance(String globalCustId, String subscriptionType, String serviceInstanceId, String responseFile) { + stubFor(put(urlMatching("/aai/v[0-9]+/business/customers/customer/" + globalCustId + "/service-subscriptions/service-subscription/" + subscriptionType + "/service-instances/service-instance/" + serviceInstanceId)) + .willReturn(aResponse() + .withStatus(200) + .withHeader("Content-Type", "text/xml") + .withBodyFile(responseFile))); + } + + public static void MockPutServiceInstance_500(String globalCustId, String subscriptionType, String serviceInstanceId) { + stubFor(put(urlMatching("/aai/v[0-9]+/business/customers/customer/" + globalCustId + "/service-subscriptions/service-subscription/" + subscriptionType + "/service-instances/service-instance/" + serviceInstanceId)) + .willReturn(aResponse() + .withStatus(500))); + } + + + /** + * Service-Subscription Mock StubResponses below + */ + public static void MockGetServiceSubscription(String globalCustId, String subscriptionType, String responseFile) { + stubFor(get(urlMatching("/aai/v[0-9]+/business/customers/customer/" + globalCustId + "/service-subscriptions/service-subscription/" + subscriptionType)) + .willReturn(aResponse() + .withStatus(200) + .withHeader("Content-Type", "text/xml") + .withBodyFile(responseFile))); + } + + public static void MockDeleteServiceSubscription(String globalCustId, String subscriptionType, int statusCode) { + stubFor(delete(urlMatching("/aai/v[0-9]+/business/customers/customer/" + globalCustId + "/service-subscriptions/service-subscription/" + subscriptionType)) + .willReturn(aResponse() + .withStatus(statusCode))); + } + + public static void MockDeleteServiceInstanceId(String globalCustId, String subscriptionType, String serviceInstanceId) { + stubFor(delete(urlMatching("/aai/v[0-9]+/business/customers/customer/" + globalCustId + "/service-subscriptions/service-subscription/" + subscriptionType + "/service-instances/service-instance/" + serviceInstanceId)) + .willReturn(aResponse() + .withStatus(200))); + } + + public static void MockPutServiceSubscription(String globalCustId, String subscriptionType) { + stubFor(put(urlMatching("/aai/v[0-9]+/business/customers/customer/" + globalCustId + "/service-subscriptions/service-subscription/" + subscriptionType)) + .willReturn(aResponse() + .withStatus(200))); + } + + public static void MockGetServiceSubscription(String globalCustId, String subscriptionType, int statusCode) { + stubFor(get(urlMatching("/aai/v[0-9]+/business/customers/customer/" + globalCustId + "/service-subscriptions/service-subscription/" + subscriptionType)) + .willReturn(aResponse() + .withStatus(statusCode))); + } + + /** + * Customer Mock StubResponses below + */ + public static void MockGetCustomer(String globalCustId, String responseFile) { + stubFor(get(urlMatching("/aai/v[0-9]+/business/customers/customer/" + globalCustId)) + .willReturn(aResponse() + .withStatus(200) + .withHeader("Content-Type", "text/xml") + .withBodyFile(responseFile))); + } + + public static void MockDeleteCustomer(String globalCustId) { + stubFor(delete(urlMatching("/aai/v[0-9]+/business/customers/customer/" + globalCustId)) + .willReturn(aResponse() + .withStatus(200))); + } + + public static void MockPutCustomer(String globalCustId) { + stubFor(put(urlMatching("/aai/v[0-9]+/business/customers/customer/" + globalCustId)) + .willReturn(aResponse() + .withStatus(200))); + } + + public static void MockPutCustomer_500(String globalCustId) { + stubFor(put(urlMatching("/aai/v[0-9]+/business/customers/customer/" + globalCustId)) + .willReturn(aResponse() + .withStatus(500))); + } + + + /** + * Generic-Vnf Mock StubResponses below + */ + public static void MockGetGenericVnfById(String vnfId, String responseFile, int statusCode){ + stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf" + vnfId)) + .willReturn(aResponse() + .withStatus(statusCode) + .withHeader("Content-Type", "text/xml") + .withBodyFile(responseFile))); + } + + public static void MockGetGenericVnfByIdWithPriority(String vnfId, int statusCode, String responseFile) { + stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf" + vnfId)) + .atPriority(1) + .willReturn(aResponse() + .withStatus(statusCode) + .withHeader("Content-Type", "text/xml") + .withBodyFile(responseFile))); + } + + public static void MockGetGenericVnfByIdWithPriority(String vnfId, String vfModuleId, int statusCode, String responseFile, int priority) { + stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/" + vnfId + "/vf-modules/vf-module/" + vfModuleId)) + .atPriority(priority) + .willReturn(aResponse() + .withStatus(statusCode) + .withHeader("Content-Type", "text/xml") + .withBodyFile(responseFile))); + } + + public static void MockGetGenericVnfByIdWithDepth(String vnfId, int depth, String responseFile){ + stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/" + vnfId + "[?]depth=" + depth)) + .willReturn(aResponse() + .withStatus(200) + .withHeader("Content-Type", "text/xml") + .withBodyFile(responseFile))); + } + + public static void MockGetGenericVnfById_404(String vnfId){ + stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/" + vnfId)) + .willReturn(aResponse() + .withStatus(404))); + } + + public static void MockGetGenericVnfById_500(String vnfId){ + stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/" + vnfId)) + .willReturn(aResponse() + .withStatus(500))); + } + + public static void MockGetGenericVnfByName(String vnfName, String responseFile){ + stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf[?]vnf-name=" + vnfName)) + .willReturn(aResponse() + .withStatus(200) + .withHeader("Content-Type", "text/xml") + .withBodyFile(responseFile))); + } + + public static void MockGetGenericVnfByNameWithDepth(String vnfName, int depth, String responseFile){ + stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf[?]vnf-name=" + vnfName + "[&]depth=" + depth)) + .willReturn(aResponse() + .withStatus(200) + .withHeader("Content-Type", "text/xml") + .withBodyFile(responseFile))); + } + + public static void MockGetGenericVnfByName_404(String vnfName){ + stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf[?]vnf-name=" + vnfName)) + .willReturn(aResponse() + .withStatus(404))); + } + + public static void MockDeleteGenericVnf(String vnfId, String resourceVersion){ + stubFor(delete(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/" + vnfId + "[?]resource-version=" + resourceVersion)) + .willReturn(aResponse() + .withStatus(204))); + } + + public static void MockDeleteGenericVnf(String vnfId, String resourceVersion, int statusCode){ + stubFor(delete(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/" + vnfId + "[?]resource-version=" + resourceVersion)) + .willReturn(aResponse() + .withStatus(statusCode))); + } + + public static void MockDeleteGenericVnf_500(String vnfId, String resourceVersion){ + stubFor(delete(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/" + vnfId + "[?]resource-version=" + resourceVersion)) + .willReturn(aResponse() + .withStatus(500))); + } + + public static void MockPutGenericVnf(String vnfId){ + stubFor(put(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/" + vnfId)) + .willReturn(aResponse() + .withStatus(200))); + } + + public static void MockPutGenericVnf(String vnfId, String requestBodyContaining, int statusCode) { + stubFor(put(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf" + vnfId)) + .withRequestBody(containing(requestBodyContaining)) + .willReturn(aResponse() + .withStatus(statusCode))); + } + + public static void MockPutGenericVnf(String vnfId, int statusCode) { + stubFor(put(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf" + vnfId)) + .willReturn(aResponse() + .withStatus(statusCode))); + } + + public static void MockPutGenericVnf_Bad(String vnfId, int statusCode){ + stubFor(put(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/" + vnfId)) + .willReturn(aResponse() + .withStatus(statusCode))); + } + + public static void MockPatchGenericVnf(String vnfId){ + stubFor(patch(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/" + vnfId)) + .willReturn(aResponse() + .withStatus(200))); + } + /** + * Vce Mock StubResponses below + */ + public static void MockGetVceById(String vnfId, String responseFile){ + stubFor(get(urlMatching("/aai/v[0-9]+/network/vces/vce/" + vnfId)) + .willReturn(aResponse() + .withStatus(200) + .withHeader("Content-Type", "text/xml") + .withBodyFile(responseFile))); + } + + public static void MockGetVceByName(String vnfName, String responseFile){ + stubFor(get(urlMatching("/aai/v[0-9]+/network/vces/vce[?]vnf-name=" + vnfName)) + .willReturn(aResponse() + .withStatus(200) + .withHeader("Content-Type", "text/xml") + .withBodyFile(responseFile))); + } + + public static void MockDeleteVce(String vnfId, String resourceVersion, int statusCode){ + stubFor(delete(urlMatching("/aai/v[0-9]+/network/vces/vce/" + vnfId + "[?]resource-version=" + resourceVersion)) + .willReturn(aResponse() + .withStatus(statusCode))); + } + + public static void MockPutVce(String vnfId){ + stubFor(put(urlMatching("/aai/v[0-9]+/network/vces/vce/" + vnfId)) + .willReturn(aResponse() + .withStatus(200))); + } + + public static void MockGetGenericVceByNameWithDepth(String vnfName, int depth, String responseFile){ + stubFor(get(urlMatching("/aai/v[0-9]+/network/vces/vce[?]vnf-name=" + vnfName + "[&]depth=" + depth)) + .willReturn(aResponse() + .withStatus(200) + .withHeader("Content-Type", "text/xml") + .withBodyFile(responseFile))); + } + + public static void MockGetVceGenericQuery(String serviceInstanceName, int depth, int statusCode, String responseFile){ + stubFor(get(urlMatching("/aai/v[0-9]+/search/generic-query[?]key=service-instance.service-instance-name:" + serviceInstanceName + "[&]start-node-type=service-instance[&]include=vce[&]depth=" + depth)) + .willReturn(aResponse() + .withStatus(statusCode) + .withHeader("Content-Type", "text/xml") + .withBodyFile(responseFile))); + } + + /** + * Tenant Mock StubResponses below + */ + public static void MockGetTenantGenericQuery(String customer, String serviceType, String responseFile) { + stubFor(get(urlMatching("/aai/v[0-9]+/search/generic-query[?]key=customer.global-customer-id:" + customer + "&key=service-subscription.service-type:" + serviceType + "&start-node-type=service-subscription&include=tenant&include=service-subscription&depth=1")) + .willReturn(aResponse() + .withStatus(200) + .withHeader("Content-Type", "text/xml") + .withBodyFile(responseFile))); + } + + public static void MockGetTenant(String tenantId, String responseFile) { + stubFor(get(urlEqualTo("/aai/v2/cloud-infrastructure/tenants/tenant/" + tenantId)) + .willReturn(aResponse() + .withStatus(200) + .withHeader("Content-Type", "text/xml") + .withBodyFile(responseFile))); + } + + /** + * Network Mock StubResponses below + */ + public static void MockGetNetwork(String networkId, String responseFile, int statusCode) { + stubFor(get(urlMatching("/aai/v[0-9]+/network/l3-networks/l3-network/" + networkId)) + .willReturn(aResponse() + .withStatus(statusCode) + .withHeader("Content-Type", "text/xml") + .withBodyFile(responseFile))); + } + + public static void MockPutNetwork(String networkId, int statusCode, String responseFile) { + stubFor(put(urlMatching("/aai/v[0-9]+/network/l3-networks/l3-network/" + networkId)) + .willReturn(aResponse() + .withStatus(statusCode) + .withHeader("Content-Type", "text/xml") + .withBodyFile(responseFile))); + } + + public static void MockPutNetwork(String networkPolicyId, String responseFile, int statusCode) { + stubFor(put(urlMatching("/aai/v[0-9]+/network/network-policies/network-policy/" + networkPolicyId)) + .willReturn(aResponse() + .withStatus(statusCode) + .withHeader("Content-Type", "text/xml") + .withBodyFile(responseFile))); + } + + public static void MockGetNetworkName(String networkPolicyName, String responseFile, int statusCode) { + stubFor(get(urlMatching("/aai/v[0-9]+/network/l3-networks/l3-network[?]network-name=" + networkPolicyName)) + .willReturn(aResponse() + .withStatus(statusCode) + .withHeader("Content-Type", "text/xml") + .withBodyFile(responseFile))); + } + + public static void MockGetNetworkVpnBinding(String networkBindingId, String responseFile, int statusCode) { + stubFor(get(urlMatching("/aai/v[0-9]+/network/vpn-bindings/vpn-binding/" + networkBindingId)) + .willReturn(aResponse() + .withStatus(statusCode) + .withHeader("Content-Type", "text/xml") + .withBodyFile(responseFile))); + } + + public static void MockGetNetworkPolicy(String networkPolicy, String responseFile, int statusCode) { + stubFor(get(urlMatching("/aai/v[0-9]+/network/network-policies/network-policy/" + networkPolicy)) + .willReturn(aResponse() + .withStatus(statusCode) + .withHeader("Content-Type", "text/xml") + .withBodyFile(responseFile))); + } + + public static void MockGetNetworkPolicyfqdn(String networkPolicy, String responseFile, int statusCode) { + stubFor(get(urlMatching("/aai/v[0-9]+/network/network-policies/network-policy[?]network-policy-fqdn=" + networkPolicy)) + .willReturn(aResponse() + .withStatus(statusCode) + .withHeader("Content-Type", "text/xml") + .withBodyFile(responseFile))); + } + + public static void MockGetNetworkRouteTable(String networkRouteId, String responseFile, int statusCode) { + stubFor(get(urlMatching("/aai/v[0-9]+/network/route-table-references/route-table-reference/" + networkRouteId)) + .willReturn(aResponse() + .withStatus(statusCode) + .withHeader("Content-Type", "text/xml") + .withBodyFile(responseFile))); + } + + public static void MockPatchVfModuleId(String vnfId, String vfModuleId) { + stubFor(patch(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/" + vnfId + "/vf-modules/vf-module/" + vfModuleId)) + .willReturn(aResponse() + .withStatus(200))); + } + + + /** + * Cloud infrastructure below + */ + + public static void MockGetCloudRegion(String cloudRegionId, int statusCode, String responseFile) { + stubFor(get(urlMatching("/aai/v[0-9]+/cloud-infrastructure/cloud-regions/cloud-region/att-aic/" + cloudRegionId)) + .willReturn(aResponse() + .withStatus(statusCode) + .withHeader("Content-Type", "text/xml") + .withBodyFile(responseFile))); + } + + /** + * Volume Group StubResponse below + */ + public static void MockGetVolumeGroupById(String cloudRegionId, String volumeGroupId, String responseFile) { + stubFor(get(urlMatching("/aai/v[0-9]+/cloud-infrastructure/cloud-regions/cloud-region/att-aic/" + cloudRegionId + "/volume-groups/volume-group/" + volumeGroupId)) + .willReturn(aResponse() + .withStatus(200) + .withHeader("Content-Type", "text/xml") + .withBodyFile(responseFile))); + } + + public static void MockPutVolumeGroupById(String cloudRegionId, String volumeGroupId, String responseFile, int statusCode) { + stubFor(put(urlMatching("/aai/v[0-9]+/cloud-infrastructure/cloud-regions/cloud-region/att-aic/" + cloudRegionId + "/volume-groups/volume-group/" + volumeGroupId)) + .willReturn(aResponse() + .withStatus(statusCode) + .withHeader("Content-Type", "text/xml") + .withBodyFile(responseFile))); + } + + public static void MockGetVolumeGroupByName(String cloudRegionId, String volumeGroupName, String responseFile, int statusCode) { + stubFor(get(urlMatching("/aai/v[0-9]+/cloud-infrastructure/cloud-regions/cloud-region/att-aic/" + cloudRegionId + "/volume-groups[?]volume-group-name=" + volumeGroupName)) + .willReturn(aResponse() + .withStatus(statusCode) + .withHeader("Content-Type", "text/xml") + .withBodyFile(responseFile))); + } + + public static void MockDeleteVolumeGroupById(String cloudRegionId, String volumeGroupId, String resourceVersion, int statusCode) { + stubFor(delete(urlMatching("/aai/v[0-9]+/cloud-infrastructure/cloud-regions/cloud-region/att-aic/" + cloudRegionId + "/volume-groups/volume-group/" + volumeGroupId + "[?]resource-version=" + resourceVersion)) + .willReturn(aResponse() + .withStatus(statusCode))); + } + + /** + * VF-Module StubResponse below + * @param statusCode TODO + */ + public static void MockGetVfModuleId(String vnfId, String vfModuleId, String responseFile, int statusCode) { + stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/" + vnfId + "/vf-modules/vf-module/" + vfModuleId)) + .willReturn(aResponse() + .withStatus(statusCode) + .withHeader("Content-Type", "text/xml") + .withBodyFile(responseFile))); + } + + public static void MockGetVfModuleIdNoResponse(String vnfId, String requestContaining, String vfModuleId) { + stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/" + vnfId + "/vf-modules/vf-module/" + vfModuleId)) + .withRequestBody(containing(requestContaining)) + .willReturn(aResponse() + .withStatus(200) + .withHeader("Content-Type", "text/xml"))); + } + + public static void MockPutVfModuleIdNoResponse(String vnfId, String requestContaining, String vfModuleId) { + stubFor(put(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/" + vnfId +"/vf-modules/vf-module/" +vfModuleId)) + .withRequestBody(containing(requestContaining)) + .willReturn(aResponse() + .withStatus(200))); + } + + public static void MockPutVfModuleId(String vnfId, String vfModuleId) { + stubFor(put(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/" + vnfId + "/vf-modules/vf-module/" + vfModuleId)) + .willReturn(aResponse() + .withStatus(200))); + } + + public static void MockPutVfModuleId(String vnfId, String vfModuleId, int returnCode) { + stubFor(put(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/" + vnfId + "/vf-modules/vf-module/" + vfModuleId)) + .willReturn(aResponse() + .withStatus(returnCode))); + } + + public static void MockDeleteVfModuleId(String vnfId, String vfModuleId, String resourceVersion, int returnCode) { + stubFor(delete(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/" + vnfId + "/vf-modules/vf-module/" + vfModuleId + "/[?]resource-version=" + resourceVersion)) + .willReturn(aResponse() + .withStatus(returnCode))); + } + + //// Deprecated Stubs below - to be deleted once unit test that reference them are refactored to use common ones above //// + @Deprecated + public static void MockGetVceById(){ + stubFor(get(urlMatching("/aai/v[0-9]+/network/vces/vce/testVnfId123?depth=1")) + .willReturn(aResponse() + .withStatus(200) + .withHeader("Content-Type", "text/xml") + .withBodyFile("GenericFlows/getVceResponse.xml"))); + } + @Deprecated + public static void MockGetVceByName(){ + stubFor(get(urlMatching("/aai/v[0-9]+/network/vces/vce[?]vnf-name=testVnfName123")) + .willReturn(aResponse() + .withStatus(200) + .withHeader("Content-Type", "text/xml") + .withBodyFile("GenericFlows/getVceByNameResponse.xml"))); + } + @Deprecated + public static void MockPutVce(){ + stubFor(put(urlMatching("/aai/v[0-9]+/network/vces/vce/testVnfId123")) + .willReturn(aResponse() + .withStatus(200))); + } + @Deprecated + public static void MockDeleteVce(){ + stubFor(delete(urlMatching("/aai/v[0-9]+/network/vces/vce/testVnfId123[?]resource-version=testReVer123")) + .willReturn(aResponse() + .withStatus(204))); + } + @Deprecated + public static void MockDeleteVce_404(){ + stubFor(delete(urlMatching("/aai/v[0-9]+/network/vces/vce/testVnfId123[?]resource-version=testReVer123")) + .willReturn(aResponse() + .withStatus(404))); + } + + @Deprecated + public static void MockDeleteServiceSubscription(){ + stubFor(delete(urlMatching("/aai/v[0-9]+/business/customers/customer/1604-MVM-26/service-subscriptions/service-subscription/SDN-ETHERNET-INTERNET[?]resource-version=1234")) + .willReturn(aResponse() + .withStatus(204))); + } + @Deprecated + public static void MockGetServiceSubscription(){ + stubFor(get(urlMatching("/aai/v[0-9]+/business/customers/customer/1604-MVM-26/service-subscriptions/service-subscription/SDN-ETHERNET-INTERNET")) + .willReturn(aResponse() + .withStatus(200) + .withHeader("Content-Type", "text/xml") + .withBodyFile("GenericFlows/getServiceSubscription.xml"))); + } + @Deprecated + public static void MockGetServiceSubscription_200Empty(){ + stubFor(get(urlMatching("/aai/v[0-9]+/business/customers/customer/1604-MVM-26/service-subscriptions/service-subscription/SDN-ETHERNET-INTERNET[?]resource-version=1234")) + .willReturn(aResponse() + .withStatus(200) + .withHeader("Content-Type", "text/xml") + .withBody(" "))); + } + @Deprecated + public static void MockGetServiceSubscription_404() { + stubFor(get(urlMatching("/aai/v[0-9]+/business/customers/customer/1604-MVM-26/service-subscriptions/service-subscription/SDN-ETHERNET-INTERNET")) + .willReturn(aResponse() + .withStatus(404))); + } + @Deprecated + public static void MockGENPSIPutServiceInstance(){ + stubFor(put(urlMatching("/aai/v[0-9]+/business/customers/customer/1604-MVM-26/service-subscriptions/service-subscription/SDN-ETHERNET-INTERNET/service-instances/service-instance/MIS%252F1604%252F0026%252FSW_INTERNET")) + .willReturn(aResponse() + .withStatus(200) + .withHeader("Content-Type", "text/xml") + .withBodyFile("GenericPutServiceInstance/GenericPutServiceInstance_PutServiceInstance_AAIResponse_Success.xml"))); + } + + @Deprecated + public static void MockGENPSIPutServiceSubscription(){ + stubFor(put(urlMatching("/aai/v[0-9]+/business/customers/customer/1604-MVM-26/service-subscriptions/service-subscription/SDN-ETHERNET-INTERNET")) + .willReturn(aResponse() + .withStatus(200) + .withHeader("Content-Type", "text/xml") + .withBodyFile("GenericPutServiceInstance/GenericPutServiceInstance_PutServiceInstance_AAIResponse_Success.xml"))); + } + @Deprecated + public static void MockGENPSIPutServiceInstance_get500(){ + stubFor(put(urlMatching("/aai/v[0-9]+/business/customers/customer/1604-MVM-26/service-subscriptions/service-subscription/SDN-ETHERNET-INTERNET/service-instances/service-instance/MIS%252F1604%252F0026%252FSW_INTERNET")) + .willReturn(aResponse() + .withStatus(500) + .withHeader("Content-Type", "text/xml") + .withBodyFile("GenericPutServiceInstance/aaiFault.xml"))); + } + + @Deprecated + public static void MockGetGenericVnfById(){ + stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/testVnfId123")) + .willReturn(aResponse() + .withStatus(200) + .withHeader("Content-Type", "text/xml") + .withBodyFile("GenericFlows/getGenericVnfByNameResponse.xml"))); + } + @Deprecated + public static void MockGetGenericVnfById_404(){ + stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/testVnfId123")) + .willReturn(aResponse() + .withStatus(404))); + } + @Deprecated + public static void MockGetGenericVnfByName(){ + stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf[?]vnf-name=testVnfName123")) + .willReturn(aResponse() + .withStatus(200) + .withHeader("Content-Type", "text/xml") + .withBodyFile("GenericFlows/getGenericVnfResponse.xml"))); + } + @Deprecated + public static void MockGetGenericVnfByName_hasRelationships(){ + stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf[?]vnf-name=testVnfName123")) + .willReturn(aResponse() + .withStatus(200) + .withHeader("Content-Type", "text/xml") + .withBodyFile("GenericFlows/getGenericVnfResponse_hasRelationships.xml"))); + } + @Deprecated + public static void MockGetGenericVnfById_hasRelationships(){ + stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/testVnfId123")) + .willReturn(aResponse() + .withStatus(200) + .withHeader("Content-Type", "text/xml") + .withBodyFile("GenericFlows/getGenericVnfResponse_hasRelationships.xml"))); + } + @Deprecated + public static void MockGetGenericVnfById_500(){ + stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/testVnfId123")) + .willReturn(aResponse() + .withStatus(500))); + } + @Deprecated + public static void MockGetGenericVnfByName_404(){ + stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf[?]vnf-name=testVnfName123")) + .willReturn(aResponse() + .withStatus(404))); + } + @Deprecated + public static void MockPutGenericVnf(){ + stubFor(put(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/testVnfId123")) + .willReturn(aResponse() + .withStatus(200))); + } + @Deprecated + public static void MockPutGenericVnf_400(){ + stubFor(put(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/testVnfId123")) + .willReturn(aResponse() + .withStatus(400))); + } + @Deprecated + public static void MockDeleteGenericVnf(){ + stubFor(delete(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/testVnfId123[?]resource-version=testReVer123")) + .willReturn(aResponse() + .withStatus(204))); + } + @Deprecated + public static void MockDeleteGenericVnf_404(){ + stubFor(delete(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/testVnfId123[?]resource-version=testReVer123")) + .willReturn(aResponse() + .withStatus(404))); + } + @Deprecated + public static void MockDeleteGenericVnf_500(){ + stubFor(delete(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/testVnfId123[?]resource-version=testReVer123")) + .willReturn(aResponse() + .withStatus(500))); + } + @Deprecated + public static void MockDeleteGenericVnf_412(){ + stubFor(delete(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/testVnfId123[[?]]resource-version=testReVer123")) + .willReturn(aResponse() + .withStatus(412))); + } + +} diff --git a/bpmn/MSOMockServer/src/main/resources/__files/sdncSimResponse.xml b/bpmn/MSOMockServer/src/main/resources/__files/sdncSimResponse.xml index eef8f06a90..bef293dfde 100644 --- a/bpmn/MSOMockServer/src/main/resources/__files/sdncSimResponse.xml +++ b/bpmn/MSOMockServer/src/main/resources/__files/sdncSimResponse.xml @@ -1,19 +1,19 @@ - - - - - - - d325c9a7-84c0-4081-b979-9cc773a0976d - 200 - OK - - <layer3-service-list - xmlns="com:att:sdnctl:l3api"><service-instance-id>0XX/VXXX/003717//Shakeout</service-instance-id><service-status><rpc-name>svc-topology-operation</rpc-name><rpc-action>delete</rpc-action><request-status>synccomplete</request-status><final-indicator>Y</final-indicator><l3sdn-action>DisconnectLayer3ServiceRequest</l3sdn-action><response-timestamp>2015-10-22T02:11:52.010Z</response-timestamp></service-status><service-data><svc-config-additional-data/></service-data></layer3-service-list> - - - - + + + + + + + d325c9a7-84c0-4081-b979-9cc773a0976d + 200 + OK + + <layer3-service-list + xmlns="com:att:sdnctl:l3api"><service-instance-id>0XX/VXXX/003717//Shakeout</service-instance-id><service-status><rpc-name>svc-topology-operation</rpc-name><rpc-action>delete</rpc-action><request-status>synccomplete</request-status><final-indicator>Y</final-indicator><l3sdn-action>DisconnectLayer3ServiceRequest</l3sdn-action><response-timestamp>2015-10-22T02:11:52.010Z</response-timestamp></service-status><service-data><svc-config-additional-data/></service-data></layer3-service-list> + + + + diff --git a/bpmn/MSORESTClient/pom.xml b/bpmn/MSORESTClient/pom.xml index d2e294d5c0..2c899084f8 100644 --- a/bpmn/MSORESTClient/pom.xml +++ b/bpmn/MSORESTClient/pom.xml @@ -1,52 +1,52 @@ - - - 4.0.0 - - - org.openecomp.mso - bpmn + + + 4.0.0 + + + org.openecomp.mso + bpmn 1.1.0-SNAPSHOT - - - org.openecomp.mso - MSORESTClient - - jar - - MSO REST Client API - - - - org.evosuite - evosuite-standalone-runtime - ${evosuiteVersion} - test - - - org.apache.httpcomponents - httpmime - 4.5 - - - com.metaparadigm - json-rpc - 1.0 - - - - org.mockito - mockito-all - 1.10.19 - test - - - - - MSORESTClient - - - - - - + + + org.openecomp.mso + MSORESTClient + + jar + + MSO REST Client API + + + + org.evosuite + evosuite-standalone-runtime + ${evosuiteVersion} + test + + + org.apache.httpcomponents + httpmime + 4.5 + + + com.metaparadigm + json-rpc + 1.0 + + + + org.mockito + mockito-all + 1.10.19 + test + + + + + MSORESTClient + + + + + + diff --git a/bpmn/MSOURN-plugin/pom.xml b/bpmn/MSOURN-plugin/pom.xml index 6022f4865b..ac75b53c08 100644 --- a/bpmn/MSOURN-plugin/pom.xml +++ b/bpmn/MSOURN-plugin/pom.xml @@ -1,71 +1,71 @@ - - 4.0.0 - - - org.openecomp.mso - bpmn - 1.1.0-SNAPSHOT - - - org.openecomp.mso - cockpit-urnmap-plugin - - jar - - MSO URN Mapping Cockpit Plugin - - - - org.camunda.bpm.webapp - camunda-webapp - classes - ${camunda.version} - - - commons-fileupload - commons-fileupload - - - - - commons-fileupload - commons-fileupload - 1.3.2 - - - javax.ws.rs - javax.ws.rs-api - 2.0 - - - - org.camunda.bpm - camunda-engine - ${camunda.version} - - - com.h2database - h2 - test - - - javax.servlet - javax.servlet-api - 3.0.1 - provided - - - org.openecomp.mso - common - ${project.version} - compile - - - org.evosuite - evosuite-standalone-runtime - ${evosuiteVersion} - test - - + + 4.0.0 + + + org.openecomp.mso + bpmn + 1.1.0-SNAPSHOT + + + org.openecomp.mso + cockpit-urnmap-plugin + + jar + + MSO URN Mapping Cockpit Plugin + + + + org.camunda.bpm.webapp + camunda-webapp + classes + ${camunda.version} + + + commons-fileupload + commons-fileupload + + + + + commons-fileupload + commons-fileupload + 1.3.2 + + + javax.ws.rs + javax.ws.rs-api + 2.0 + + + + org.camunda.bpm + camunda-engine + ${camunda.version} + + + com.h2database + h2 + test + + + javax.servlet + javax.servlet-api + 3.0.1 + provided + + + org.openecomp.mso + common + ${project.version} + compile + + + org.evosuite + evosuite-standalone-runtime + ${evosuiteVersion} + test + + \ No newline at end of file diff --git a/bpmn/MSOURN-plugin/src/main/java/org/openecomp/camunda/bpmn/plugin/urnmap/URNMapPlugin.java b/bpmn/MSOURN-plugin/src/main/java/org/openecomp/camunda/bpmn/plugin/urnmap/URNMapPlugin.java index fc08d2d54e..09fdc1c85e 100644 --- a/bpmn/MSOURN-plugin/src/main/java/org/openecomp/camunda/bpmn/plugin/urnmap/URNMapPlugin.java +++ b/bpmn/MSOURN-plugin/src/main/java/org/openecomp/camunda/bpmn/plugin/urnmap/URNMapPlugin.java @@ -1,53 +1,53 @@ -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - MSO - * ================================================================================ - * 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.openecomp.camunda.bpmn.plugin.urnmap; - -import java.util.Arrays; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import org.camunda.bpm.cockpit.plugin.spi.impl.AbstractCockpitPlugin; -import org.openecomp.camunda.bpmn.plugin.urnmap.resources.URNMapPluginRootResource; - - - -public class URNMapPlugin extends AbstractCockpitPlugin{ - public static final String ID = "urnMap-plugin"; - - public String getId() { - return ID; - } - - @Override - public Set> getResourceClasses() { - Set> classes = new HashSet>(); - - classes.add(URNMapPluginRootResource.class); - - return classes; - } - - @Override - public List getMappingFiles() { - return Arrays.asList("org/openecomp/camunda/bpm/plugin/urnmap/queries/urnMap.xml"); - } -} +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.camunda.bpmn.plugin.urnmap; + +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import org.camunda.bpm.cockpit.plugin.spi.impl.AbstractCockpitPlugin; +import org.openecomp.camunda.bpmn.plugin.urnmap.resources.URNMapPluginRootResource; + + + +public class URNMapPlugin extends AbstractCockpitPlugin{ + public static final String ID = "urnMap-plugin"; + + public String getId() { + return ID; + } + + @Override + public Set> getResourceClasses() { + Set> classes = new HashSet>(); + + classes.add(URNMapPluginRootResource.class); + + return classes; + } + + @Override + public List getMappingFiles() { + return Arrays.asList("org/openecomp/camunda/bpm/plugin/urnmap/queries/urnMap.xml"); + } +} diff --git a/bpmn/MSOURN-plugin/src/main/java/org/openecomp/camunda/bpmn/plugin/urnmap/db/MyBatisExtendedSessionFactory.java b/bpmn/MSOURN-plugin/src/main/java/org/openecomp/camunda/bpmn/plugin/urnmap/db/MyBatisExtendedSessionFactory.java index 728042008d..f7cc311e77 100644 --- a/bpmn/MSOURN-plugin/src/main/java/org/openecomp/camunda/bpmn/plugin/urnmap/db/MyBatisExtendedSessionFactory.java +++ b/bpmn/MSOURN-plugin/src/main/java/org/openecomp/camunda/bpmn/plugin/urnmap/db/MyBatisExtendedSessionFactory.java @@ -1,89 +1,89 @@ -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - MSO - * ================================================================================ - * 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.openecomp.camunda.bpmn.plugin.urnmap.db; - -import org.camunda.bpm.engine.ProcessEngineConfiguration; -import org.camunda.bpm.engine.impl.cfg.ProcessEngineConfigurationImpl; -import org.camunda.bpm.engine.impl.cfg.StandaloneProcessEngineConfiguration; -import org.camunda.bpm.engine.impl.interceptor.CommandContextInterceptor; -import org.camunda.bpm.engine.impl.interceptor.CommandInterceptor; -import org.camunda.bpm.engine.impl.interceptor.LogInterceptor; -import org.camunda.bpm.engine.impl.util.ReflectUtil; - -import java.io.InputStream; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -public class MyBatisExtendedSessionFactory extends StandaloneProcessEngineConfiguration { - - private String resourceName; - - protected void init() { - throw new IllegalArgumentException( - "Normal 'init' on process engine only used for extended MyBatis mappings is not allowed, please use 'initFromProcessEngineConfiguration'. You cannot construct a process engine with this configuration."); - } - - /** - * initialize the {@link ProcessEngineConfiguration} from an existing one, - * just using the database settings and initialize the database / MyBatis - * stuff. - */ - public void initFromProcessEngineConfiguration(ProcessEngineConfigurationImpl processEngineConfiguration, String resourceName) { - this.resourceName = resourceName; - - setDatabaseType(processEngineConfiguration.getDatabaseType()); - setDataSource(processEngineConfiguration.getDataSource()); - setDatabaseTablePrefix(processEngineConfiguration.getDatabaseTablePrefix()); - - initDataSource(); - //initVariableTypes(); - initCommandContextFactory(); - initTransactionFactory(); - initTransactionContextFactory(); - initCommandExecutors(); - initSqlSessionFactory(); - initIncidentHandlers(); - initIdentityProviderSessionFactory(); - initSessionFactories(); - } - - /** - * In order to always open a new command context set the property - * "alwaysOpenNew" to true inside the CommandContextInterceptor. - * - * If you execute the custom queries inside the process engine - * (for example in a service task), you have to do this. - */ - @Override - protected Collection getDefaultCommandInterceptorsTxRequired() { - List defaultCommandInterceptorsTxRequired = new ArrayList(); - defaultCommandInterceptorsTxRequired.add(new LogInterceptor()); - defaultCommandInterceptorsTxRequired.add(new CommandContextInterceptor(commandContextFactory, this, true)); - return defaultCommandInterceptorsTxRequired; - } - - @Override - protected InputStream getMyBatisXmlConfigurationSteam() { - return ReflectUtil.getResourceAsStream(resourceName); - } - -} +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.camunda.bpmn.plugin.urnmap.db; + +import org.camunda.bpm.engine.ProcessEngineConfiguration; +import org.camunda.bpm.engine.impl.cfg.ProcessEngineConfigurationImpl; +import org.camunda.bpm.engine.impl.cfg.StandaloneProcessEngineConfiguration; +import org.camunda.bpm.engine.impl.interceptor.CommandContextInterceptor; +import org.camunda.bpm.engine.impl.interceptor.CommandInterceptor; +import org.camunda.bpm.engine.impl.interceptor.LogInterceptor; +import org.camunda.bpm.engine.impl.util.ReflectUtil; + +import java.io.InputStream; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +public class MyBatisExtendedSessionFactory extends StandaloneProcessEngineConfiguration { + + private String resourceName; + + protected void init() { + throw new IllegalArgumentException( + "Normal 'init' on process engine only used for extended MyBatis mappings is not allowed, please use 'initFromProcessEngineConfiguration'. You cannot construct a process engine with this configuration."); + } + + /** + * initialize the {@link ProcessEngineConfiguration} from an existing one, + * just using the database settings and initialize the database / MyBatis + * stuff. + */ + public void initFromProcessEngineConfiguration(ProcessEngineConfigurationImpl processEngineConfiguration, String resourceName) { + this.resourceName = resourceName; + + setDatabaseType(processEngineConfiguration.getDatabaseType()); + setDataSource(processEngineConfiguration.getDataSource()); + setDatabaseTablePrefix(processEngineConfiguration.getDatabaseTablePrefix()); + + initDataSource(); + //initVariableTypes(); + initCommandContextFactory(); + initTransactionFactory(); + initTransactionContextFactory(); + initCommandExecutors(); + initSqlSessionFactory(); + initIncidentHandlers(); + initIdentityProviderSessionFactory(); + initSessionFactories(); + } + + /** + * In order to always open a new command context set the property + * "alwaysOpenNew" to true inside the CommandContextInterceptor. + * + * If you execute the custom queries inside the process engine + * (for example in a service task), you have to do this. + */ + @Override + protected Collection getDefaultCommandInterceptorsTxRequired() { + List defaultCommandInterceptorsTxRequired = new ArrayList(); + defaultCommandInterceptorsTxRequired.add(new LogInterceptor()); + defaultCommandInterceptorsTxRequired.add(new CommandContextInterceptor(commandContextFactory, this, true)); + return defaultCommandInterceptorsTxRequired; + } + + @Override + protected InputStream getMyBatisXmlConfigurationSteam() { + return ReflectUtil.getResourceAsStream(resourceName); + } + +} diff --git a/bpmn/MSOURN-plugin/src/main/java/org/openecomp/camunda/bpmn/plugin/urnmap/db/MyBatisQueryCommandExecutor.java b/bpmn/MSOURN-plugin/src/main/java/org/openecomp/camunda/bpmn/plugin/urnmap/db/MyBatisQueryCommandExecutor.java index e7140cd318..02b128f4ee 100644 --- a/bpmn/MSOURN-plugin/src/main/java/org/openecomp/camunda/bpmn/plugin/urnmap/db/MyBatisQueryCommandExecutor.java +++ b/bpmn/MSOURN-plugin/src/main/java/org/openecomp/camunda/bpmn/plugin/urnmap/db/MyBatisQueryCommandExecutor.java @@ -1,44 +1,44 @@ -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - MSO - * ================================================================================ - * 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.openecomp.camunda.bpmn.plugin.urnmap.db; - -import org.camunda.bpm.engine.impl.cfg.ProcessEngineConfigurationImpl; -import org.camunda.bpm.engine.impl.interceptor.Command; - -/** - * Helper to initialize a minimized process engine which does all the transaction and MyBatis mapping stuff for us - * and can be used to execute queries. - */ -public class MyBatisQueryCommandExecutor { - - private MyBatisExtendedSessionFactory myBatisExtendedSessionFactory; - - public MyBatisQueryCommandExecutor(ProcessEngineConfigurationImpl processEngineConfiguration, String mappingResourceName) { - myBatisExtendedSessionFactory = new MyBatisExtendedSessionFactory(); - myBatisExtendedSessionFactory.initFromProcessEngineConfiguration(processEngineConfiguration, mappingResourceName); - } - - public T executeQueryCommand(Command command) { - return myBatisExtendedSessionFactory.getCommandExecutorTxRequired().execute(command); - } - - -} +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.camunda.bpmn.plugin.urnmap.db; + +import org.camunda.bpm.engine.impl.cfg.ProcessEngineConfigurationImpl; +import org.camunda.bpm.engine.impl.interceptor.Command; + +/** + * Helper to initialize a minimized process engine which does all the transaction and MyBatis mapping stuff for us + * and can be used to execute queries. + */ +public class MyBatisQueryCommandExecutor { + + private MyBatisExtendedSessionFactory myBatisExtendedSessionFactory; + + public MyBatisQueryCommandExecutor(ProcessEngineConfigurationImpl processEngineConfiguration, String mappingResourceName) { + myBatisExtendedSessionFactory = new MyBatisExtendedSessionFactory(); + myBatisExtendedSessionFactory.initFromProcessEngineConfiguration(processEngineConfiguration, mappingResourceName); + } + + public T executeQueryCommand(Command command) { + return myBatisExtendedSessionFactory.getCommandExecutorTxRequired().execute(command); + } + + +} diff --git a/bpmn/MSOURN-plugin/src/main/java/org/openecomp/camunda/bpmn/plugin/urnmap/db/URNData.java b/bpmn/MSOURN-plugin/src/main/java/org/openecomp/camunda/bpmn/plugin/urnmap/db/URNData.java index ac8b2e15ee..59c41b1e42 100644 --- a/bpmn/MSOURN-plugin/src/main/java/org/openecomp/camunda/bpmn/plugin/urnmap/db/URNData.java +++ b/bpmn/MSOURN-plugin/src/main/java/org/openecomp/camunda/bpmn/plugin/urnmap/db/URNData.java @@ -1,47 +1,47 @@ -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - MSO - * ================================================================================ - * 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.openecomp.camunda.bpmn.plugin.urnmap.db; - -public class URNData { - - private String URNName; - private String URNValue; - private String Ver_; - public String getURNName() { - return URNName; - } - public void setURNName(String uRNName) { - URNName = uRNName; - } - public String getURNValue() { - return URNValue; - } - public void setURNValue(String uRNValue) { - URNValue = uRNValue; - } - public String getVer_() { - return Ver_; - } - public void setVer_(String ver_) { - Ver_ = ver_; - } - -} +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.camunda.bpmn.plugin.urnmap.db; + +public class URNData { + + private String URNName; + private String URNValue; + private String Ver_; + public String getURNName() { + return URNName; + } + public void setURNName(String uRNName) { + URNName = uRNName; + } + public String getURNValue() { + return URNValue; + } + public void setURNValue(String uRNValue) { + URNValue = uRNValue; + } + public String getVer_() { + return Ver_; + } + public void setVer_(String ver_) { + Ver_ = ver_; + } + +} diff --git a/bpmn/MSOURN-plugin/src/main/java/org/openecomp/camunda/bpmn/plugin/urnmap/db/URNService.java b/bpmn/MSOURN-plugin/src/main/java/org/openecomp/camunda/bpmn/plugin/urnmap/db/URNService.java index 3838343aba..c512c35c68 100644 --- a/bpmn/MSOURN-plugin/src/main/java/org/openecomp/camunda/bpmn/plugin/urnmap/db/URNService.java +++ b/bpmn/MSOURN-plugin/src/main/java/org/openecomp/camunda/bpmn/plugin/urnmap/db/URNService.java @@ -1,48 +1,48 @@ -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - MSO - * ================================================================================ - * 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.openecomp.camunda.bpmn.plugin.urnmap.db; - -import java.util.List; - -import org.camunda.bpm.engine.ProcessEngines; -import org.camunda.bpm.engine.impl.ProcessEngineImpl; -import org.camunda.bpm.engine.impl.cfg.ProcessEngineConfigurationImpl; -import org.camunda.bpm.engine.impl.interceptor.Command; -import org.camunda.bpm.engine.impl.interceptor.CommandContext; - -public class URNService { - - - public List getProperties() { - ProcessEngineImpl processEngine = (ProcessEngineImpl) ProcessEngines.getDefaultProcessEngine(); - ProcessEngineConfigurationImpl processEngineConfiguration = processEngine.getProcessEngineConfiguration(); - - MyBatisQueryCommandExecutor commandExecutor = new MyBatisQueryCommandExecutor(processEngineConfiguration, "mappings.xml"); - return commandExecutor.executeQueryCommand(new Command>() { - - @SuppressWarnings("unchecked") - public List execute(CommandContext commandContext) { - return (List) commandContext.getDbSqlSession().selectList("retrieveUrnKeyValuePair", null); - } - }); - } - -} +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.camunda.bpmn.plugin.urnmap.db; + +import java.util.List; + +import org.camunda.bpm.engine.ProcessEngines; +import org.camunda.bpm.engine.impl.ProcessEngineImpl; +import org.camunda.bpm.engine.impl.cfg.ProcessEngineConfigurationImpl; +import org.camunda.bpm.engine.impl.interceptor.Command; +import org.camunda.bpm.engine.impl.interceptor.CommandContext; + +public class URNService { + + + public List getProperties() { + ProcessEngineImpl processEngine = (ProcessEngineImpl) ProcessEngines.getDefaultProcessEngine(); + ProcessEngineConfigurationImpl processEngineConfiguration = processEngine.getProcessEngineConfiguration(); + + MyBatisQueryCommandExecutor commandExecutor = new MyBatisQueryCommandExecutor(processEngineConfiguration, "mappings.xml"); + return commandExecutor.executeQueryCommand(new Command>() { + + @SuppressWarnings("unchecked") + public List execute(CommandContext commandContext) { + return (List) commandContext.getDbSqlSession().selectList("retrieveUrnKeyValuePair", null); + } + }); + } + +} diff --git a/bpmn/MSOURN-plugin/src/main/java/org/openecomp/camunda/bpmn/plugin/urnmap/resources/ProcessInstanceResource.java b/bpmn/MSOURN-plugin/src/main/java/org/openecomp/camunda/bpmn/plugin/urnmap/resources/ProcessInstanceResource.java index 4a155809e5..51ceb0d1ab 100644 --- a/bpmn/MSOURN-plugin/src/main/java/org/openecomp/camunda/bpmn/plugin/urnmap/resources/ProcessInstanceResource.java +++ b/bpmn/MSOURN-plugin/src/main/java/org/openecomp/camunda/bpmn/plugin/urnmap/resources/ProcessInstanceResource.java @@ -1,96 +1,96 @@ -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - MSO - * ================================================================================ - * 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.openecomp.camunda.bpmn.plugin.urnmap.resources; - -import java.util.List; -import java.util.StringTokenizer; - -import javax.ws.rs.GET; -import javax.ws.rs.POST; -import javax.ws.rs.PUT; - -import org.camunda.bpm.cockpit.db.QueryParameters; -import org.camunda.bpm.cockpit.plugin.resource.AbstractPluginResource; -import org.camunda.bpm.cockpit.db.CommandExecutor; -import org.openecomp.camunda.bpmn.plugin.urnmap.db.*; - -public class ProcessInstanceResource extends AbstractPluginResource { - - public ProcessInstanceResource(String engineName) { - super(engineName); - } - - @GET - public List getUrnDataMap() { - List list = getQueryService() - .executeQuery( - "cockpit.urnMap.retrieveUrnKeyValuePair", - new QueryParameters()); - - System.out.println("urnmap-plugin project - Results Retrieved: "); - System.out.println("URNName: " + " " + "URNValue: " ); - for(URNData d: list) - { - System.out.println( d.getURNName() + " " + d.getURNValue()); - } - - return list; - } - - @PUT - //public void insertNewRow(String key_, String value_) - public void insertNewRow(String temp) - { - System.out.println("AddNewRow: XXXXXXXXXXXXXXXXX ---> " + temp); - StringTokenizer st = new StringTokenizer(temp, "|"); - String key_ = ""; - String value_ = ""; - - while(st.hasMoreTokens()) { - key_ = st.nextToken(); - value_ = st.nextToken(); - System.out.println(key_ + "\t" + value_); - } - - System.out.println("AddNewRow: XXXXXXXXXXXXXXXXX ---> key: " + key_ + " , Value: " + value_); - URNData nRow = new URNData(); - nRow.setVer_("1"); - nRow.setURNName(key_); - nRow.setURNValue(value_); - - getQueryService().executeQuery("cockpit.urnMap.insertNewRow", nRow, URNData.class); - - System.out.println("AddNewRow: XXXXXX END XXXXXXXXXXX"); - } - - @POST - // public void getPersistData(List myList) { - public void getPersistData(URNData d) { - - System.out.println("getPersistData: UrnName: " + d.getURNName() + " , URNValue: " + d.getURNValue() ); - - getQueryService().executeQuery("cockpit.urnMap.persistURNData", d, URNData.class); - //getQueryService().executeQuery("cockpit.sample.persistURNData", d, ProcessInstanceCountDto.class); - - - System.out.println("XXXXXXXXXX - END - XXXXXXXXXXXXXXX"); - } -} +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.camunda.bpmn.plugin.urnmap.resources; + +import java.util.List; +import java.util.StringTokenizer; + +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; + +import org.camunda.bpm.cockpit.db.QueryParameters; +import org.camunda.bpm.cockpit.plugin.resource.AbstractPluginResource; +import org.camunda.bpm.cockpit.db.CommandExecutor; +import org.openecomp.camunda.bpmn.plugin.urnmap.db.*; + +public class ProcessInstanceResource extends AbstractPluginResource { + + public ProcessInstanceResource(String engineName) { + super(engineName); + } + + @GET + public List getUrnDataMap() { + List list = getQueryService() + .executeQuery( + "cockpit.urnMap.retrieveUrnKeyValuePair", + new QueryParameters()); + + System.out.println("urnmap-plugin project - Results Retrieved: "); + System.out.println("URNName: " + " " + "URNValue: " ); + for(URNData d: list) + { + System.out.println( d.getURNName() + " " + d.getURNValue()); + } + + return list; + } + + @PUT + //public void insertNewRow(String key_, String value_) + public void insertNewRow(String temp) + { + System.out.println("AddNewRow: XXXXXXXXXXXXXXXXX ---> " + temp); + StringTokenizer st = new StringTokenizer(temp, "|"); + String key_ = ""; + String value_ = ""; + + while(st.hasMoreTokens()) { + key_ = st.nextToken(); + value_ = st.nextToken(); + System.out.println(key_ + "\t" + value_); + } + + System.out.println("AddNewRow: XXXXXXXXXXXXXXXXX ---> key: " + key_ + " , Value: " + value_); + URNData nRow = new URNData(); + nRow.setVer_("1"); + nRow.setURNName(key_); + nRow.setURNValue(value_); + + getQueryService().executeQuery("cockpit.urnMap.insertNewRow", nRow, URNData.class); + + System.out.println("AddNewRow: XXXXXX END XXXXXXXXXXX"); + } + + @POST + // public void getPersistData(List myList) { + public void getPersistData(URNData d) { + + System.out.println("getPersistData: UrnName: " + d.getURNName() + " , URNValue: " + d.getURNValue() ); + + getQueryService().executeQuery("cockpit.urnMap.persistURNData", d, URNData.class); + //getQueryService().executeQuery("cockpit.sample.persistURNData", d, ProcessInstanceCountDto.class); + + + System.out.println("XXXXXXXXXX - END - XXXXXXXXXXXXXXX"); + } +} diff --git a/bpmn/MSOURN-plugin/src/main/java/org/openecomp/camunda/bpmn/plugin/urnmap/resources/URNMapPluginRootResource.java b/bpmn/MSOURN-plugin/src/main/java/org/openecomp/camunda/bpmn/plugin/urnmap/resources/URNMapPluginRootResource.java index d31fec66b9..0e1ccd96d8 100644 --- a/bpmn/MSOURN-plugin/src/main/java/org/openecomp/camunda/bpmn/plugin/urnmap/resources/URNMapPluginRootResource.java +++ b/bpmn/MSOURN-plugin/src/main/java/org/openecomp/camunda/bpmn/plugin/urnmap/resources/URNMapPluginRootResource.java @@ -1,42 +1,42 @@ -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - MSO - * ================================================================================ - * 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.openecomp.camunda.bpmn.plugin.urnmap.resources; - -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; - -import org.camunda.bpm.cockpit.plugin.resource.AbstractPluginRootResource; -import org.openecomp.camunda.bpmn.plugin.urnmap.URNMapPlugin; - -@SuppressWarnings("deprecation") -@Path("plugin/" + URNMapPlugin.ID) -public class URNMapPluginRootResource extends AbstractPluginRootResource -{ - public URNMapPluginRootResource() { - super(URNMapPlugin.ID); - //super(""); - } - - @Path("{engineName}/process-instance") - public URNResource getProcessInstanceResource(@PathParam("engineName") String engineName) { - return subResource(new URNResource(engineName), engineName); - } -} +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.camunda.bpmn.plugin.urnmap.resources; + +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; + +import org.camunda.bpm.cockpit.plugin.resource.AbstractPluginRootResource; +import org.openecomp.camunda.bpmn.plugin.urnmap.URNMapPlugin; + +@SuppressWarnings("deprecation") +@Path("plugin/" + URNMapPlugin.ID) +public class URNMapPluginRootResource extends AbstractPluginRootResource +{ + public URNMapPluginRootResource() { + super(URNMapPlugin.ID); + //super(""); + } + + @Path("{engineName}/process-instance") + public URNResource getProcessInstanceResource(@PathParam("engineName") String engineName) { + return subResource(new URNResource(engineName), engineName); + } +} diff --git a/bpmn/MSOURN-plugin/src/main/java/org/openecomp/camunda/bpmn/plugin/urnmap/resources/URNResource.java b/bpmn/MSOURN-plugin/src/main/java/org/openecomp/camunda/bpmn/plugin/urnmap/resources/URNResource.java index 5838130a92..3dc6c249f5 100644 --- a/bpmn/MSOURN-plugin/src/main/java/org/openecomp/camunda/bpmn/plugin/urnmap/resources/URNResource.java +++ b/bpmn/MSOURN-plugin/src/main/java/org/openecomp/camunda/bpmn/plugin/urnmap/resources/URNResource.java @@ -1,205 +1,205 @@ -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - MSO - * ================================================================================ - * 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.openecomp.camunda.bpmn.plugin.urnmap.resources; -/*** -import java.beans.Statement; -import java.sql.DriverManager; -import java.sql.ResultSet; -import java.sql.SQLException; -*/ -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.util.ArrayList; -import java.util.List; -import java.util.StringTokenizer; - -import javax.naming.Context; -import javax.naming.InitialContext; -import javax.sql.DataSource; -import javax.ws.rs.GET; -import javax.ws.rs.POST; -import javax.ws.rs.PUT; - -import org.camunda.bpm.cockpit.db.QueryParameters; -import org.camunda.bpm.cockpit.plugin.resource.AbstractCockpitPluginResource; - - -//import org.camunda.bpm.cockpit.plugin.resource.AbstractPluginResource; -import org.openecomp.camunda.bpmn.plugin.urnmap.db.URNData; -import org.openecomp.mso.logger.MsoLogger; - - -//public class ProcessInstanceResource extends AbstractPluginResource { -public class URNResource extends AbstractCockpitPluginResource{ - public URNResource(String engineName) { - super(engineName); - } - - private Connection conn; - private static MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL); - @GET - public List getUrnDataMap() - { - List list = new ArrayList(); - - try { - - conn = getDBConnection(); - PreparedStatement psData = conn - .prepareStatement("select * from MSO_URN_MAPPING order by NAME_"); - - ResultSet r = psData.executeQuery(); - - while(r.next()) - { - URNData d = new URNData(); - d.setURNName(r.getString("NAME_")); - d.setURNValue(r.getString("VALUE_")); - d.setVer_( r.getString("REV_")); - - list.add(d); - } - - psData.close(); - conn.close(); - - } catch (Exception e) - { - - e.printStackTrace(); - } - - for(URNData d: list) - { - msoLogger.debug( d.getURNName() + " " + d.getURNValue()); - //msoLogger.debug("Started Executing " + getTaskName()); - msoLogger.debug("Started Executing " + d.getURNName() + " " + d.getURNValue()); - } - - return list; - } - - public List getUrnDataMapOLD() - { - - List list = getQueryService() - .executeQuery("cockpit.urnMap.retrieveUrnKeyValuePair", new QueryParameters()); - - msoLogger.debug("urnmap-plugin project - Results Retrieved: "); - msoLogger.debug("URNName: " + " " + "URNValue: " ); - - for(URNData d: list) - { - //msoLogger.debug( d.getURNName() + " " + d.getURNValue()); - msoLogger.debug( d.getURNName() + " " + d.getURNValue()); - } - - return list; - } - - public Connection getDBConnection() - { - try { - - if(conn == null) - { - Context ctx = new InitialContext(); - DataSource ds = (DataSource)ctx.lookup("java:jboss/datasources/ProcessEngine");//jboss - conn = ds.getConnection(); - - } - - } catch (Exception e) - { - - e.printStackTrace(); - } - - return conn; - } - - @PUT - public void insertNewRow(String temp) - { - msoLogger.debug("AddNewRow: XXXXXXXXXXXXXXXXX ---> " + temp); - msoLogger.debug("AddNewRow: EngineName ---> " + engineName); - - StringTokenizer st = new StringTokenizer(temp, "|"); - String key_ = ""; - String value_ = ""; - - while(st.hasMoreTokens()) { - key_ = st.nextToken(); - value_ = st.nextToken(); - msoLogger.debug(key_ + "\t" + value_); - } - - msoLogger.debug("AddNewRow: XXXXXXXXXXXXXXXXX ---> key: " + key_ + " , Value: " + value_); - final URNData nRow = new URNData(); - nRow.setVer_("1"); - final String myKey = key_; - final String myValue = value_; - - msoLogger.debug("----------- START ----------------------"); - try { - - conn = getDBConnection(); - PreparedStatement psData = conn - .prepareStatement("Insert into MSO_URN_MAPPING values ('" + key_ + "', '" + value_ + "', '1')"); - - psData.executeUpdate(); - - psData.close(); - conn.close(); - //} - - } catch (Exception e) - { - - e.printStackTrace(); - } - // getQueryService().executeQuery("cockpit.urnMap.insertNewRow", nRow, URNData.class); - } - - @POST - public void getPersistData(URNData d) { - - //getQueryService().executeQuery("cockpit.urnMap.persistURNData", d, URNData.class); - - try { - - conn = getDBConnection(); - PreparedStatement psData = conn - .prepareStatement("UPDATE MSO_URN_MAPPING set VALUE_ ='"+ d.getURNValue() + "' WHERE NAME_='" + d.getURNName() + "'"); - - psData.executeUpdate(); - - psData.close(); - conn.close(); - } catch (Exception e) - { - - e.printStackTrace(); - } - - } -} +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * 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.openecomp.camunda.bpmn.plugin.urnmap.resources; +/*** +import java.beans.Statement; +import java.sql.DriverManager; +import java.sql.ResultSet; +import java.sql.SQLException; +*/ +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.util.ArrayList; +import java.util.List; +import java.util.StringTokenizer; + +import javax.naming.Context; +import javax.naming.InitialContext; +import javax.sql.DataSource; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; + +import org.camunda.bpm.cockpit.db.QueryParameters; +import org.camunda.bpm.cockpit.plugin.resource.AbstractCockpitPluginResource; + + +//import org.camunda.bpm.cockpit.plugin.resource.AbstractPluginResource; +import org.openecomp.camunda.bpmn.plugin.urnmap.db.URNData; +import org.openecomp.mso.logger.MsoLogger; + + +//public class ProcessInstanceResource extends AbstractPluginResource { +public class URNResource extends AbstractCockpitPluginResource{ + public URNResource(String engineName) { + super(engineName); + } + + private Connection conn; + private static MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL); + @GET + public List getUrnDataMap() + { + List list = new ArrayList(); + + try { + + conn = getDBConnection(); + PreparedStatement psData = conn + .prepareStatement("select * from MSO_URN_MAPPING order by NAME_"); + + ResultSet r = psData.executeQuery(); + + while(r.next()) + { + URNData d = new URNData(); + d.setURNName(r.getString("NAME_")); + d.setURNValue(r.getString("VALUE_")); + d.setVer_( r.getString("REV_")); + + list.add(d); + } + + psData.close(); + conn.close(); + + } catch (Exception e) + { + + e.printStackTrace(); + } + + for(URNData d: list) + { + msoLogger.debug( d.getURNName() + " " + d.getURNValue()); + //msoLogger.debug("Started Executing " + getTaskName()); + msoLogger.debug("Started Executing " + d.getURNName() + " " + d.getURNValue()); + } + + return list; + } + + public List getUrnDataMapOLD() + { + + List list = getQueryService() + .executeQuery("cockpit.urnMap.retrieveUrnKeyValuePair", new QueryParameters()); + + msoLogger.debug("urnmap-plugin project - Results Retrieved: "); + msoLogger.debug("URNName: " + " " + "URNValue: " ); + + for(URNData d: list) + { + //msoLogger.debug( d.getURNName() + " " + d.getURNValue()); + msoLogger.debug( d.getURNName() + " " + d.getURNValue()); + } + + return list; + } + + public Connection getDBConnection() + { + try { + + if(conn == null) + { + Context ctx = new InitialContext(); + DataSource ds = (DataSource)ctx.lookup("java:jboss/datasources/ProcessEngine");//jboss + conn = ds.getConnection(); + + } + + } catch (Exception e) + { + + e.printStackTrace(); + } + + return conn; + } + + @PUT + public void insertNewRow(String temp) + { + msoLogger.debug("AddNewRow: XXXXXXXXXXXXXXXXX ---> " + temp); + msoLogger.debug("AddNewRow: EngineName ---> " + engineName); + + StringTokenizer st = new StringTokenizer(temp, "|"); + String key_ = ""; + String value_ = ""; + + while(st.hasMoreTokens()) { + key_ = st.nextToken(); + value_ = st.nextToken(); + msoLogger.debug(key_ + "\t" + value_); + } + + msoLogger.debug("AddNewRow: XXXXXXXXXXXXXXXXX ---> key: " + key_ + " , Value: " + value_); + final URNData nRow = new URNData(); + nRow.setVer_("1"); + final String myKey = key_; + final String myValue = value_; + + msoLogger.debug("----------- START ----------------------"); + try { + + conn = getDBConnection(); + PreparedStatement psData = conn + .prepareStatement("Insert into MSO_URN_MAPPING values ('" + key_ + "', '" + value_ + "', '1')"); + + psData.executeUpdate(); + + psData.close(); + conn.close(); + //} + + } catch (Exception e) + { + + e.printStackTrace(); + } + // getQueryService().executeQuery("cockpit.urnMap.insertNewRow", nRow, URNData.class); + } + + @POST + public void getPersistData(URNData d) { + + //getQueryService().executeQuery("cockpit.urnMap.persistURNData", d, URNData.class); + + try { + + conn = getDBConnection(); + PreparedStatement psData = conn + .prepareStatement("UPDATE MSO_URN_MAPPING set VALUE_ ='"+ d.getURNValue() + "' WHERE NAME_='" + d.getURNName() + "'"); + + psData.executeUpdate(); + + psData.close(); + conn.close(); + } catch (Exception e) + { + + e.printStackTrace(); + } + + } +} diff --git a/bpmn/MSOURN-plugin/src/main/resources/mappings.xml b/bpmn/MSOURN-plugin/src/main/resources/mappings.xml index 3141dfee4c..c66704ed15 100644 --- a/bpmn/MSOURN-plugin/src/main/resources/mappings.xml +++ b/bpmn/MSOURN-plugin/src/main/resources/mappings.xml @@ -1,32 +1,32 @@ - - - - - - - - - - - - - - + + + + + + + + + + + + + + diff --git a/bpmn/MSOURN-plugin/src/test/java/org/openecomp/camunda/bpmn/plugin/urnmap/URNMapPluginESTest.java b/bpmn/MSOURN-plugin/src/test/java/org/openecomp/camunda/bpmn/plugin/urnmap/URNMapPluginESTest.java index 386835c55d..e8d1af566a 100644 --- a/bpmn/MSOURN-plugin/src/test/java/org/openecomp/camunda/bpmn/plugin/urnmap/URNMapPluginESTest.java +++ b/bpmn/MSOURN-plugin/src/test/java/org/openecomp/camunda/bpmn/plugin/urnmap/URNMapPluginESTest.java @@ -1,43 +1,43 @@ -/* - * This file was automatically generated by EvoSuite - * Mon Nov 14 13:49:02 GMT 2016 - */ - -package org.openecomp.camunda.bpmn.plugin.urnmap; - -import org.junit.Test; - -import static org.junit.Assert.*; - -import java.util.List; -import java.util.Set; - -import org.evosuite.runtime.EvoRunner; -import org.evosuite.runtime.EvoRunnerParameters; -import org.junit.runner.RunWith; -import org.openecomp.camunda.bpmn.plugin.urnmap.URNMapPlugin; - -@RunWith(EvoRunner.class) @EvoRunnerParameters(mockJVMNonDeterminism = true, useVFS = true, useVNET = true, resetStaticState = true, useJEE = true) -public class URNMapPluginESTest extends URNMapPluginESTestscaffolding { - - @Test(timeout = 4000) - public void test0() throws Throwable { - URNMapPlugin uRNMapPlugin0 = new URNMapPlugin(); - Set> set0 = uRNMapPlugin0.getResourceClasses(); - assertFalse(set0.isEmpty()); - } - - @Test(timeout = 4000) - public void test1() throws Throwable { - URNMapPlugin uRNMapPlugin0 = new URNMapPlugin(); - String string0 = uRNMapPlugin0.getId(); - assertEquals("urnMap-plugin", string0); - } - - @Test(timeout = 4000) - public void test2() throws Throwable { - URNMapPlugin uRNMapPlugin0 = new URNMapPlugin(); - List list0 = uRNMapPlugin0.getMappingFiles(); - assertEquals(1, list0.size()); - } -} +/* + * This file was automatically generated by EvoSuite + * Mon Nov 14 13:49:02 GMT 2016 + */ + +package org.openecomp.camunda.bpmn.plugin.urnmap; + +import org.junit.Test; + +import static org.junit.Assert.*; + +import java.util.List; +import java.util.Set; + +import org.evosuite.runtime.EvoRunner; +import org.evosuite.runtime.EvoRunnerParameters; +import org.junit.runner.RunWith; +import org.openecomp.camunda.bpmn.plugin.urnmap.URNMapPlugin; + +@RunWith(EvoRunner.class) @EvoRunnerParameters(mockJVMNonDeterminism = true, useVFS = true, useVNET = true, resetStaticState = true, useJEE = true) +public class URNMapPluginESTest extends URNMapPluginESTestscaffolding { + + @Test(timeout = 4000) + public void test0() throws Throwable { + URNMapPlugin uRNMapPlugin0 = new URNMapPlugin(); + Set> set0 = uRNMapPlugin0.getResourceClasses(); + assertFalse(set0.isEmpty()); + } + + @Test(timeout = 4000) + public void test1() throws Throwable { + URNMapPlugin uRNMapPlugin0 = new URNMapPlugin(); + String string0 = uRNMapPlugin0.getId(); + assertEquals("urnMap-plugin", string0); + } + + @Test(timeout = 4000) + public void test2() throws Throwable { + URNMapPlugin uRNMapPlugin0 = new URNMapPlugin(); + List list0 = uRNMapPlugin0.getMappingFiles(); + assertEquals(1, list0.size()); + } +} diff --git a/bpmn/MSOURN-plugin/src/test/java/org/openecomp/camunda/bpmn/plugin/urnmap/URNMapPluginESTestscaffolding.java b/bpmn/MSOURN-plugin/src/test/java/org/openecomp/camunda/bpmn/plugin/urnmap/URNMapPluginESTestscaffolding.java index d01955f3fb..8a24352bd4 100644 --- a/bpmn/MSOURN-plugin/src/test/java/org/openecomp/camunda/bpmn/plugin/urnmap/URNMapPluginESTestscaffolding.java +++ b/bpmn/MSOURN-plugin/src/test/java/org/openecomp/camunda/bpmn/plugin/urnmap/URNMapPluginESTestscaffolding.java @@ -1,91 +1,91 @@ -/** - * Scaffolding file used to store all the setups needed to run - * tests automatically generated by EvoSuite - * Mon Nov 14 13:49:02 GMT 2016 - */ - -package org.openecomp.camunda.bpmn.plugin.urnmap; - -import org.evosuite.runtime.annotation.EvoSuiteClassExclude; -import org.junit.BeforeClass; -import org.junit.Before; -import org.junit.After; -import org.junit.AfterClass; -import org.evosuite.runtime.sandbox.Sandbox; - -@EvoSuiteClassExclude -public class URNMapPluginESTestscaffolding { - - @org.junit.Rule - public org.evosuite.runtime.vnet.NonFunctionalRequirementRule nfr = new org.evosuite.runtime.vnet.NonFunctionalRequirementRule(); - - private static final java.util.Properties defaultProperties = (java.util.Properties) java.lang.System.getProperties().clone(); - - private org.evosuite.runtime.thread.ThreadStopper threadStopper = new org.evosuite.runtime.thread.ThreadStopper (org.evosuite.runtime.thread.KillSwitchHandler.getInstance(), 3000); - - @BeforeClass - public static void initEvoSuiteFramework() { - org.evosuite.runtime.RuntimeSettings.className = "org.openecomp.camunda.bpmn.plugin.urnmap.URNMapPlugin"; - org.evosuite.runtime.GuiSupport.initialize(); - org.evosuite.runtime.RuntimeSettings.maxNumberOfThreads = 100; - org.evosuite.runtime.RuntimeSettings.maxNumberOfIterationsPerLoop = 10000; - org.evosuite.runtime.RuntimeSettings.mockSystemIn = true; - org.evosuite.runtime.RuntimeSettings.sandboxMode = org.evosuite.runtime.sandbox.Sandbox.SandboxMode.RECOMMENDED; - org.evosuite.runtime.sandbox.Sandbox.initializeSecurityManagerForSUT(); - org.evosuite.runtime.classhandling.JDKClassResetter.init(); - initializeClasses(); - org.evosuite.runtime.Runtime.getInstance().resetRuntime(); - } - - @AfterClass - public static void clearEvoSuiteFramework(){ - Sandbox.resetDefaultSecurityManager(); - java.lang.System.setProperties((java.util.Properties) defaultProperties.clone()); - } - - @Before - public void initTestCase(){ - threadStopper.storeCurrentThreads(); - threadStopper.startRecordingTime(); - org.evosuite.runtime.jvm.ShutdownHookHandler.getInstance().initHandler(); - org.evosuite.runtime.sandbox.Sandbox.goingToExecuteSUTCode(); - - org.evosuite.runtime.GuiSupport.setHeadless(); - org.evosuite.runtime.Runtime.getInstance().resetRuntime(); - org.evosuite.runtime.agent.InstrumentingAgent.activate(); - } - - @After - public void doneWithTestCase(){ - threadStopper.killAndJoinClientThreads(); - org.evosuite.runtime.jvm.ShutdownHookHandler.getInstance().safeExecuteAddedHooks(); - org.evosuite.runtime.classhandling.JDKClassResetter.reset(); - resetClasses(); - org.evosuite.runtime.sandbox.Sandbox.doneWithExecutingSUTCode(); - org.evosuite.runtime.agent.InstrumentingAgent.deactivate(); - org.evosuite.runtime.GuiSupport.restoreHeadlessMode(); - } - - - private static void initializeClasses() { - org.evosuite.runtime.classhandling.ClassStateSupport.initializeClasses(URNMapPluginESTestscaffolding.class.getClassLoader() , - "org.camunda.bpm.webapp.plugin.spi.impl.AbstractAppPlugin", - "org.camunda.bpm.webapp.plugin.spi.AppPlugin", - "org.camunda.bpm.cockpit.plugin.resource.AbstractPluginRootResource", - "org.camunda.bpm.cockpit.plugin.spi.impl.AbstractCockpitPlugin", - "org.camunda.bpm.webapp.plugin.resource.AbstractAppPluginRootResource", - "org.camunda.bpm.cockpit.plugin.spi.CockpitPlugin", - "org.openecomp.camunda.bpmn.plugin.urnmap.resources.URNMapPluginRootResource", - "org.camunda.bpm.cockpit.plugin.resource.AbstractCockpitPluginRootResource", - "org.openecomp.camunda.bpmn.plugin.urnmap.URNMapPlugin" - ); - } - - private static void resetClasses() { - org.evosuite.runtime.classhandling.ClassResetter.getInstance().setClassLoader(URNMapPluginESTestscaffolding.class.getClassLoader()); - - org.evosuite.runtime.classhandling.ClassStateSupport.resetClasses( - "org.openecomp.camunda.bpmn.plugin.urnmap.URNMapPlugin" - ); - } -} +/** + * Scaffolding file used to store all the setups needed to run + * tests automatically generated by EvoSuite + * Mon Nov 14 13:49:02 GMT 2016 + */ + +package org.openecomp.camunda.bpmn.plugin.urnmap; + +import org.evosuite.runtime.annotation.EvoSuiteClassExclude; +import org.junit.BeforeClass; +import org.junit.Before; +import org.junit.After; +import org.junit.AfterClass; +import org.evosuite.runtime.sandbox.Sandbox; + +@EvoSuiteClassExclude +public class URNMapPluginESTestscaffolding { + + @org.junit.Rule + public org.evosuite.runtime.vnet.NonFunctionalRequirementRule nfr = new org.evosuite.runtime.vnet.NonFunctionalRequirementRule(); + + private static final java.util.Properties defaultProperties = (java.util.Properties) java.lang.System.getProperties().clone(); + + private org.evosuite.runtime.thread.ThreadStopper threadStopper = new org.evosuite.runtime.thread.ThreadStopper (org.evosuite.runtime.thread.KillSwitchHandler.getInstance(), 3000); + + @BeforeClass + public static void initEvoSuiteFramework() { + org.evosuite.runtime.RuntimeSettings.className = "org.openecomp.camunda.bpmn.plugin.urnmap.URNMapPlugin"; + org.evosuite.runtime.GuiSupport.initialize(); + org.evosuite.runtime.RuntimeSettings.maxNumberOfThreads = 100; + org.evosuite.runtime.RuntimeSettings.maxNumberOfIterationsPerLoop = 10000; + org.evosuite.runtime.RuntimeSettings.mockSystemIn = true; + org.evosuite.runtime.RuntimeSettings.sandboxMode = org.evosuite.runtime.sandbox.Sandbox.SandboxMode.RECOMMENDED; + org.evosuite.runtime.sandbox.Sandbox.initializeSecurityManagerForSUT(); + org.evosuite.runtime.classhandling.JDKClassResetter.init(); + initializeClasses(); + org.evosuite.runtime.Runtime.getInstance().resetRuntime(); + } + + @AfterClass + public static void clearEvoSuiteFramework(){ + Sandbox.resetDefaultSecurityManager(); + java.lang.System.setProperties((java.util.Properties) defaultProperties.clone()); + } + + @Before + public void initTestCase(){ + threadStopper.storeCurrentThreads(); + threadStopper.startRecordingTime(); + org.evosuite.runtime.jvm.ShutdownHookHandler.getInstance().initHandler(); + org.evosuite.runtime.sandbox.Sandbox.goingToExecuteSUTCode(); + + org.evosuite.runtime.GuiSupport.setHeadless(); + org.evosuite.runtime.Runtime.getInstance().resetRuntime(); + org.evosuite.runtime.agent.InstrumentingAgent.activate(); + } + + @After + public void doneWithTestCase(){ + threadStopper.killAndJoinClientThreads(); + org.evosuite.runtime.jvm.ShutdownHookHandler.getInstance().safeExecuteAddedHooks(); + org.evosuite.runtime.classhandling.JDKClassResetter.reset(); + resetClasses(); + org.evosuite.runtime.sandbox.Sandbox.doneWithExecutingSUTCode(); + org.evosuite.runtime.agent.InstrumentingAgent.deactivate(); + org.evosuite.runtime.GuiSupport.restoreHeadlessMode(); + } + + + private static void initializeClasses() { + org.evosuite.runtime.classhandling.ClassStateSupport.initializeClasses(URNMapPluginESTestscaffolding.class.getClassLoader() , + "org.camunda.bpm.webapp.plugin.spi.impl.AbstractAppPlugin", + "org.camunda.bpm.webapp.plugin.spi.AppPlugin", + "org.camunda.bpm.cockpit.plugin.resource.AbstractPluginRootResource", + "org.camunda.bpm.cockpit.plugin.spi.impl.AbstractCockpitPlugin", + "org.camunda.bpm.webapp.plugin.resource.AbstractAppPluginRootResource", + "org.camunda.bpm.cockpit.plugin.spi.CockpitPlugin", + "org.openecomp.camunda.bpmn.plugin.urnmap.resources.URNMapPluginRootResource", + "org.camunda.bpm.cockpit.plugin.resource.AbstractCockpitPluginRootResource", + "org.openecomp.camunda.bpmn.plugin.urnmap.URNMapPlugin" + ); + } + + private static void resetClasses() { + org.evosuite.runtime.classhandling.ClassResetter.getInstance().setClassLoader(URNMapPluginESTestscaffolding.class.getClassLoader()); + + org.evosuite.runtime.classhandling.ClassStateSupport.resetClasses( + "org.openecomp.camunda.bpmn.plugin.urnmap.URNMapPlugin" + ); + } +} diff --git a/bpmn/MSOURN-plugin/src/test/java/org/openecomp/camunda/bpmn/plugin/urnmap/db/URNDataESTest.java b/bpmn/MSOURN-plugin/src/test/java/org/openecomp/camunda/bpmn/plugin/urnmap/db/URNDataESTest.java index f42e2a49a4..dedd6b37fc 100644 --- a/bpmn/MSOURN-plugin/src/test/java/org/openecomp/camunda/bpmn/plugin/urnmap/db/URNDataESTest.java +++ b/bpmn/MSOURN-plugin/src/test/java/org/openecomp/camunda/bpmn/plugin/urnmap/db/URNDataESTest.java @@ -1,88 +1,88 @@ -/* - * This file was automatically generated by EvoSuite - * Mon Nov 14 13:48:50 GMT 2016 - */ - -package org.openecomp.camunda.bpmn.plugin.urnmap.db; - -import org.junit.Test; - -import static org.junit.Assert.*; - -import org.evosuite.runtime.EvoRunner; -import org.evosuite.runtime.EvoRunnerParameters; -import org.junit.runner.RunWith; -import org.openecomp.camunda.bpmn.plugin.urnmap.db.URNData; - -@RunWith(EvoRunner.class) @EvoRunnerParameters(mockJVMNonDeterminism = true, useVFS = true, useVNET = true, resetStaticState = true, useJEE = true) -public class URNDataESTest extends URNDataESTestscaffolding { - - @Test(timeout = 4000) - public void test0() throws Throwable { - URNData uRNData0 = new URNData(); - uRNData0.setVer_("yE)"); - String string0 = uRNData0.getVer_(); - assertEquals("yE)", string0); - } - - @Test(timeout = 4000) - public void test1() throws Throwable { - URNData uRNData0 = new URNData(); - uRNData0.setURNValue("Dw]M@,~.D"); - String string0 = uRNData0.getURNValue(); - assertEquals("Dw]M@,~.D", string0); - } - - @Test(timeout = 4000) - public void test2() throws Throwable { - URNData uRNData0 = new URNData(); - uRNData0.setURNName(""); - String string0 = uRNData0.getURNName(); - assertEquals("", string0); - } - - @Test(timeout = 4000) - public void test3() throws Throwable { - URNData uRNData0 = new URNData(); - String string0 = uRNData0.getVer_(); - assertNull(string0); - } - - @Test(timeout = 4000) - public void test4() throws Throwable { - URNData uRNData0 = new URNData(); - String string0 = uRNData0.getURNValue(); - assertNull(string0); - } - - @Test(timeout = 4000) - public void test5() throws Throwable { - URNData uRNData0 = new URNData(); - String string0 = uRNData0.getURNName(); - assertNull(string0); - } - - @Test(timeout = 4000) - public void test6() throws Throwable { - URNData uRNData0 = new URNData(); - uRNData0.setURNValue(""); - String string0 = uRNData0.getURNValue(); - assertEquals("", string0); - } - - @Test(timeout = 4000) - public void test7() throws Throwable { - URNData uRNData0 = new URNData(); - uRNData0.setVer_(""); - String string0 = uRNData0.getVer_(); - assertEquals("", string0); - } - - @Test(timeout = 4000) - public void test8() throws Throwable { - URNData uRNData0 = new URNData(); - uRNData0.setURNName("2Gv9h[mmV=,z\"VSY`t)"); - String string0 = uRNData0.getURNName(); - assertEquals("2Gv9h[mmV=,z\"VSY`t)", string0); - } -} +/* + * This file was automatically generated by EvoSuite + * Mon Nov 14 13:48:50 GMT 2016 + */ + +package org.openecomp.camunda.bpmn.plugin.urnmap.db; + +import org.junit.Test; + +import static org.junit.Assert.*; + +import org.evosuite.runtime.EvoRunner; +import org.evosuite.runtime.EvoRunnerParameters; +import org.junit.runner.RunWith; +import org.openecomp.camunda.bpmn.plugin.urnmap.db.URNData; + +@RunWith(EvoRunner.class) @EvoRunnerParameters(mockJVMNonDeterminism = true, useVFS = true, useVNET = true, resetStaticState = true, useJEE = true) +public class URNDataESTest extends URNDataESTestscaffolding { + + @Test(timeout = 4000) + public void test0() throws Throwable { + URNData uRNData0 = new URNData(); + uRNData0.setVer_("yE)"); + String string0 = uRNData0.getVer_(); + assertEquals("yE)", string0); + } + + @Test(timeout = 4000) + public void test1() throws Throwable { + URNData uRNData0 = new URNData(); + uRNData0.setURNValue("Dw]M@,~.D"); + String string0 = uRNData0.getURNValue(); + assertEquals("Dw]M@,~.D", string0); + } + + @Test(timeout = 4000) + public void test2() throws Throwable { + URNData uRNData0 = new URNData(); + uRNData0.setURNName(""); + String string0 = uRNData0.getURNName(); + assertEquals("", string0); + } + + @Test(timeout = 4000) + public void test3() throws Throwable { + URNData uRNData0 = new URNData(); + String string0 = uRNData0.getVer_(); + assertNull(string0); + } + + @Test(timeout = 4000) + public void test4() throws Throwable { + URNData uRNData0 = new URNData(); + String string0 = uRNData0.getURNValue(); + assertNull(string0); + } + + @Test(timeout = 4000) + public void test5() throws Throwable { + URNData uRNData0 = new URNData(); + String string0 = uRNData0.getURNName(); + assertNull(string0); + } + + @Test(timeout = 4000) + public void test6() throws Throwable { + URNData uRNData0 = new URNData(); + uRNData0.setURNValue(""); + String string0 = uRNData0.getURNValue(); + assertEquals("", string0); + } + + @Test(timeout = 4000) + public void test7() throws Throwable { + URNData uRNData0 = new URNData(); + uRNData0.setVer_(""); + String string0 = uRNData0.getVer_(); + assertEquals("", string0); + } + + @Test(timeout = 4000) + public void test8() throws Throwable { + URNData uRNData0 = new URNData(); + uRNData0.setURNName("2Gv9h[mmV=,z\"VSY`t)"); + String string0 = uRNData0.getURNName(); + assertEquals("2Gv9h[mmV=,z\"VSY`t)", string0); + } +} diff --git a/bpmn/MSOURN-plugin/src/test/java/org/openecomp/camunda/bpmn/plugin/urnmap/db/URNDataESTestscaffolding.java b/bpmn/MSOURN-plugin/src/test/java/org/openecomp/camunda/bpmn/plugin/urnmap/db/URNDataESTestscaffolding.java index cb0adccf12..eef0d9b0aa 100644 --- a/bpmn/MSOURN-plugin/src/test/java/org/openecomp/camunda/bpmn/plugin/urnmap/db/URNDataESTestscaffolding.java +++ b/bpmn/MSOURN-plugin/src/test/java/org/openecomp/camunda/bpmn/plugin/urnmap/db/URNDataESTestscaffolding.java @@ -1,78 +1,78 @@ -/** - * Scaffolding file used to store all the setups needed to run - * tests automatically generated by EvoSuite - * Mon Nov 14 13:48:50 GMT 2016 - */ - -package org.openecomp.camunda.bpmn.plugin.urnmap.db; - -import org.evosuite.runtime.annotation.EvoSuiteClassExclude; -import org.junit.BeforeClass; -import org.junit.Before; -import org.junit.After; -import org.junit.AfterClass; -import org.evosuite.runtime.sandbox.Sandbox; - -@EvoSuiteClassExclude -public class URNDataESTestscaffolding { - - @org.junit.Rule - public org.evosuite.runtime.vnet.NonFunctionalRequirementRule nfr = new org.evosuite.runtime.vnet.NonFunctionalRequirementRule(); - - private static final java.util.Properties defaultProperties = (java.util.Properties) java.lang.System.getProperties().clone(); - - private org.evosuite.runtime.thread.ThreadStopper threadStopper = new org.evosuite.runtime.thread.ThreadStopper (org.evosuite.runtime.thread.KillSwitchHandler.getInstance(), 3000); - - @BeforeClass - public static void initEvoSuiteFramework() { - org.evosuite.runtime.RuntimeSettings.className = "org.openecomp.camunda.bpmn.plugin.urnmap.db.URNData"; - org.evosuite.runtime.GuiSupport.initialize(); - org.evosuite.runtime.RuntimeSettings.maxNumberOfThreads = 100; - org.evosuite.runtime.RuntimeSettings.maxNumberOfIterationsPerLoop = 10000; - org.evosuite.runtime.RuntimeSettings.mockSystemIn = true; - org.evosuite.runtime.RuntimeSettings.sandboxMode = org.evosuite.runtime.sandbox.Sandbox.SandboxMode.RECOMMENDED; - org.evosuite.runtime.sandbox.Sandbox.initializeSecurityManagerForSUT(); - org.evosuite.runtime.classhandling.JDKClassResetter.init(); - initializeClasses(); - org.evosuite.runtime.Runtime.getInstance().resetRuntime(); - } - - @AfterClass - public static void clearEvoSuiteFramework(){ - Sandbox.resetDefaultSecurityManager(); - java.lang.System.setProperties((java.util.Properties) defaultProperties.clone()); - } - - @Before - public void initTestCase(){ - threadStopper.storeCurrentThreads(); - threadStopper.startRecordingTime(); - org.evosuite.runtime.jvm.ShutdownHookHandler.getInstance().initHandler(); - org.evosuite.runtime.sandbox.Sandbox.goingToExecuteSUTCode(); - - org.evosuite.runtime.GuiSupport.setHeadless(); - org.evosuite.runtime.Runtime.getInstance().resetRuntime(); - org.evosuite.runtime.agent.InstrumentingAgent.activate(); - } - - @After - public void doneWithTestCase(){ - threadStopper.killAndJoinClientThreads(); - org.evosuite.runtime.jvm.ShutdownHookHandler.getInstance().safeExecuteAddedHooks(); - org.evosuite.runtime.classhandling.JDKClassResetter.reset(); - resetClasses(); - org.evosuite.runtime.sandbox.Sandbox.doneWithExecutingSUTCode(); - org.evosuite.runtime.agent.InstrumentingAgent.deactivate(); - org.evosuite.runtime.GuiSupport.restoreHeadlessMode(); - } - - - private static void initializeClasses() { - org.evosuite.runtime.classhandling.ClassStateSupport.initializeClasses(URNDataESTestscaffolding.class.getClassLoader() , - "org.openecomp.camunda.bpmn.plugin.urnmap.db.URNData" - ); - } - - private static void resetClasses() { - } -} +/** + * Scaffolding file used to store all the setups needed to run + * tests automatically generated by EvoSuite + * Mon Nov 14 13:48:50 GMT 2016 + */ + +package org.openecomp.camunda.bpmn.plugin.urnmap.db; + +import org.evosuite.runtime.annotation.EvoSuiteClassExclude; +import org.junit.BeforeClass; +import org.junit.Before; +import org.junit.After; +import org.junit.AfterClass; +import org.evosuite.runtime.sandbox.Sandbox; + +@EvoSuiteClassExclude +public class URNDataESTestscaffolding { + + @org.junit.Rule + public org.evosuite.runtime.vnet.NonFunctionalRequirementRule nfr = new org.evosuite.runtime.vnet.NonFunctionalRequirementRule(); + + private static final java.util.Properties defaultProperties = (java.util.Properties) java.lang.System.getProperties().clone(); + + private org.evosuite.runtime.thread.ThreadStopper threadStopper = new org.evosuite.runtime.thread.ThreadStopper (org.evosuite.runtime.thread.KillSwitchHandler.getInstance(), 3000); + + @BeforeClass + public static void initEvoSuiteFramework() { + org.evosuite.runtime.RuntimeSettings.className = "org.openecomp.camunda.bpmn.plugin.urnmap.db.URNData"; + org.evosuite.runtime.GuiSupport.initialize(); + org.evosuite.runtime.RuntimeSettings.maxNumberOfThreads = 100; + org.evosuite.runtime.RuntimeSettings.maxNumberOfIterationsPerLoop = 10000; + org.evosuite.runtime.RuntimeSettings.mockSystemIn = true; + org.evosuite.runtime.RuntimeSettings.sandboxMode = org.evosuite.runtime.sandbox.Sandbox.SandboxMode.RECOMMENDED; + org.evosuite.runtime.sandbox.Sandbox.initializeSecurityManagerForSUT(); + org.evosuite.runtime.classhandling.JDKClassResetter.init(); + initializeClasses(); + org.evosuite.runtime.Runtime.getInstance().resetRuntime(); + } + + @AfterClass + public static void clearEvoSuiteFramework(){ + Sandbox.resetDefaultSecurityManager(); + java.lang.System.setProperties((java.util.Properties) defaultProperties.clone()); + } + + @Before + public void initTestCase(){ + threadStopper.storeCurrentThreads(); + threadStopper.startRecordingTime(); + org.evosuite.runtime.jvm.ShutdownHookHandler.getInstance().initHandler(); + org.evosuite.runtime.sandbox.Sandbox.goingToExecuteSUTCode(); + + org.evosuite.runtime.GuiSupport.setHeadless(); + org.evosuite.runtime.Runtime.getInstance().resetRuntime(); + org.evosuite.runtime.agent.InstrumentingAgent.activate(); + } + + @After + public void doneWithTestCase(){ + threadStopper.killAndJoinClientThreads(); + org.evosuite.runtime.jvm.ShutdownHookHandler.getInstance().safeExecuteAddedHooks(); + org.evosuite.runtime.classhandling.JDKClassResetter.reset(); + resetClasses(); + org.evosuite.runtime.sandbox.Sandbox.doneWithExecutingSUTCode(); + org.evosuite.runtime.agent.InstrumentingAgent.deactivate(); + org.evosuite.runtime.GuiSupport.restoreHeadlessMode(); + } + + + private static void initializeClasses() { + org.evosuite.runtime.classhandling.ClassStateSupport.initializeClasses(URNDataESTestscaffolding.class.getClassLoader() , + "org.openecomp.camunda.bpmn.plugin.urnmap.db.URNData" + ); + } + + private static void resetClasses() { + } +} diff --git a/bpmn/MSOURN-plugin/src/test/java/org/openecomp/camunda/bpmn/plugin/urnmap/db/URNServiceESTest.java b/bpmn/MSOURN-plugin/src/test/java/org/openecomp/camunda/bpmn/plugin/urnmap/db/URNServiceESTest.java index 9838ff023d..b79468cfd0 100644 --- a/bpmn/MSOURN-plugin/src/test/java/org/openecomp/camunda/bpmn/plugin/urnmap/db/URNServiceESTest.java +++ b/bpmn/MSOURN-plugin/src/test/java/org/openecomp/camunda/bpmn/plugin/urnmap/db/URNServiceESTest.java @@ -1,36 +1,36 @@ -/* - * This file was automatically generated by EvoSuite - * Mon Nov 14 13:47:07 GMT 2016 - */ - -package org.openecomp.camunda.bpmn.plugin.urnmap.db; - -import org.junit.Test; - -import static org.junit.Assert.*; -import static org.evosuite.runtime.EvoAssertions.*; - -import org.evosuite.runtime.EvoRunner; -import org.evosuite.runtime.EvoRunnerParameters; -import org.junit.runner.RunWith; -import org.openecomp.camunda.bpmn.plugin.urnmap.db.URNService; - -@RunWith(EvoRunner.class) @EvoRunnerParameters(mockJVMNonDeterminism = true, useVFS = true, useVNET = true, resetStaticState = true, useJEE = true) -public class URNServiceESTest extends URNServiceESTestscaffolding { - - @Test(timeout = 4000) - public void test0() throws Throwable { - URNService uRNService0 = new URNService(); - // Undeclared exception! - try { - uRNService0.getProperties(); - fail("Expecting exception: NullPointerException"); - - } catch(NullPointerException e) { - // - // no message in exception (getMessage() returned null) - // - verifyException("org.openecomp.camunda.bpmn.plugin.urnmap.db.URNService", e); - } - } -} +/* + * This file was automatically generated by EvoSuite + * Mon Nov 14 13:47:07 GMT 2016 + */ + +package org.openecomp.camunda.bpmn.plugin.urnmap.db; + +import org.junit.Test; + +import static org.junit.Assert.*; +import static org.evosuite.runtime.EvoAssertions.*; + +import org.evosuite.runtime.EvoRunner; +import org.evosuite.runtime.EvoRunnerParameters; +import org.junit.runner.RunWith; +import org.openecomp.camunda.bpmn.plugin.urnmap.db.URNService; + +@RunWith(EvoRunner.class) @EvoRunnerParameters(mockJVMNonDeterminism = true, useVFS = true, useVNET = true, resetStaticState = true, useJEE = true) +public class URNServiceESTest extends URNServiceESTestscaffolding { + + @Test(timeout = 4000) + public void test0() throws Throwable { + URNService uRNService0 = new URNService(); + // Undeclared exception! + try { + uRNService0.getProperties(); + fail("Expecting exception: NullPointerException"); + + } catch(NullPointerException e) { + // + // no message in exception (getMessage() returned null) + // + verifyException("org.openecomp.camunda.bpmn.plugin.urnmap.db.URNService", e); + } + } +} diff --git a/bpmn/MSOURN-plugin/src/test/java/org/openecomp/camunda/bpmn/plugin/urnmap/db/URNServiceESTestscaffolding.java b/bpmn/MSOURN-plugin/src/test/java/org/openecomp/camunda/bpmn/plugin/urnmap/db/URNServiceESTestscaffolding.java index 887e11acb6..dbbce2d67b 100644 --- a/bpmn/MSOURN-plugin/src/test/java/org/openecomp/camunda/bpmn/plugin/urnmap/db/URNServiceESTestscaffolding.java +++ b/bpmn/MSOURN-plugin/src/test/java/org/openecomp/camunda/bpmn/plugin/urnmap/db/URNServiceESTestscaffolding.java @@ -1,97 +1,97 @@ -/** - * Scaffolding file used to store all the setups needed to run - * tests automatically generated by EvoSuite - * Mon Nov 14 13:47:07 GMT 2016 - */ - -package org.openecomp.camunda.bpmn.plugin.urnmap.db; - -import org.evosuite.runtime.annotation.EvoSuiteClassExclude; -import org.junit.BeforeClass; -import org.junit.Before; -import org.junit.After; -import org.junit.AfterClass; -import org.evosuite.runtime.sandbox.Sandbox; - -@EvoSuiteClassExclude -public class URNServiceESTestscaffolding { - - @org.junit.Rule - public org.evosuite.runtime.vnet.NonFunctionalRequirementRule nfr = new org.evosuite.runtime.vnet.NonFunctionalRequirementRule(); - - private static final java.util.Properties defaultProperties = (java.util.Properties) java.lang.System.getProperties().clone(); - - private org.evosuite.runtime.thread.ThreadStopper threadStopper = new org.evosuite.runtime.thread.ThreadStopper (org.evosuite.runtime.thread.KillSwitchHandler.getInstance(), 3000); - - @BeforeClass - public static void initEvoSuiteFramework() { - org.evosuite.runtime.RuntimeSettings.className = "org.openecomp.camunda.bpmn.plugin.urnmap.db.URNService"; - org.evosuite.runtime.GuiSupport.initialize(); - org.evosuite.runtime.RuntimeSettings.maxNumberOfThreads = 100; - org.evosuite.runtime.RuntimeSettings.maxNumberOfIterationsPerLoop = 10000; - org.evosuite.runtime.RuntimeSettings.mockSystemIn = true; - org.evosuite.runtime.RuntimeSettings.sandboxMode = org.evosuite.runtime.sandbox.Sandbox.SandboxMode.RECOMMENDED; - org.evosuite.runtime.sandbox.Sandbox.initializeSecurityManagerForSUT(); - org.evosuite.runtime.classhandling.JDKClassResetter.init(); - initializeClasses(); - org.evosuite.runtime.Runtime.getInstance().resetRuntime(); - } - - @AfterClass - public static void clearEvoSuiteFramework(){ - Sandbox.resetDefaultSecurityManager(); - java.lang.System.setProperties((java.util.Properties) defaultProperties.clone()); - } - - @Before - public void initTestCase(){ - threadStopper.storeCurrentThreads(); - threadStopper.startRecordingTime(); - org.evosuite.runtime.jvm.ShutdownHookHandler.getInstance().initHandler(); - org.evosuite.runtime.sandbox.Sandbox.goingToExecuteSUTCode(); - - org.evosuite.runtime.GuiSupport.setHeadless(); - org.evosuite.runtime.Runtime.getInstance().resetRuntime(); - org.evosuite.runtime.agent.InstrumentingAgent.activate(); - } - - @After - public void doneWithTestCase(){ - threadStopper.killAndJoinClientThreads(); - org.evosuite.runtime.jvm.ShutdownHookHandler.getInstance().safeExecuteAddedHooks(); - org.evosuite.runtime.classhandling.JDKClassResetter.reset(); - resetClasses(); - org.evosuite.runtime.sandbox.Sandbox.doneWithExecutingSUTCode(); - org.evosuite.runtime.agent.InstrumentingAgent.deactivate(); - org.evosuite.runtime.GuiSupport.restoreHeadlessMode(); - } - - - private static void initializeClasses() { - org.evosuite.runtime.classhandling.ClassStateSupport.initializeClasses(URNServiceESTestscaffolding.class.getClassLoader() , - "org.camunda.bpm.engine.ProcessEngineException", - "org.openecomp.camunda.bpmn.plugin.urnmap.db.URNService", - "org.camunda.bpm.engine.impl.interceptor.Command", - "org.camunda.bpm.engine.ClassLoadingException", - "org.camunda.bpm.engine.ProcessEngine", - "org.camunda.bpm.engine.ProcessEngines", - "org.camunda.bpm.engine.ProcessEngineInfo", - "org.camunda.bpm.application.ProcessApplicationUnavailableException", - "org.camunda.bpm.engine.impl.ProcessEngineImpl", - "org.camunda.bpm.engine.impl.context.Context", - "org.camunda.bpm.engine.impl.util.ReflectUtil", - "org.camunda.bpm.engine.ProcessEngineServices", - "org.openecomp.camunda.bpmn.plugin.urnmap.db.URNData" - ); - } - - private static void resetClasses() { - org.evosuite.runtime.classhandling.ClassResetter.getInstance().setClassLoader(URNServiceESTestscaffolding.class.getClassLoader()); - - org.evosuite.runtime.classhandling.ClassStateSupport.resetClasses( - "org.camunda.bpm.engine.impl.context.Context", - "org.camunda.bpm.engine.ProcessEngines", - "org.camunda.bpm.engine.impl.util.ReflectUtil" - ); - } -} +/** + * Scaffolding file used to store all the setups needed to run + * tests automatically generated by EvoSuite + * Mon Nov 14 13:47:07 GMT 2016 + */ + +package org.openecomp.camunda.bpmn.plugin.urnmap.db; + +import org.evosuite.runtime.annotation.EvoSuiteClassExclude; +import org.junit.BeforeClass; +import org.junit.Before; +import org.junit.After; +import org.junit.AfterClass; +import org.evosuite.runtime.sandbox.Sandbox; + +@EvoSuiteClassExclude +public class URNServiceESTestscaffolding { + + @org.junit.Rule + public org.evosuite.runtime.vnet.NonFunctionalRequirementRule nfr = new org.evosuite.runtime.vnet.NonFunctionalRequirementRule(); + + private static final java.util.Properties defaultProperties = (java.util.Properties) java.lang.System.getProperties().clone(); + + private org.evosuite.runtime.thread.ThreadStopper threadStopper = new org.evosuite.runtime.thread.ThreadStopper (org.evosuite.runtime.thread.KillSwitchHandler.getInstance(), 3000); + + @BeforeClass + public static void initEvoSuiteFramework() { + org.evosuite.runtime.RuntimeSettings.className = "org.openecomp.camunda.bpmn.plugin.urnmap.db.URNService"; + org.evosuite.runtime.GuiSupport.initialize(); + org.evosuite.runtime.RuntimeSettings.maxNumberOfThreads = 100; + org.evosuite.runtime.RuntimeSettings.maxNumberOfIterationsPerLoop = 10000; + org.evosuite.runtime.RuntimeSettings.mockSystemIn = true; + org.evosuite.runtime.RuntimeSettings.sandboxMode = org.evosuite.runtime.sandbox.Sandbox.SandboxMode.RECOMMENDED; + org.evosuite.runtime.sandbox.Sandbox.initializeSecurityManagerForSUT(); + org.evosuite.runtime.classhandling.JDKClassResetter.init(); + initializeClasses(); + org.evosuite.runtime.Runtime.getInstance().resetRuntime(); + } + + @AfterClass + public static void clearEvoSuiteFramework(){ + Sandbox.resetDefaultSecurityManager(); + java.lang.System.setProperties((java.util.Properties) defaultProperties.clone()); + } + + @Before + public void initTestCase(){ + threadStopper.storeCurrentThreads(); + threadStopper.startRecordingTime(); + org.evosuite.runtime.jvm.ShutdownHookHandler.getInstance().initHandler(); + org.evosuite.runtime.sandbox.Sandbox.goingToExecuteSUTCode(); + + org.evosuite.runtime.GuiSupport.setHeadless(); + org.evosuite.runtime.Runtime.getInstance().resetRuntime(); + org.evosuite.runtime.agent.InstrumentingAgent.activate(); + } + + @After + public void doneWithTestCase(){ + threadStopper.killAndJoinClientThreads(); + org.evosuite.runtime.jvm.ShutdownHookHandler.getInstance().safeExecuteAddedHooks(); + org.evosuite.runtime.classhandling.JDKClassResetter.reset(); + resetClasses(); + org.evosuite.runtime.sandbox.Sandbox.doneWithExecutingSUTCode(); + org.evosuite.runtime.agent.InstrumentingAgent.deactivate(); + org.evosuite.runtime.GuiSupport.restoreHeadlessMode(); + } + + + private static void initializeClasses() { + org.evosuite.runtime.classhandling.ClassStateSupport.initializeClasses(URNServiceESTestscaffolding.class.getClassLoader() , + "org.camunda.bpm.engine.ProcessEngineException", + "org.openecomp.camunda.bpmn.plugin.urnmap.db.URNService", + "org.camunda.bpm.engine.impl.interceptor.Command", + "org.camunda.bpm.engine.ClassLoadingException", + "org.camunda.bpm.engine.ProcessEngine", + "org.camunda.bpm.engine.ProcessEngines", + "org.camunda.bpm.engine.ProcessEngineInfo", + "org.camunda.bpm.application.ProcessApplicationUnavailableException", + "org.camunda.bpm.engine.impl.ProcessEngineImpl", + "org.camunda.bpm.engine.impl.context.Context", + "org.camunda.bpm.engine.impl.util.ReflectUtil", + "org.camunda.bpm.engine.ProcessEngineServices", + "org.openecomp.camunda.bpmn.plugin.urnmap.db.URNData" + ); + } + + private static void resetClasses() { + org.evosuite.runtime.classhandling.ClassResetter.getInstance().setClassLoader(URNServiceESTestscaffolding.class.getClassLoader()); + + org.evosuite.runtime.classhandling.ClassStateSupport.resetClasses( + "org.camunda.bpm.engine.impl.context.Context", + "org.camunda.bpm.engine.ProcessEngines", + "org.camunda.bpm.engine.impl.util.ReflectUtil" + ); + } +} diff --git a/bpmn/MSOURN-plugin/src/test/java/org/openecomp/camunda/bpmn/plugin/urnmap/resources/ProcessInstanceResourceESTest.java b/bpmn/MSOURN-plugin/src/test/java/org/openecomp/camunda/bpmn/plugin/urnmap/resources/ProcessInstanceResourceESTest.java index 8f45b8a0af..21ca18c3f7 100644 --- a/bpmn/MSOURN-plugin/src/test/java/org/openecomp/camunda/bpmn/plugin/urnmap/resources/ProcessInstanceResourceESTest.java +++ b/bpmn/MSOURN-plugin/src/test/java/org/openecomp/camunda/bpmn/plugin/urnmap/resources/ProcessInstanceResourceESTest.java @@ -1,88 +1,88 @@ -/* - * This file was automatically generated by EvoSuite - * Mon Nov 14 13:45:16 GMT 2016 - */ - -package org.openecomp.camunda.bpmn.plugin.urnmap.resources; - -import org.junit.Test; - -import static org.junit.Assert.*; -import static org.evosuite.runtime.EvoAssertions.*; - -import java.util.NoSuchElementException; - -import org.evosuite.runtime.EvoRunner; -import org.evosuite.runtime.EvoRunnerParameters; -import org.junit.runner.RunWith; -import org.openecomp.camunda.bpmn.plugin.urnmap.db.URNData; -import org.openecomp.camunda.bpmn.plugin.urnmap.resources.ProcessInstanceResource; - -@RunWith(EvoRunner.class) @EvoRunnerParameters(mockJVMNonDeterminism = true, useVFS = true, useVNET = true, resetStaticState = true, useJEE = true) -public class ProcessInstanceResourceESTest extends ProcessInstanceResourceESTestscaffolding { - - @Test(timeout = 4000) - public void test0() throws Throwable { - ProcessInstanceResource processInstanceResource0 = new ProcessInstanceResource((String) null); - // Undeclared exception! - try { - processInstanceResource0.getUrnDataMap(); - fail("Expecting exception: NullPointerException"); - - } catch(NullPointerException e) { - // - // no message in exception (getMessage() returned null) - // - verifyException("org.camunda.bpm.cockpit.Cockpit", e); - } - } - - @Test(timeout = 4000) - public void test1() throws Throwable { - ProcessInstanceResource processInstanceResource0 = new ProcessInstanceResource("DEUtDF$-rb|D]l9"); - // Undeclared exception! - try { - processInstanceResource0.insertNewRow("DEUtDF$-rb|D]l9"); - fail("Expecting exception: NullPointerException"); - - } catch(NullPointerException e) { - // - // no message in exception (getMessage() returned null) - // - verifyException("org.camunda.bpm.cockpit.Cockpit", e); - } - } - - @Test(timeout = 4000) - public void test2() throws Throwable { - URNData uRNData0 = new URNData(); - ProcessInstanceResource processInstanceResource0 = new ProcessInstanceResource("|"); - // Undeclared exception! - try { - processInstanceResource0.getPersistData(uRNData0); - fail("Expecting exception: NullPointerException"); - - } catch(NullPointerException e) { - // - // no message in exception (getMessage() returned null) - // - verifyException("org.camunda.bpm.cockpit.Cockpit", e); - } - } - - @Test(timeout = 4000) - public void test3() throws Throwable { - ProcessInstanceResource processInstanceResource0 = new ProcessInstanceResource("xGUKD= Ea6(aT"); - // Undeclared exception! - try { - processInstanceResource0.insertNewRow("xGUKD= Ea6(aT"); - fail("Expecting exception: NoSuchElementException"); - - } catch(NoSuchElementException e) { - // - // no message in exception (getMessage() returned null) - // - verifyException("java.util.StringTokenizer", e); - } - } -} +/* + * This file was automatically generated by EvoSuite + * Mon Nov 14 13:45:16 GMT 2016 + */ + +package org.openecomp.camunda.bpmn.plugin.urnmap.resources; + +import org.junit.Test; + +import static org.junit.Assert.*; +import static org.evosuite.runtime.EvoAssertions.*; + +import java.util.NoSuchElementException; + +import org.evosuite.runtime.EvoRunner; +import org.evosuite.runtime.EvoRunnerParameters; +import org.junit.runner.RunWith; +import org.openecomp.camunda.bpmn.plugin.urnmap.db.URNData; +import org.openecomp.camunda.bpmn.plugin.urnmap.resources.ProcessInstanceResource; + +@RunWith(EvoRunner.class) @EvoRunnerParameters(mockJVMNonDeterminism = true, useVFS = true, useVNET = true, resetStaticState = true, useJEE = true) +public class ProcessInstanceResourceESTest extends ProcessInstanceResourceESTestscaffolding { + + @Test(timeout = 4000) + public void test0() throws Throwable { + ProcessInstanceResource processInstanceResource0 = new ProcessInstanceResource((String) null); + // Undeclared exception! + try { + processInstanceResource0.getUrnDataMap(); + fail("Expecting exception: NullPointerException"); + + } catch(NullPointerException e) { + // + // no message in exception (getMessage() returned null) + // + verifyException("org.camunda.bpm.cockpit.Cockpit", e); + } + } + + @Test(timeout = 4000) + public void test1() throws Throwable { + ProcessInstanceResource processInstanceResource0 = new ProcessInstanceResource("DEUtDF$-rb|D]l9"); + // Undeclared exception! + try { + processInstanceResource0.insertNewRow("DEUtDF$-rb|D]l9"); + fail("Expecting exception: NullPointerException"); + + } catch(NullPointerException e) { + // + // no message in exception (getMessage() returned null) + // + verifyException("org.camunda.bpm.cockpit.Cockpit", e); + } + } + + @Test(timeout = 4000) + public void test2() throws Throwable { + URNData uRNData0 = new URNData(); + ProcessInstanceResource processInstanceResource0 = new ProcessInstanceResource("|"); + // Undeclared exception! + try { + processInstanceResource0.getPersistData(uRNData0); + fail("Expecting exception: NullPointerException"); + + } catch(NullPointerException e) { + // + // no message in exception (getMessage() returned null) + // + verifyException("org.camunda.bpm.cockpit.Cockpit", e); + } + } + + @Test(timeout = 4000) + public void test3() throws Throwable { + ProcessInstanceResource processInstanceResource0 = new ProcessInstanceResource("xGUKD= Ea6(aT"); + // Undeclared exception! + try { + processInstanceResource0.insertNewRow("xGUKD= Ea6(aT"); + fail("Expecting exception: NoSuchElementException"); + + } catch(NoSuchElementException e) { + // + // no message in exception (getMessage() returned null) + // + verifyException("java.util.StringTokenizer", e); + } + } +} diff --git a/bpmn/MSOURN-plugin/src/test/java/org/openecomp/camunda/bpmn/plugin/urnmap/resources/ProcessInstanceResourceESTestscaffolding.java b/bpmn/MSOURN-plugin/src/test/java/org/openecomp/camunda/bpmn/plugin/urnmap/resources/ProcessInstanceResourceESTestscaffolding.java index 27ae3e4dcd..4408adac67 100644 --- a/bpmn/MSOURN-plugin/src/test/java/org/openecomp/camunda/bpmn/plugin/urnmap/resources/ProcessInstanceResourceESTestscaffolding.java +++ b/bpmn/MSOURN-plugin/src/test/java/org/openecomp/camunda/bpmn/plugin/urnmap/resources/ProcessInstanceResourceESTestscaffolding.java @@ -1,94 +1,94 @@ -/** - * Scaffolding file used to store all the setups needed to run - * tests automatically generated by EvoSuite - * Mon Nov 14 13:45:16 GMT 2016 - */ - -package org.openecomp.camunda.bpmn.plugin.urnmap.resources; - -import org.evosuite.runtime.annotation.EvoSuiteClassExclude; -import org.junit.BeforeClass; -import org.junit.Before; -import org.junit.After; -import org.junit.AfterClass; -import org.evosuite.runtime.sandbox.Sandbox; - -@EvoSuiteClassExclude -public class ProcessInstanceResourceESTestscaffolding { - - @org.junit.Rule - public org.evosuite.runtime.vnet.NonFunctionalRequirementRule nfr = new org.evosuite.runtime.vnet.NonFunctionalRequirementRule(); - - private static final java.util.Properties defaultProperties = (java.util.Properties) java.lang.System.getProperties().clone(); - - private org.evosuite.runtime.thread.ThreadStopper threadStopper = new org.evosuite.runtime.thread.ThreadStopper (org.evosuite.runtime.thread.KillSwitchHandler.getInstance(), 3000); - - @BeforeClass - public static void initEvoSuiteFramework() { - org.evosuite.runtime.RuntimeSettings.className = "org.openecomp.camunda.bpmn.plugin.urnmap.resources.ProcessInstanceResource"; - org.evosuite.runtime.GuiSupport.initialize(); - org.evosuite.runtime.RuntimeSettings.maxNumberOfThreads = 100; - org.evosuite.runtime.RuntimeSettings.maxNumberOfIterationsPerLoop = 10000; - org.evosuite.runtime.RuntimeSettings.mockSystemIn = true; - org.evosuite.runtime.RuntimeSettings.sandboxMode = org.evosuite.runtime.sandbox.Sandbox.SandboxMode.RECOMMENDED; - org.evosuite.runtime.sandbox.Sandbox.initializeSecurityManagerForSUT(); - org.evosuite.runtime.classhandling.JDKClassResetter.init(); - initializeClasses(); - org.evosuite.runtime.Runtime.getInstance().resetRuntime(); - } - - @AfterClass - public static void clearEvoSuiteFramework(){ - Sandbox.resetDefaultSecurityManager(); - java.lang.System.setProperties((java.util.Properties) defaultProperties.clone()); - } - - @Before - public void initTestCase(){ - threadStopper.storeCurrentThreads(); - threadStopper.startRecordingTime(); - org.evosuite.runtime.jvm.ShutdownHookHandler.getInstance().initHandler(); - org.evosuite.runtime.sandbox.Sandbox.goingToExecuteSUTCode(); - - org.evosuite.runtime.GuiSupport.setHeadless(); - org.evosuite.runtime.Runtime.getInstance().resetRuntime(); - org.evosuite.runtime.agent.InstrumentingAgent.activate(); - } - - @After - public void doneWithTestCase(){ - threadStopper.killAndJoinClientThreads(); - org.evosuite.runtime.jvm.ShutdownHookHandler.getInstance().safeExecuteAddedHooks(); - org.evosuite.runtime.classhandling.JDKClassResetter.reset(); - resetClasses(); - org.evosuite.runtime.sandbox.Sandbox.doneWithExecutingSUTCode(); - org.evosuite.runtime.agent.InstrumentingAgent.deactivate(); - org.evosuite.runtime.GuiSupport.restoreHeadlessMode(); - } - - - private static void initializeClasses() { - org.evosuite.runtime.classhandling.ClassStateSupport.initializeClasses(ProcessInstanceResourceESTestscaffolding.class.getClassLoader() , - "org.camunda.bpm.cockpit.plugin.resource.AbstractCockpitPluginResource", - "org.camunda.bpm.cockpit.CockpitRuntimeDelegate", - "org.camunda.bpm.webapp.plugin.resource.AbstractAppPluginResource", - "org.camunda.bpm.webapp.AppRuntimeDelegate", - "org.camunda.bpm.cockpit.plugin.resource.AbstractPluginResource", - "org.camunda.bpm.cockpit.db.QueryService", - "org.camunda.bpm.engine.ProcessEngine", - "org.openecomp.camunda.bpmn.plugin.urnmap.resources.ProcessInstanceResource", - "org.camunda.bpm.engine.ProcessEngineServices", - "org.camunda.bpm.cockpit.db.CommandExecutor", - "org.camunda.bpm.cockpit.Cockpit", - "org.openecomp.camunda.bpmn.plugin.urnmap.db.URNData" - ); - } - - private static void resetClasses() { - org.evosuite.runtime.classhandling.ClassResetter.getInstance().setClassLoader(ProcessInstanceResourceESTestscaffolding.class.getClassLoader()); - - org.evosuite.runtime.classhandling.ClassStateSupport.resetClasses( - "org.camunda.bpm.cockpit.Cockpit" - ); - } -} +/** + * Scaffolding file used to store all the setups needed to run + * tests automatically generated by EvoSuite + * Mon Nov 14 13:45:16 GMT 2016 + */ + +package org.openecomp.camunda.bpmn.plugin.urnmap.resources; + +import org.evosuite.runtime.annotation.EvoSuiteClassExclude; +import org.junit.BeforeClass; +import org.junit.Before; +import org.junit.After; +import org.junit.AfterClass; +import org.evosuite.runtime.sandbox.Sandbox; + +@EvoSuiteClassExclude +public class ProcessInstanceResourceESTestscaffolding { + + @org.junit.Rule + public org.evosuite.runtime.vnet.NonFunctionalRequirementRule nfr = new org.evosuite.runtime.vnet.NonFunctionalRequirementRule(); + + private static final java.util.Properties defaultProperties = (java.util.Properties) java.lang.System.getProperties().clone(); + + private org.evosuite.runtime.thread.ThreadStopper threadStopper = new org.evosuite.runtime.thread.ThreadStopper (org.evosuite.runtime.thread.KillSwitchHandler.getInstance(), 3000); + + @BeforeClass + public static void initEvoSuiteFramework() { + org.evosuite.runtime.RuntimeSettings.className = "org.openecomp.camunda.bpmn.plugin.urnmap.resources.ProcessInstanceResource"; + org.evosuite.runtime.GuiSupport.initialize(); + org.evosuite.runtime.RuntimeSettings.maxNumberOfThreads = 100; + org.evosuite.runtime.RuntimeSettings.maxNumberOfIterationsPerLoop = 10000; + org.evosuite.runtime.RuntimeSettings.mockSystemIn = true; + org.evosuite.runtime.RuntimeSettings.sandboxMode = org.evosuite.runtime.sandbox.Sandbox.SandboxMode.RECOMMENDED; + org.evosuite.runtime.sandbox.Sandbox.initializeSecurityManagerForSUT(); + org.evosuite.runtime.classhandling.JDKClassResetter.init(); + initializeClasses(); + org.evosuite.runtime.Runtime.getInstance().resetRuntime(); + } + + @AfterClass + public static void clearEvoSuiteFramework(){ + Sandbox.resetDefaultSecurityManager(); + java.lang.System.setProperties((java.util.Properties) defaultProperties.clone()); + } + + @Before + public void initTestCase(){ + threadStopper.storeCurrentThreads(); + threadStopper.startRecordingTime(); + org.evosuite.runtime.jvm.ShutdownHookHandler.getInstance().initHandler(); + org.evosuite.runtime.sandbox.Sandbox.goingToExecuteSUTCode(); + + org.evosuite.runtime.GuiSupport.setHeadless(); + org.evosuite.runtime.Runtime.getInstance().resetRuntime(); + org.evosuite.runtime.agent.InstrumentingAgent.activate(); + } + + @After + public void doneWithTestCase(){ + threadStopper.killAndJoinClientThreads(); + org.evosuite.runtime.jvm.ShutdownHookHandler.getInstance().safeExecuteAddedHooks(); + org.evosuite.runtime.classhandling.JDKClassResetter.reset(); + resetClasses(); + org.evosuite.runtime.sandbox.Sandbox.doneWithExecutingSUTCode(); + org.evosuite.runtime.agent.InstrumentingAgent.deactivate(); + org.evosuite.runtime.GuiSupport.restoreHeadlessMode(); + } + + + private static void initializeClasses() { + org.evosuite.runtime.classhandling.ClassStateSupport.initializeClasses(ProcessInstanceResourceESTestscaffolding.class.getClassLoader() , + "org.camunda.bpm.cockpit.plugin.resource.AbstractCockpitPluginResource", + "org.camunda.bpm.cockpit.CockpitRuntimeDelegate", + "org.camunda.bpm.webapp.plugin.resource.AbstractAppPluginResource", + "org.camunda.bpm.webapp.AppRuntimeDelegate", + "org.camunda.bpm.cockpit.plugin.resource.AbstractPluginResource", + "org.camunda.bpm.cockpit.db.QueryService", + "org.camunda.bpm.engine.ProcessEngine", + "org.openecomp.camunda.bpmn.plugin.urnmap.resources.ProcessInstanceResource", + "org.camunda.bpm.engine.ProcessEngineServices", + "org.camunda.bpm.cockpit.db.CommandExecutor", + "org.camunda.bpm.cockpit.Cockpit", + "org.openecomp.camunda.bpmn.plugin.urnmap.db.URNData" + ); + } + + private static void resetClasses() { + org.evosuite.runtime.classhandling.ClassResetter.getInstance().setClassLoader(ProcessInstanceResourceESTestscaffolding.class.getClassLoader()); + + org.evosuite.runtime.classhandling.ClassStateSupport.resetClasses( + "org.camunda.bpm.cockpit.Cockpit" + ); + } +} diff --git a/bpmn/MSOURN-plugin/src/test/java/org/openecomp/camunda/bpmn/plugin/urnmap/resources/URNMapPluginRootResourceESTest.java b/bpmn/MSOURN-plugin/src/test/java/org/openecomp/camunda/bpmn/plugin/urnmap/resources/URNMapPluginRootResourceESTest.java index 85a7f341f2..c1dccfcb2b 100644 --- a/bpmn/MSOURN-plugin/src/test/java/org/openecomp/camunda/bpmn/plugin/urnmap/resources/URNMapPluginRootResourceESTest.java +++ b/bpmn/MSOURN-plugin/src/test/java/org/openecomp/camunda/bpmn/plugin/urnmap/resources/URNMapPluginRootResourceESTest.java @@ -1,42 +1,42 @@ -/* - * This file was automatically generated by EvoSuite - * Mon Nov 14 13:48:27 GMT 2016 - */ - -package org.openecomp.camunda.bpmn.plugin.urnmap.resources; - -import org.junit.Test; - -import static org.junit.Assert.*; -import static org.evosuite.shaded.org.mockito.Mockito.*; - -import javax.servlet.ServletContext; -import javax.ws.rs.core.HttpHeaders; -import javax.ws.rs.core.UriInfo; - -import org.camunda.bpm.webapp.plugin.resource.AbstractAppPluginRootResource; -import org.evosuite.runtime.EvoRunner; -import org.evosuite.runtime.EvoRunnerParameters; -import org.evosuite.runtime.ViolatedAssumptionAnswer; -import org.evosuite.runtime.javaee.injection.Injector; -import org.junit.runner.RunWith; -import org.openecomp.camunda.bpmn.plugin.urnmap.resources.URNMapPluginRootResource; -import org.openecomp.camunda.bpmn.plugin.urnmap.resources.URNResource; - -@RunWith(EvoRunner.class) @EvoRunnerParameters(mockJVMNonDeterminism = true, useVFS = true, useVNET = true, resetStaticState = true, useJEE = true) -public class URNMapPluginRootResourceESTest extends URNMapPluginRootResourceESTestscaffolding { - - @Test(timeout = 4000) - public void test0() throws Throwable { - URNMapPluginRootResource uRNMapPluginRootResource0 = new URNMapPluginRootResource(); - HttpHeaders httpHeaders0 = mock(HttpHeaders.class, new ViolatedAssumptionAnswer()); - Injector.inject(uRNMapPluginRootResource0, (Class) AbstractAppPluginRootResource.class, "headers", (Object) httpHeaders0); - ServletContext servletContext0 = mock(ServletContext.class, new ViolatedAssumptionAnswer()); - Injector.inject(uRNMapPluginRootResource0, (Class) AbstractAppPluginRootResource.class, "servletContext", (Object) servletContext0); - UriInfo uriInfo0 = mock(UriInfo.class, new ViolatedAssumptionAnswer()); - Injector.inject(uRNMapPluginRootResource0, (Class) AbstractAppPluginRootResource.class, "uriInfo", (Object) uriInfo0); - Injector.validateBean(uRNMapPluginRootResource0, (Class) URNMapPluginRootResource.class); - URNResource uRNResource0 = uRNMapPluginRootResource0.getProcessInstanceResource("}+njRy')#n?K^"); - assertNotNull(uRNResource0); - } -} +/* + * This file was automatically generated by EvoSuite + * Mon Nov 14 13:48:27 GMT 2016 + */ + +package org.openecomp.camunda.bpmn.plugin.urnmap.resources; + +import org.junit.Test; + +import static org.junit.Assert.*; +import static org.evosuite.shaded.org.mockito.Mockito.*; + +import javax.servlet.ServletContext; +import javax.ws.rs.core.HttpHeaders; +import javax.ws.rs.core.UriInfo; + +import org.camunda.bpm.webapp.plugin.resource.AbstractAppPluginRootResource; +import org.evosuite.runtime.EvoRunner; +import org.evosuite.runtime.EvoRunnerParameters; +import org.evosuite.runtime.ViolatedAssumptionAnswer; +import org.evosuite.runtime.javaee.injection.Injector; +import org.junit.runner.RunWith; +import org.openecomp.camunda.bpmn.plugin.urnmap.resources.URNMapPluginRootResource; +import org.openecomp.camunda.bpmn.plugin.urnmap.resources.URNResource; + +@RunWith(EvoRunner.class) @EvoRunnerParameters(mockJVMNonDeterminism = true, useVFS = true, useVNET = true, resetStaticState = true, useJEE = true) +public class URNMapPluginRootResourceESTest extends URNMapPluginRootResourceESTestscaffolding { + + @Test(timeout = 4000) + public void test0() throws Throwable { + URNMapPluginRootResource uRNMapPluginRootResource0 = new URNMapPluginRootResource(); + HttpHeaders httpHeaders0 = mock(HttpHeaders.class, new ViolatedAssumptionAnswer()); + Injector.inject(uRNMapPluginRootResource0, (Class) AbstractAppPluginRootResource.class, "headers", (Object) httpHeaders0); + ServletContext servletContext0 = mock(ServletContext.class, new ViolatedAssumptionAnswer()); + Injector.inject(uRNMapPluginRootResource0, (Class) AbstractAppPluginRootResource.class, "servletContext", (Object) servletContext0); + UriInfo uriInfo0 = mock(UriInfo.class, new ViolatedAssumptionAnswer()); + Injector.inject(uRNMapPluginRootResource0, (Class) AbstractAppPluginRootResource.class, "uriInfo", (Object) uriInfo0); + Injector.validateBean(uRNMapPluginRootResource0, (Class) URNMapPluginRootResource.class); + URNResource uRNResource0 = uRNMapPluginRootResource0.getProcessInstanceResource("}+njRy')#n?K^"); + assertNotNull(uRNResource0); + } +} diff --git a/bpmn/MSOURN-plugin/src/test/java/org/openecomp/camunda/bpmn/plugin/urnmap/resources/URNMapPluginRootResourceESTestscaffolding.java b/bpmn/MSOURN-plugin/src/test/java/org/openecomp/camunda/bpmn/plugin/urnmap/resources/URNMapPluginRootResourceESTestscaffolding.java index 9b556d7006..1033de9c54 100644 --- a/bpmn/MSOURN-plugin/src/test/java/org/openecomp/camunda/bpmn/plugin/urnmap/resources/URNMapPluginRootResourceESTestscaffolding.java +++ b/bpmn/MSOURN-plugin/src/test/java/org/openecomp/camunda/bpmn/plugin/urnmap/resources/URNMapPluginRootResourceESTestscaffolding.java @@ -1,119 +1,119 @@ -/** - * Scaffolding file used to store all the setups needed to run - * tests automatically generated by EvoSuite - * Mon Nov 14 13:48:27 GMT 2016 - */ - -package org.openecomp.camunda.bpmn.plugin.urnmap.resources; - -import org.evosuite.runtime.annotation.EvoSuiteClassExclude; -import org.junit.BeforeClass; -import org.junit.Before; -import org.junit.After; -import org.junit.AfterClass; -import org.evosuite.runtime.sandbox.Sandbox; - -@EvoSuiteClassExclude -public class URNMapPluginRootResourceESTestscaffolding { - - @org.junit.Rule - public org.evosuite.runtime.vnet.NonFunctionalRequirementRule nfr = new org.evosuite.runtime.vnet.NonFunctionalRequirementRule(); - - private static final java.util.Properties defaultProperties = (java.util.Properties) java.lang.System.getProperties().clone(); - - private org.evosuite.runtime.thread.ThreadStopper threadStopper = new org.evosuite.runtime.thread.ThreadStopper (org.evosuite.runtime.thread.KillSwitchHandler.getInstance(), 3000); - - @BeforeClass - public static void initEvoSuiteFramework() { - org.evosuite.runtime.RuntimeSettings.className = "org.openecomp.camunda.bpmn.plugin.urnmap.resources.URNMapPluginRootResource"; - org.evosuite.runtime.GuiSupport.initialize(); - org.evosuite.runtime.RuntimeSettings.maxNumberOfThreads = 100; - org.evosuite.runtime.RuntimeSettings.maxNumberOfIterationsPerLoop = 10000; - org.evosuite.runtime.RuntimeSettings.mockSystemIn = true; - org.evosuite.runtime.RuntimeSettings.sandboxMode = org.evosuite.runtime.sandbox.Sandbox.SandboxMode.RECOMMENDED; - org.evosuite.runtime.sandbox.Sandbox.initializeSecurityManagerForSUT(); - org.evosuite.runtime.classhandling.JDKClassResetter.init(); - initializeClasses(); - org.evosuite.runtime.Runtime.getInstance().resetRuntime(); - } - - @AfterClass - public static void clearEvoSuiteFramework(){ - Sandbox.resetDefaultSecurityManager(); - java.lang.System.setProperties((java.util.Properties) defaultProperties.clone()); - } - - @Before - public void initTestCase(){ - threadStopper.storeCurrentThreads(); - threadStopper.startRecordingTime(); - org.evosuite.runtime.jvm.ShutdownHookHandler.getInstance().initHandler(); - org.evosuite.runtime.sandbox.Sandbox.goingToExecuteSUTCode(); - - org.evosuite.runtime.GuiSupport.setHeadless(); - org.evosuite.runtime.Runtime.getInstance().resetRuntime(); - org.evosuite.runtime.agent.InstrumentingAgent.activate(); - } - - @After - public void doneWithTestCase(){ - threadStopper.killAndJoinClientThreads(); - org.evosuite.runtime.jvm.ShutdownHookHandler.getInstance().safeExecuteAddedHooks(); - org.evosuite.runtime.classhandling.JDKClassResetter.reset(); - resetClasses(); - org.evosuite.runtime.sandbox.Sandbox.doneWithExecutingSUTCode(); - org.evosuite.runtime.agent.InstrumentingAgent.deactivate(); - org.evosuite.runtime.GuiSupport.restoreHeadlessMode(); - } - - - private static void initializeClasses() { - org.evosuite.runtime.classhandling.ClassStateSupport.initializeClasses(URNMapPluginRootResourceESTestscaffolding.class.getClassLoader() , - "org.camunda.bpm.webapp.plugin.resource.AbstractAppPluginResource", - "org.camunda.bpm.webapp.plugin.spi.AppPlugin", - "org.openecomp.camunda.bpmn.plugin.urnmap.resources.URNResource", - "com.att.eelf.i18n.EELFResourceManager$RESOURCE_TYPES", - "org.camunda.bpm.webapp.plugin.resource.AbstractAppPluginRootResource", - "org.openecomp.mso.logger.MsoLogger$ErrorCode", - "org.camunda.bpm.cockpit.Cockpit", - "com.att.eelf.configuration.EELFLogger", - "org.camunda.bpm.engine.rest.exception.RestException", - "com.att.eelf.configuration.SLF4jWrapper", - "com.att.eelf.i18n.EELFResourceManager", - "org.openecomp.camunda.bpmn.plugin.urnmap.db.URNData", - "org.openecomp.mso.logger.MsoLogger", - "org.openecomp.mso.logger.MessageEnum", - "com.att.eelf.i18n.EELFResolvableErrorEnum", - "org.openecomp.mso.logger.MsoLogger$ResponseCode", - "org.camunda.bpm.cockpit.plugin.resource.AbstractPluginRootResource", - "org.openecomp.mso.entity.MsoRequest", - "org.camunda.bpm.webapp.AppRuntimeDelegate", - "org.openecomp.mso.logger.MsoLogger$StatusCode", - "com.att.eelf.configuration.EELFManager", - "org.openecomp.camunda.bpmn.plugin.urnmap.resources.URNMapPluginRootResource", - "com.att.eelf.i18n.EELFMsgs", - "org.camunda.bpm.cockpit.plugin.resource.AbstractCockpitPluginRootResource", - "com.att.eelf.configuration.EELFLogger$Level", - "org.camunda.bpm.cockpit.plugin.resource.AbstractCockpitPluginResource", - "org.openecomp.mso.logger.MsoLogger$Catalog" - ); - } - - private static void resetClasses() { - org.evosuite.runtime.classhandling.ClassResetter.getInstance().setClassLoader(URNMapPluginRootResourceESTestscaffolding.class.getClassLoader()); - - org.evosuite.runtime.classhandling.ClassStateSupport.resetClasses( - "org.camunda.bpm.cockpit.Cockpit", - "org.openecomp.mso.logger.MsoLogger$Catalog", - "org.openecomp.mso.logger.MsoLogger", - "com.att.eelf.i18n.EELFResourceManager", - "com.att.eelf.i18n.EELFMsgs", - "com.att.eelf.i18n.EELFResourceManager$RESOURCE_TYPES", - "com.att.eelf.configuration.EELFLogger$Level", - "com.att.eelf.configuration.EELFManager", - "org.openecomp.mso.logger.MessageEnum", - "org.openecomp.camunda.bpmn.plugin.urnmap.resources.URNResource", - "org.camunda.bpm.webapp.plugin.resource.AbstractAppPluginRootResource" - ); - } -} +/** + * Scaffolding file used to store all the setups needed to run + * tests automatically generated by EvoSuite + * Mon Nov 14 13:48:27 GMT 2016 + */ + +package org.openecomp.camunda.bpmn.plugin.urnmap.resources; + +import org.evosuite.runtime.annotation.EvoSuiteClassExclude; +import org.junit.BeforeClass; +import org.junit.Before; +import org.junit.After; +import org.junit.AfterClass; +import org.evosuite.runtime.sandbox.Sandbox; + +@EvoSuiteClassExclude +public class URNMapPluginRootResourceESTestscaffolding { + + @org.junit.Rule + public org.evosuite.runtime.vnet.NonFunctionalRequirementRule nfr = new org.evosuite.runtime.vnet.NonFunctionalRequirementRule(); + + private static final java.util.Properties defaultProperties = (java.util.Properties) java.lang.System.getProperties().clone(); + + private org.evosuite.runtime.thread.ThreadStopper threadStopper = new org.evosuite.runtime.thread.ThreadStopper (org.evosuite.runtime.thread.KillSwitchHandler.getInstance(), 3000); + + @BeforeClass + public static void initEvoSuiteFramework() { + org.evosuite.runtime.RuntimeSettings.className = "org.openecomp.camunda.bpmn.plugin.urnmap.resources.URNMapPluginRootResource"; + org.evosuite.runtime.GuiSupport.initialize(); + org.evosuite.runtime.RuntimeSettings.maxNumberOfThreads = 100; + org.evosuite.runtime.RuntimeSettings.maxNumberOfIterationsPerLoop = 10000; + org.evosuite.runtime.RuntimeSettings.mockSystemIn = true; + org.evosuite.runtime.RuntimeSettings.sandboxMode = org.evosuite.runtime.sandbox.Sandbox.SandboxMode.RECOMMENDED; + org.evosuite.runtime.sandbox.Sandbox.initializeSecurityManagerForSUT(); + org.evosuite.runtime.classhandling.JDKClassResetter.init(); + initializeClasses(); + org.evosuite.runtime.Runtime.getInstance().resetRuntime(); + } + + @AfterClass + public static void clearEvoSuiteFramework(){ + Sandbox.resetDefaultSecurityManager(); + java.lang.System.setProperties((java.util.Properties) defaultProperties.clone()); + } + + @Before + public void initTestCase(){ + threadStopper.storeCurrentThreads(); + threadStopper.startRecordingTime(); + org.evosuite.runtime.jvm.ShutdownHookHandler.getInstance().initHandler(); + org.evosuite.runtime.sandbox.Sandbox.goingToExecuteSUTCode(); + + org.evosuite.runtime.GuiSupport.setHeadless(); + org.evosuite.runtime.Runtime.getInstance().resetRuntime(); + org.evosuite.runtime.agent.InstrumentingAgent.activate(); + } + + @After + public void doneWithTestCase(){ + threadStopper.killAndJoinClientThreads(); + org.evosuite.runtime.jvm.ShutdownHookHandler.getInstance().safeExecuteAddedHooks(); + org.evosuite.runtime.classhandling.JDKClassResetter.reset(); + resetClasses(); + org.evosuite.runtime.sandbox.Sandbox.doneWithExecutingSUTCode(); + org.evosuite.runtime.agent.InstrumentingAgent.deactivate(); + org.evosuite.runtime.GuiSupport.restoreHeadlessMode(); + } + + + private static void initializeClasses() { + org.evosuite.runtime.classhandling.ClassStateSupport.initializeClasses(URNMapPluginRootResourceESTestscaffolding.class.getClassLoader() , + "org.camunda.bpm.webapp.plugin.resource.AbstractAppPluginResource", + "org.camunda.bpm.webapp.plugin.spi.AppPlugin", + "org.openecomp.camunda.bpmn.plugin.urnmap.resources.URNResource", + "com.att.eelf.i18n.EELFResourceManager$RESOURCE_TYPES", + "org.camunda.bpm.webapp.plugin.resource.AbstractAppPluginRootResource", + "org.openecomp.mso.logger.MsoLogger$ErrorCode", + "org.camunda.bpm.cockpit.Cockpit", + "com.att.eelf.configuration.EELFLogger", + "org.camunda.bpm.engine.rest.exception.RestException", + "com.att.eelf.configuration.SLF4jWrapper", + "com.att.eelf.i18n.EELFResourceManager", + "org.openecomp.camunda.bpmn.plugin.urnmap.db.URNData", + "org.openecomp.mso.logger.MsoLogger", + "org.openecomp.mso.logger.MessageEnum", + "com.att.eelf.i18n.EELFResolvableErrorEnum", + "org.openecomp.mso.logger.MsoLogger$ResponseCode", + "org.camunda.bpm.cockpit.plugin.resource.AbstractPluginRootResource", + "org.openecomp.mso.entity.MsoRequest", + "org.camunda.bpm.webapp.AppRuntimeDelegate", + "org.openecomp.mso.logger.MsoLogger$StatusCode", + "com.att.eelf.configuration.EELFManager", + "org.openecomp.camunda.bpmn.plugin.urnmap.resources.URNMapPluginRootResource", + "com.att.eelf.i18n.EELFMsgs", + "org.camunda.bpm.cockpit.plugin.resource.AbstractCockpitPluginRootResource", + "com.att.eelf.configuration.EELFLogger$Level", + "org.camunda.bpm.cockpit.plugin.resource.AbstractCockpitPluginResource", + "org.openecomp.mso.logger.MsoLogger$Catalog" + ); + } + + private static void resetClasses() { + org.evosuite.runtime.classhandling.ClassResetter.getInstance().setClassLoader(URNMapPluginRootResourceESTestscaffolding.class.getClassLoader()); + + org.evosuite.runtime.classhandling.ClassStateSupport.resetClasses( + "org.camunda.bpm.cockpit.Cockpit", + "org.openecomp.mso.logger.MsoLogger$Catalog", + "org.openecomp.mso.logger.MsoLogger", + "com.att.eelf.i18n.EELFResourceManager", + "com.att.eelf.i18n.EELFMsgs", + "com.att.eelf.i18n.EELFResourceManager$RESOURCE_TYPES", + "com.att.eelf.configuration.EELFLogger$Level", + "com.att.eelf.configuration.EELFManager", + "org.openecomp.mso.logger.MessageEnum", + "org.openecomp.camunda.bpmn.plugin.urnmap.resources.URNResource", + "org.camunda.bpm.webapp.plugin.resource.AbstractAppPluginRootResource" + ); + } +} diff --git a/bpmn/MSOURN-plugin/src/test/java/org/openecomp/camunda/bpmn/plugin/urnmap/resources/URNResourceESTest.java b/bpmn/MSOURN-plugin/src/test/java/org/openecomp/camunda/bpmn/plugin/urnmap/resources/URNResourceESTest.java index b6b5478130..ca0426339a 100644 --- a/bpmn/MSOURN-plugin/src/test/java/org/openecomp/camunda/bpmn/plugin/urnmap/resources/URNResourceESTest.java +++ b/bpmn/MSOURN-plugin/src/test/java/org/openecomp/camunda/bpmn/plugin/urnmap/resources/URNResourceESTest.java @@ -1,165 +1,165 @@ -/* - * This file was automatically generated by EvoSuite - * Mon Nov 14 13:47:41 GMT 2016 - */ - -package org.openecomp.camunda.bpmn.plugin.urnmap.resources; - -import org.junit.Test; - -import static org.junit.Assert.*; -import static org.evosuite.shaded.org.mockito.Mockito.*; -import static org.evosuite.runtime.EvoAssertions.*; - -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.util.List; -import java.util.NoSuchElementException; - -import org.evosuite.runtime.EvoRunner; -import org.evosuite.runtime.EvoRunnerParameters; -import org.evosuite.runtime.PrivateAccess; -import org.evosuite.runtime.ViolatedAssumptionAnswer; -import org.junit.runner.RunWith; -import org.openecomp.camunda.bpmn.plugin.urnmap.db.URNData; -import org.openecomp.camunda.bpmn.plugin.urnmap.resources.URNResource; - -@RunWith(EvoRunner.class) @EvoRunnerParameters(mockJVMNonDeterminism = true, useVFS = true, useVNET = true, resetStaticState = true, useJEE = true) -public class URNResourceESTest extends URNResourceESTestscaffolding { - - @Test(timeout = 4000) - public void test00() throws Throwable { - URNResource uRNResource0 = new URNResource("pE|b"); - PreparedStatement preparedStatement0 = mock(PreparedStatement.class, new ViolatedAssumptionAnswer()); - doReturn((-3202)).when(preparedStatement0).executeUpdate(); - Connection connection0 = mock(Connection.class, new ViolatedAssumptionAnswer()); - doReturn("").when(connection0).toString(); - doReturn(preparedStatement0).when(connection0).prepareStatement(anyString()); - PrivateAccess.setVariable((Class) URNResource.class, uRNResource0, "conn", (Object) connection0); - uRNResource0.insertNewRow("pE|b"); - } - - @Test(timeout = 4000) - public void test01() throws Throwable { - URNResource uRNResource0 = new URNResource("pE|b"); - Connection connection0 = mock(Connection.class, new ViolatedAssumptionAnswer()); - doReturn((String) null).when(connection0).toString(); - doReturn((PreparedStatement) null).when(connection0).prepareStatement(anyString()); - PrivateAccess.setVariable((Class) URNResource.class, uRNResource0, "conn", (Object) connection0); - uRNResource0.insertNewRow("pE|b"); - } - - @Test(timeout = 4000) - public void test02() throws Throwable { - URNResource uRNResource0 = new URNResource(""); - List list0 = uRNResource0.getUrnDataMap(); - assertTrue(list0.isEmpty()); - } - - @Test(timeout = 4000) - public void test03() throws Throwable { - URNResource uRNResource0 = new URNResource("pE|b"); - PreparedStatement preparedStatement0 = mock(PreparedStatement.class, new ViolatedAssumptionAnswer()); - doReturn((-3202)).when(preparedStatement0).executeUpdate(); - Connection connection0 = mock(Connection.class, new ViolatedAssumptionAnswer()); - doReturn("").when(connection0).toString(); - doReturn(preparedStatement0).when(connection0).prepareStatement(anyString()); - PrivateAccess.setVariable((Class) URNResource.class, uRNResource0, "conn", (Object) connection0); - URNData uRNData0 = new URNData(); - uRNResource0.getPersistData(uRNData0); - assertNull(uRNData0.getVer_()); - } - - @Test(timeout = 4000) - public void test04() throws Throwable { - URNResource uRNResource0 = new URNResource("pE|b"); - Connection connection0 = mock(Connection.class, new ViolatedAssumptionAnswer()); - doReturn((String) null).when(connection0).toString(); - doReturn((PreparedStatement) null).when(connection0).prepareStatement(anyString()); - PrivateAccess.setVariable((Class) URNResource.class, uRNResource0, "conn", (Object) connection0); - URNData uRNData0 = new URNData(); - uRNResource0.getPersistData(uRNData0); - assertNull(uRNData0.getVer_()); - } - - @Test(timeout = 4000) - public void test05() throws Throwable { - URNResource uRNResource0 = new URNResource("LR6iOYH?>Bg%1-x=lK"); - // Undeclared exception! - try { - uRNResource0.insertNewRow("LR6iOYH?>Bg%1-x=lK"); - fail("Expecting exception: NoSuchElementException"); - - } catch(NoSuchElementException e) { - // - // no message in exception (getMessage() returned null) - // - verifyException("java.util.StringTokenizer", e); - } - } - - @Test(timeout = 4000) - public void test06() throws Throwable { - URNResource uRNResource0 = new URNResource(""); - // Undeclared exception! - try { - uRNResource0.insertNewRow((String) null); - fail("Expecting exception: NullPointerException"); - - } catch(NullPointerException e) { - // - // no message in exception (getMessage() returned null) - // - verifyException("java.util.StringTokenizer", e); - } - } - - @Test(timeout = 4000) - public void test07() throws Throwable { - URNResource uRNResource0 = new URNResource("pE|b"); - // Undeclared exception! - try { - uRNResource0.getUrnDataMapOLD(); - fail("Expecting exception: NullPointerException"); - - } catch(NullPointerException e) { - // - // no message in exception (getMessage() returned null) - // - verifyException("org.camunda.bpm.cockpit.Cockpit", e); - } - } - - @Test(timeout = 4000) - public void test08() throws Throwable { - URNResource uRNResource0 = new URNResource(""); - Connection connection0 = uRNResource0.getDBConnection(); - assertNull(connection0); - } - - @Test(timeout = 4000) - public void test09() throws Throwable { - URNResource uRNResource0 = new URNResource("pE|b"); - Connection connection0 = mock(Connection.class, new ViolatedAssumptionAnswer()); - doReturn((String) null).when(connection0).toString(); - PrivateAccess.setVariable((Class) URNResource.class, uRNResource0, "conn", (Object) connection0); - Connection connection1 = uRNResource0.getDBConnection(); - assertSame(connection1, connection0); - } - - @Test(timeout = 4000) - public void test10() throws Throwable { - URNResource uRNResource0 = new URNResource("pE|b"); - ResultSet resultSet0 = mock(ResultSet.class, new ViolatedAssumptionAnswer()); - doReturn(false).when(resultSet0).next(); - PreparedStatement preparedStatement0 = mock(PreparedStatement.class, new ViolatedAssumptionAnswer()); - doReturn(resultSet0).when(preparedStatement0).executeQuery(); - Connection connection0 = mock(Connection.class, new ViolatedAssumptionAnswer()); - doReturn("").when(connection0).toString(); - doReturn(preparedStatement0).when(connection0).prepareStatement(anyString()); - PrivateAccess.setVariable((Class) URNResource.class, uRNResource0, "conn", (Object) connection0); - List list0 = uRNResource0.getUrnDataMap(); - assertTrue(list0.isEmpty()); - } -} +/* + * This file was automatically generated by EvoSuite + * Mon Nov 14 13:47:41 GMT 2016 + */ + +package org.openecomp.camunda.bpmn.plugin.urnmap.resources; + +import org.junit.Test; + +import static org.junit.Assert.*; +import static org.evosuite.shaded.org.mockito.Mockito.*; +import static org.evosuite.runtime.EvoAssertions.*; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.util.List; +import java.util.NoSuchElementException; + +import org.evosuite.runtime.EvoRunner; +import org.evosuite.runtime.EvoRunnerParameters; +import org.evosuite.runtime.PrivateAccess; +import org.evosuite.runtime.ViolatedAssumptionAnswer; +import org.junit.runner.RunWith; +import org.openecomp.camunda.bpmn.plugin.urnmap.db.URNData; +import org.openecomp.camunda.bpmn.plugin.urnmap.resources.URNResource; + +@RunWith(EvoRunner.class) @EvoRunnerParameters(mockJVMNonDeterminism = true, useVFS = true, useVNET = true, resetStaticState = true, useJEE = true) +public class URNResourceESTest extends URNResourceESTestscaffolding { + + @Test(timeout = 4000) + public void test00() throws Throwable { + URNResource uRNResource0 = new URNResource("pE|b"); + PreparedStatement preparedStatement0 = mock(PreparedStatement.class, new ViolatedAssumptionAnswer()); + doReturn((-3202)).when(preparedStatement0).executeUpdate(); + Connection connection0 = mock(Connection.class, new ViolatedAssumptionAnswer()); + doReturn("").when(connection0).toString(); + doReturn(preparedStatement0).when(connection0).prepareStatement(anyString()); + PrivateAccess.setVariable((Class) URNResource.class, uRNResource0, "conn", (Object) connection0); + uRNResource0.insertNewRow("pE|b"); + } + + @Test(timeout = 4000) + public void test01() throws Throwable { + URNResource uRNResource0 = new URNResource("pE|b"); + Connection connection0 = mock(Connection.class, new ViolatedAssumptionAnswer()); + doReturn((String) null).when(connection0).toString(); + doReturn((PreparedStatement) null).when(connection0).prepareStatement(anyString()); + PrivateAccess.setVariable((Class) URNResource.class, uRNResource0, "conn", (Object) connection0); + uRNResource0.insertNewRow("pE|b"); + } + + @Test(timeout = 4000) + public void test02() throws Throwable { + URNResource uRNResource0 = new URNResource(""); + List list0 = uRNResource0.getUrnDataMap(); + assertTrue(list0.isEmpty()); + } + + @Test(timeout = 4000) + public void test03() throws Throwable { + URNResource uRNResource0 = new URNResource("pE|b"); + PreparedStatement preparedStatement0 = mock(PreparedStatement.class, new ViolatedAssumptionAnswer()); + doReturn((-3202)).when(preparedStatement0).executeUpdate(); + Connection connection0 = mock(Connection.class, new ViolatedAssumptionAnswer()); + doReturn("").when(connection0).toString(); + doReturn(preparedStatement0).when(connection0).prepareStatement(anyString()); + PrivateAccess.setVariable((Class) URNResource.class, uRNResource0, "conn", (Object) connection0); + URNData uRNData0 = new URNData(); + uRNResource0.getPersistData(uRNData0); + assertNull(uRNData0.getVer_()); + } + + @Test(timeout = 4000) + public void test04() throws Throwable { + URNResource uRNResource0 = new URNResource("pE|b"); + Connection connection0 = mock(Connection.class, new ViolatedAssumptionAnswer()); + doReturn((String) null).when(connection0).toString(); + doReturn((PreparedStatement) null).when(connection0).prepareStatement(anyString()); + PrivateAccess.setVariable((Class) URNResource.class, uRNResource0, "conn", (Object) connection0); + URNData uRNData0 = new URNData(); + uRNResource0.getPersistData(uRNData0); + assertNull(uRNData0.getVer_()); + } + + @Test(timeout = 4000) + public void test05() throws Throwable { + URNResource uRNResource0 = new URNResource("LR6iOYH?>Bg%1-x=lK"); + // Undeclared exception! + try { + uRNResource0.insertNewRow("LR6iOYH?>Bg%1-x=lK"); + fail("Expecting exception: NoSuchElementException"); + + } catch(NoSuchElementException e) { + // + // no message in exception (getMessage() returned null) + // + verifyException("java.util.StringTokenizer", e); + } + } + + @Test(timeout = 4000) + public void test06() throws Throwable { + URNResource uRNResource0 = new URNResource(""); + // Undeclared exception! + try { + uRNResource0.insertNewRow((String) null); + fail("Expecting exception: NullPointerException"); + + } catch(NullPointerException e) { + // + // no message in exception (getMessage() returned null) + // + verifyException("java.util.StringTokenizer", e); + } + } + + @Test(timeout = 4000) + public void test07() throws Throwable { + URNResource uRNResource0 = new URNResource("pE|b"); + // Undeclared exception! + try { + uRNResource0.getUrnDataMapOLD(); + fail("Expecting exception: NullPointerException"); + + } catch(NullPointerException e) { + // + // no message in exception (getMessage() returned null) + // + verifyException("org.camunda.bpm.cockpit.Cockpit", e); + } + } + + @Test(timeout = 4000) + public void test08() throws Throwable { + URNResource uRNResource0 = new URNResource(""); + Connection connection0 = uRNResource0.getDBConnection(); + assertNull(connection0); + } + + @Test(timeout = 4000) + public void test09() throws Throwable { + URNResource uRNResource0 = new URNResource("pE|b"); + Connection connection0 = mock(Connection.class, new ViolatedAssumptionAnswer()); + doReturn((String) null).when(connection0).toString(); + PrivateAccess.setVariable((Class) URNResource.class, uRNResource0, "conn", (Object) connection0); + Connection connection1 = uRNResource0.getDBConnection(); + assertSame(connection1, connection0); + } + + @Test(timeout = 4000) + public void test10() throws Throwable { + URNResource uRNResource0 = new URNResource("pE|b"); + ResultSet resultSet0 = mock(ResultSet.class, new ViolatedAssumptionAnswer()); + doReturn(false).when(resultSet0).next(); + PreparedStatement preparedStatement0 = mock(PreparedStatement.class, new ViolatedAssumptionAnswer()); + doReturn(resultSet0).when(preparedStatement0).executeQuery(); + Connection connection0 = mock(Connection.class, new ViolatedAssumptionAnswer()); + doReturn("").when(connection0).toString(); + doReturn(preparedStatement0).when(connection0).prepareStatement(anyString()); + PrivateAccess.setVariable((Class) URNResource.class, uRNResource0, "conn", (Object) connection0); + List list0 = uRNResource0.getUrnDataMap(); + assertTrue(list0.isEmpty()); + } +} diff --git a/bpmn/MSOURN-plugin/src/test/java/org/openecomp/camunda/bpmn/plugin/urnmap/resources/URNResourceESTestscaffolding.java b/bpmn/MSOURN-plugin/src/test/java/org/openecomp/camunda/bpmn/plugin/urnmap/resources/URNResourceESTestscaffolding.java index 61ef8e6c0b..33171b951e 100644 --- a/bpmn/MSOURN-plugin/src/test/java/org/openecomp/camunda/bpmn/plugin/urnmap/resources/URNResourceESTestscaffolding.java +++ b/bpmn/MSOURN-plugin/src/test/java/org/openecomp/camunda/bpmn/plugin/urnmap/resources/URNResourceESTestscaffolding.java @@ -1,400 +1,400 @@ -/** - * Scaffolding file used to store all the setups needed to run - * tests automatically generated by EvoSuite - * Mon Nov 14 13:47:41 GMT 2016 - */ - -package org.openecomp.camunda.bpmn.plugin.urnmap.resources; - -import org.evosuite.runtime.annotation.EvoSuiteClassExclude; -import org.junit.BeforeClass; -import org.junit.Before; -import org.junit.After; -import org.junit.AfterClass; -import org.evosuite.runtime.sandbox.Sandbox; - -@EvoSuiteClassExclude -public class URNResourceESTestscaffolding { - - @org.junit.Rule - public org.evosuite.runtime.vnet.NonFunctionalRequirementRule nfr = new org.evosuite.runtime.vnet.NonFunctionalRequirementRule(); - - private static final java.util.Properties defaultProperties = (java.util.Properties) java.lang.System.getProperties().clone(); - - private org.evosuite.runtime.thread.ThreadStopper threadStopper = new org.evosuite.runtime.thread.ThreadStopper (org.evosuite.runtime.thread.KillSwitchHandler.getInstance(), 3000); - - @BeforeClass - public static void initEvoSuiteFramework() { - org.evosuite.runtime.RuntimeSettings.className = "org.openecomp.camunda.bpmn.plugin.urnmap.resources.URNResource"; - org.evosuite.runtime.GuiSupport.initialize(); - org.evosuite.runtime.RuntimeSettings.maxNumberOfThreads = 100; - org.evosuite.runtime.RuntimeSettings.maxNumberOfIterationsPerLoop = 10000; - org.evosuite.runtime.RuntimeSettings.mockSystemIn = true; - org.evosuite.runtime.RuntimeSettings.sandboxMode = org.evosuite.runtime.sandbox.Sandbox.SandboxMode.RECOMMENDED; - org.evosuite.runtime.sandbox.Sandbox.initializeSecurityManagerForSUT(); - org.evosuite.runtime.classhandling.JDKClassResetter.init(); - initializeClasses(); - org.evosuite.runtime.Runtime.getInstance().resetRuntime(); - } - - @AfterClass - public static void clearEvoSuiteFramework(){ - Sandbox.resetDefaultSecurityManager(); - java.lang.System.setProperties((java.util.Properties) defaultProperties.clone()); - } - - @Before - public void initTestCase(){ - threadStopper.storeCurrentThreads(); - threadStopper.startRecordingTime(); - org.evosuite.runtime.jvm.ShutdownHookHandler.getInstance().initHandler(); - org.evosuite.runtime.sandbox.Sandbox.goingToExecuteSUTCode(); - - org.evosuite.runtime.GuiSupport.setHeadless(); - org.evosuite.runtime.Runtime.getInstance().resetRuntime(); - org.evosuite.runtime.agent.InstrumentingAgent.activate(); - } - - @After - public void doneWithTestCase(){ - threadStopper.killAndJoinClientThreads(); - org.evosuite.runtime.jvm.ShutdownHookHandler.getInstance().safeExecuteAddedHooks(); - org.evosuite.runtime.classhandling.JDKClassResetter.reset(); - resetClasses(); - org.evosuite.runtime.sandbox.Sandbox.doneWithExecutingSUTCode(); - org.evosuite.runtime.agent.InstrumentingAgent.deactivate(); - org.evosuite.runtime.GuiSupport.restoreHeadlessMode(); - } - - - private static void initializeClasses() { - org.evosuite.runtime.classhandling.ClassStateSupport.initializeClasses(URNResourceESTestscaffolding.class.getClassLoader() , - "org.h2.store.LobStorage", - "com.mysql.jdbc.VersionedStringProperty", - "com.mysql.jdbc.StatementInterceptorV2", - "com.mysql.jdbc.ConnectionPropertiesImpl$ConnectionProperty", - "org.h2.engine.SessionInterface", - "org.h2.index.BaseIndex", - "com.mysql.jdbc.ConnectionPropertiesImpl$LongConnectionProperty", - "org.h2.store.fs.FileNioMemData", - "org.h2.store.fs.FileNioMem", - "org.h2.store.fs.FilePathCrypt$FileCrypt", - "org.h2.result.Row", - "org.h2.engine.RightOwner", - "org.h2.table.TableView", - "com.mysql.jdbc.JDBC4ClientInfoProvider", - "com.mysql.jdbc.CachedResultSetMetaData", - "org.h2.store.fs.FileMem$1", - "com.mysql.jdbc.ConnectionFeatureNotAvailableException", - "org.h2.security.BlockCipher", - "org.h2.command.CommandInterface", - "com.mysql.jdbc.MysqlIO", - "com.mysql.jdbc.Connection", - "com.att.eelf.i18n.EELFMsgs", - "com.mysql.jdbc.ConnectionPropertiesImpl", - "org.h2.constant.DbSettings", - "com.mysql.jdbc.SingleByteCharsetConverter", - "com.mysql.jdbc.PingTarget", - "org.h2.index.PageIndex", - "org.h2.util.BitField", - "org.h2.value.ValueNull", - "org.h2.value.ValueShort", - "com.mysql.jdbc.SocketFactory", - "org.h2.value.ValueDecimal", - "com.mysql.jdbc.PacketTooBigException", - "com.mysql.jdbc.log.StandardLogger", - "com.mysql.jdbc.ConnectionImpl$3", - "com.mysql.jdbc.ConnectionImpl$2", - "com.mysql.jdbc.ConnectionImpl$5", - "com.mysql.jdbc.ConnectionImpl$4", - "com.mysql.jdbc.ConnectionImpl$7", - "com.mysql.jdbc.ConnectionImpl$6", - "org.h2.util.SmallLRUCache", - "org.h2.mvstore.Chunk", - "com.mysql.jdbc.ConnectionImpl$9", - "com.mysql.jdbc.ConnectionImpl$8", - "com.mysql.jdbc.log.Log", - "com.mysql.jdbc.ConnectionPropertiesImpl$MemorySizeConnectionProperty", - "com.mysql.jdbc.StringUtils", - "org.h2.mvstore.MVStore", - "org.h2.engine.DbObjectBase", - "org.h2.store.FileLock", - "com.mysql.jdbc.ResultSetImpl", - "org.h2.schema.Sequence", - "org.h2.value.Value", - "org.h2.store.fs.FilePathMem", - "com.mysql.jdbc.ConnectionPropertiesImpl$BooleanConnectionProperty", - "org.h2.store.fs.FilePath", - "org.h2.engine.DatabaseCloser", - "org.h2.expression.ExpressionColumn", - "com.mysql.jdbc.Statement", - "com.mysql.jdbc.Buffer", - "org.h2.store.fs.FilePathNioMem", - "com.mysql.jdbc.ParameterBindings", - "org.h2.security.SecureFileStore", - "org.h2.store.fs.FileMem", - "com.mysql.jdbc.BufferRow", - "org.h2.expression.Expression", - "org.h2.store.fs.FileSplit", - "org.h2.util.Utils$1", - "org.h2.value.CompareMode", - "org.h2.util.Utils", - "com.mysql.jdbc.exceptions.MySQLTimeoutException", - "org.h2.command.dml.SetTypes", - "org.openecomp.mso.logger.MsoLogger$ErrorCode", - "org.h2.jdbcx.JdbcDataSourceFactory", - "com.mysql.jdbc.Util", - "org.camunda.bpm.cockpit.Cockpit", - "org.h2.value.ValueString", - "org.h2.value.ValueJavaObject", - "org.h2.store.PageStore", - "com.mysql.jdbc.ConnectionPropertiesImpl$XmlMap", - "org.h2.schema.Schema", - "org.h2.engine.SettingsBase", - "com.mysql.jdbc.CommunicationsException", - "org.h2.value.CompareModeDefault", - "org.h2.engine.SessionWithState", - "org.h2.table.TableLinkConnection", - "org.h2.message.Trace", - "org.h2.engine.Comment", - "org.h2.util.New", - "org.camunda.bpm.engine.ProcessEngine", - "org.h2.value.ValueInt", - "org.h2.util.CacheWriter", - "com.mysql.jdbc.CompressedInputStream", - "org.h2.result.ResultInterface", - "org.h2.util.StringUtils", - "org.camunda.bpm.cockpit.plugin.resource.AbstractCockpitPluginResource", - "org.h2.table.IndexColumn", - "org.openecomp.mso.logger.MsoLogger$Catalog", - "org.h2.value.CompareModeIcu4J", - "com.mysql.jdbc.ResultSetRow", - "com.mysql.jdbc.ConnectionImpl", - "com.mysql.jdbc.log.NullLogger", - "org.camunda.bpm.cockpit.db.QueryService", - "org.camunda.bpm.engine.ProcessEngineServices", - "com.mysql.jdbc.JDBC4PreparedStatement", - "org.h2.schema.SchemaObject", - "org.h2.store.FileStore", - "org.h2.engine.SessionRemote", - "org.h2.value.ValueUuid", - "org.h2.mvstore.type.DataType", - "org.h2.index.IndexType", - "org.h2.value.ValueDate", - "org.h2.result.SearchRow", - "org.h2.table.Table", - "org.openecomp.camunda.bpmn.plugin.urnmap.db.URNData", - "org.h2.store.fs.FileMemData", - "org.h2.value.ValueFloat", - "org.openecomp.mso.entity.MsoRequest", - "org.camunda.bpm.webapp.AppRuntimeDelegate", - "org.h2.value.Transfer", - "com.mysql.jdbc.Messages", - "org.h2.store.fs.FileDisk", - "com.mysql.jdbc.NetworkResources", - "org.h2.result.RowList", - "com.mysql.jdbc.CallableStatement$CallableStatementParamInfo", - "org.h2.constant.ErrorCode", - "com.mysql.jdbc.Collation", - "org.h2.message.TraceObject", - "com.mysql.jdbc.ByteArrayRow", - "org.h2.store.fs.FileChannelOutputStream", - "org.h2.value.ValueBoolean", - "org.h2.value.ValueLobDb", - "org.h2.util.SourceCompiler", - "org.h2.engine.UserDataType", - "org.h2.constraint.Constraint", - "org.h2.table.TableBase", - "org.h2.jdbcx.JdbcConnectionPool", - "com.mysql.jdbc.authentication.Sha256PasswordPlugin", - "org.h2.value.ValueLong", - "org.h2.engine.DbObject", - "com.mysql.jdbc.JDBC4CallableStatement", - "org.h2.util.SortedProperties", - "org.h2.value.ValueStringIgnoreCase", - "org.h2.table.PlanItem", - "org.h2.jdbcx.JdbcXAConnection", - "org.h2.engine.UserAggregate", - "org.h2.message.DbException", - "com.mysql.jdbc.JDBC4ServerPreparedStatement", - "org.h2.mvstore.MVMapConcurrent", - "com.mysql.jdbc.Extension", - "org.hsqldb.jdbc.JDBCDriver", - "org.h2.engine.Database", - "org.h2.api.DatabaseEventListener", - "org.h2.jdbcx.JdbcDataSource", - "org.h2.schema.TriggerObject", - "org.h2.store.DataReader", - "com.mysql.jdbc.StatementImpl", - "org.hsqldb.jdbc.JDBCDriver$1", - "org.h2.value.ValueBytes", - "org.h2.value.ValueResultSet", - "com.att.eelf.i18n.EELFResolvableErrorEnum", - "org.h2.value.ValueDouble", - "com.mysql.jdbc.CallableStatement$CallableStatementParam", - "org.h2.schema.SchemaObjectBase", - "com.att.eelf.configuration.EELFLogger$Level", - "com.mysql.jdbc.StatementImpl$CancelTask$1", - "org.h2.mvstore.Page", - "org.h2.index.PageDelegateIndex", - "org.h2.store.fs.FileBase", - "com.mysql.jdbc.StatementImpl$CancelTask", - "org.openecomp.camunda.bpmn.plugin.urnmap.resources.URNResource", - "org.h2.message.TraceWriter", - "com.att.eelf.i18n.EELFResourceManager$RESOURCE_TYPES", - "com.att.eelf.configuration.EELFLogger", - "org.h2.table.Column", - "org.h2.engine.Session", - "org.h2.engine.Mode", - "com.mysql.jdbc.exceptions.MySQLTransientException", - "org.h2.engine.Setting", - "org.h2.util.SourceCompiler$1", - "org.h2.value.ValueArray", - "com.mysql.jdbc.MySQLConnection", - "org.h2.util.TempFileDeleter", - "org.h2.store.fs.FileNioMem$1", - "com.mysql.jdbc.AuthenticationPlugin", - "org.h2.util.MathUtils", - "org.h2.mvstore.DataUtils", - "org.h2.store.fs.FilePathSplit", - "org.h2.value.ValueStringFixed", - "com.mysql.jdbc.JDBC4Connection", - "com.mysql.jdbc.NonRegisteringDriver$1", - "org.h2.engine.User", - "org.h2.value.ValueTimestamp", - "org.h2.value.Value$ValueBlob", - "org.h2.store.fs.FilePathWrapper", - "org.h2.constant.SysProperties", - "com.mysql.jdbc.IterateBlock", - "org.h2.table.RegularTable", - "com.mysql.jdbc.Util$RandStructcture", - "org.h2.store.fs.FileChannelInputStream", - "com.mysql.jdbc.exceptions.MySQLStatementCancelledException", - "com.mysql.jdbc.PreparedStatement", - "org.h2.compress.Compressor", - "com.mysql.jdbc.util.LRUCache", - "com.mysql.jdbc.util.ReadAheadInputStream", - "org.h2.index.Index", - "com.mysql.jdbc.MysqlDataTruncation", - "com.mysql.jdbc.CharsetMapping", - "org.h2.store.fs.FilePathDisk", - "org.h2.mvstore.MVMap", - "com.mysql.jdbc.Field", - "com.att.eelf.configuration.SLF4jWrapper", - "com.mysql.jdbc.PreparedStatement$BatchVisitor", - "org.h2.store.DataHandler", - "org.h2.jdbc.JdbcConnection", - "org.openecomp.mso.logger.MsoLogger", - "com.mysql.jdbc.ConnectionPropertiesImpl$StringConnectionProperty", - "com.mysql.jdbc.ConnectionProperties", - "org.h2.Driver", - "org.h2.engine.Role", - "com.mysql.jdbc.Driver", - "org.h2.value.ValueByte", - "com.mysql.jdbc.ServerPreparedStatement", - "org.camunda.bpm.cockpit.db.CommandExecutor", - "com.mysql.jdbc.exceptions.MySQLNonTransientException", - "org.camunda.bpm.cockpit.CockpitRuntimeDelegate", - "org.camunda.bpm.webapp.plugin.resource.AbstractAppPluginResource", - "com.mysql.jdbc.MysqlSavepoint", - "com.mysql.jdbc.CallableStatement", - "com.mysql.jdbc.RowData", - "org.h2.value.Value$ValueClob", - "com.att.eelf.i18n.EELFResourceManager", - "org.h2.value.ValueJavaObject$NotSerialized", - "org.h2.value.CaseInsensitiveMap", - "com.mysql.jdbc.CallableStatement$CallableStatementParamInfoJDBC3", - "org.h2.util.IOUtils", - "com.mysql.jdbc.PreparedStatement$ParseInfo", - "org.h2.message.TraceSystem", - "org.openecomp.mso.logger.MessageEnum", - "org.openecomp.mso.logger.MsoLogger$ResponseCode", - "org.openecomp.mso.logger.MsoLogger$StatusCode", - "com.att.eelf.configuration.EELFManager", - "com.mysql.jdbc.StreamingNotifiable", - "com.mysql.jdbc.ResultSetInternalMethods", - "org.h2.command.Prepared", - "com.mysql.jdbc.ConnectionPropertiesImpl$IntegerConnectionProperty", - "com.mysql.jdbc.NonRegisteringDriver", - "org.h2.jdbc.JdbcSQLException", - "org.h2.mvstore.MVMap$MapBuilder", - "org.h2.engine.ConnectionInfo", - "com.att.eelf.i18n.EELFResourceManager$1", - "com.mysql.jdbc.ExceptionInterceptor", - "org.h2.value.ValueTime" - ); - } - - private static void resetClasses() { - org.evosuite.runtime.classhandling.ClassResetter.getInstance().setClassLoader(URNResourceESTestscaffolding.class.getClassLoader()); - - org.evosuite.runtime.classhandling.ClassStateSupport.resetClasses( - "org.openecomp.mso.logger.MsoLogger$Catalog", - "org.openecomp.mso.logger.MsoLogger", - "com.att.eelf.i18n.EELFResourceManager", - "com.att.eelf.i18n.EELFMsgs", - "com.att.eelf.i18n.EELFResourceManager$RESOURCE_TYPES", - "com.att.eelf.configuration.EELFLogger$Level", - "com.att.eelf.configuration.EELFManager", - "org.openecomp.mso.logger.MessageEnum", - "org.openecomp.camunda.bpmn.plugin.urnmap.resources.URNResource", - "org.camunda.bpm.cockpit.Cockpit", - "org.h2.jdbcx.JdbcConnectionPool", - "org.h2.message.TraceObject", - "com.mysql.jdbc.NonRegisteringDriver", - "com.mysql.jdbc.Driver", - "org.hsqldb.jdbc.JDBCDriver", - "org.h2.Driver", - "org.h2.jdbcx.JdbcDataSource", - "org.h2.jdbcx.JdbcDataSourceFactory", - "org.h2.message.TraceSystem", - "org.h2.util.Utils", - "org.h2.util.MathUtils", - "org.h2.constant.SysProperties", - "org.h2.message.Trace", - "org.h2.util.StringUtils", - "org.h2.value.Value", - "org.h2.value.ValueDecimal", - "org.h2.jdbcx.JdbcXAConnection", - "org.h2.mvstore.MVStore", - "com.mysql.jdbc.Messages", - "com.mysql.jdbc.ConnectionPropertiesImpl", - "com.mysql.jdbc.Util", - "com.mysql.jdbc.ConnectionImpl", - "com.mysql.jdbc.JDBC4Connection", - "com.mysql.jdbc.ConnectionPropertiesImpl$ConnectionProperty", - "com.mysql.jdbc.ConnectionPropertiesImpl$BooleanConnectionProperty", - "com.mysql.jdbc.ConnectionPropertiesImpl$IntegerConnectionProperty", - "com.mysql.jdbc.ConnectionPropertiesImpl$MemorySizeConnectionProperty", - "com.mysql.jdbc.ConnectionPropertiesImpl$StringConnectionProperty", - "com.mysql.jdbc.ConnectionPropertiesImpl$LongConnectionProperty", - "com.mysql.jdbc.StringUtils", - "com.mysql.jdbc.CharsetMapping", - "com.mysql.jdbc.log.StandardLogger", - "org.h2.engine.SessionRemote", - "org.h2.mvstore.DataUtils", - "org.h2.message.DbException", - "org.h2.constant.ErrorCode", - "org.h2.jdbc.JdbcSQLException", - "org.h2.command.dml.SetTypes", - "org.h2.engine.ConnectionInfo", - "org.h2.engine.Database", - "org.h2.util.BitField", - "org.h2.engine.Mode", - "org.h2.store.fs.FilePath", - "org.h2.store.fs.FilePathDisk", - "org.h2.store.fs.FilePathMem", - "org.h2.store.fs.FilePathNioMem", - "org.h2.store.fs.FilePathSplit", - "org.h2.constant.DbSettings", - "org.h2.value.CompareMode", - "org.h2.store.FileLock", - "org.h2.util.SortedProperties", - "org.h2.table.Table", - "com.mysql.jdbc.StatementImpl", - "com.mysql.jdbc.PreparedStatement", - "com.mysql.jdbc.MysqlIO", - "com.mysql.jdbc.CallableStatement" - ); - } -} +/** + * Scaffolding file used to store all the setups needed to run + * tests automatically generated by EvoSuite + * Mon Nov 14 13:47:41 GMT 2016 + */ + +package org.openecomp.camunda.bpmn.plugin.urnmap.resources; + +import org.evosuite.runtime.annotation.EvoSuiteClassExclude; +import org.junit.BeforeClass; +import org.junit.Before; +import org.junit.After; +import org.junit.AfterClass; +import org.evosuite.runtime.sandbox.Sandbox; + +@EvoSuiteClassExclude +public class URNResourceESTestscaffolding { + + @org.junit.Rule + public org.evosuite.runtime.vnet.NonFunctionalRequirementRule nfr = new org.evosuite.runtime.vnet.NonFunctionalRequirementRule(); + + private static final java.util.Properties defaultProperties = (java.util.Properties) java.lang.System.getProperties().clone(); + + private org.evosuite.runtime.thread.ThreadStopper threadStopper = new org.evosuite.runtime.thread.ThreadStopper (org.evosuite.runtime.thread.KillSwitchHandler.getInstance(), 3000); + + @BeforeClass + public static void initEvoSuiteFramework() { + org.evosuite.runtime.RuntimeSettings.className = "org.openecomp.camunda.bpmn.plugin.urnmap.resources.URNResource"; + org.evosuite.runtime.GuiSupport.initialize(); + org.evosuite.runtime.RuntimeSettings.maxNumberOfThreads = 100; + org.evosuite.runtime.RuntimeSettings.maxNumberOfIterationsPerLoop = 10000; + org.evosuite.runtime.RuntimeSettings.mockSystemIn = true; + org.evosuite.runtime.RuntimeSettings.sandboxMode = org.evosuite.runtime.sandbox.Sandbox.SandboxMode.RECOMMENDED; + org.evosuite.runtime.sandbox.Sandbox.initializeSecurityManagerForSUT(); + org.evosuite.runtime.classhandling.JDKClassResetter.init(); + initializeClasses(); + org.evosuite.runtime.Runtime.getInstance().resetRuntime(); + } + + @AfterClass + public static void clearEvoSuiteFramework(){ + Sandbox.resetDefaultSecurityManager(); + java.lang.System.setProperties((java.util.Properties) defaultProperties.clone()); + } + + @Before + public void initTestCase(){ + threadStopper.storeCurrentThreads(); + threadStopper.startRecordingTime(); + org.evosuite.runtime.jvm.ShutdownHookHandler.getInstance().initHandler(); + org.evosuite.runtime.sandbox.Sandbox.goingToExecuteSUTCode(); + + org.evosuite.runtime.GuiSupport.setHeadless(); + org.evosuite.runtime.Runtime.getInstance().resetRuntime(); + org.evosuite.runtime.agent.InstrumentingAgent.activate(); + } + + @After + public void doneWithTestCase(){ + threadStopper.killAndJoinClientThreads(); + org.evosuite.runtime.jvm.ShutdownHookHandler.getInstance().safeExecuteAddedHooks(); + org.evosuite.runtime.classhandling.JDKClassResetter.reset(); + resetClasses(); + org.evosuite.runtime.sandbox.Sandbox.doneWithExecutingSUTCode(); + org.evosuite.runtime.agent.InstrumentingAgent.deactivate(); + org.evosuite.runtime.GuiSupport.restoreHeadlessMode(); + } + + + private static void initializeClasses() { + org.evosuite.runtime.classhandling.ClassStateSupport.initializeClasses(URNResourceESTestscaffolding.class.getClassLoader() , + "org.h2.store.LobStorage", + "com.mysql.jdbc.VersionedStringProperty", + "com.mysql.jdbc.StatementInterceptorV2", + "com.mysql.jdbc.ConnectionPropertiesImpl$ConnectionProperty", + "org.h2.engine.SessionInterface", + "org.h2.index.BaseIndex", + "com.mysql.jdbc.ConnectionPropertiesImpl$LongConnectionProperty", + "org.h2.store.fs.FileNioMemData", + "org.h2.store.fs.FileNioMem", + "org.h2.store.fs.FilePathCrypt$FileCrypt", + "org.h2.result.Row", + "org.h2.engine.RightOwner", + "org.h2.table.TableView", + "com.mysql.jdbc.JDBC4ClientInfoProvider", + "com.mysql.jdbc.CachedResultSetMetaData", + "org.h2.store.fs.FileMem$1", + "com.mysql.jdbc.ConnectionFeatureNotAvailableException", + "org.h2.security.BlockCipher", + "org.h2.command.CommandInterface", + "com.mysql.jdbc.MysqlIO", + "com.mysql.jdbc.Connection", + "com.att.eelf.i18n.EELFMsgs", + "com.mysql.jdbc.ConnectionPropertiesImpl", + "org.h2.constant.DbSettings", + "com.mysql.jdbc.SingleByteCharsetConverter", + "com.mysql.jdbc.PingTarget", + "org.h2.index.PageIndex", + "org.h2.util.BitField", + "org.h2.value.ValueNull", + "org.h2.value.ValueShort", + "com.mysql.jdbc.SocketFactory", + "org.h2.value.ValueDecimal", + "com.mysql.jdbc.PacketTooBigException", + "com.mysql.jdbc.log.StandardLogger", + "com.mysql.jdbc.ConnectionImpl$3", + "com.mysql.jdbc.ConnectionImpl$2", + "com.mysql.jdbc.ConnectionImpl$5", + "com.mysql.jdbc.ConnectionImpl$4", + "com.mysql.jdbc.ConnectionImpl$7", + "com.mysql.jdbc.ConnectionImpl$6", + "org.h2.util.SmallLRUCache", + "org.h2.mvstore.Chunk", + "com.mysql.jdbc.ConnectionImpl$9", + "com.mysql.jdbc.ConnectionImpl$8", + "com.mysql.jdbc.log.Log", + "com.mysql.jdbc.ConnectionPropertiesImpl$MemorySizeConnectionProperty", + "com.mysql.jdbc.StringUtils", + "org.h2.mvstore.MVStore", + "org.h2.engine.DbObjectBase", + "org.h2.store.FileLock", + "com.mysql.jdbc.ResultSetImpl", + "org.h2.schema.Sequence", + "org.h2.value.Value", + "org.h2.store.fs.FilePathMem", + "com.mysql.jdbc.ConnectionPropertiesImpl$BooleanConnectionProperty", + "org.h2.store.fs.FilePath", + "org.h2.engine.DatabaseCloser", + "org.h2.expression.ExpressionColumn", + "com.mysql.jdbc.Statement", + "com.mysql.jdbc.Buffer", + "org.h2.store.fs.FilePathNioMem", + "com.mysql.jdbc.ParameterBindings", + "org.h2.security.SecureFileStore", + "org.h2.store.fs.FileMem", + "com.mysql.jdbc.BufferRow", + "org.h2.expression.Expression", + "org.h2.store.fs.FileSplit", + "org.h2.util.Utils$1", + "org.h2.value.CompareMode", + "org.h2.util.Utils", + "com.mysql.jdbc.exceptions.MySQLTimeoutException", + "org.h2.command.dml.SetTypes", + "org.openecomp.mso.logger.MsoLogger$ErrorCode", + "org.h2.jdbcx.JdbcDataSourceFactory", + "com.mysql.jdbc.Util", + "org.camunda.bpm.cockpit.Cockpit", + "org.h2.value.ValueString", + "org.h2.value.ValueJavaObject", + "org.h2.store.PageStore", + "com.mysql.jdbc.ConnectionPropertiesImpl$XmlMap", + "org.h2.schema.Schema", + "org.h2.engine.SettingsBase", + "com.mysql.jdbc.CommunicationsException", + "org.h2.value.CompareModeDefault", + "org.h2.engine.SessionWithState", + "org.h2.table.TableLinkConnection", + "org.h2.message.Trace", + "org.h2.engine.Comment", + "org.h2.util.New", + "org.camunda.bpm.engine.ProcessEngine", + "org.h2.value.ValueInt", + "org.h2.util.CacheWriter", + "com.mysql.jdbc.CompressedInputStream", + "org.h2.result.ResultInterface", + "org.h2.util.StringUtils", + "org.camunda.bpm.cockpit.plugin.resource.AbstractCockpitPluginResource", + "org.h2.table.IndexColumn", + "org.openecomp.mso.logger.MsoLogger$Catalog", + "org.h2.value.CompareModeIcu4J", + "com.mysql.jdbc.ResultSetRow", + "com.mysql.jdbc.ConnectionImpl", + "com.mysql.jdbc.log.NullLogger", + "org.camunda.bpm.cockpit.db.QueryService", + "org.camunda.bpm.engine.ProcessEngineServices", + "com.mysql.jdbc.JDBC4PreparedStatement", + "org.h2.schema.SchemaObject", + "org.h2.store.FileStore", + "org.h2.engine.SessionRemote", + "org.h2.value.ValueUuid", + "org.h2.mvstore.type.DataType", + "org.h2.index.IndexType", + "org.h2.value.ValueDate", + "org.h2.result.SearchRow", + "org.h2.table.Table", + "org.openecomp.camunda.bpmn.plugin.urnmap.db.URNData", + "org.h2.store.fs.FileMemData", + "org.h2.value.ValueFloat", + "org.openecomp.mso.entity.MsoRequest", + "org.camunda.bpm.webapp.AppRuntimeDelegate", + "org.h2.value.Transfer", + "com.mysql.jdbc.Messages", + "org.h2.store.fs.FileDisk", + "com.mysql.jdbc.NetworkResources", + "org.h2.result.RowList", + "com.mysql.jdbc.CallableStatement$CallableStatementParamInfo", + "org.h2.constant.ErrorCode", + "com.mysql.jdbc.Collation", + "org.h2.message.TraceObject", + "com.mysql.jdbc.ByteArrayRow", + "org.h2.store.fs.FileChannelOutputStream", + "org.h2.value.ValueBoolean", + "org.h2.value.ValueLobDb", + "org.h2.util.SourceCompiler", + "org.h2.engine.UserDataType", + "org.h2.constraint.Constraint", + "org.h2.table.TableBase", + "org.h2.jdbcx.JdbcConnectionPool", + "com.mysql.jdbc.authentication.Sha256PasswordPlugin", + "org.h2.value.ValueLong", + "org.h2.engine.DbObject", + "com.mysql.jdbc.JDBC4CallableStatement", + "org.h2.util.SortedProperties", + "org.h2.value.ValueStringIgnoreCase", + "org.h2.table.PlanItem", + "org.h2.jdbcx.JdbcXAConnection", + "org.h2.engine.UserAggregate", + "org.h2.message.DbException", + "com.mysql.jdbc.JDBC4ServerPreparedStatement", + "org.h2.mvstore.MVMapConcurrent", + "com.mysql.jdbc.Extension", + "org.hsqldb.jdbc.JDBCDriver", + "org.h2.engine.Database", + "org.h2.api.DatabaseEventListener", + "org.h2.jdbcx.JdbcDataSource", + "org.h2.schema.TriggerObject", + "org.h2.store.DataReader", + "com.mysql.jdbc.StatementImpl", + "org.hsqldb.jdbc.JDBCDriver$1", + "org.h2.value.ValueBytes", + "org.h2.value.ValueResultSet", + "com.att.eelf.i18n.EELFResolvableErrorEnum", + "org.h2.value.ValueDouble", + "com.mysql.jdbc.CallableStatement$CallableStatementParam", + "org.h2.schema.SchemaObjectBase", + "com.att.eelf.configuration.EELFLogger$Level", + "com.mysql.jdbc.StatementImpl$CancelTask$1", + "org.h2.mvstore.Page", + "org.h2.index.PageDelegateIndex", + "org.h2.store.fs.FileBase", + "com.mysql.jdbc.StatementImpl$CancelTask", + "org.openecomp.camunda.bpmn.plugin.urnmap.resources.URNResource", + "org.h2.message.TraceWriter", + "com.att.eelf.i18n.EELFResourceManager$RESOURCE_TYPES", + "com.att.eelf.configuration.EELFLogger", + "org.h2.table.Column", + "org.h2.engine.Session", + "org.h2.engine.Mode", + "com.mysql.jdbc.exceptions.MySQLTransientException", + "org.h2.engine.Setting", + "org.h2.util.SourceCompiler$1", + "org.h2.value.ValueArray", + "com.mysql.jdbc.MySQLConnection", + "org.h2.util.TempFileDeleter", + "org.h2.store.fs.FileNioMem$1", + "com.mysql.jdbc.AuthenticationPlugin", + "org.h2.util.MathUtils", + "org.h2.mvstore.DataUtils", + "org.h2.store.fs.FilePathSplit", + "org.h2.value.ValueStringFixed", + "com.mysql.jdbc.JDBC4Connection", + "com.mysql.jdbc.NonRegisteringDriver$1", + "org.h2.engine.User", + "org.h2.value.ValueTimestamp", + "org.h2.value.Value$ValueBlob", + "org.h2.store.fs.FilePathWrapper", + "org.h2.constant.SysProperties", + "com.mysql.jdbc.IterateBlock", + "org.h2.table.RegularTable", + "com.mysql.jdbc.Util$RandStructcture", + "org.h2.store.fs.FileChannelInputStream", + "com.mysql.jdbc.exceptions.MySQLStatementCancelledException", + "com.mysql.jdbc.PreparedStatement", + "org.h2.compress.Compressor", + "com.mysql.jdbc.util.LRUCache", + "com.mysql.jdbc.util.ReadAheadInputStream", + "org.h2.index.Index", + "com.mysql.jdbc.MysqlDataTruncation", + "com.mysql.jdbc.CharsetMapping", + "org.h2.store.fs.FilePathDisk", + "org.h2.mvstore.MVMap", + "com.mysql.jdbc.Field", + "com.att.eelf.configuration.SLF4jWrapper", + "com.mysql.jdbc.PreparedStatement$BatchVisitor", + "org.h2.store.DataHandler", + "org.h2.jdbc.JdbcConnection", + "org.openecomp.mso.logger.MsoLogger", + "com.mysql.jdbc.ConnectionPropertiesImpl$StringConnectionProperty", + "com.mysql.jdbc.ConnectionProperties", + "org.h2.Driver", + "org.h2.engine.Role", + "com.mysql.jdbc.Driver", + "org.h2.value.ValueByte", + "com.mysql.jdbc.ServerPreparedStatement", + "org.camunda.bpm.cockpit.db.CommandExecutor", + "com.mysql.jdbc.exceptions.MySQLNonTransientException", + "org.camunda.bpm.cockpit.CockpitRuntimeDelegate", + "org.camunda.bpm.webapp.plugin.resource.AbstractAppPluginResource", + "com.mysql.jdbc.MysqlSavepoint", + "com.mysql.jdbc.CallableStatement", + "com.mysql.jdbc.RowData", + "org.h2.value.Value$ValueClob", + "com.att.eelf.i18n.EELFResourceManager", + "org.h2.value.ValueJavaObject$NotSerialized", + "org.h2.value.CaseInsensitiveMap", + "com.mysql.jdbc.CallableStatement$CallableStatementParamInfoJDBC3", + "org.h2.util.IOUtils", + "com.mysql.jdbc.PreparedStatement$ParseInfo", + "org.h2.message.TraceSystem", + "org.openecomp.mso.logger.MessageEnum", + "org.openecomp.mso.logger.MsoLogger$ResponseCode", + "org.openecomp.mso.logger.MsoLogger$StatusCode", + "com.att.eelf.configuration.EELFManager", + "com.mysql.jdbc.StreamingNotifiable", + "com.mysql.jdbc.ResultSetInternalMethods", + "org.h2.command.Prepared", + "com.mysql.jdbc.ConnectionPropertiesImpl$IntegerConnectionProperty", + "com.mysql.jdbc.NonRegisteringDriver", + "org.h2.jdbc.JdbcSQLException", + "org.h2.mvstore.MVMap$MapBuilder", + "org.h2.engine.ConnectionInfo", + "com.att.eelf.i18n.EELFResourceManager$1", + "com.mysql.jdbc.ExceptionInterceptor", + "org.h2.value.ValueTime" + ); + } + + private static void resetClasses() { + org.evosuite.runtime.classhandling.ClassResetter.getInstance().setClassLoader(URNResourceESTestscaffolding.class.getClassLoader()); + + org.evosuite.runtime.classhandling.ClassStateSupport.resetClasses( + "org.openecomp.mso.logger.MsoLogger$Catalog", + "org.openecomp.mso.logger.MsoLogger", + "com.att.eelf.i18n.EELFResourceManager", + "com.att.eelf.i18n.EELFMsgs", + "com.att.eelf.i18n.EELFResourceManager$RESOURCE_TYPES", + "com.att.eelf.configuration.EELFLogger$Level", + "com.att.eelf.configuration.EELFManager", + "org.openecomp.mso.logger.MessageEnum", + "org.openecomp.camunda.bpmn.plugin.urnmap.resources.URNResource", + "org.camunda.bpm.cockpit.Cockpit", + "org.h2.jdbcx.JdbcConnectionPool", + "org.h2.message.TraceObject", + "com.mysql.jdbc.NonRegisteringDriver", + "com.mysql.jdbc.Driver", + "org.hsqldb.jdbc.JDBCDriver", + "org.h2.Driver", + "org.h2.jdbcx.JdbcDataSource", + "org.h2.jdbcx.JdbcDataSourceFactory", + "org.h2.message.TraceSystem", + "org.h2.util.Utils", + "org.h2.util.MathUtils", + "org.h2.constant.SysProperties", + "org.h2.message.Trace", + "org.h2.util.StringUtils", + "org.h2.value.Value", + "org.h2.value.ValueDecimal", + "org.h2.jdbcx.JdbcXAConnection", + "org.h2.mvstore.MVStore", + "com.mysql.jdbc.Messages", + "com.mysql.jdbc.ConnectionPropertiesImpl", + "com.mysql.jdbc.Util", + "com.mysql.jdbc.ConnectionImpl", + "com.mysql.jdbc.JDBC4Connection", + "com.mysql.jdbc.ConnectionPropertiesImpl$ConnectionProperty", + "com.mysql.jdbc.ConnectionPropertiesImpl$BooleanConnectionProperty", + "com.mysql.jdbc.ConnectionPropertiesImpl$IntegerConnectionProperty", + "com.mysql.jdbc.ConnectionPropertiesImpl$MemorySizeConnectionProperty", + "com.mysql.jdbc.ConnectionPropertiesImpl$StringConnectionProperty", + "com.mysql.jdbc.ConnectionPropertiesImpl$LongConnectionProperty", + "com.mysql.jdbc.StringUtils", + "com.mysql.jdbc.CharsetMapping", + "com.mysql.jdbc.log.StandardLogger", + "org.h2.engine.SessionRemote", + "org.h2.mvstore.DataUtils", + "org.h2.message.DbException", + "org.h2.constant.ErrorCode", + "org.h2.jdbc.JdbcSQLException", + "org.h2.command.dml.SetTypes", + "org.h2.engine.ConnectionInfo", + "org.h2.engine.Database", + "org.h2.util.BitField", + "org.h2.engine.Mode", + "org.h2.store.fs.FilePath", + "org.h2.store.fs.FilePathDisk", + "org.h2.store.fs.FilePathMem", + "org.h2.store.fs.FilePathNioMem", + "org.h2.store.fs.FilePathSplit", + "org.h2.constant.DbSettings", + "org.h2.value.CompareMode", + "org.h2.store.FileLock", + "org.h2.util.SortedProperties", + "org.h2.table.Table", + "com.mysql.jdbc.StatementImpl", + "com.mysql.jdbc.PreparedStatement", + "com.mysql.jdbc.MysqlIO", + "com.mysql.jdbc.CallableStatement" + ); + } +} -- cgit 1.2.3-korg